copy, file_get_contents, file_put_contents doesn't get full content in new file

I'm trying to download a file that exists on different server and move it to my new server.
I've tried
$file = file_get_contents("https://exampleurl.com/file/download.txt");
file_put_contents("C:/directory/to/report/data.csv", $file);
as well
$remote_file_url = "https://exampleurl.com/file/download.txt";
$local_file = C:/directory/to/report/data.csv;
$copy = copy( $remote_file_url, $local_file );
But the file never completes, it cuts off towards the end of the file. When I download the file directly from the url it's complete everytime.
I'm looking for a way to make sure the file is downloaded completely

Answer:
Use Curl request generally file_get_contents timeout which causes this sort of errors and only the partial content gets loaded. Try this:
$ch=curl_init("https://exampleurl.com/file/download.txt"); //create a c url session
$timeout=300; //set time limit here depends upon the operations being done on the remote server currently its 5mins
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); //set timeout for request
$content = curl_exec($ch);//execute request
if($content)
{
    $localfile = fopen("path to local file", "w"); //create or open a existing file
    if(fwrite($localfile , $content)) //write data received
        echo "success";
    else
        echo "unable to write file";
    fclose($localfile ); //close the file

}
else //error occured while executing the request on the remote server
    echo "Request Failed";


0 Response to "copy, file_get_contents, file_put_contents doesn't get full content in new file"

Đăng nhận xét

Popular Posts

Popular Posts