Sending POST requests with PHP
August 28, 07 by Andrew VayanisI recently found myself writing a REST web service, which, in my opinion, is the easiest way to create a web service, for a project at work. Using XML.com’s How to Create a REST protocol as my Guide, I went to work. However, when I tried to create a service to update some data, I wasn’t sure how to send my data in a POST request using PHP. After some stumbling around, I found what I was looking for on Wez Furlong’s blog which led me to PHP’s documentation on HTTP and HTTPS wrappers.
The following is a code snippet from the HTTP and HTTPS documentation that shows how to easily send data using HTTP POST:
$postdata = http_build_query( array( 'var1' => 'some content', 'var2' => 'doh' ) ); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://example.com/submit.php', false, $context);
Quick Explanation
- http_build_query: Generates an URL-encoded string from an associative array. Example: array(’key1′ => ‘value1′, ‘key2′ => ‘value2′) becomes “key1=value1&key2=value2″
This properly encodes the data for the post transaction.
- stream_context_create: Creates and returns a resource to a stream context from an associative array of arrays in the format $arr[’wrapper’][’option’] = $value
This creates a linear output stream to be sent during the request transmission.
- file_get_contents: Acts exactly like file(); except that it reads an entire file into a string.
This requests a file resource and puts the result into a string.