The Algorithm

Sending post data from within php. Explaining Furlong Script.

by Apoorv Parijat on Oct.22, 2009, under scripts

There are few ways using which you can send post data without using forms. One way to do is by using curl , the command line tool for sending files using URL syntax. The other I found is this simple script by Wez Furlong , one of the core PHP developers.
function do_post_request($url, $data, $optional_headers = null)
{
$params = array(‘http’ => array(
‘method’ => ‘POST’,
‘content’ => $data ));
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = @fopen($url, ‘rb’, false, $ctx);
if (!$fp) {
throw new Exception(“Problem with $url, $php_errormsg”);
}
$response = @stream_get_contents($fp);
if ($response === false) {
throw new Exception(“Problem reading data from $url, $php_errormsg”);
}
return $response;
}
?>


$data:

This argument contains the data as in “variable1=value1&variable2=value2″ form. You can generate such data by first making a associative array of ‘variable’ => ‘value’ and then calling ‘http_build_query’ function as described :
$data = array (‘variable’ => ‘value’,'variable1′=>’value1′);

$data = http_build_query($data);

$url:

$url is the url path of file which will receive post data.
The method that is doing the real job is stream_context_create($params). It takes an associative array as parameter which contains method type (get/post) and content (pseudo form data) and creates a post query. Next using the fopen method we open the url sending the context generated by the stream_context_create as parameter and get its content using stream_get_content.

Usage Tips:
Save the script in postScript.php file in your package and include the file wherever you want to use it. Structure as follows:

<?php

include(‘postScript.php’);

$data = array (‘variable1′=>’value1′,’variable2′=>’value2′);

$data = http_build_query($data);

$url = ‘http://127.0.0.1/post.php’;

echo do_post_request($url,$data);

?>

PS: Don’t forget ‘echo’ before do_post_request.

:, ,

Leave a Reply

Visit our friends!

A few highly recommended friends...

Archives

All entries, chronologically...