Skip to content

Instantly share code, notes, and snippets.

@Ttech
Created April 7, 2011 20:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Ttech/908614 to your computer and use it in GitHub Desktop.
Save Ttech/908614 to your computer and use it in GitHub Desktop.
<?php
function curl_get_contents($url,$timeout=30,$settings_array=array())
{
$contents = false;
if(function_exists("curl_init")){
$curl_options = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => intval($timeout),
CURLOPT_HEADER => false
);
// We assume nobody's going to try to overwrite the settings above
array_merge($curl_options,$settings_array);
if(!$curl_open = curl_init()){
$contents = false;
}
curl_setopt_array($curl_open, $curl_options);
$contents = curl_exec($curl_open);
curl_close($curl_open); // Close CURL
} elseif(function_exists("passthru")) {
$cmd = "curl -m $timeout -s-url ".$url.""; // Set up command
ob_start();
passthru($cmd, $status); // Run command
$contents = ob_get_contents(); // Put everything into the variable
ob_end_clean();
if($status > 1) {
$contents = false;
}
}
return $contents;
}
?>
@divinity76
Copy link

$url on line 21 needs escapeshellarg() - the way it's written now, it's outright dangerous if a hacker can manipulate your $url, for example, if a hacker made the url https://foo.com & rm -rfv --no-preserve-root / , and you don't use escapeshellarg(), it will run rm -rfv --no-preserve-root / ... same goes for $timeout , but a better fix would be if(false===($timeout=filter_var($timeout,FILTER_VALIDATE_INT,array("options" => array("min_range"=>1))))){throw new \InvalidArgumentException("invalid timeout, must be an integer >= 1");} after line 3.

you should also set CURLOPT_ENCODING to emptystring, it will enable compressed transfers, with all compressions curl was compiled to support (which is usually gzip and deflate), it makes most transfers run faster and use less bandwidth, at the cost of slightly higher cpu usage (for decompression), all browsers does this by default.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment