I 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:

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

  1. http_build_query: Generates an URL-encoded string from an associative array.

    1
    array('key1' => 'value1', 'key2' => 'value2')

    becomes

    1
    "key1=value1&key2=value2"

    This properly encodes the data for the post transaction.

  2. stream_context_create: Creates and returns a resource to a stream context from an associative array of arrays in the format

    1
    $arr['wrapper']['option'] = $value

    This creates a linear output stream to be sent during the request transmission.

  3. 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.