Need a website? An update? A specific function or application? Click here

Tips and Tricks

Sending a POST request using PHP
(This article is for webmasters with some PHP experience)

From time to time there arises the need to send an HTTP POST request without a form. Some turn to cURL or the libcurl library to do the job. If you don't have cURL at your disposal, or prefer not to use it, there is a PHP-only solution. The function shown below is an example of how to do this.

code block

Let's walk through the code. First, this function accepts 3 parameters:

"$url" is the address of the script to which the data will be sent.

"$data" of course is the data that will be sent. It is in the form of an array of variable/value pairs which should be used with PHP's http_build_query() function which I'll describe later.

"$optional_headers" is a string of any additional HTTP headers that need to be sent, such as 'Referer'. A default value of null is assigned.

The first line inside the function creates an associative array with the given $data and the headers. The next two lines find out if any optional headers have been given, and if so, populates the $params array with that info.

An associative array is used because that is what the PHP function "stream_context_create()" requires. And as you can see it receives it in the next line.

Specifically, "stream_context_create()" is used to create a stream and PHPs "fopen()" function is used to send that stream to the specific address/script for processing.

The variable $response is created to catch the results of the remote script processing, and to return that info to the local script. As you can see "$response" sits inside a conditional that does some ever-important error handling, always recommended.

As mentioned earlier, the $data variable is an array of variable/value pairs --- that need to be url encoded --- and this can be assembled using PHPs http_build_query() function.

Here is an example:

code block


GaryBlatt.com · chicago area web design    Valid HTML 4.01Valid CSS

Gary Blatt
Web Designer for Hire

Contact me

View Recent Projects