2016-07-15 54 views
2

您好,我有命令行代码:卷曲HTTP认证工作,完善在命令行但不PHP

curl 'http://192.168.0.1:80/' -H 'Authorization: Basic my_auth' 

在PHP中:

$process = curl_init($ip); 
//just for "shore" 
      curl_setopt($data, CURLOPT_HTTPHEADER, 
      array(
       "Authorization: Basic " . base64_encode($username . ":" . $password) 
      )); 
      curl_setopt($process, CURLOPT_HTTPAUTH, CURLAUTH_ANY); 
      curl_setopt($process, CURLOPT_USERPWD, $login . ":" . $password); 
      curl_setopt($process, CURLOPT_CONNECTTIMEOUT, 10); 
      curl_setopt($process, CURLOPT_TIMEOUT, 10); 

      curl_setopt($process, CURLOPT_RETURNTRANSFER, 1); 
      curl_setopt($process, CURLOPT_VERBOSE, 1); 
      curl_setopt($process, CURLOPT_HEADER, 1); 

      $return = curl_exec($process); 

的结果我看到:401 ... 在apache2的日志:

  • HTTP 1.0,假设靠近身体< HTTP后/1.0 401未经授权<日期:星期五,2016年7月15日9点27分20秒GMT <服务器:宝儿/ 0.94.13 < 连接:关闭< WWW身份验证:基本境界= “服务” < 内容类型:text/HTML; charset = ISO-8859-1 < Set-Cookie: SESSIONID = 068054d0; <
  • 关闭连接53
  • 发行请求给此URL: ''
  • 主机名(在192.168.0.1 DNS缓存
  • 试图192.168.0.1发现...
  • 连接到192.168.0.1基本my_code主机::使用基本与用户 '管理员'

    GET/HTTP/1.0授权)端口80(#54)

  • 服务器授权192.1 68.0.1接受:/

  • HTTP 1.0,假设身体< HTTP/1.0 401未经授权<日期后收盘:周五,2016年7月15日9点27分二十零秒GMT <服务器:宝儿/ 0.94.13 < 连接:关闭

  • 身份验证问题。忽略这一点。 < WWW-Authenticate:Basic realm =“service”< Content-Type:text/html; charset = ISO-8859-1 < Set-Cookie:SESSIONID = 068054d0; <
  • 关闭连接54
  • +0

    天哪,巨大的错误))) “上岸”=> “确定”)SRY我的英文不好 – Melixion

    +0

    解决: curl_setopt($过程,CURLOPT_COOKIEFILE, 'cookiefile.txt'); – Melixion

    回答

    0

    那不是如何使用curl发送基本认证。对于Basic,预期的标题是Authorization: Basic <base64 encoded string>,其中编码的字符串是“:”。使用curl(假设没有其他配置)使用“-u”开关来完成此OOTB的方法。例如:

    curl -u "user:pass" http://<endpoint>/ 
    

    如果您发送标题“手动”,您必须首先对base64进行编码。

    现在,您的PHP代码正确,您的curl调用不正确。这意味着服务如何解释Authorization存在问题。