Download Remote File to Server with PHP

Viewed 57546

I've been looking all over the place for the last two days and trying everything and still can't get anything to work. I feel like this should be a relatively simple thing to do.

All I want to do is download a remote file from a URL to a directory on my server.

So, for example, if

$_url = http://www.freewarelovers.com/android/download/temp/1306495040_Number_Blink_1.1.1.apk

and $_dir = /www/downloads/

Then when all is said and done I want 1306495040_Number_Blink_1.1.1.apk in /www/downloads/

I've tried the copy() function, I've tried

file_put_contents("$_dir.$_file_name", file_get_contents($_url));

and get the following error:

file_get_contents(): failed to open stream: HTTP request failed!

8 Answers

With validations...

Validate if file exists first:

function doesUrlExists($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if($code == 200){
        $status = true;
    }else{
        $status = false;
    }
    curl_close($ch);
    return $status;
}

And then put file content (with laravel storage class):

 if(!doesUrlExists($url_file)) {
     die('The remote file is not accessible. Please check the URL.');
 }

 Storage::disk('local')
          ->put($file_destintation, fopen($url_file, 'r'));
Related