php - 我想检查此 cURL 代码中的站点是否存在?

标签 php curl

我使用此代码从其他服务器获取响应/结果,我想知道如何检查该站点是否存在?

$ch = curl_init('http://domain.com/curl.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
if (!$result)
// it will execute some codes if there is no result echoed from curl.php

最佳答案

您真正需要做的就是一个 HEAD 请求,以查看您是否在重定向后收到 200 OK 消息。 你不需要为此做一个完整的 body 请求。事实上,你根本不应该。

function check_alive($url, $timeout = 10) {
  $ch = curl_init($url);

  // Set request options
  curl_setopt_array($ch, array(
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_NOBODY => true,
    CURLOPT_TIMEOUT => $timeout,
    CURLOPT_USERAGENT => "page-check/1.0" 
  ));

  // Execute request
  curl_exec($ch);

  // Check if an error occurred
  if(curl_errno($ch)) {
    curl_close($ch);
    return false;
  }

  // Get HTTP response code
  $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);

  // Page is alive if 200 OK is received
  return $code === 200;
}

关于php - 我想检查此 cURL 代码中的站点是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6541785/

相关文章:

javascript - 为什么javascript + CSS显示设置使单选按钮消失?

PHP 不再投票一次,我如何在我的代码中编写此代码?

PHP/MySQL - 删除不工作

使用curl和json-c从C调用json web服务

php - 如何从 YouTube API 获取 YouTube 视频缩略图?

curl - 仅从 FTP 下载二进制文件的 header

php - 如何在提交表单后自动选择列表菜单中的选中项?

php - 银条 MAMP Pro : get_magic_quotes_gpc

android - 通过curl连接GCM时出现JSON异常

php - 通过 PHP 获取 Amazon EC2 实例 ID