在PHP中使用try / catch和cURL

时间:2012-07-02 16:10:27

标签: php curl

我以为我已经解决了这个问题,但我显然没有解决这个问题,并且希望有人能够对我做错的事情有所了解。我试图获取一段PHP代码来检查服务器上的文件并根据响应执行操作。该文件是一个简单的文本文件,上面写有“true”或“false”字样。如果文件存在或返回为“true”,则脚本将转到一个URL。如果它不存在(即服务器不可用)或返回为“假”,则脚本转到第二个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”。

这似乎是一种令人费解的方式,但该文件位于第三方服务器上(我无法控制)并需要进行检查,因为第三方供应商可能决定强制将故障转移到第二方url,同时对第一个url进行维护工作。因此,为什么我不能只检查文件是否存在。

我已经在本地设置上进行了测试,并且所有操作都符合预期。当文件不存在时出现问题。 $ fb = curl_exec($ curl);不会失败,它只返回一个空值。我曾经想过,因为这是在IIS PHP服务器上,问题可能是服务器上的PHP相关,但我现在在本地(在Unix系统上)看到这个问题。

如果有人能说清楚我可能做错了什么,我真的很感激。测试这个文件的方式可能还要短得多,我可能要做很多事情,所以非常感谢任何帮助。

Ť

1 个答案:

答案 0 :(得分:29)

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>';