【问题标题】:php - notification in stream_context_set_params() not calledphp - 未调用 stream_context_set_params() 中的通知
【发布时间】:2018-11-22 07:08:07
【问题描述】:

我在 php (Wordpress) 中使用此代码来检查下载进度:

// Create context
$context = stream_context_create();
stream_context_set_params( $context, [ 'notification' => 'my_stream_notification_callback' ] );

// Declare progress function
function my_stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {
    print_r(func_get_args());
}

// Call download
$wp_upload_dir = wp_upload_dir();
file_put_contents( $wp_upload_dir['basedir'] . '/contact.htm', fopen( 'http://php.net/contact', 'r' ), null, $context );

代码确实成功下载了/wp-content/uploads/文件夹中的文件,但不打印任何通知/进度。

我也尝试在my_stream_notification_callback() 函数中写入error_log(),但它没有在那里写入任何内容,并且debug.log 文件为空。这意味着通知回调根本没有被调用。

有人知道为什么会这样吗?

这是一个代码相似但问题不同的问题: Download files file_put_contents with progress 显然,在为类/对象方法函数修复了回调函数之后,该代码对他有效。虽然我正在尝试一个更简单的回调函数,但它肯定可以工作。

有什么想法吗?

-- 编辑--

我在 php.net 上找到了一个示例: http://php.net/manual/en/function.stream-notification-callback.php

我使用了那个例子,它似乎有效。

查看我使用的代码(与示例略有不同):

$ctx = stream_context_create();
stream_context_set_params( $ctx, [
    "notification" => function ( $notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max ) {
        print_r(func_get_args());
    },
] );

file_get_contents( "http://php.net/contact", false, $ctx );

现在这段代码可以工作并打印出进度通知:

这是否意味着file_put_contents()fopen() 存在file_get_contents() 没有的上下文/通知问题?

--编辑--

以下是实际有效的更改:

file_put_contents( $wp_upload_dir['basedir'] . '/contact.htm', fopen( 'http://php.net/contact', 'r', null, $context ) );

意思是,我们不是将 $context 应用于file_put_contents(),而是将其应用于fopen() 调用并且它有效!

【问题讨论】:

    标签: php wordpress fopen file-put-contents


    【解决方案1】:

    http://php.net/stream_context_set_params 的文档中所述,notification 回调仅针对ftphttp 连接触发。当您使用它向本地目录写入内容时(通过另一个协议),很明显为什么从不调用回调。

    【讨论】:

    • 感谢 Nico 的回答。但是在这个 SO 帖子 (stackoverflow.com/questions/34292472/…) 中,用户让它为 file_put_content() 工作,是 php 设置/配置的一些差异吗?
    • 你确定吗?他多次声称所有方法都不起作用
    • 我认为你是对的,这家伙已经接受了答案,这让人觉得他的问题已经解决了。但代码实际上不起作用。我对我的代码做了一点改动,它可以工作。这个想法就是你所说的上下文应用于文件写入,而它应该应用于文件读取部分。让我用修复更新我的问题。
    猜你喜欢
    • 2010-11-22
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    • 2020-03-24
    • 1970-01-01
    相关资源
    最近更新 更多