PHP: Send POST request WITHOUT cURL.

This is a short PHP tutorial on how to send a HTTP POST request without using cURL. This may be helpful for those of you that require an easy alternative to PHP’s cURL extension.

Custom POST function.

Let’s create a customĀ post function that doesn’t use any of the cURL functions:

Take some time to read through the comments in the code above, as these explain how the POST request is constructed and sent via file_get_contents.

How to use the post function.

The custom function above takes in two parameters:

  • A URL string. This is the URL that we want to send a POST request to.
  • An associative array containing the POST variables that we want to send.

Here is an example of the function being used:

In the PHP code above, we are sending a POST request to example.com. There are two post variables: These are calledĀ foo and name.

Failed requests and error handling.

Note that our custom post function will throw an Exception if the HTTP request fails. This means that you can catch any failed POST requests like so:

If you run the code above, you will be met with the following output:

POST request failed: file_get_contents(http://google.com): failed to open stream: HTTP request failed! HTTP/1.0 405 Method Not Allowed

This 405 error occurs because Google does not accept POST requests.

Note: If you do have access to PHP’s cURL functions, then I would suggest that you use them. The cURL functions come with a lot of different options, many of which are extremely useful.

Hopefully, you found this alternative to be useful!

Facebook Comments