2010-09-11 43 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到它。我不知道如果有周围没有任何漂亮的包装,但你总是可以创建自己的:)