Site Cloner PHP Script
Bargain Hunter PHP Script
Job Hunter PHP Script
Site Login and Access Control PHP Script

Use Curl to Post Form Data

Curl is an amazing extension that returns the source code of a desired webpage into a string. This simple tutorial will explain how you can code a simple script so that the actual website will process the form data as though you are a real visitor that submitted the form.

Let’s break down the following code. The desired url is https://example.com/login.php. Since we know the username and password, an array is created so the form can properly validate. After that, curl is initialized followed by a whack of options.

Among other things, these options options provide a referring url which make the request believe that you viewed index.php before filling out the form at login.php.

The CURLOPT_FOLLOWLOCATION is to ensure that you will be redirected to an appropriate page. Sometimes, you login and the PHP script will redirect you to a new page. Without this option, you will not be redirected and could end up with a blank page without any data.

The CURLOPT_HEADER was included so that the string adds the header details.

The CURLOPT_POST and CURLOPT_POSTFIELDS options are required to ensure that this is a post request and that it contains the adequate form fields, which in this case is the username and password. Since curl uses GET by default, it is very important to satisfy all requirements for making a POST request.

The actual string($html), is printed and contains the web page that exists after a valid login. However, if the login was invalid, you would see the page that would be returned if you sent the wrong credentials.

This example was shown with an authenticated login. However, it could be used to send data from any typical form. If you use a tool like Firebug, you can easily retrieve the post fields and create an array for the details you need to send; such as a simple contact form that requires a first name, last name, email address and phone number. On the other hand, you may only need a username, password, validate password and email address to POST to a form for which you want to submit a free membership.

 <?php

$url = 'https://example.com/login.php';
$data = array('username' => 'admin', 'password' => 'my_password');
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, 'https://example.com/index.php');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$html = curl_exec($ch);

echo $html;

If you want to see a complete list of curl options, you can find them at http://php.net/manual/en/function.curl-setopt.php.