问题
I try to write code with download file and return status (downloaded bytes). To download file I use file_put_contents and it's work.
function downloadLink($link,$destination)
{
$ctx = stream_context_create();
stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));
$mb_download = file_put_contents($destination, fopen($link, 'r'),null,$ctx);
return $mb_download;
}
function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {
file_put_contents( 'progress.txt', '' );
$fp = fopen('progress.txt', 'a' );
fputs( $fp,$bytes_transferred);
fclose( $fp );
echo 1;
}
It's my functions. I have problem to use callback function because all function is inside the same class. Now stream_notification_callback is not use. I try change declaration to
stream_context_set_params($ctx, array("notification" => "$this->stream_notification_callback()"));
Or
stream_context_set_params($ctx, array("notification" => $this->stream_notification_callback()));
But it's not working.
回答1:
You should try with
stream_context_set_params($ctx, array(
"notification" => array($this, 'stream_notification_callback')
));
回答2:
After the implementation of what Matei Mihai said, it actually still does not work because the context is used in the file_put_contents()
function while it should be used in the fopen()
function.
Therefore this:
$mb_download = file_put_contents($destination, fopen($link, 'r'),null,$ctx);
Should actually be this:
$mb_download = file_put_contents( $destination, fopen( $link, 'r', null, $ctx) );
And then it would work!
来源:https://stackoverflow.com/questions/34292472/download-files-file-put-contents-with-progress