How can I use Guzzle to download files?

Guzzle is a PHP HTTP client that simplifies the process of sending HTTP requests and integrating with web services. To download files using Guzzle, you should send a GET request to the file URL and then write the response body directly to a file.

Here's a step-by-step example of how you can use Guzzle to download a file:

  1. Install Guzzle: If you haven't already installed Guzzle, you can do so using Composer, PHP's dependency manager. Run the following command in your project's root directory:
   composer require guzzlehttp/guzzle
  1. Create a PHP script to download the file: Use the following code to download a file using Guzzle. Make sure to replace http://example.com/file.pdf with the actual URL of the file you want to download and path/to/your/downloaded_file.pdf with the path where you want to save the file on your local system.
   <?php

   require 'vendor/autoload.php';

   use GuzzleHttp\Client;
   use GuzzleHttp\Exception\RequestException;

   $client = new Client();
   $url = 'http://example.com/file.pdf'; // URL of the file to download
   $saveTo = 'path/to/your/downloaded_file.pdf'; // Local path to save the file

   try {
       $response = $client->request('GET', $url, ['sink' => $saveTo]);
       echo "File downloaded successfully to " . $saveTo;
   } catch (RequestException $e) {
       echo "Error: " . $e->getMessage();
       if ($e->hasResponse()) {
           echo "\nHTTP Status Code: " . $e->getResponse()->getStatusCode();
       }
   }

In the above code, the sink option is used to specify the file path where the response body should be saved. Guzzle will stream the download directly to the file, which is efficient and avoids loading the entire file into memory.

  1. Run the PHP script: Execute the script from the command line or a web server to start the file download.
   php your-script.php
  1. Check for errors: The above script includes a basic error handling mechanism. If something goes wrong during the request (e.g., the file is not found, the server is down, etc.), an exception will be thrown, and you will see an error message in the output.

  2. File permissions: Ensure that the directory where you're trying to save the file has the proper write permissions. If the script can't write to the specified location, the file download will fail.

Guzzle provides a powerful and flexible way to interact with HTTP resources, and its streaming capabilities make it suitable for downloading large files without exhausting memory limits. Remember to handle exceptions and errors appropriately in your production code to ensure a robust application.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon