Submitting forms using PHP cURL

Listed under

In the previous article, we covered the PHP cURL basics. Specifically, we learned how to connect to a remote URL and retrieve the URL’s contents. In this article we will learn how to simulate form submission using PHP cURL.

To submit forms using cURL, we need to follow the below steps:

  1. Prepare the data to be posted
  2. Connect to the remote URL
  3. Post (submit) the data
  4. Fetch response and display it to the user

You may want to download the script used in this tutorial before starting.

Prepare data to be posted

Form data is essentially sent as name value pairs in the format “field1=field1_value&field2=field2_value&field3=field3_value”.

field1, field 2 etc. refer to the form fields and the field1_value, field2_value etc. refer to values of these fields. For our example we will assume that the data we want to post to the remote URL is contained in an associative array like so:

<?php
$data = array();
$data['first_name'] = 'Jatinder';
$data['last_name'] = 'Thind';
$data['password'] = 'secret';
$data['email'] = 'me@abc.com';
?>

When a browser submits the form, it automatically urlencodes the data before sending it off. Similarly we will need to urlencode all data before posting it through cURL. You can find more about urlencode here.

<?php
$post_str = '';
foreach($data as $key=>$val) {
	$post_str .= $key.'='.urlencode($val).'&';
}
$post_str = substr($post_str, 0, -1);
?>

The above code will leave us with string “first_name=Jatinder&last_name=Thind&password=secret&email=me%40abc.com” which can now be sent to the remote URL through cURL.

Connect to the remote URL

We have already covered this in the previous tutorial on PHP cURL. Here is the code again in a nutshell.

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com/form-handler.php' );
?>

Post (submit) the form data

First we instruct cURL to a regular HTTP POST.

<?php
curl_setopt($ch, CURLOPT_POST, TRUE);
?>

Next we tell cURL which data to send in the HTTP POST.

<?php
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_str);
?>

Execute request and fetch the response

<?php
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>

The above code snippet executes the cURL request, fetches the response of the form handler script and displays it to the user.

You can download the complete source code for the above PHP cURL tutorial here.

>>

Comments

Terrell Aug 31, 2009

You have some great tutorials. Do you plan to create anymore for curl?

Post your comment
All comments are manually verified. So don't waste your time posting spam.

  Textile Help

Bookmark and Share