PHP How-to: HTTP POST without using cURL (Example)

Written by Leif Stenfeldt. Posted in PHP, Programmering

You wanna call a remote web service using HTTP POST in your PHP, but you do not wanna use cURL as cURL might not be supported in your web host. The following codes explain how you can do it without using cURL.

We prepare two very simple pages, p1.php and p2.php to test out and show it works. p1.php is the page that opens a HTTP POST connection to p2.php and p2.php will print out all the submitted POST variables (title, name and passport) in a table. The code example is as follows:

p1.php


'Mr','name'=>'Jason J','passport'=>'J7726458B');
$data = http_build_query($data_array);
 
/** Now call the p2.php in HTTP POST by using function do_post_request */
echo do_post_request('http://localhost/p2.php', $data);
 
 
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;
}
?>

p2.php

<?php
/**
The page p2.php is to display all the submitted $_POST parameters
*/
?>
<table cellpadding="1" cellspacing="1" style="width:500px;font-family:verdana,arial;width:500px;">
	<tr>
		<td colspan="2"><b>Your submitted info</b></td>
	</tr>
	<tr>
		<td width="30%"><b>Title</b></td>
		<td width="70%"><?php if ( isset($_POST['title'])) echo $_POST['title'];?></td>
	</tr>
	<tr>
		<td width="30%"><b>Name</b></td>
		<td width="70%"><?php if ( isset($_POST['name'])) echo $_POST['name'];?></td>
	</tr>
	<tr>
		<td width="30%"><b>Passport</b></td>
		<td width="70%"><?php if ( isset($_POST['passport'])) echo $_POST['passport'];?></td>
	</tr>
</table>
896 views

Leave a comment