PHP Curl 获取网站状态码和内容 (200, 301, 404, 500) 示例代码
// Function to check the status code of a URL
function checkStatusCode($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $statusCode;
}
// Function to retrieve content from a URL
function getContent($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RANGE, '0-500');
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
// URL to test
$url = 'http://www.jb51.net/';
// Check status code of the URL
$statusCode = checkStatusCode($url);
echo 'Status Code: ' . $statusCode . PHP_EOL;
// Retrieve content from the URL
$content = getContent($url);
echo $content;
?>
该代码示例展示了如何使用 PHP Curl 库来获取网站的状态码和内容。代码中定义了两个函数:checkStatusCode 用于检查 URL 状态码,getContent 用于获取 URL 内容。示例代码中使用 http://www.jb51.net/ 作为测试 URL,您可以根据需要修改它。
该示例代码涵盖了常见的几种状态码,包括 200 (成功), 301 (永久重定向), 404 (页面未找到), 500 (服务器错误)。您还可以根据自己的需要添加其他状态码的处理逻辑。
代码说明:
curl_init()函数初始化一个 cURL 会话。curl_setopt()函数设置 cURL 选项。CURLOPT_URL设置要访问的 URL。CURLOPT_RETURNTRANSFER设置为 true 表示返回结果字符串而不是直接输出。curl_exec()函数执行 cURL 请求。curl_getinfo()函数获取 cURL 请求的信息,包括状态码。curl_close()函数关闭 cURL 会话。
通过该示例代码,您可以轻松地使用 PHP Curl 库获取网站的状态码和内容,并根据需要进行相应的处理。
原文地址: http://www.cveoy.top/t/topic/bxx5 著作权归作者所有。请勿转载和采集!