在 PHP 中使用 try/catch with cURL


Using a try/catch with cURL in PHP

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

此示例仅介绍文件测试的处理。"测试.htm"的内容要么是"真",要么是"假"。

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

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

如果有人能阐明我可能做错了什么,我将不胜感激。测试此文件的方法可能要短得多,我可能会走很长的路来做到这一点,所以非常感谢任何帮助。

T

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

我们可以从以下代码中得到错误

$result = curl_exec($ch);
if(curl_errno($ch))
    echo 'Curl error: '.curl_error($ch);
curl_close ($ch);  

参考资料 - https://stackoverflow.com/a/18015365/2442749