【发布时间】: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