Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to download a file in PHP

Tags:

php

Which would be the best way to download a file from another domain in PHP? i.e. A zip file.

like image 829
Gerardo Avatar asked Dec 30 '22 02:12

Gerardo


2 Answers

The easiest one is file_get_contents(), a more advanced way would be with cURL for example. You can store the data to your harddrive with file_put_contents().

like image 190
Patrick Glandien Avatar answered Jan 09 '23 18:01

Patrick Glandien


normally, the fopen functions work for remote files too, so you could do the following to circumvent the memory limit (but it's slower than file_get_contents)

<?php
$remote = fopen("http://www.example.com/file.zip", "rb");
$local = fopen("local_name_of_file.zip", 'w');
while (!feof($remote)) {
  $content = fread($remote, 8192);
  fwrite($local, $content);
}
fclose($local);
fclose($remote);
?>

copied from here: http://www.php.net/fread

like image 21
stefs Avatar answered Jan 09 '23 19:01

stefs