Alternative to file_get_contents?


#1

So at the moment i am using file get contents to send command… Problem is my site often times out after that because it takes awhile to load

Can someone suggest me what should i use instead and how would it look?

I use this eight now
@file_get_contents(“www.mysite.com/something.php?something={command}”);

What could i use instead… Curl? But how, can smeone write the code please?


#2

Why not make an API return JSON and make an internal PHP request to that JSON? Some frameworks enable this functionality quite nicely (such as Laravel).


#3

I don’t know how to make this. I don’t have any coding experience


#4

Try this:

	function getDataFromUrl($url) {
		$ch = curl_init();
		$timeout = 5;
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
		$data = curl_exec($ch);
		curl_close($ch);
		return $data;
	}

#5

^ This can also be modified to pretend it’s a web browser (for sites like facebook that require a user agent)

function getDataFromUrl($url) {
        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
        curl_setopt($ch,CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; en-US)");
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

Alternatively…

function getDataFromUrl($url) {
  $data = '';
  $page = fopen($url, "rb");
  while (!feof($page))
  {
    $data .= fread($page, 2048);
  }
  fclose($page);
  return $data;
}

In my opinion, the cURL method yougapi used is the best way…


#6

My function -

if(!function_exists('dzs_get_contents')){
    function dzs_get_contents($url){
    if( function_exists('curl_init') ) { // if cURL is available, use it...
                $ch = curl_init($url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_HEADER, 0);
                curl_setopt($ch, CURLOPT_TIMEOUT, 10);
                $cache = curl_exec($ch);
                curl_close($ch);
        } else {
                $cache = @file_get_contents($url); // ...if not, use the common file_get_contents()
        }
        return $cache;
    }
}

#7

Problem of the curl is… If i make multiple curls and then one of the links is down/broken, none of the commands will be executed


#8

Hello Joe,

You can go down a couple levels lower than file_get_contents (which is just a wrapper for fopen/fread/fclose) and try with fsockopen to have access to a timeout parameter. Here is a sample function:

function http_get($host, $resource, $timeout)
{
	$fp = fsockopen($host, 80, $errno, $errstr, $timeout);
	if ($fp !== false)
	{
		$h = "GET $resource HTTP/1.1\r
";
		$h .= "Host: $host\r
";
		$h .= "Connection: Close\r
\r
";
		stream_set_timeout($fp, $timeout * 10000);
		fwrite($fp, $h);
		$buff = "";
		while (!feof($fp)) {
			$buff .= fgets($fp, 256);
		}
		fclose($fp);
		return $buff;
	}
	return false;
}

Here is a usage example :

if ( ($response = http_get("www.mysite.com", "/something.php?something={command}", 15) ) !== false )
{
	//Do something here with the $response
	//Start by trimming the headers first ($response will contain "HTTP/1.1 200 OK" ... and/or other headers)
}	
else
{
	exit("HTTP Get failed");
}

Downside is : this is very low level. Unless your GET request will run something on the server and you don’t care for the response, you are better served using cURL or some other abstract library for this kind of queries.

You can control now your side of the timeout using the third argument of the http_get function. However, if the server times out while proccessing the request - you can’t really do much, no matter the function/library/client you use, except send another request upon server failure and hope for success.

Cheers. Omar.


#9

Also if you only have access to file_get_contents there is a way to pass a “timeout” (plus other cool stuff) to it, eg:

$opts = array('http' =>
  array(
    'method'  => 'POST',
    'header'  => "Content-Type: text/xml\r
".
      "Authorization: Basic ".base64_encode("$https_user:$https_password")."\r
",
    'content' => $body,
    'timeout' => 60
  )
);

$context  = stream_context_create($opts);
$url = 'https://something.com';
$result = file_get_contents($url, false, $context);