php:发布到网址需要身份验证

时间:2010-09-11 08:09:42

标签: php post

我需要在网址上发帖需要先进行身份验证,在C#中,我可以这样做

    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中执行此操作?

2 个答案:

答案 0 :(得分: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。我不确定它周围是否有任何不错的包装,但你总是可以创建自己的包装:)

答案 1 :(得分:1)

使用cURL的示例:

<?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);
?>