PHP How-to: HTTP POST without using cURL

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php
/** Using http_build_query() to build parameters */
$data_array =array('title'=>'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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?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>

You should see the page as follow why you open your web browser to http://localhost/p1.php, which is the result printed by p2.php.

Note: Function do_post_request obtained from netevil.

Enter your email address to subscribe our newsletter or feed for FREE:

Delivered by FeedBurner


Bookmark with:

[Delicious]    [Digg]    [Reddit]    [Facebook]    [StumbleUpon]

0 Responses to “PHP How-to: HTTP POST without using cURL”


  1. No Comments

Leave a Reply

You must login to post a comment.