Webエンジニア向けプログラミング解説動画をYouTubeで配信中!
▶ チャンネル登録はこちら

【PHP8.x】CURLKHMATCH_MISSING定数の使い方

CURLKHMATCH_MISSING定数の使い方について、初心者にもわかりやすく解説します。

作成日: 更新日:

基本的な使い方

CURLKHMATCH_MISSING定数は、PHPのcURL拡張機能において、Kerberos認証(GSSAPI認証)を利用する際のホストキー検証結果を表す定数の一つです。cURLは、ウェブサーバーなどとデータを安全にやり取りするために広く利用されるライブラリで、様々な通信プロトコルをサポートしています。Kerberos認証は、ネットワーク上でユーザーやサービスを安全に認証するための仕組みであり、接続先のサーバーの身元を確認することでセキュリティを強化します。

この定数、CURLKHMATCH_MISSINGは、cURLがKerberos認証を通じてサーバーに接続しようとした際に、そのサーバーの「ホストキー」がまったく見つからなかった状況を示します。ホストキーは、特定のサーバーを識別し、その真正性を確認するために使用される情報です。CURLKHMATCH_MISSINGの値が返される場合、cURLは接続先のサーバーの身元を安全に検証するためのキー情報を持っていないことを意味します。

これは、通常、セキュリティ上の問題を示唆しており、信頼できないサーバーへの接続である可能性や、認証プロセスに何らかの不備があることを警告しています。システム開発において、この定数が示す状態を適切に検出することで、不正な接続を防止したり、認証失敗時の適切なエラーハンドリングを行ったりすることが可能です。システムエンジニアとしては、このようなセキュリティ関連の定数の意味を理解し、安全なアプリケーション開発に役立てることが重要です。

構文(syntax)

1<?php
2echo CURLKHMATCH_MISSING;
3?>

引数(parameters)

引数なし

引数はありません

戻り値(return)

戻り値なし

戻り値はありません

サンプルコード

PHP cURLMOPTSSHホストキー検証を実践

