代码之家  ›  专栏  ›  技术社区  ›  David Christiansen

使用HTTP基本身份验证从PHP发出表单发布请求

  •  10
  • David Christiansen  · 技术社区  · 15 年前

    我希望这是一个相对直截了当的事情,我的谷歌技术在这个场合让我失望了。我有一个基本的身份验证保护资源,我想让PHP针对它执行一个PostHTTP请求。

    我试过注射 认证:基本(加密U/P数据) 在那些看起来不起作用的标题中-所以我想知道 灰颅骨 我是说stackoverflow提供任何指导。

    $req .= "&cmd=_initiate_query";
    $header = "POST /someendpoint HTTP/1.1\r\n".
            "Host:example.com\n".
            "Content-Type: application/x-www-form-urlencoded\r\n".
            "User-Agent: PHP-Code\r\n".
            "Content-Length: " . strlen($req) . "\r\n".
            "Connection: close\r\n\r\n";
    $fp = fsockopen ('ssl://example.com', 443, $errno, $errstr, 30);
    if (!$fp) {
        // HTTP ERROR
    } else {
        fputs ($fp, $header . $req);
        while (!feof($fp)) {
            $result .= fgets ($fp, 128);
        }
        fclose ($fp);
    }
    
    2 回复  |  直到 15 年前
        1
  •  4
  •   Richy B.    15 年前

    使用:

    $header = "POST /someendpoint HTTP/1.1\r\n".
            "Host:example.com\n".
            "Content-Type: application/x-www-form-urlencoded\r\n".
            "User-Agent: PHP-Code\r\n".
            "Content-Length: " . strlen($req) . "\r\n".
            "Authorization: Basic ".base64_encode($username.':'.$password)."\r\n".
            "Connection: close\r\n\r\n";
    

    应该工作了-你确定这是一个基本的认证系统吗?可能值得使用类似 CharlesProxy 为了确保它是一个身份验证(然后您还可以复制授权字符串!).

        2
  •  -3
  •   Phil Rae    15 年前

    这是我用来执行POST请求的函数。希望它能做你想做的:

    function http_post($server, $port, $url, $vars) {
    
    // get urlencoded vesion of $vars array 
    $urlencoded = ""; 
    
    foreach ($vars as $Index => $Value) 
        $urlencoded .= urlencode($Index ) . "=" . urlencode($Value) . "&"; 
    
    $urlencoded = substr($urlencoded,0,-1);  
    
    $headers = "POST $url HTTP/1.0\r\n" 
    . "Content-Type: application/x-www-form-urlencoded\r\n" 
    . "Content-Length: ". strlen($urlencoded) . "\r\n\r\n"; 
    
    $fp = fsockopen($server, $port, $errno, $errstr, 10); 
    if (!$fp) return "ERROR: fsockopen failed.\r\nError no: $errno - $errstr"; 
    
    fputs($fp, $headers); 
    fputs($fp, $urlencoded); 
    
    $ret = ""; 
    while (!feof($fp)) $ret .= fgets($fp, 1024); 
    
    fclose($fp); 
    return $ret; }
    

    下面是我使用它将post变量转发到API的一个例子

    $response = http_post("www.nochex.com", 80, "/nochex.dll/apc/apc", $_POST);