PHP cURL basics
With the cURL library we can make even complicated http requests with ease. Let's see first how can we open a webpage:#start the cURL session $ch = curl_init(); #set the settings #URL curl_setopt($ch, CURLOPT_URL, "google.com"); #we don't want to output the result curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); #make the request $result= curl_exec($ch); #close the session to free up the resources curl_close($ch);
With the code above gonna have the result of the request in the $result variable. I know some people would say:"what?? i cud make this with less code with file_get_contents". That's true but first file_get_contents is slower than cURL, second if there is no response from the remote server file_get_contents will throw an error. With cURL you can set a timeout for the connection and if there is no response within that it will cancel the request.
Here is an example:
$options = array(
CURLOPT_URL => 'http://www.google.com/',
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_CONNECTTIMEOUT => 5 # set the timeout to 5 secs
);
$ch = curl_init();
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
curl_close($ch);
The code above has two diferencies from the previous one. One is we set the timeout and second we passed the options as an array wich is more comfortable.
We can extend this method even more. For instance we can set cURL to follow redirections or to sent a POST request, or set HTTP headers like the referer:
$options = array(
CURLOPT_URL => 'http://www.google.com/',
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_CONNECTTIMEOUT => 5 ,
CURLOPT_MAXREDIRS => 5, #number of redirects to follow
CURLOPT_REFERER => "seo.forum.hu"#http referer
);
$ch = curl_init();
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
curl_close($ch);
Now we saw a couple of GET request let's do a POST. For instace if we would like to submit a POST search form on a 3rd party website cURL is very handy
For instance we have the following form:
<form method="post" action="celurl.php"> <label>Kulcsszo</label><input name="keyword" type="text" /> <input name="search" type="submit" /> </form>We see the target is the "celurl.php" and we have 2 fields, a text and a submit:
$options = array(
CURLOPT_URL => 'http://www.pisti-shopja.com/',
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_CONNECTTIMEOUT => 5 ,
CURLOPT_REFERER => "google.com"
CURLOPT_POST => 1,#we want a POST request
CURLOPT_POSTFIELDS => "keyword=".urlencode("a kulcsszo amire keresunk")."&search=1"#the content of the post. name => value pairs of data
);
$ch = curl_init();
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
curl_close($ch);
Now you know how to use te basics of cURL but there is even more good features of this library so I might write more about it in the future.

