Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
function curl_get_contents($url, $timeout = 30, $settings_array = array())
{
$return 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()) {
$return = false;
}
curl_setopt_array($curl_open, $curl_options);
$return = 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
$return = ob_get_contents(); // Put everything into the variable
ob_end_clean();
if ($status > 1) {
return false;
}
}
return $return;
}
@divinity76
Copy link

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 too

@divinity76
Copy link

also, $url on line 22 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.

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