下载文件 file_put_contents 有进度

Download files file_put_contents with progress

我尝试编写带有下载文件和 return 状态(已下载字节数)的代码。 要下载文件,我使用 file_put_contents 并且可以正常工作。

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;
}

这是我的职能。我在使用回调函数时遇到问题,因为所有函数都在同一个 class 中。现在 stream_notification_callback 是没有用的。我尝试将声明更改为

stream_context_set_params($ctx, array("notification" => "$this->stream_notification_callback()"));

stream_context_set_params($ctx, array("notification" => $this->stream_notification_callback()));

但是没用。

你应该试试

stream_context_set_params($ctx, array(
    "notification" => array($this, 'stream_notification_callback')
));

Matei Mihai说的实现后,其实还是不行,因为context用在file_put_contents()函数中,而应该用在fopen()函数中

因此:

$mb_download = file_put_contents($destination, fopen($link, 'r'),null,$ctx);

实际上应该是这样的:

$mb_download = file_put_contents( $destination, fopen( $link, 'r', null, $ctx) );

然后就可以了!