函式名稱:stream_notification_callback()
函式描述:該函式用於處理流通知的回撥函式。
適用版本:PHP 4 >= 4.3.0, PHP 5, PHP 7
語法:void stream_notification_callback(int $notification_code, int $severity, string $message, int $message_code, int $bytes_transferred, int $bytes_max)
引數:
- $notification_code:通知程式碼,表示不同的通知型別,例如STREAM_NOTIFY_CONNECT、STREAM_NOTIFY_AUTH_REQUIRED等。
- $severity:表示通知的嚴重程度,例如STREAM_NOTIFY_SEVERITY_INFO、STREAM_NOTIFY_SEVERITY_WARN等。
- $message:通知訊息的字串描述。
- $message_code:通知訊息的程式碼。
- $bytes_transferred:已傳輸的位元組數。
- $bytes_max:最大傳輸位元組數。
返回值:無返回值。
示例:
function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {
switch ($notification_code) {
case STREAM_NOTIFY_CONNECT:
echo "連線建立成功!\n";
break;
case STREAM_NOTIFY_AUTH_REQUIRED:
echo "需要進行身份驗證!\n";
break;
case STREAM_NOTIFY_AUTH_RESULT:
echo "身份驗證結果:$message\n";
break;
case STREAM_NOTIFY_FILE_SIZE_IS:
echo "檔案大小:$bytes_max 位元組\n";
break;
case STREAM_NOTIFY_PROGRESS:
echo "已傳輸位元組數:$bytes_transferred / $bytes_max\n";
break;
case STREAM_NOTIFY_COMPLETED:
echo "傳輸完成!\n";
break;
case STREAM_NOTIFY_FAILURE:
echo "傳輸失敗!\n";
break;
case STREAM_NOTIFY_RESOLVE:
echo "正在解析主機資訊...\n";
break;
case STREAM_NOTIFY_MIME_TYPE_IS:
echo "MIME 型別:$message\n";
break;
default:
echo "未知通知型別\n";
break;
}
}
$stream_context = stream_context_create();
stream_context_set_params($stream_context, ['notification' => 'stream_notification_callback']);
$file = fopen('http://example.com', 'r', false, $stream_context);
在上面的示例中,我們定義了一個名為stream_notification_callback的回撥函式來處理流通知。該函式根據傳入的notification_code引數判斷不同的通知型別,並進行相應的處理。在開啟一個URL資源時,我們透過stream_context_create()函式建立了一個流上下文,然後使用stream_context_set_params()函式設定了notification引數為我們定義的回撥函式。最後,我們使用fopen()函式開啟了一個URL資源,並觸發了相應的通知,透過回撥函式輸出了相應的資訊。