CURL Post Data in PHP

This post is an introduction to a new series I will be writing about CURL in PHP. To start with I am assuming you have basic knowledge of Both PHP to an intermediate level and understand the difference between POST and GET request types. The series will start off basic, giving you a general idea of what CURL is and how it can be very useful when building applications in PHP. It will then progress to more advanced topics such as screen scraping, brute force attacks and data analyising. To get started, have a read through PHP: cURL – Manual.

Once you've read the above manual, emphasising curl_setopt you will understand that CURL is basically a way of making requests to a resource. This resource is most commonly an API end point, such as a REST Interface. I'm going to start off with the basic idea of sending basic post data to a url, as you would do when submitting a form. I have set up a secret file at this location As you can see, the message clearly states: “Nothing to see here.”. I must admit, the message is a lie; There is a secret message, or maybe even a few. However, the only way to reveal the message is to send some post data along to the url. The message will be revealed by simply sending “answer=openesame” to the url as post parameters. Below is the code you'd use to do that.

$ch = curl_init('');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('answer' => 'opensesame'));
echo curl_exec($ch);

You should see the secret message now printed out to your screen, with a special key and a link to the next post in this series. Please take note of this key, it will become important when all of the tutorials are complete. If you have any questions please comment below or contact me and I will do my best to answer them.