簡體   English   中英

使用HTTP基本身份驗證從PHP發出FORM POST請求

[英]Issue FORM POST Request From PHP using HTTP Basic Authentication

我希望這是一個相對直接的事情,而且我的谷歌技能在這個場合讓我失望了。 我有一個BASIC身份驗證保護資源,我想讓PHP執行POST HTTP請求。

我已經嘗試將身份驗證:基本(加密的u / p數據)注入到看起來不起作用的標題中 - 所以我想知道, Greyskull的功能是否可以表示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);
}

使用:

$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這樣的東西來查看原始標題數據可能是值得的,以確保它是一個身份驗證(然后你也可以復制授權字符串!)。

這是我用來執行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); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM