Search code examples
phpvideodownload

Replace urllib.request urlopen in PHP


I have a URL which can not download using video file using PHP. I have to run it ones in browser so that code can start downloading videos from it.

I have tried using curl, it fails to download video on first hit to url through code. I have tried using Ajax call by creating video blob, it works however because of cron job, javascript can not work.

I need solution in PHP.


Solution

  • Use Guzzle in PHP

       require_once('guzzle/vendor/autoload.php');
    
       use GuzzleHttp\Client;
       use GuzzleHttp\Exception\RequestException;
    
       $client = new Client();
       $url = 'video url'; // URL of the file to download
       $file_name = 'filename.mp4';
       $saveTo = $save_file_loc = __DIR__."/".$file_name; // 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();
           }
       }