1<?php
2
3/**
4 * A class to demonstrate the usage context of the CURLKHMATCH_MISSING constant
5 * within multi-cURL operations, specifically related to SSH host key verification.
6 */
7class CurlMultiSshHostKeyDemo
8{
9    /**
10     * Callback function for CURLMOPT_SERVER_DOMAIN_CALLBACK.
11     * This method is invoked by cURL when connecting to an SSH/SFTP server
12     * to verify the server's host key. It returns one of the CURLKHMATCH_* constants.
13     *
14     * For demonstration, this callback is configured to simulate a missing host key
15     * for 'sftp.example.com'.
16     *
17     * @param resource $multi_handle The cURL multi handle.
18     * @param string $hostname The hostname to check.
19     * @param int $port The port number.
20     * @param array $fingerprints An array of fingerprints from the server.
21     * @return int One of the CURLKHMATCH_* constants (e.g., CURLKHMATCH_OK, CURLKHMATCH_MISSING, CURLKHMATCH_MISMATCH).
22     */
23    public static function sshHostKeyVerificationCallback($multi_handle, $hostname, $port, $fingerprints)
24    {
25        // In a real application, this callback would:
26        // 1. Look up $hostname in a known_hosts file (e.g., ~/.ssh/known_hosts).
27        // 2. Compare the provided $fingerprints against those stored for $hostname.
28        // 3. Return CURLKHMATCH_OK if there's a match.
29        // 4. Return CURLKHMATCH_MISMATCH if a key exists but doesn't match.
30        // 5. Return CURLKHMATCH_MISSING if no key is found for $hostname.
31
32        echo "[Callback] Attempting to verify host key for '{$hostname}':{$port}\n";
33
34        // Simulate a scenario where the host key for 'sftp.example.com' is not found.
35        if ($hostname === 'sftp.example.com') {
36            echo "[Callback] Simulating a missing host key for '{$hostname}'. Returning CURLKHMATCH_MISSING.\n";
37            return CURLKHMATCH_MISSING;
38        }
39
40        // For any other hostname, simulate a successful verification for demonstration purposes.
41        echo "[Callback] Host key for '{$hostname}' considered OK (for demo). Returning CURLKHMATCH_OK.\n";
42        return CURLKHMATCH_OK;
43    }
44
45    /**
46     * Demonstrates multi-cURL operations with an SSH host key verification callback.
47     * This function sets up two cURL handles:
48     * 1. An SFTP handle configured to trigger the host key callback, where `CURLKHMATCH_MISSING` is simulated.
49     * 2. A standard HTTP handle, which will not trigger the SSH callback.
50     */
51    public static function runDemonstration()
52    {
53        // Initialize a multi cURL handle. This allows managing multiple cURL transfers concurrently.
54        $multi_handle = curl_multi_init();
55
56        if ($multi_handle === false) {
57            echo "Error: Failed to initialize multi cURL handle.\n";
58            return;
59        }
60
61        // Set the CURLMOPT_SERVER_DOMAIN_CALLBACK for the multi handle.
62        // This makes the `sshHostKeyVerificationCallback` method responsible
63        // for verifying SSH host keys for any SFTP/SCP transfers managed by this multi handle.
64        curl_multi_setopt($multi_handle, CURLMOPT_SERVER_DOMAIN_CALLBACK, [self::class, 'sshHostKeyVerificationCallback']);
65
66        // --- Create a cURL easy handle for an SFTP transfer ---
67        // This handle is configured to connect to a placeholder SFTP server,
68        // which will trigger the SSH host key verification callback.
69        $ch_sftp = curl_init();
70        if ($ch_sftp === false) {
71            echo "Error: Failed to initialize cURL handle for SFTP.\n";
72            curl_multi_close($multi_handle);
73            return;
74        }
75
76        $sftp_url = 'sftp://sftp.example.com/remote/path/file.txt'; // Placeholder URL
77        curl_setopt($ch_sftp, CURLOPT_URL, $sftp_url);
78        curl_setopt($ch_sftp, CURLOPT_PROTOCOLS, CURLPROTO_SFTP); // Specify SFTP protocol
79        curl_setopt($ch_sftp, CURLOPT_USERNAME, 'testuser');
80        curl_setopt($ch_sftp, CURLOPT_PASSWORD, 'testpass');
81        curl_setopt($ch_sftp, CURLOPT_SSH_AUTH_TYPES, CURLSSH_AUTH_PASSWORD);
82        // Setting CURLOPT_SSH_KNOWNHOSTS to an empty string ensures that
83        // the CURLMOPT_SERVER_DOMAIN_CALLBACK is always called for host key verification.
84        curl_setopt($ch_sftp, CURLOPT_SSH_KNOWNHOSTS, '');
85        // Enable verbose output for this handle to see detailed cURL messages,
86        // including those from the host key verification process.
87        curl_setopt($ch_sftp, CURLOPT_VERBOSE, true);
88
89        // Add the SFTP easy handle to the multi handle.
90        curl_multi_add_handle($multi_handle, $ch_sftp);
91
92        // --- Create another cURL easy handle for a standard HTTP request ---
93        // This handle will perform a regular HTTP request and will NOT trigger the SSH callback.
94        $ch_http = curl_init();
95        if ($ch_http === false) {
96            echo "Error: Failed to initialize cURL handle for HTTP.\n";
97            curl_multi_remove_handle($multi_handle, $ch_sftp);
98            curl_close($ch_sftp);
99            curl_multi_close($multi_handle);
100            return;
101        }
102        curl_setopt($ch_http, CURLOPT_URL, 'http://example.com');
103        curl_setopt($ch_http, CURLOPT_RETURNTRANSFER, true); // Return the transfer as a string
104        curl_multi_add_handle($multi_handle, $ch_http);
105
106        $running_handles = null;
107        // Initial state for the multi-cURL loop.
108        // CURLM_CALL_MULTI_PERFORM indicates that curl_multi_exec might need to be called again immediately.
109        $exec_status = CURLM_CALL_MULTI_PERFORM;
110
111        // Main multi-cURL execution loop.
112        // This loop continues as long as there are active transfers and no errors on the multi handle.
113        do {
114            // Execute the multi cURL transfers. This function processes existing transfers
115            // and starts new ones if possible.
116            $exec_status = curl_multi_exec($multi_handle, $running_handles);
117
118            if ($exec_status === CURLM_CALL_MULTI_PERFORM) {
119                // If curl_multi_exec returns CURLM_CALL_MULTI_PERFORM, it means
120                // there's more internal work to do immediately. We call it again
121                // without waiting to ensure all internal processing is complete.
122                continue;
123            }
124
125            if ($running_handles > 0) {
126                // If there are still active transfers, wait for activity on any handle.
127                // This prevents the loop from consuming 100% CPU.
128                // A timeout of 1 second is used; adjust as needed for real applications.
129                $select_result = curl_multi_select($multi_handle, 1.0);
130                if ($select_result === -1) {
131                    echo "Warning: curl_multi_select returned an error.\n";
132                }
133            }
134
135        } while ($running_handles > 0 && $exec_status === CURLM_OK);
136
137        if ($exec_status !== CURLM_OK) {
138            echo "Error: curl_multi_exec failed: " . curl_multi_strerror($exec_status) . "\n";
139        }
140
141        // After the loop, check for completed transfers and their results.
142        // curl_multi_info_read returns an array for each completed transfer.
143        while ($info = curl_multi_info_read($multi_handle)) {
144            if ($info['msg'] === CURLMSG_DONE) {
145                $handle_done = $info['handle'];
146                $result_code = $info['result']; // The CURLcode from the individual easy handle
147
148                echo "\n--- Transfer Completed ---\n";
149                echo "URL: " . curl_getinfo($handle_done, CURLINFO_EFFECTIVE_URL) . "\n";
150                echo "Result code: " . $result_code . " (" . curl_strerror($result_code) . ")\n";
151
152                if ($result_code !== CURLE_OK) {
153                    echo "Error details: " . curl_error($handle_done) . "\n";
154                    // For the SFTP handle, since the callback returned CURLKHMATCH_MISSING,
155                    // you would likely see an error like CURLE_PEER_FAILED_VERIFICATION
156                    // or CURLE_SSH (depending on PHP/cURL version and error reporting).
157                } else {
158                    $content = curl_multi_getcontent($handle_done);
159                    echo "Content (partial): " . substr($content, 0, 100) . "...\n";
160                }
161
162                // Remove and close the individual handle after processing its result.
163                curl_multi_remove_handle($multi_handle, $handle_done);
164                curl_close($handle_done);
165            }
166        }
167
168        // Close the multi cURL handle, freeing all associated resources.
169        curl_multi_close($multi_handle);
170    }
171}
172
173// Execute the demonstration.
174CurlMultiSshHostKeyDemo::runDemonstration();
175

