The Pursuit of Happyness

<?php

function post_request($url, $data) {
// Convert the data array into URL Parameters like a=b&foo=bar etc.
$data = http_build_query($data);

// parse the given URL
$url = parse_url($url);

if ($url['scheme'] != 'http') {
return "Error:Only HTTP request are supported!";
}

// extract host and path:
$host = $url['host'];
$path = $url['path'];
$res = '';

// open a socket connection on port 80 - timeout: 300 sec
if ($fp = fsockopen($host, 80, $errno, $errstr, 300)) {
$reqBody = $data;
$reqHeader = "POST $path HTTP/1.1\r\n" . "Host: $host\r\n";
$reqHeader .= "Content-type: application/x-www-form-urlencoded\r\n"
. "Content-length: " . strlen($reqBody) . "\r\n"
. "Connection: close\r\n\r\n";

/* send request */
fwrite($fp, $reqHeader);
fwrite($fp, $reqBody);

while(!feof($fp)) {
$res .= fgets($fp, 1024);
}

fclose($fp);
} else {
return "Error:Cannot Connect!";
}

// split the result header from the content
$result = explode("\r\n\r\n", $res, 2);

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

return $content;
}

// usage
$url =  "http://www.example.com/receiver.php";
$data = array("key" => "value");
$res = post_request($url, $value);

?> 
 

Comment +0