Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use CURL instead of file_get_contents?

I use file_get_contents function to get and show external links on my specific page.

In my local file everything is okay, but my server doesn't support the file_get_contents function, so I tried to use cURL with the below code:

function file_get_contents_curl($url) {     $ch = curl_init();      curl_setopt($ch, CURLOPT_HEADER, 0);     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);     curl_setopt($ch, CURLOPT_URL, $url);      $data = curl_exec($ch);     curl_close($ch);      return $data; }   echo file_get_contents_curl('http://google.com'); 

But it returns a blank page. What is wrong?

like image 513
Morteza Avatar asked Dec 16 '11 22:12

Morteza


People also ask

Is cURL faster than file_get_contents?

This is old topic but on my last test on one my API, cURL is faster and more stable. Sometimes file_get_contents on larger request need over 5 seconds when cURL need only from 1.4 to 1.9 seconds what is double faster.

What is the difference between file_get_contents () function and file () function?

The file_get_contents() function reads a file into a string. The file_put_contents() function writes data to a file.


2 Answers

try this:

function file_get_contents_curl($url) {     $ch = curl_init();      curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);     curl_setopt($ch, CURLOPT_HEADER, 0);     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);     curl_setopt($ch, CURLOPT_URL, $url);     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);             $data = curl_exec($ch);     curl_close($ch);      return $data; } 
like image 78
lord_viper Avatar answered Oct 03 '22 20:10

lord_viper


This should work

function curl_load($url){     curl_setopt($ch=curl_init(), CURLOPT_URL, $url);     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);     $response = curl_exec($ch);     curl_close($ch);     return $response; }  $url = "http://www.google.com"; echo curl_load($url); 
like image 20
CLUEL3SS Avatar answered Oct 03 '22 20:10

CLUEL3SS