【问题标题】:How do I get the HTTP-Code for a .htpasswd-protected url using cURL?如何使用 cURL 获取受 .htpasswd 保护的 url 的 HTTP 代码?
【发布时间】:2016-04-05 15:28:34
【问题描述】:

我正在尝试使用 curl 访问受保护的站点 (.htpasswd) 以检查其是否可访问并返回类似 200 或 302 的代码。

我尝试使用错误的密码和用户名访问它。我不想登录,我只想检查它是否在线/可访问。

curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "aaa:bbb");

如何通过 curl 获取 401 代码?

我像这样检查 http 代码,但在 htpasswd 中,它是空的

$code = curl_getinfo($ch, CURLINFO_HTTP_CODE),true

提前谢谢你!

【问题讨论】:

  • 你是用PHP还是这个命令行?
  • 我正在使用 PHP-curl 扩展
  • 你需要用cURL吗,get_headers()不包含你需要的信息吗?
  • 您可以在curl_exec($ch) 之后使用$info = curl_getinfo($ch) 并检查$info["http_code"]
  • @jeroen 这行不通,因为我无法使用 get_headers() 跟踪重定向

标签: php curl


【解决方案1】:

如果你在 curl_getinfo 函数中使用 CURLINFO_HTTP_CODE 属性,你可以从 curl 中获取状态码,如下所示:

<?php
$URL = 'http://yourdomain.com/protected_dir';
$Auth_Username = "username_here";
$Auth_Password = "password_here";

//make curl request
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_USERPWD, "{$Auth_Username}:{$Auth_Password}");  

$Output = curl_exec($ch);

//get http code
$HTTP_Code = curl_getinfo($ch, CURLINFO_HTTP_CODE);    //this is important to get the http code.
curl_close($ch);

echo 'HTTP code: ' . $HTTP_Code;
?>

【讨论】:

  • 谢谢,CURLOPT_HEADER 不见了。 http-code 现在可以正确返回了。
猜你喜欢
  • 2012-10-02
  • 1970-01-01
  • 2014-07-07
  • 1970-01-01
  • 2020-02-19
  • 2014-08-24
  • 2012-08-01
相关资源
最近更新 更多