2010-09-11 45 views
1

我需要做一個張貼到URL這需要認證第一,在C#中,我能做到這一點PHP:張貼到URL需要認證

HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url); 
    myRequest.Method = "POST"; 
    myRequest.ContentType = "application/x-www-form-urlencoded"; 
    myRequest.Credentials = new NetworkCredential(username, password); 
    myRequest.PreAuthenticate = true; 

    Stream newStream = myRequest.GetRequestStream(); 
    newStream.Close(); 

    // Get response 
    try 
    { 
     HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse(); 
     return response.StatusDescription; 

     // some other code 
    } 
    catch (Exception ex) 
    { 
     return ex.Message; 
    } 

如何做到這一點在PHP?

回答

1

一個例子使用捲曲:

<?php 
$url = "http://example.com/"; 
$username = 'user'; 
$password = 'pass'; 
// create a new cURL resource 
$myRequest = curl_init($url); 

// do a POST request, using application/x-www-form-urlencoded type 
curl_setopt($myRequest, CURLOPT_POST, TRUE); 
// credentials 
curl_setopt($myRequest, CURLOPT_USERPWD, "$username:$password"); 
// returns the response instead of displaying it 
curl_setopt($myRequest, CURLOPT_RETURNTRANSFER, 1); 

// do request, the response text is available in $response 
$response = curl_exec($myRequest); 
// status code, for example, 200 
$statusCode = curl_getinfo($myRequest, CURLINFO_HTTP_CODE); 

// close cURL resource, and free up system resources 
curl_close($myRequest); 
?> 
1

只看右邊的「關聯」的問題讓我來Issue FORM POST Request From PHP using HTTP Basic Authentication其接受的答案似乎是你想要的。

的另一種方法,用更多的方法,將與stream_create_context()按照手冊中看到:http://www.php.net/manual/en/function.stream-context-create.php#91775

在你寫出來的實際POST發送到服務器無論哪種方式,然後打開到該服務器的連接,並寫POST到它。我不知道如果有周圍沒有任何漂亮的包裝,但你總是可以創建自己的:)