You are here: Home » All Posts » PHP Form » How to submit a form using PHP

How to submit a form using PHP

in PHP Form

There are situations when you want to send data using POST to a URL, either local or remote. Why would you want to do this? Probably you want to submit data to an opt-in form, but without taking a valuable visitor away from your site. Or maybe you want to send data to several applications for various purposes, which would be impossible to do in the usual manner. So how can we deal with this problem?

Simulate submitting a form using cURL

So what is cURL anyway? cURL stands for “Client URL", and it is a library of functions that can be used to connect through a wide range of protocols, such as HTTP, FTP, telnet and so on. cURL also speaks HTTPS, so it can be used to communicate with secure servers.

What we are going to use is, cURL HTTP. cURL supports POST and GET methods, file uploads, cookies, user/password authentications, even using proxy servers for connecting.

It can literally be used to programmatically simulate browsing behavior. It can connect to a remote site, login by posting username and password to the login form or by using HTTP authentication, then retrieve pages or upload files. All of this using pure PHP code.

So how do I use cURL to post data?

Begin by creating a new connection.

$curl_connection =
  curl_init('http://www.domainname.com/target_url.php');

A new connection is created using curl_init() function, which takes the target URL as parameter (The URL where we want to post our data). The target URL is same as the "action" parameters of a normal form, which would look like this:

<form method="post" action="http://www.domainname.com/target_url.php">

Now let's set some options for our connection. We can do this using the curl_setopt() function. Go to curl_setopt() reference page for more information on curl_setopt() and a complete list of options.

curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
	curl_setopt($curl_connection, CURLOPT_USERAGENT,
	"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
	curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);

What options do we set here?

First, we set the connection timeout to 30 seconds, so we don't have our script waiting indefinitely if the remote server fails to respond.

Then we set how cURL will identify itself to the remote server. Some servers will return different content for different browsers (or agents, such as spiders of the search engines), so we want our request to look like it is coming from a popular browser.

CURLOPT_RETURNTRANSFER set to true forces cURL not to display the output of the request, but return it as a string.

Then we set CURLOPT_SSL_VERIFYPEER option to false, so the request will not trigger an error in case of an invalid, expired or not signed SSL certificate.

Finally, we set CURLOPT_FOLLOWLOCATION to 1 to instruct cURL to follow "Location: " redirects found in the headers sent by the remote site.

Now we must prepare the data that we want to post. We can first store this in an array, with the key of an element being the same as the input name of a regular form, and the value being the value that we want to post for that field.

For example,if in a regular form we would have:

<input type="text" name="firstName" value="Name">
<input type="hidden" name="action" value="Register">

we add this to our array like this:

$post_data['firstName'] = 'Name';
$post_data['action'] = 'Register'

Do the same for every form field.

Data will be posted in the following format:
key1=value1&key2=value2

In order to format the data like this, we are going to create strings for each key-value pair (for example key1=value1), put them in another array ($post_items) then combine them in one string using PHP function implode() .

foreach ( $post_data as $key => $value)
{
    $post_items[] = $key . '=' . $value;
}
$post_string = implode ('&', $post_items);

Next, we need to tell cURL which string we want to post. For this, we use the CURLOPT_POSTFIELDS option.

curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);

Finally, we execute the post, then close the connection.

$result = curl_exec($curl_connection);
curl_close($curl_connection);

By now, the data should have been posted to the remote URL. Go check this, and if it did not work properly, use curl_getinfo() function to see any errors that might have occurred.

print_r(curl_getinfo($curl_connection));

This line displays an array of information regarding the transfer. This must be used before closing the connection with curl_close();

You can also see number and description of the error by outputting curl_errno($curl_connection) and curl_error($curl_connection).

So let's put everything together. Here is our code:

<?php
//create array of data to be posted
$post_data['firstName'] = 'Name';
$post_data['action'] = 'Register';
//traverse array and prepare data for posting (key1=value1)
foreach ( $post_data as $key => $value) {
    $post_items[] = $key . '=' . $value;
}
//create the final string to be posted using implode()
$post_string = implode ('&', $post_items);
//create cURL connection
$curl_connection =
  curl_init('http://www.domainname.com/target_url.php');
