file_put_contents is unable to get whole file

649 views Asked by At

I am using hostmonster as hosting provider.

I have written below code.

$mp4_url = 'http://www.w3schools.com/html/mov_bbb.mp4';
$filename = 'sample.mp4';

file_put_contents( $filename , fopen($mp4_url, 'r' ) );

I am seeing strange behaviour. Sometimes it works but sometimes it copies only few bites like sometimes size of file is 100kb sometimes 600kb sometimes it copies whole file.

Please suggest what should I do to copy any mp4 file from any server to our server.

We have to copy large files, size can be 600MB or 1GB.

2

There are 2 answers

4
Faiz Rasool On

Try copy(). This will do your job:

$file = 'http://www.w3schools.com/html/mov_bbb.mp4';
$newfile = $_SERVER['DOCUMENT_ROOT'] . '/sample.mp4';

if ( copy($file, $newfile) ) {
    echo "Copy success!";
}else{
    echo "Copy failed.";
}
1
Thamaraiselvam On

use curl rather than using file_put_contents

$url='http://www.w3schools.com/html/mov_bbb.mp4';
$saveto='path';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$raw = curl_exec($ch);
curl_close($ch);
if (file_exists($saveto)) {
    unlink($saveto);
}
$fp = fopen($saveto, 'x');
fwrite($fp, $raw);
fclose($fp);