Use cURL to Connect To Another System

cURL is a very useful tool used to pragmatically connect and interact with other systems to do various tasks like download a Web Page or RSS feed. It is also used to send information to another computer and get a response. A common example of using cURL is when you are purchasing something online. When you get your shipping quote or authorizing your credit card, you are very likely using something like cURL.

<?
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$result = curl_exec ($ch);
?>

These 5 lines of code do a lot. In line 1 you begin creating your transaction by calling curl_init() and passing the URL you want to connect to (in this case we have a variable called $url).

Lines 2-4 set different options for the transaction. The CURLOPT_HEADER option is set to zero to signify we do not want the header information in the response. CURLOPT_RETURNTRANSFER tells cURL to assign the data we receive to a variable rather than simply output it to the screen. CURLOPT_POSTFIELDS sets what data we want to send in the header of our request. This is a very important option when interacting with other systems as this is generally where you will put your XML or other header data that is required by the system you are connecting with.

Line 5 actually executes the request. It will reach out to the $url, with $fields in the POST areas of variables and putting the data we received into the variable $result. With this variable you can do whatever you need in order to make your application work.

Leave a Reply

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