How to send POST/GET requests/data via PHP

How to send POST/GET requests/data via PHP

PHP 4.3.0 saw the introduction of the Streams API, which provides a consistent set of methods for reading and writing data to and from any specific location. Whenever you use file_get_contents() or another filesystem function, you are actually using the Streams API, albeit transparently in the background. A “stream” is simply a resource object which can be read from or written to. Streams might include:

  • A file on a local filesystem
  • An HTTP connection to a website
  • An FTP connection to a server

Streams API covers literally everything – reading, writing, renaming and deleting. As you will probably know, the unlink() or rmdir() functions are used to delete files and folders on a filesystem. What you might not know is these use the Streams API. Why, you ask? These filesystem operations can be performed on files and folders that reside on both local and remote filesystems (e.g. deleting a directory from an FTP server using rmdir()). HTTP and FTP connections are not one and the same, but it would make sense if they can share a common set of functions that naturally perform operations common to one another. That’s the Streams API in a nutshell.

So now we have that out of the way, let’s see how we can include POST/GET data within an HTTP request. As you might expect, we use the file_get_contents() function as usual, but there’s a small difference – we need to create our own stream context. In plain English, the stream context in an HTTP request essentially consists of the header information and some options for things like whether to ignore failure status codes, etc). Creating a custom context simply modifies the default options which would otherwise be used for the stream.

And with that, let’s jump right into the code:

$url = 'http://www.example.com';
 
$data = http_build_query( array( ‘name’ => ‘value’ ) );
 
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded",
        'method'  => 'POST',
        'content' => $data,
    ),
);
 
$context = stream_context_create( $options );
 
$result = file_get_contents( $url, false, $context );

So what’s going on here? Let’s look at each line:

  • First, we need to create an array with the POST data we want to send with our HTTP request. We use the http_build_query() function to convert our array into a URL-encoded format ?like=this. You can’t send arrays in HTTP requests, of course.
  • The content type you can see within the $options array is the default for forms.
  • Create our custom stream context with the $options we created.
  • Fetch the page using file_get_contents(), but using the stream context we just created. This ensures PHP sends out the HTTP request with our POST data.
Ben Stones

Sharing

Leave your comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.