Copy file from remote server or URL [duplicate] Copy file from remote server or URL [duplicate] php php

Copy file from remote server or URL [duplicate]


While copy() will accept a URL as the source argument, it may be having issues a url for the destination.

Have you tried specifying the full filesystem path to the output file? I'm assuming you're not trying to put the new file onto a remote server.

For example:

$file = 'http://3.bp.blogspot.com/-AGI4aY2SFaE/Tg8yoG3ijTI/AAAAAAAAA5k/nJB-mDhc8Ds/s400/rizal001.jpg';$newfile = $_SERVER['DOCUMENT_ROOT'] . '/img/submitted/yoyo.jpg';if ( copy($file, $newfile) ) {    echo "Copy success!";}else{    echo "Copy failed.";}

The above worked nicely for me.


I found this function in one of my old project.

private function download_file ($url, $path) {  $newfilename = $path;  $file = fopen ($url, "rb");  if ($file) {    $newfile = fopen ($newfilename, "wb");    if ($newfile)    while(!feof($file)) {      fwrite($newfile, fread($file, 1024 * 8 ), 1024 * 8 );    }  }  if ($file) {    fclose($file);  }  if ($newfile) {    fclose($newfile);  } }


If the file is not publically accessible then you cannot copy a file from a server without having access to it.

You can use ftp_get() to open up a FTP connection and copy file.

$local_file = 'localname.zip'; // the nam$server_file = 'servername.zip';$conn = ftp_connect($ftp_server);$login_result = ftp_login($conn, $ftp_user_name, $ftp_user_pass);if (ftp_get($conn, $local_file, $server_file, FTP_BINARY)) {    echo "Successfully copied";}ftp_close($conn);

But, If you want to download a file from URL

$fullPath = "filepath.pdf";if ($fd = fopen ($fullPath, "r")) {    $fsize = filesize($fullPath);    $path_parts = pathinfo($fullPath);    $ext = strtolower($path_parts["extension"]);    header("Content-type: application/octet-stream");    header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");    header("Content-length: $fsize");    header("Cache-control: private"); //use this to open files directly    while(!feof($fd)) {        $buffer = fread($fd, 2048);        echo $buffer;    }}fclose ($fd);