Using curl with PHP Tutorial

Recently while developing a database backed PHP website, the client demanded to have all forms on one site say www.client-forms-website.com, and all the data to be submitted and stored on www.client-database-website.com.

Curl was the ultimate solution. curl is the client URL function library. PHP supports it through libcurl. To enable support for libcurl when installing PHP add –with-curl=[location of curl libraries] to the configure statement before compiling. The curl package must be installed prior to installing PHP. Most major functions required when connecting to remote web servers are included in curl, including POST and GET form posting, SSL support, HTTP authentication, session and cookie handling.

Leaving out all the fancy stuff, this is what I implemented:

On www.client-forms-website.com:

Created a file “receive-form-data.php” with following code.

<?php

// Move posted data into variables.

$firstName= @$_POST[firstName];
$surName= @$_POST[surName];
$email= @$_POST[email];

//The $curlPost variable is being used to store the POST data curl will use. When forming the $curlPost variable which will be used by curl_setopt later be sure to urlencode your data prior to passing it to curl_setopt.

$curlPost = “firstname=”.urlencode($firstName).”&surname=”. urlencode($surName).”&email=”. urlencode($email).”&submitted=true”;
$ch = curl_init(); //set the handle of the curl session to $ch
curl_setopt($ch, CURLOPT_URL, ‘http:// www.client-database-website.com/process-posted-data.php’); //set the URL of the page to pass data.
curl_setopt($ch, CURLOPT_HEADER, 0); //sets whether or not the server response header should be returned, 0 means no header.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //by default curl will display the response straight to the browser as the script is executed. To counter this we enabled the CURLOPT_RETURNTRANSFER option.
curl_setopt($ch, CURLOPT_POST, 1); //tell curl to send the form response via the POST method.
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost); //option used to store the POST data.
$data = curl_exec($ch); // $data stores data returned from the remote server.
curl_close($ch);

if ($data==1) header(”location: http:// www.client-forms-website.com /thankyou.html“);

else if ($data==0) header(”location: http:// www.client-forms-website.com /error.html“);

?>

On www.client- database -website.com:

Created a file “process-posted-data.php’” with following code.

<?php

$firstName= @$_POST[firstName]; $surName= @$_POST[surName]; $email= @$_POST[email];

/* Function/lines of code to Store Data go here.*/

If (success) echo 1;

else echo 0;

?>

This is working great. Have fun.

Add a Comment

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