Showing posts with label curl_setopt. Show all posts
Showing posts with label curl_setopt. Show all posts

Saturday, August 23, 2014

Access an exteral url using php curl

I will start will a working code:
<?php
$handle=curl_init('complete url here');
curl_setopt($handle, CURLOPT_VERBOSE, true);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
$content = curl_exec($handle);

if(!curl_errno($handle))
{
    $info = curl_getinfo($handle);

    echo '<br/> Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
}
else
{
    echo 'Curl error: ' . curl_error($handle);
}

echo $content;
?>


This will first initialize the handle. Then it is setting properties which will be used to access the webpage.
After that it is checking for errors,if any. And finally it is printing the obtained webpage.

This can be modified a little bit by setting url external to curl_init:

<?php

$ch=curl_init();
$url="url";
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$curlresult=curl_exec($ch);
curl_close($ch);
echo $curlresult;

?>