What is the simplest way to download file in PHP
-
25-09-2019 - |
Question
I need to download an image from some URL to my server. However, my server's config disallowed me to do it this way:
getimagesize( $file );
Because, it generate error:
Warning: getimagesize() [function.getimagesize]: URL file-access is disabled in the server configuration in somefile.php on line 10
So, is there another way I can use that doesn't require external library?
Ok, I solved it with solution from OIS:
$filename = '/tmp/'.md5($file);
$ch = curl_init($file);
$fp = fopen($filename, "w");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
$ext = getimagesize( $filename );
Solution
You can try curl.
OTHER TIPS
it is not possible unless you modify the server configuration
If file access to URLs is disabled on your server, you can't load any content from external URLs. That's the purpose of that configuration.
On a server where it's not disabled, file_get_contents($url) is the easiest way to fetch most files.
Use the following to download the file into $imgdata
. You can then save it to a file and get its image size. You can probably remove the file saving step with a bit of work to make it faster.
$imgdata = get_file_contents($url);
file_put_contents($filename, $imgdata);
getimagesize( $filename );