Skip to main content

post request with authentication in php

Note to myself how to make a POST request in php with authentication without using cURL.

Call the function with arguments:

$data = key/value pairs
$domain = www.example.com
$port = 80
$target = /somescript

making the key/value pairs

$postdata['key1']='value1';
$postdata['key2']='value2';
//and so on..

foreach ($postdata as $key =>$value){
$postitems[] = $key.'='.$value;
}

$data = implode('&',$postitems);

reading the result

We are only interested in the content, the headers can be spliced of with explode and setting the limit to 2.

$result = explode("\r\n\r\n", $result,2);



function

You do not necessarily have to provide key/value pairs, you could also submit xml in which case the Content-Type is application/xml.

function  postrequest($data,$domain,$port,$target){
$username = 'user';
$password =  'pass';
$data_length = strlen($data);
$connection = fsockopen($domain,  $port);
fputs($connection, "POST  $target   HTTP/1.1\r\n");
fputs($connection, "Host:  $domain  \r\n");
fputs($connection, "Content-Type: application/x-www-form-urlencoded  \r\n");
fputs($connection, "Content-Length:  $data_length\r\n");
fputs($connection, "Authorization: Basic  ".base64_encode($username.':'.$password)."\r\n");
fputs($connection,  "Connection: close\r\n\r\n");
fputs($connection, $data);


$result = '';
     while(!feof($connection)) {
        //  receive the results of the request
         $result .= fgets($connection, 128);
    }

// close the socket  connection:
fclose($connection);


$result = explode("\r\n\r\n", $result,2);


$content = isset($result[1]) ? $result[1] :  '';



return $content;


}

Comments