tags:

views:

31

answers:

2

I need to do a post to a url which need to be authenticated first, in C#, i can do this

    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;
    }

how to do this in php?

A: 

Just looking at the "related" questions on the right got me to http://stackoverflow.com/questions/1198756/issue-form-post-request-from-php-using-http-basic-authentication whose accepted answer seems to be what you want.

Another way, using more methods, would be with stream_create_context() as seen in the manual: http://www.php.net/manual/en/function.stream-context-create.php#91775

In either way you are writing out the actual POST to send to the server, then opening a connection to that server and writing the POST to it. I'm not sure if there's any nice wrapper around it, but you can always create your own :)

Fanis
A: 

An example using 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);
?>
Lekensteyn