【问题标题】:Download files file_put_contents with progress下载文件 file_put_contents 的进度
【发布时间】:2016-03-21 10:26:55
【问题描述】:

我尝试用下载文件编写代码并返回状态(下载的字节)。 要下载文件,我使用 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;
}

这是我的功能。我在使用回调函数时遇到问题,因为所有函数都在同一个类中。现在不使用 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()));

但它不起作用。

【问题讨论】:

  • 它是否显示任何错误?
  • 你的回调语法错误。 "$this->stream_notification_callback()" 应该是 [$this, 'stream_notification_callback']
  • 您是否检查过php.net,因为其中提到了参数名称“通知” - 每当流触发通知时要调用的用户定义回调函数的名称。
  • 但是这个解决方案不起作用。在 stream_notification_callback 我用日志创建文件。但是这个解决方案没有运行函数stream_notification_callback,因为文件没有创建并且echo not write sth。

标签: php callback file-put-contents


【解决方案1】:

马太米海说的实现了之后,其实还是不行,因为file_put_contents()函数中使用了context,而fopen()函数中应该使用了context。

因此:

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

实际上应该是这样的:

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

然后它就可以工作了!

【讨论】:

    【解决方案2】:

    你应该试试

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

    【讨论】:

    • 不行……我用echo来检查程序是否在stream_notification_callback里面但是message是空的。
    猜你喜欢
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    • 2013-10-17
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多