gpt4 book ai didi

php - curl_exec() 总是返回 false

转载 作者:IT老高 更新时间:2023-10-28 11:53:09 35 4
gpt4 key购买 nike

我写了这段简单的代码:

$ch = curl_init();

//Set options
curl_setopt($ch, CURLOPT_URL, "http://www.php.net");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$website_content = curl_exec ($ch);

在我的例子中,$website_contentfalse。谁能建议/建议可能出了什么问题?

最佳答案

错误检查和处理是程序员的 friend 。检查初始化和执行 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() manual状态:

Returns a cURL handle on success, FALSE on errors.

我观察到当您使用它的 $url 参数并且域无法解析时返回 FALSE 的函数。如果参数未使用,函数可能永远不会返回FALSE。无论如何都要检查它,因为手册没有明确说明“错误”到底是什么。

关于php - curl_exec() 总是返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8227909/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com