在 PHP 中使用 try/catch 和 cURL

问题描述 投票:0回答:2

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

这里的这个例子,只通过文件测试的处理。 “test.htm”的内容要么是“true”,要么是“false”。

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

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

如果有人能阐明我可能做错了什么,我将不胜感激。测试此文件的方法可能也更短,我可能会走很长的路才能做到这一点,非常感谢您的帮助。

T

php curl
2个回答
41
投票

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

0
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.