//set options
curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl_connection, CURLOPT_USERAGENT,
  "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);
//set data to be posted
curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);
//perform our request
$result = curl_exec($curl_connection);
//show information regarding the request
print_r(curl_getinfo($curl_connection));
echo curl_errno($curl_connection) . '-' .
                curl_error($curl_connection);
//close the connection
curl_close($curl_connection);
?>

Post form data without using cURL

If your hosting server does not come with cURL installed (though this is rare as cURL is installed on most commercial hosting servers) and you also don’t have access to server in order to install it, there are alternatives.

One of them is using PHP’s functions fsockopen() and fputs() to send properly formatted data to a remote server. Here is a sample of code that does just this:

<?php
//create array of data to be posted
$post_data['firstName'] = 'Name';
$post_data['action'] = 'Register';
//traverse array and prepare data for posting (key1=value1)
foreach ( $post_data as $key => $value) {
    $post_items[] = $key . '=' . $value;
}
//create the final string to be posted using implode()
$post_string = implode ('&', $post_items);
//we also need to add a question mark at the beginning of the string
$post_string = '?' . $post_string;
//we are going to need the length of the data string
$data_length = strlen($post_string);
//let's open the connection
$connection = fsockopen('www.domainname.com', 80);
//sending the data
fputs($connection, "POST  /target_url.php  HTTP/1.1\r\n");
fputs($connection, "Host:  www.domainname.com \r\n");
fputs($connection,
    "Content-Type: application/x-www-form-urlencoded\r\n");
fputs($connection, "Content-Length: $data_length\r\n");
fputs($connection, "Connection: close\r\n\r\n");
fputs($connection, $post_string);
//closing the connection
fclose($connection);
?>
Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay

No related posts.

{ 52 comments }

Ari March 28, 2011 at 11:23 pm

Thanks so much for this post. I used the code as an add-on to a form-processing PHP so that I could add data to a Google Doc form spreadsheet as well as send both the form-filler and the webmaster an email via mail() in php.
It’s so great that I can deliver the data via email but also store it in a google doc.
Thanks again..

Josh July 2, 2011 at 11:33 pm

Ari,
Not sure if you’re monitoring these comments or not but would love to know who you were able to use with with GDocs forms. I’ve been trying to get it to work but to no avail! Works fine if the form action from an external form is the Google Docs form action but I just can’t get cURL to make an entry. Any tricks?
Thanks in advance!

Dan Wist March 31, 2011 at 8:39 pm

Thank you very much for this tutorial, I just used the bottom section (using fsockopen()). It worked perfectly except for the last line which is fclose($fp). This needs to be changed to fclose($connection) to close this particular connection. Thanks again!

Prasanth April 2, 2011 at 2:26 pm

Corrected. Thanks for spotting this.

proistorikos April 3, 2011 at 11:13 am

Amazing tutorial thank you soo much :D i was looking for something like this

Chris April 5, 2011 at 3:20 pm

This tutorial is great and you did a really good job of breaking down the options that are necessary when using cURL. Thank you so much.

Andy Lai April 5, 2011 at 3:54 pm

Hi Guys,
 
I am trying to do a POST and expect a return value. Seem like I am unable to get a return value. Please assists…
 

 
$post_value = ‘?key1=value&key2=Value2′;
$data_length = strlen($post_value);
 
$WebConnector = fsockopen(‘www.domainname.com/target_URL.php’, 80);
 
 
fputs($WebConnector, “POST  /target_url.php  HTTP/1.1\r\n”);
fputs($WebConnector, “Host: www.domainname.com \r\n”);
fputs($WebConnector,”Content-Type: application/x-www-form-urlencoded\r\n”);
fputs($WebConnector, “Content-Length: $data_length \r\n”);
fputs($WebConnector, “Connection: close\r\n\r\n”);
fputs($WebConnector, $post_value);
 
echo $WebConnector;
//closing the connection
fclose($WebConnector);
 
echo ‘Test’;

Bob Nyce April 6, 2011 at 2:33 pm

Can this method be used if the form is normally submitted through a Javascript using the onSubmit handler?
For Example the normal form tag is <form name=’form’ method=’post’ onSubmit=”return SubmitWebForm()”>
Thanks for your help.

