[英]stream_context_set_params vs. stream_context_set_option
[英]php - notification in stream_context_set_params() not called
我正在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()
來進行my_stream_notification_callback()
但該函數未在其中寫入任何內容,並且debug.log
文件為空。 這意味着根本沒有調用通知回調。
任何人都知道為什么會發生這種情況嗎?
這是一個具有類似代碼但有不同問題的問題: 下載帶有進度的文件file_put_contents顯然,在為類/對象方法函數固定了回調函數之后,該代碼對他有效。 當我嘗試一個更簡單的回調函數時,它肯定可以正常工作。
有任何想法嗎?
-編輯-
我在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()
調用,它可以工作!
如http://php.net/stream_context_set_params上的文檔中所述, notification
回調僅針對ftp
和http
連接觸發。 當您使用它(通過另一個協議)將內容寫入本地目錄時,很明顯為什么從不調用回調。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.