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);
?>





← Previous Comments
Next Comments →
after putting all the data to the curl.. how can i go to the paypal page?
Thanks!!! I’ve been working an an iphone app that controls embedded WiFi devices, and I couldn’t get a PHP http request to work before this one!!! I really appreciate it!
I want to create a form on my wordpress page or post that will allow my logged in subscribers to register into another of my wordpress websites. Will this do what I want, and if so, how do I find a coder who can create a form for me that will do this? Are you available for coding?
Thanks
I really cant do the submit button work!!
Please tel me how to do it? I have seen the codes and tried a lot ..
Please someone help me!! Now I m totally hopeless….
Thanks everyone..
thanks a lot for the script. But i want to ask that how to submit data the site is using user credentials.
Actually i want to submit data to a site but your code doesn’t work as the site need user credentials.
So, can you help me for submitting data on a site having user credentials.
Thanks in advance.
Thank you. Great tutorial!
Genius! I’ve been pulling my hair out all morning trying to figure this out. Now I’m finally getting somewhere! Thank you very much!
Dude u RoCk !!
Thanks everyone..
This is really cleared a lot to me, how ever i wanted to know
how to open external site (ie: hidemyass.com) and fill up the textbox and hit submite button
then fitch the results,
can we do this using php ?
cURL GETS the contents of a web page, it does not take your browser there.
$result = curl_exec($curl_connection);
to view the html you can echo $result; BUT this html code will be on your site, so any local references to images, javascript and css files will fail to load.
This is the best curl guide I’ve found on internet (and I surf a looooot), great job! Simply amazing… I will refer others to this source for sure…. it’s just that the PHP manual is too hard for me to follow, I started PHP few weeks ago (actually without any previous programming language experience nor HTTP requests knowledge) and your submission is so perfectly clear even to me that it just stunts me… actually, right now I’m thinking this couldn’t been done any simplier! Thank you for your hard work and altruism.
P.S. it’s same for fsockopen() and fputs() part.
P.S.2 curl is sooo powerful :O, I just fell in love with it
.
Awesome guide! Would love to see how it can work with other types of data like images and files.
Simple. Just change the URL to that of an image ie http://www.website.com/image.png This will get the contents of that image, which can then be saved using something like fopen.
If you want to output them directly to the browser, you will need to output the appropriate headers first ie header(‘Content-Type:image/png’); You can get the headers that were sent to you and just reproduce them. (Sorry but I dont have access to my code where I am at this moment to explain how)
Other files will contain what will be outputed to a browser, so dont assume you can view source files using this. (ie a php file that produces html code will give you the generated html, not the original pre-processed php coding)
curl_setopt ($ch, CURLOPT_COOKIEJAR, ‘cookie.txt’);
you can also use this for bypassing session ticket systems in some forms.
example:
on the initial “pass” you would parse the cURL response using regex for the hidden ticket input name and value to pass on to the POST operation. This ocurrs prior to submitting, but within the same script and cURL /initialization and execution.
the COOKIEJAR CURLOPT I posted above is an important part for more secure servers for this.
Not manual, audio, or visual challenge-response systems though. that isnt possible without some extremely advanced coding, and that type of Character Recognition (O/CR) rarely works on the more advanced captcha.
hmm this comment section did not display my INPUT tag example above. Unfortunate that this comment system does not allow for html code display … its a coding site LOL.
nice
Hey man you made may day really was looking for this curl function.Now i got it. Thanks
But how about the form grabbing the var’s and sending them forword. been having diffuclties there
this link will help u
a simple example for post using curl
http://phpdog.blogspot.in/2012/02/http-post-using-php-curl.html
i want to post my form to vtu server to fetch result.i used abov code,but its not showing the result after submission of the university seat number..help me..
← Previous Comments
Next Comments →
Comments on this entry are closed.