【PHP8.x】CURLMSG_DONE定数の使い方
CURLMSG_DONE定数の使い方について、初心者にもわかりやすく解説します。
基本的な使い方
CURLMSG_DONE定数は、PHPのCURL拡張機能において、複数のネットワーク通信を並行して行う際に、個々の通信処理が完了したことを表す定数です。
PHPのCURL拡張機能は、HTTPやFTPなどの様々なプロトコルを通じて外部のサーバーと通信を行うための機能を提供します。この定数は、特に「CURLマルチハンドル」と呼ばれる機能を使用する際に利用されます。CURLマルチハンドルは、複数のネットワークリクエストを同時に実行し、それらを効率的に管理するための仕組みです。各個別のリクエストは「CURLイージーハンドル」として扱われます。
CURLMSG_DONE定数は、これらのイージーハンドルの一つがデータの送受信を終え、完了状態になったときに発生するメッセージのタイプを識別するために使用されます。開発者は、curl_multi_info_read()関数を使って、完了した通信に関する情報(どのイージーハンドルが完了したか、結果はどうだったかなど)をキューから読み出すことができます。この際、読み出したメッセージのタイプがCURLMSG_DONEであるかどうかをチェックすることで、特定の通信処理が終了したことを正確に判断し、次の処理へと進むことが可能になります。
これにより、アプリケーションは複数のネットワークリクエストを非同期的に処理し、それぞれの完了イベントを適切に検知して後続の処理を実行できるようになります。この定数は、多数のネットワークリクエストを効率よく並行処理するシステムを構築する上で非常に重要な役割を果たします。
構文(syntax)
1echo CURLMSG_DONE;
引数(parameters)
引数なし
引数はありません
戻り値(return)
戻り値なし
戻り値はありません
サンプルコード
PHP: curl_multi_getcontentで複数URL並列取得
1<?php 2 3/** 4 * Fetches content from multiple URLs concurrently using cURL multi interface. 5 * Demonstrates the use of CURLMSG_DONE to identify completed transfers 6 * and curl_multi_getcontent to retrieve their results. 7 * 8 * @param array $urls An array of URLs to fetch. 9 */ 10function fetchMultipleUrls(array $urls): void 11{ 12 // Initialize a cURL multi handle 13 $mh = curl_multi_init(); 14 if ($mh === false) { 15 echo "Error: Failed to initialize cURL multi handle.\n"; 16 return; 17 } 18 19 $handles = []; // Array to store individual cURL handles and their associated URLs 20 21 // Initialize individual cURL handles for each URL 22 foreach ($urls as $url) { 23 $ch = curl_init(); 24 if ($ch === false) { 25 echo "Error: Failed to initialize cURL handle for URL: {$url}\n"; 26 continue; 27 } 28 29 // Set cURL options for each handle 30 curl_setopt($ch, CURLOPT_URL, $url); 31 curl_setopt($ch, CURLOPT_HEADER, 0); // Do not return HTTP headers 32 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the transfer as a string 33 34 // Add the individual handle to the multi handle 35 curl_multi_add_handle($mh, $ch); 36 $handles[(string)$ch] = $ch; // Store handle with its resource ID as key for easy lookup 37 } 38 39 $active = null; // Will hold the number of active handles 40 41 // Execute the transfers concurrently 42 do { 43 $status = curl_multi_exec($mh, $active); 44 // Wait for activity on any of the cURL handles if there's no error and active transfers remain 45 if ($status === CURLM_CALL_MULTI_PERFORM || $active > 0) { 46 // Select will block until activity is detected or timeout occurs 47 curl_multi_select($mh); 48 } 49 } while ($active && $status === CURLM_OK); // Continue as long as there are active transfers and no errors 50 51 // Process completed transfers 52 // curl_multi_info_read returns messages about completed transfers 53 while ($info = curl_multi_info_read($mh)) { 54 // CURLMSG_DONE indicates that an individual handle has completed its transfer 55 if ($info['msg'] === CURLMSG_DONE) { 56 $ch = $info['handle']; // Get the individual cURL handle that completed 57 $url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); // Get the URL from the completed handle 58 59 // Retrieve the content of the completed transfer 60 $content = curl_multi_getcontent($ch); 61 $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 62 63 echo "--------------------------------------------------------\n"; 64 echo "Completed URL: {$url}\n"; 65 echo "HTTP Code: {$httpCode}\n"; 66 echo "Content Snippet (first 200 chars):\n"; 67 echo substr($content, 0, 200) . (strlen($content) > 200 ? "..." : "") . "\n"; 68 echo "--------------------------------------------------------\n\n"; 69 70 // Remove the completed handle from the multi handle 71 curl_multi_remove_handle($mh, $ch); 72 // Close the individual cURL handle 73 curl_close($ch); 74 unset($handles[(string)$ch]); // Remove from our tracking array 75 } 76 } 77 78 // Close the multi cURL handle 79 curl_multi_close($mh); 80} 81 82// --- Example Usage --- 83// Make sure these URLs are accessible. Using public test URLs is recommended. 84$urlsToFetch = [ 85 'https://example.com/', 86 'https://www.php.net/manual/en/function.curl-multi-getcontent.php', 87 'https://httpbin.org/get?param=test', // A public service for testing HTTP requests 88 'https://en.wikipedia.org/wiki/PHP', 89]; 90 91// Check if the cURL extension is loaded before attempting to use it 92if (extension_loaded('curl')) { 93 fetchMultipleUrls($urlsToFetch); 94} else { 95 echo "cURL extension is not loaded. Please enable it in your php.ini configuration.\n"; 96}
このサンプルコードは、PHPのcURL拡張機能を使って、複数のURLからウェブページのコンテンツを並行して効率的に取得する方法を示しています。特に、並行処理で個々の転送が完了したことを判断するためにCURLMSG_DONE定数を使用し、その完了した転送のデータを取得するためにcurl_multi_getcontent関数を利用する流れを説明しています。
まず、curl_multi_init()で複数のcURL操作を管理する「マルチハンドル」を初期化し、取得したいURLごとに個別のcURLハンドルを作成します。この際、ページのコンテンツを文字列として返すようCURLOPT_RETURNTRANSFERオプションをtrueに設定します。これらの個別ハンドルはcurl_multi_add_handle()でマルチハンドルに追加され、curl_multi_exec()とcurl_multi_select()を使ってリクエストを並行して実行します。
転送が完了すると、curl_multi_info_read()が情報メッセージを返します。このメッセージのmsgキーがCURLMSG_DONE定数と一致する場合、その転送が正常に完了したことを意味します。CURLMSG_DONEは引数も戻り値もありませんが、この値によってコードは完了した転送を識別できます。
完了した転送のハンドルに対してcurl_multi_getcontent()を呼び出すことで、取得したウェブページのHTMLコンテンツなどを文字列として受け取ることができます。この関数は引数として完了した個別cURLハンドルを受け取り、その転送結果であるコンテンツの文字列を返します。最後に、使用したハンドルを適切に閉じ、多数のリソースへのアクセスを効率的に処理します。
curl_multi_getcontentは、CURLOPT_RETURNTRANSFERがtrueに設定されている場合にのみ内容を取得できます。この設定を忘れると期待通りの結果が得られません。CURLMSG_DONEは、並行処理中の個別のcURL転送が正常に完了したことを示す定数です。この定数を使って完了した転送を特定し、curl_multi_getcontentでその結果を取得します。cURLハンドルは、curl_init()やcurl_multi_init()で作成したら、処理終了時に必ずcurl_close()やcurl_multi_close()で解放してください。リソースリークを防ぎ、システムの安定性を保つ上で非常に重要です。また、cURL関数の戻り値を常に確認し、エラーハンドリングを適切に行うことで、予期せぬ問題に対応できます。
PHP cURLマルチで複数URLを並行取得する
1<?php 2 3/** 4 * Fetches multiple URLs concurrently using PHP's cURL multi interface. 5 * 6 * This function demonstrates how to use `curl_multi_exec` to manage 7 * multiple cURL handles simultaneously and how to detect when a transfer 8 * is complete using `curl_multi_info_read` and the `CURLMSG_DONE` constant. 9 * 10 * @param array<string> $urls An array of URLs to fetch. 11 * @return array<string, array<string, mixed>> An associative array where keys are URLs 12 * and values are arrays containing the status, content/error details. 13 */ 14function fetchMultipleUrls(array $urls): array 15{ 16 // Initialize a cURL multi handle 17 $multiHandle = curl_multi_init(); 18 $handles = []; // Array to store individual cURL handles 19 $results = []; // Array to store results for each URL 20 21 // 1. Create and add individual cURL handles to the multi handle 22 foreach ($urls as $id => $url) { 23 $ch = curl_init(); // Initialize an individual cURL handle 24 if ($ch === false) { 25 // Handle error if curl_init fails 26 $results[$url] = ['status' => 'error', 'error_message' => 'Failed to initialize cURL handle.']; 27 continue; 28 } 29 30 // Set options for the individual handle 31 curl_setopt($ch, CURLOPT_URL, $url); 32 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the transfer as a string 33 curl_setopt($ch, CURLOPT_TIMEOUT, 10); // Set a timeout for each request 34 35 // Add the individual handle to the multi handle 36 curl_multi_add_handle($multiHandle, $ch); 37 $handles[$id] = $ch; // Store the handle for later access 38 } 39 40 $active = null; // Will be updated by curl_multi_exec to indicate active transfers 41 42 // 2. Execute the multi-handle loop until all transfers are complete 43 do { 44 // Run the sub-connections. This function drives the actual transfers. 45 // It should be called repeatedly until $active is 0. 46 $multiResultCode = curl_multi_exec($multiHandle, $active); 47 48 // Wait for activity on any of the cURL connections. 49 // This prevents the loop from consuming 100% CPU when waiting for network I/O. 50 if ($active > 0) { 51 // Wait up to 1 second for activity on any easy handle. 52 // A timeout of 0 would poll immediately. 53 curl_multi_select($multiHandle, 1.0); 54 } 55 56 // 3. Process any completed transfers 57 // Loop through messages about completed transfers 58 while ($info = curl_multi_info_read($multiHandle)) { 59 // Check if a transfer has finished (CURLMSG_DONE) 60 if ($info['msg'] === CURLMSG_DONE) { 61 $ch = $info['handle']; // The individual cURL handle that completed 62 $effectiveUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); 63 $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 64 $error = curl_error($ch); 65 $errno = curl_errno($ch); 66 67 if ($errno === CURLE_OK) { // Check if the transfer completed successfully 68 $content = curl_multi_getcontent($ch); // Get the returned content 69 $results[$effectiveUrl] = [ 70 'status' => 'success', 71 'http_code' => $httpCode, 72 'content' => $content, 73 'content_length' => strlen((string)$content) 74 ]; 75 } else { 76 // Handle cURL-specific errors 77 $results[$effectiveUrl] = [ 78 'status' => 'error', 79 'error_code' => $errno, 80 'error_message' => $error 81 ]; 82 } 83 84 // Important: Remove the completed handle from the multi handle 85 // and close it to free resources. 86 curl_multi_remove_handle($multiHandle, $ch); 87 curl_close($ch); 88 } 89 } 90 // Continue the loop as long as there are active transfers and no multi-cURL error 91 } while ($active > 0 && $multiResultCode === CURLM_OK); 92 93 // 4. Close the cURL multi handle 94 curl_multi_close($multiHandle); 95 96 return $results; 97} 98 99// --- Example Usage --- 100$urlsToFetch = [ 101 'http://example.com', // A valid, simple URL 102 'https://www.google.com/', // Another valid URL 103 'http://invalid-domain-12345.com/', // An URL that will likely fail (DNS resolution error) 104 'https://httpbin.org/delay/2', // An URL that introduces a delay 105]; 106 107// Execute the concurrent fetches 108echo "Starting concurrent URL fetches...\n\n"; 109$fetchedData = fetchMultipleUrls($urlsToFetch); 110echo "All fetches completed.\n\n"; 111 112// Print the results 113foreach ($fetchedData as $url => $data) { 114 echo "URL: " . $url . "\n"; 115 if ($data['status'] === 'success') { 116 echo " Status: Success (HTTP Code: " . $data['http_code'] . ")\n"; 117 echo " Content Length: " . $data['content_length'] . " bytes\n"; 118 // Optionally, print a snippet of the content 119 // echo " Content Snippet: " . substr($data['content'], 0, 100) . "...\n"; 120 } else { 121 echo " Status: Error\n"; 122 echo " Error Code: " . $data['error_code'] . "\n"; 123 echo " Error Message: " . $data['error_message'] . "\n"; 124 } 125 echo "\n"; 126} 127 128?>
CURLMSG_DONEは、PHPのcURL拡張機能で提供される定数で、複数のcURLリクエストを並行して処理する「cURLマルチインターフェース」において、個々のデータ転送が完了したことを示すために利用されます。
このサンプルコードのfetchMultipleUrls関数は、複数のURLを同時に取得する処理を実装しています。curl_multi_initでマルチハンドルを初期化し、各URLに対して個別のcURLハンドルを作成してマルチハンドルに追加します。
データ転送はcurl_multi_execを繰り返し呼び出すことで進められますが、この際、curl_multi_info_read関数が転送に関するメッセージを返します。CURLMSG_DONEは、このメッセージに含まれるmsgキーの値として、特定のcURLハンドルによるURLへのアクセス(データ転送)が成功または失敗にかかわらず終了したことを示します。これにより、コードはどのリクエストが完了したかを正確に判断し、取得したコンテンツや発生したエラーなどの結果を適切に処理し、該当するハンドルを閉じることができます。
CURLMSG_DONEは定数であるため、引数を持ちません。また、戻り値もありません。
このPHPのサンプルコードは、複数のHTTPリクエストを並行して実行するcURLマルチインターフェースの使い方を示しています。初心者が特に注意すべき点は、個々のcURLハンドルが転送を完了した際に、必ずcurl_multi_remove_handleでマルチハンドルから外し、その後curl_closeで閉じることです。このリソース解放を怠ると、メモリリークやリソース枯渇の原因となります。
CURLMSG_DONE定数は、curl_multi_info_readが返す情報の一部として、個別の転送が正常に、またはエラーで完了したことを示します。この情報を受け取ったタイミングで、転送結果の取得やエラーハンドリングを行い、上記の通り忘れずにリソースを解放してください。また、curl_multi_execはネットワークの状況に応じて繰り返し呼び出す必要があり、curl_multi_selectを利用して効率的に待機することで、CPU使用率を抑えることができます。各cURLリクエストにはCURLOPT_TIMEOUTを設定し、応答のないサーバーによるプログラムのハングアップを防ぐことも大切です。