Thursday, 7 March 2013

POST Data without CURL in PHP

file_get_contents() and stream_context_create() can be used for making POST requests instead of CURL. Following code snippet explains how the data can be posted and retrieved.

$post = http_build_query(array(
    "username" => "postuser",
    "password" => "postpassword",
    "example" => "any data",
));

$context = stream_context_create(array("http"=>array(
     "method" => "POST",
     "header" => "Content-Type: application/x-www-form-urlencoded\r\n" .
                 "Content-Length: ". strlen($post) . "\r\n",  
     "content" => $post,
))); 

$page = file_get_contents("http://example.com/login.php", false, $context);

The posted data can be retrieved at the other end i.e. login.php as a normal post
variable in the following fashion.
 
echo $_POST['username'];
echo $_POST['password'];
echo $_POST['example']; 

No comments:

Post a Comment