Some of the web hosts don’t support some of the main file handling functions like fopen and file_get_contents. In this post I’m sharing another way of fetching contents of a file or a web address. I’m talking about Curl which has become most popular PHP function for the purpose of crawling and getting contents of any web page or a file. Its usage is simple and similar to fopen and file_get_contents.
PHP
This simple PHP function will do all the work. CURL settings can be modified. All CURL settings start with curl_setopt. You can see that in below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php function curl_file_get_contents($url) { $ch = curl_init(); //initiate curl curl_setopt($ch, CURLOPT_HEADER, 0);//0 means response headers will not be included in output. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //1 means curl will return the contents as output of this function, instead of printing them inside this function. curl_setopt($ch, CURLOPT_URL, $url); $data = curl_exec($ch);//request sent to the url curl_close($ch); return $data; } ?> |
Usage
1 2 3 4 |
<?php $curl_response = curl_file_get_contents('http://earlysandwich.com'); echo $curl_response; ?> |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// This is an fopen example $data = fopen("http://earlysandwich.com", "r"); echo $data; // Replace this with CURL like this $data = curl_file_get_contents("http://earlysandwich.com"); echo $data; // This is file_get_contents example $data = file_get_contents("http://earlysandwich.com"); echo $data; //Replace file_get_contents with curl_file_get_contents $data = curl_file_get_contents("http://earlysandwich.com"); echo $data; |
Complete Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php function curl_file_get_contents($url) { $ch = curl_init(); //initiate curl curl_setopt($ch, CURLOPT_HEADER, 0);//0 means response headers will not be included in output. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //1 means curl will return the contents as output of this function, instead of printing them inside this function. curl_setopt($ch, CURLOPT_URL, $url); $data = curl_exec($ch);//request sent to the url curl_close($ch); return $data; } $curl_response = curl_file_get_contents('http://earlysandwich.com'); //Just change URL to what ever page you want to fetch echo $curl_response; ?> |