简体   繁体   中英

php - notification in stream_context_set_params() not called

I am using this code in php (Wordpress) to check for download progress:

// 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 );

The code does download the file successfully in the /wp-content/uploads/ folder, but does not print any notification / progress.

I tried also by writing to error_log() in the my_stream_notification_callback() function but it does not write anything there and the debug.log file is empty. Which means the notification callback is not being called at all.

Anyone has any idea why this would happen?

Here is a question with similar code but different problem: Download files file_put_contents with progress Evidently, the code works for him after the callback function was fixed for a class/object method function. While I am trying a simpler callback function that should definitely work.

Any ideas?

-- EDIT --

I found an example on php.net here: http://php.net/manual/en/function.stream-notification-callback.php

I used that example and it seems to work.

See the code I used (a bit changed from the example):

$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 );

Now this code works and prints out the progress notifications:

Does it mean that file_put_contents() or fopen() has problems with context/notifications that file_get_contents() do not have?

--EDIT--

Here is the change what actually works:

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

Means, instead of applying $context to file_put_contents() we apply it to fopen() call and it works!

As given in the documentation at http://php.net/stream_context_set_params , the notification callback is only triggered for ftp and http connections. As you use it to write something to a local directory (through another protocol), it's pretty obvious why the callback is never called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM