To download a file from a URL using Guzzle in PHP, you can follow these steps:
Install Guzzle HTTP client library using composer:
composer require guzzlehttp/guzzle
Use the following PHP code to download the file:
<?php
require 'vendor/autoload.php'; // Include autoloader from Composer
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
$url = '<URL_OF_FILE>'; // Specify the URL of the file to be downloaded
$savePath = '<SAVE_PATH>'; // Specify the path to save the downloaded file
$client = new Client();
try {
$response = $client->get($url, ['sink' => $savePath]);
echo "File downloaded successfully!";
} catch (RequestException $e) {
// Handle request exception
echo "Error downloading file: " . $e->getMessage();
}
Make sure to replace <URL_OF_FILE>
with the actual URL of the file you want to download, and <SAVE_PATH>
with the desired location to save the downloaded file.
The code uses Guzzle's get()
method to send a GET request to the specified URL. The sink
option is used to specify the path to save the downloaded file. The file will be saved to the specified path on successful download of the file. In case of any request exception, it will be caught in the catch
block and an error message will be shown.