To upload a file to a remote server using Guzzle in PHP, follow these steps:
composer require guzzlehttp/guzzle
require 'vendor/autoload.php';
$client = new GuzzleHttp\Client();
$file_path = '/path/to/file.jpg';
$server_url = 'http://example.com/upload.php';
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.
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.