How to upload a file to a remote server using Guzzle in PHP?

To upload a file to a remote server using Guzzle in PHP, follow these steps:

  1. Install Guzzle via Composer. Run the following command in your project folder:
composer require guzzlehttp/guzzle
  1. Create a PHP script and include the Guzzle autoloader at the top:
require 'vendor/autoload.php';
  1. Initialize a Guzzle client:
$client = new GuzzleHttp\Client();
  1. Define the file path and the remote server URL:
$file_path = '/path/to/file.jpg'; $server_url = 'http://example.com/upload.php';
  1. Create a Guzzle POST request and attach the file:
$response = $client->post($server_url, [ 'multipart' => [ [ 'name' => 'file', 'contents' => fopen($file_path, 'r'), ], ] ]);

In the code above, 'file' is the name of the file input field expected by the remote server. You can adjust it according to your server's requirements.

  1. Handle the response:
if ($response->getStatusCode() == 200) { echo 'File uploaded successfully!'; } else { echo 'Upload failed!'; }

The above code checks if the response status code is 200 to determine if the upload was successful.

That's it! You have successfully uploaded a file to a remote server using Guzzle in PHP.