PHPのCURLKHMATCH_MISSING定数は、cURLのマルチハンドラを用いたSSH/SFTP接続時に、サーバーのホスト鍵を検証する際に利用されます。この定数自体は引数や戻り値を持たず、特定の整数値を表します。その主な役割は、CURLMOPT_SERVER_DOMAIN_CALLBACKオプションで設定されるコールバック関数の戻り値として使用され、「接続しようとしているサーバーのホスト鍵が、既知のホストリスト(known_hosts)に見つからなかった」という状態を示すことです。

サンプルコードは、複数のcURL転送を同時に管理するマルチcURL環境で、このCURLKHMATCH_MISSING定数がどのように使われるかを実演しています。まず、curl_multi_init()でマルチハンドラを初期化し、SSHホスト鍵の検証を担当するカスタム関数sshHostKeyVerificationCallbackをCURLMOPT_SERVER_DOMAIN_CALLBACKに設定します。このコールバック関数は、特定のSFTPホスト(sftp.example.com)への接続試行時に、ホスト鍵が見つからない状況をシミュレートし、戻り値としてCURLKHMATCH_MISSINGを返します。

その後、curl_multi_exec()関数をループ内で呼び出して転送の進行を管理します。curl_multi_exec()がCURLM_CALL_MULTI_PERFORMという戻り値を返す場合、cURL内部でさらに処理がすぐに必要なため、ループは待機せずにcurl_multi_exec()を再度実行します。このデモンストレーションでは、CURLKHMATCH_MISSINGが返された結果、SFTP転送は鍵検証失敗によるエラーとして処理され、SSHホスト鍵検証の重要性を示しています。

