Close

cURL with Basic Example

  • Home
  •  / 
  • PHP
  •  / 
  • cURL with Basic Example

cURL with Basic Example

cURL is basically a library that lets you make HTTP requests in PHP. It is often used to access data from outside web pages. Common uses include reading rss feeds or accessing third-party API systems. The libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. It also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP’s ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.

 

Basic Example:

index.php

<?PHP

/*Initialize*/
$ch=curl_init();

/*Set Options*/
//Url to send the request
curl_setopt($ch, CURLOPT_URL, ‘http://www.gayatrisoft.co/’);

//Return instead of outputting directly
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

//Weather to include the header in the ouput. Set to false here
curl_setopt($ch, CURLOPT_HEADER, FALSE);

/*Execute*/
$output= curl_exec($ch);

/*Close*/
curl_close($ch);

/*Output*/
//print_r($output);

/*Post data with cURL*/

/*Basic Setup*/
$url=”http://localhost/cURL/output.php”;

$query_data = array(
‘query’ => ‘Some Stuff’,
‘method’ => ‘post’,
‘ya’ => ‘hoo’
);

/*Initialize*/
$ch=curl_init();

/*Set Options*/
curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, $query_data);

/*Excute*/
$output1= curl_exec($ch);

if($output1 == FALSE) {
echo “cURL Error: ” . curl_error($ch);
}

/*Close*/
curl_close($ch);

/*Display Raw output*/
print_r($output1);

?>

output.php

<?php print_r($_POST); ?>

 

Another Example without using cURL:

<?php
$file = simplexml_load_file(‘http://www.gayatrisoft.co/blog/’);
print “<ul>\n”;
foreach ($file->website->item as $item){
print “<li>$item->title</li>\n”;
}
print “</ul>”;
?>

 

Same Example of using cURL:

<?php

$ch = curl_init(“http://www.gayatrisoft.co/blog/”);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);

$file = simplexml_load_string(curl_exec($ch));
curl_close($ch);

print “<ul>\n”;
foreach ($file->website->item as $item){
print “<li>$item->title</li>\n”;
}
print “</ul>”;

/*Saving output*/

$ch = curl_init(“http://www.gayatrisoft.co/blog/”);

$fp = fopen(“output.html”, “w”);

curl_setopt($ch, CURLOPT_FILE, $fp);

curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);

curl_close($ch);

fclose($fp);

?>

PHP Developer

Related Posts

Leave a Reply

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