-
- Wednesday, January 21, 2009
- Make a Post Request through PHP Script
Making a GET Request through PHP is very easy, you can treat the URL of the target page as a file, open it using fopen while include the parameters in the URL String:
$result = file_get_contents("www.example.com?param1=value1¶m2=value2");
But some times GET does not work, specially when you need to communicate with other platforms "other servers" which already written and expect a POST request.
Making a Post Request is Easy to, but it is a little tricky, because in POST requests you can not add the paramters to the end of the URL as in GET, instead you need to send them in the HTTP headers, and in order to do that, you need to open a socket using fsocketopen and send all the HTTP headers that the target server expect:
function PostRequest($url, $referer, $_data) {
// convert variables array to string:
$data = array();
while(list($n,$v) = each($_data)){
$data[] = urlencode($n)."=".urlencode($v);
}
$data = implode('&', $data);
// format --> test1=a&test2=b etc.
// parse the given URL
$url = parse_url($url);
if ($url['scheme'] != 'http') {
die('Only HTTP request are supported !');
}
// extract host and path:
$host = $url['host'];
$path = $url['path'];
// open a socket connection on port 80
$fp = fsockopen($host, 80);
// send the request headers:
fputs($fp, "POST $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Referer: $referer\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ". strlen($data) ."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $data);
$result = '';
while(!feof($fp)) {
// receive the results of the request
$result .= fgets($fp, 128);
}
// close the socket connection:
fclose($fp);
// split the result header from the content
$result = explode("\r\n\r\n", $result, 2);
$header = isset($result[0]) ? $result[0] : '';
$content = isset($result[1]) ? $result[1] : '';
// return as array:
return array($header, $content);
}
using the above function is very easy, you just need to put all your parameters in an associative array and pass it to the function:
$data = array(
'test' => "foobar\ntest",
'okay' => 'yes',
'number' => 2
);
list($header, $content) = PostRequest(
"http://www.example.com/post_to.php", // the url to post to
"http://www.example.com/post.php", // the url of the post script "this file"
$data
);
echo $content;
-