PHP & CURL: step by step


After you read this article: Getting data without risking death with PHP, CURL, you’ve seen the power of CURL. I’ll write more about CURL to introduce a useful PHP class written by me and use it regularly. But first let’s take a CURL research through the examples, step by step:

Example 1: GET, include response header

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://demo.tutorialspots.com/');
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0');
curl_setopt($ch, CURLOPT_REFERER, 'https://www.google.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);

echo $data = curl_exec($ch);

result:

HTTP/1.1 200 OK
Date: Fri, 10 Aug 2012 16:05:17 GMT
Server: LiteSpeed
Connection: close
X-Powered-By: PHP/5.2.17
Content-Type: text/html
Content-Length: 29

Wellcome to tutorialspots.com

If you use CURL class

$class = new CURL;
$class->referer = 'https://www.google.com';
echo $class->get("http://demo.tutorialspots.com/");

you get the same result.

Example 2: POST

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://demo.tutorialspots.com/curl/post.php');
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'site=tutorialspots.com&title=Free Online Tutorials');

echo $data = curl_exec($ch);

Code of http://demo.tutorialspots.com/curl/post.php

result:

Array
(
[site] => tutorialspots.com
[title] => Free Online Tutorials
)

If you use CURL class

$class = new CURL;
echo $class->post("http://demo.tutorialspots.com/curl/post.php",'site=tutorialspots.com&title=Free Online Tutorials',2);

you get the same result.

Next: PHP & CURL: step by step – HTTPS Source grabber

Related Post

,

No comments yet.

Leave a Reply