错误检查和处理是程序员的朋友。检查初始化和执行 cURL 函数的返回值。curl_error()
和 curl_errno()
将包含更多信息,以防万一发生故障:
try {
$ch = curl_init();
// Check if initialization had gone wrong*
if ($ch === false) {
throw new Exception('failed to initialize');
}
// Better to explicitly set URL
curl_setopt($ch, CURLOPT_URL, 'http://example.com/');
// That needs to be set; content will spill to STDOUT otherwise
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Set more options
curl_setopt(/* ... */);
$content = curl_exec($ch);
// Check the return value of curl_exec(), too
if ($content === false) {
throw new Exception(curl_error($ch), curl_errno($ch));
}
// Check HTTP return code, too; might be something else than 200
$httpReturnCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
/* Process $content here */
} catch(Exception $e) {
trigger_error(sprintf(
'Curl failed with error #%d: %s',
$e->getCode(), $e->getMessage()),
E_USER_ERROR);
} finally {
// Close curl handle unless it failed to initialize
if (is_resource($ch)) {
curl_close($ch);
}
}
*该手册指出:curl_init()
成功时返回 cURL 句柄,错误时返回 FALSE。
我观察到当您使用其参数时返回的函数,并且无法解析域。如果该参数未使用,则该函数可能永远不会返回 。但是,无论如何都要检查它,因为手册没有明确说明“错误”实际上是什么。FALSE
$url
FALSE