How to send files using Guzzle in PHP?
To send a file using Guzzle, you can utilize Guzzle’s multipart request method. Here is an example code demonstrating how to send a file with Guzzle:
require 'vendor/autoload.php'; //加载Guzzle库
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7;
// 创建一个Guzzle客户端
$client = new Client();
// 要上传的文件
$file = '/path/to/file.jpg';
// 发送文件
$response = $client->request('POST', 'http://example.com/upload', [
'multipart' => [
[
'name' => 'file',
'contents' => fopen($file, 'r'),
'filename' => 'file.jpg'
]
],
]);
// 输出响应内容
echo $response->getBody();
In the example above, we start by creating a Guzzle client. Next, we specify the path of the file to upload and use the multipart option to add the file to the request. Finally, we send a POST request to http://example.com/upload and output the response content.
Please note that you may need to install the guzzlehttp/guzzle library, which can be done through Composer.
composer require guzzlehttp/guzzle
This way, you can use Guzzle to send files.