このサンプルコードは、PHPのcURL拡張における非同期処理とSSHホストキー検証の基本を示しています。CURLKHMATCH_MISSINGは、SSH/SFTP接続時にホストキーが見つからない場合にコールバック関数が返す定数で、実運用ではセキュリティのためにknown_hostsファイルなどを適切に参照し、判断する必要があります。サンプルでは意図的にMISSINGを返し、その結果接続が失敗するシナリオを表現しています。また、curl_multi_execがCURLM_CALL_MULTI_PERFORMを返した場合、内部処理が残っているため、すぐに再度curl_multi_execを呼び出す必要がある点に注意してください。このループ構造はマルチcURLを正しく動作させるために不可欠です。非同期処理のエラーハンドリングとリソース解放も忘れずに行ってください。

PHP: curl_multi_selectで並列HTTPリクエスト

1<?php
2
3/**
4 * Executes multiple HTTP requests concurrently using curl_multi_select.
5 * This function demonstrates how to perform asynchronous network operations
6 * efficiently and also includes information about the CURLKHMATCH_MISSING constant.
7 */
8function performConcurrentHttpRequests(): void
9{
10    // URLs to be fetched concurrently
11    $urls = [
12        'https://example.com/',
13        'https://php.net/',
14        'https://www.google.com/',
15    ];
16
17    // Initialize a cURL multi handle
18    $multiHandle = curl_multi_init();
19    if ($multiHandle === false) {
20        echo "Error: Failed to initialize cURL multi handle.\n";
21        return;
22    }
23
24    $curlHandles = []; // Array to store individual cURL handles
25    foreach ($urls as $id => $url) {
26        $ch = curl_init($url);
27        if ($ch === false) {
28            echo "Error: Failed to initialize cURL handle for $url.\n";
29            continue;
30        }
31
32        // Set cURL options for each handle
33        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return content as a string
34        curl_setopt($ch, CURLOPT_HEADER, false);      // Do not include headers in output
35        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Follow any redirects
36        curl_setopt($ch, CURLOPT_TIMEOUT, 10);          // Set a timeout for the request (10 seconds)
37
38        // Add the individual cURL handle to the multi handle
39        curl_multi_add_handle($multiHandle, $ch);
40        $curlHandles[$id] = $ch;
41    }
42
43    if (empty($curlHandles)) {
44        echo "No cURL handles were successfully created or added.\n";
45        curl_multi_close($multiHandle);
46        return;
47    }
48
49    $active = null; // Will be updated by curl_multi_exec to indicate if any handles are still active
50
51    // Execute all requests concurrently
52    do {
53        // Run the sub-connections
54        $status = curl_multi_exec($multiHandle, $active);
55
56        // Check for cURL multi errors
57        if ($status > CURLM_OK) {
58            echo "cURL multi error: " . curl_multi_strerror($status) . "\n";
59            break;
60        }
61
62        // If there are still active handles, wait for activity on any of them
63        if ($active && curl_multi_select($multiHandle) === -1) {
64            // If curl_multi_select returns -1, there might be an issue,
65            // or no file descriptors are ready. Wait a short period to prevent busy-looping.
66            usleep(100);
67        }
68
69    } while ($active > 0); // Continue as long as there are active transfers
70
71    echo "--- cURL Request Results ---\n";
72
73    // Retrieve results from each completed handle
74    foreach ($curlHandles as $id => $ch) {
75        $content = curl_multi_getcontent($ch); // Get the content returned by the request
76        $info = curl_getinfo($ch);             // Get information about the transfer
77
78        echo "URL: " . ($info['url'] ?? 'N/A') . "\n";
79        echo "HTTP Status: " . ($info['http_code'] ?? 'N/A') . "\n";
80        // For brevity, we don't print the full content.
81        // echo "Content snippet: " . (is_string($content) ? substr($content, 0, 100) : 'N/A') . "...\n";
82        echo "--------------------------\n";
83
84        // Remove the handle from the multi handle and close it
85        curl_multi_remove_handle($multiHandle, $ch);
86        curl_close($ch);
87    }
88
89    // Close the cURL multi handle
90    curl_multi_close($multiHandle);
91
92    echo "\n--- Additional cURL Constant Information ---\n";
93    // CURLKHMATCH_MISSING is a cURL constant used in SSH/SFTP host key verification.
94    // It indicates that the remote host's public key was not found in the known_hosts file.
95    // This constant's value is 2. It is typically checked when using options like
96    // CURLOPT_SSH_KNOWNHOSTS to determine the status of a host key match.
97    echo "The value of CURLKHMATCH_MISSING is: " . CURLKHMATCH_MISSING . "\n";
98    echo "This constant is part of cURL's SSH support and indicates a specific host key verification status.\n";
99}
100
101// Execute the function to perform the concurrent cURL requests
102performConcurrentHttpRequests();

