Introduction

In this post I will talk about using cURL to post data to a server. Curl it’s a library that you can use to get data from a server or send it back. It was created by Daniel Stenberg and it works with ftp,gopher,telnet,file,dict,ldap, http and https protocols. I am not gone write here how you can make to configure and install, I want to show you a method to post data to a server on the http protocol.

How it works? 

You need to initiate a cURL session, put the url of the server you wanna POST data, put the options for the current session, execute session and get the data you need.

 

Here is a list of cURL functions that can help you to post data:

 
curl_init – it’s is used to initiate a cURL session

curl_setopt – it helps you to pass option to cURL for the next transfer.

curl_exec – executes a cURL session

curl_error – containts the last error of cURL sesion that was executed

 

Here is a sample code for posting data in PHP:

 

function datapost($URLServer,$postdata)
{
 
 
 
$agent = "Mozilla/5.0";
 
$cURL_Session = curl_init();
 
curl_setopt($cURL_Session, CURLOPT_URL,$URLServer);<span> </span>
 
curl_setopt($cURL_Session, CURLOPT_USERAGENT, $agent);
 
curl_setopt($cURL_Session, CURLOPT_POST, 1);
 
curl_setopt($cURL_Session, CURLOPT_POSTFIELDS,$postdata);
 
curl_setopt($cURL_Session, CURLOPT_RETURNTRANSFER, 1);
 
curl_setopt($cURL_Session, CURLOPT_FOLLOWLOCATION, 1);
 
$result = curl_exec ($cURL_Session);
 
return $result;<span> </span>
 
}
 
 
 
$htmlsource= datapost("http://www.example.com/script.php","param1=value1&param2=value2")

 

 

So first we initiate the cURL sesion with curl_init() and after that we set some options for the current session with curl_setopt and after that we execute the session and get the result.

 

CURLOPT_URL,$URLServer – this option sets the target script.

CURLOPT_USERAGENT,agent – this is optional, it sends to the server an agent.

CURLOPT_POST – this should be set to 1 because we make a post to the server.

CURLOPT_POSTFIELDS – here we should pass the parameters and there values

CURLOPT_RETURNTRANSFER – should be set to 1(because we store the source of the result in a variable) otherwhise the result will be printed on page

CURLOPT_FOLLOWLOCATION – is important if the server it redirects you after you post the data. If the server redirects should be set to 1.

 

If you wanna store a cookie when you execute the sesion you should use:

 

 
curl_setopt($cURL_Session, CURLOPT_COOKIEFILE, $path_to_cookie);
 
curl_setopt($cURL_Session, CURLOPT_COOKIEJAR, $path_to_cookie);