Skip to main content

Submitting forms using PHP cURL

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:

$data = array(); $data['first_name'] = 'Jatinder'; $data['last_name'] = 'Thind'; $data['password'] = 'secret'; $data['email'] = ''; 

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.

 $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&” which can now be sent to the remote URL through cURL.

Connect to the remote URL

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

 $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, ‘’ ); 

Post (submit) the form data

First we instruct cURL to a regular HTTP POST.

 curl_setopt($ch, CURLOPT_POST, TRUE); 

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

 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_str); 

Execute request and fetch the response

 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.

One thought to “Submitting forms using PHP cURL”

Comments are closed.