このサンプルコードは、PHPのcURL拡張機能を使って複数のHTTPリクエストを並行して処理する方法を示しています。まず、curl_multi_init()で「マルチハンドル」と呼ばれる複数のcURLリクエストを管理するオブジェクトを作成します。次に、curl_init()で個々のURLに対するリクエスト(「シングルハンドル」)を作成し、オプションを設定後、curl_multi_add_handle()でそれらをマルチハンドルに追加します。

リクエストの実行はcurl_multi_exec()で行われ、curl_multi_select()はその実行中のリクエストが完了するのを効率的に待機する役割を担います。curl_multi_select()は、引数に与えられたマルチハンドルのいずれかのリクエストにデータ転送などの活動があった場合、準備ができたファイルディスクリプタの数を整数で返します。待機中にエラーが発生した場合は-1を返します。これにより、CPUを無駄に消費せず、イベント駆動型で処理を進めることができます。

コードの最後で触れられているCURLKHMATCH_MISSINGは、cURLのSSH/SFTP通信で利用される定数です。これは、接続先のリモートホストの公開鍵が、既知のホストを記録するファイル(known_hosts)に見つからなかった状態を示す整数値2です。この定数自体に引数や戻り値はありませんが、ホストキーの照合結果を判断する際などに利用されます。

このサンプルコードは、複数のHTTPリクエストを並行して効率的に実行する方法を示しています。curl_multi_selectが-1を返す場合、無限ループを防ぐため短い待機(usleepなど)を入れることが重要です。また、初期化したcURLハンドルやマルチハンドルは、処理の終了時に必ずcurl_closeやcurl_multi_closeで解放し、リソースリークを防ぐようにしてください。CURLKHMATCH_MISSING定数は、SSH/SFTP接続時のホストキー検証に関連するもので、このコードの主要なHTTP並行処理とは直接的な関係がない点も理解しておきましょう。各関数のエラー戻り値も適切に確認し、堅牢な処理を心がけてください。

関連コンテンツ

関連IT用語

関連プログラミング言語