14

私はこれを解決したと思っていましたが、明らかにそうではなく、誰かが私が間違っていることを明らかにできることを望んでいました. サーバー上のファイルをチェックし、応答に基づいてアクションを実行する PHP コードを取得しようとしています。このファイルは、「true」または「false」という単語が書かれた単純なテキスト ファイルです。ファイルが存在するか、戻り値が「true」の場合、スクリプトは 1 つの URL に移動します。存在しない場合 (つまり、サーバーが利用できない場合)、または戻り値が "false" の場合、スクリプトは 2 番目の URL に移動します。以下は、私が今まで使ってきたコードのスニペットです。

$options[CURLOPT_URL] = 'https://[domain]/test.htm';

$options[CURLOPT_PORT] = 443;
$options[CURLOPT_FRESH_CONNECT] = true;
$options[CURLOPT_FOLLOWLOCATION] = false;
$options[CURLOPT_FAILONERROR] = true;
$options[CURLOPT_RETURNTRANSFER] = true;
$options[CURLOPT_TIMEOUT] = 10;

// Preset $response var to false and output
$fb = "";
$response = "false";
echo '<p class="response1">'.$response.'</p>';

try {
    $curl = curl_init();
    echo curl_setopt_array($curl, $options);
    // If curl request returns a value, I set it to the var here. 
    // If the file isn't found (server offline), the try/catch fails and var should stay as false.
    $fb = curl_exec($curl);
    curl_close($curl);
}
catch(Exception $e){
    throw new Exception("Invalid URL",0,$e);
}

if($fb == "true" || $fb == "false") {
    echo '<p class="response2">'.$fb.'</p>';
    $response = $fb;
}

// If cURL was successful, $response should now be true, otherwise it will have stayed false.
echo '<p class="response3">'.$response.'</p>';

この例では、ファイル テストの処理のみを行います。「test.htm」の内容は「true」または「false」です。

これは複雑な方法のように思えるかもしれませんが、ファイルはサードパーティのサーバー上にあり (私はこれを制御できません)、サードパーティのベンダーが 2 番目の URL へのフェイルオーバーを強制することを決定する可能性があるため、チェックする必要があります。最初の URL のメンテナンス作業を行っています。したがって、ファイルの存在を確認できないのはなぜですか。

ローカル セットアップでテストしたところ、すべて期待どおりに動作しました。ファイルが存在しない場合に問題が発生します。$fb = curl_exec($curl); 失敗しません。空の値を返すだけです。これは IIS PHP サーバー上にあるため、問題はサーバー上の PHP に関連している可能性があると考えていましたが、現在、この問題はローカル (Unix システム上) で発生しています。

誰かが私が間違っているかもしれないことに光を当てることができれば、本当に感謝しています. このファイルをテストするためのはるかに短い方法もあるかもしれません.

T

4

1 に答える 1

40

cURL は例外をスローしません。これは、バインド先の C ライブラリのシン ラッパーです。

より正しいパターンを使用するように例を修正しました。

$options[CURLOPT_URL] = 'https://[domain]/test.htm';

$options[CURLOPT_PORT] = 443;
$options[CURLOPT_FRESH_CONNECT] = true;
$options[CURLOPT_FOLLOWLOCATION] = false;
$options[CURLOPT_FAILONERROR] = true;
$options[CURLOPT_RETURNTRANSFER] = true; // curl_exec will not return true if you use this, it will instead return the request body
$options[CURLOPT_TIMEOUT] = 10;

// Preset $response var to false and output
$fb = "";
$response = false;// don't quote booleans
echo '<p class="response1">'.$response.'</p>';

$curl = curl_init();
curl_setopt_array($curl, $options);
// If curl request returns a value, I set it to the var here. 
// If the file isn't found (server offline), the try/catch fails and var should stay as false.
$fb = curl_exec($curl);
curl_close($curl);

if($fb !== false) {
    echo '<p class="response2">'.$fb.'</p>';
    $response = $fb;
}

// If cURL was successful, $response should now be true, otherwise it will have stayed false.
echo '<p class="response3">'.$response.'</p>';
于 2012-07-02T16:21:27.103 に答える