我在php(wordpress)中使用此代码检查下载进度:
$context = stream_context_create();
stream_context_set_params( $context, [ 'notification' => 'my_stream_notification_callback' ] );
function my_stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {
print_r(func_get_args());
}
$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/
文件夹,但不打印任何通知/进度。
我也试着写信给
error_log()
在
my_stream_notification_callback()
函数,但它不在其中写入任何内容,
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应用于
文件放置目录()
我们应用于
FOpen-()
打电话就行了!