我有以下功能:
function file_get_contents_curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, random_user_agent());
curl_setopt($ch, CURLOPT_HTTPHEADER, 'Content-type: text/plain');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
我需要在此函数中包含一些逻辑,如果URL的响应代码是例如404,则返回null
$data
变量。我举了一个我正在寻找的例子:
function file_get_contents_curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, random_user_agent());
curl_setopt($ch, CURLOPT_HTTPHEADER, 'Content-type: text/plain');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
if (empty($data) or (HTTP response code is 404)) {
// some kind of an error happened
die(curl_error($ch));
curl_close($ch);
$data = null;
return $data;
} else {
// everything is ok
return $data;
}
}
答案 0 :(得分:1)
在curl_getinfo($ch)
调用
curl_close()
答案 1 :(得分:1)
function file_get_contents_curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, random_user_agent());
curl_setopt($ch, CURLOPT_HTTPHEADER, 'Content-type: text/plain');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
if (empty($data) OR (curl_getinfo($ch, CURLINFO_HTTP_CODE == 404))) {
// some kind of an error happened
die(curl_error($ch));
curl_close($ch);
$data = null;
return $data;
} else {
// everything is ok
return $data;
}
}