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:

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.

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 PHP cURL tutorial. Here is the code again in a nutshell.

Post (submit) the form data

First we instruct cURL to a regular HTTP POST.

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

Execute request and fetch the response

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 on “Submitting forms using PHP cURL

Leave a Reply

Your email address will not be published. Required fields are marked *

*