Prasanth April 6, 2011 at 4:53 pm

Yes.
referring how client-side code differs from server side (like PHP ) would help.

Laura May 3, 2011 at 12:57 pm

By default is this script suppose to redirect the user to the URL where the data is being posted? If not how do I send the post data to a page along with the user.

Roberto May 10, 2011 at 5:40 pm

This is what I need, too. I have tried the code (the second one) and it does not redirect the user to the page, it remain on the php script sending the post. I need to redirect also the user to the landing page, so the second server can set a cookie on the visitor’s browser according the variable posted (that is a remote login).
Thank you in advance for any help

EdWood June 6, 2011 at 12:42 am

I need too :)

Jason May 19, 2011 at 9:21 pm

//set POST variables
$url = ‘http://www.domain.com/signup.php’;
$??? = ‘someone@email.com’;

Alexander May 20, 2011 at 6:49 am

Thanks for this tutorial.
It’s very helpful for me!

Linto June 13, 2011 at 11:41 pm

Hi
I tried this(the curl method)
I have this code in one.php and i am sending the post to two.php
In two.php,at the end of  code, there is  page redirection to Google.com
 
Everything is happening but not the page redirection.
How can i achieve this
Please help, thanks in advance
 

Moemen June 21, 2011 at 10:58 am

Thanks for this tutorial.
It’s very helpful for me!

Cool Email Forwards July 5, 2011 at 1:11 pm

This works great! This is very helpful for me. Thanks for posting this!!!

MoCua.Com July 22, 2011 at 1:02 pm

Thanks very much

Mark July 23, 2011 at 12:15 am

Could this be used to submit ebay listings to auction bump websites in a semi automated way?
eg code on auction bump site
<form action=”speedy_bump.php” method=”post” name=”upl_form” id=”upl_form” style=”margin: 0;”>
<input type=”hidden” name=”bms” value=”X” />
<input type=”hidden” name=”maxmet” value=”" />

<table bgcolor=”#ffffff” cellspacing=”0″ cellpadding=”0″>
<tr><td class=”speedy_form”><img src=”speedy_images/itemnumber.png” alt=”eBay item number” width=100 height=30 border=0></td><td class=”speedy_form”><input type=”text” name=”item” size=”12″ maxlength=”12″ value=”" /></td>
<td class=”speedy_form”>
<input type=”submit” name=”up_auction” id=”up_auction” value=”Speedy Bump” onclick=”document.upl_form.up_auction.disabled=true; document.upl_form.up_auction.value=’Speedy Bump’; document.upl_form.submit();” />
</td>

<td class=”faster” valign=”middle”>Just enter your eBay item number and we do the rest!</td>

</tr><tr><td colspan=4 class=”"><br></td></tr>
</table>
</form>

adrian lee July 26, 2011 at 9:06 am

will i be able to Post form data without using cURL in a dot net server using php?

Bintang August 13, 2011 at 1:19 pm

Great tutorial. Now I can create a spam bot using this script.
Thanks you. LOL

Dress up August 17, 2011 at 4:22 am

What do you think of when the information you give is very interesting and useful? Thanks a lot.

Butch August 18, 2011 at 9:49 pm

I am a novice programmer and currently teaching myself a little bit about database programs. Right now I am trying to insert a hyperlink into record in my database. I need to be able to take a piece of information from one of the fields in the record, “insert” it into the text field on the webpage and submit the php form. my question i guess is can i do this with an http:// string with the proper arguments.

Indika August 24, 2011 at 1:55 am

Dear Friends,
I am working with a code to POST data to a website to login (username , password).
1. After sending the request how can we grab the URL of result web page that gives by the web server for the POST request. Because end of the result URL gives a session ID that unique to whole logged session of that web site.
2. How can we display the result web site in a browser.

Anyway your posting regarding the POST request is really help me to plan my code. Thanks for that.
Pls be kind enough to help me in my questions.
lndika

Rebecca November 19, 2011 at 5:23 pm

Hello! Sorry off topic … What theme you are using? I checked the source but only can see Thesis version … Or this is a custom theme? We really like it and would like to know where can we buy it?

thanks,
Bec

Comments on this entry are closed.

Previous post:

Next post: