Skip to content

Instantly share code, notes, and snippets.

@aliqorbani
Created April 27, 2019 10:35
Show Gist options
  • Save aliqorbani/381aa4fd877632ef9b43fdc393109f14 to your computer and use it in GitHub Desktop.
Save aliqorbani/381aa4fd877632ef9b43fdc393109f14 to your computer and use it in GitHub Desktop.
here i customized a function to return json data correctly (some servers like stackexchange do not allow users to get data from out of browser for security reasons).
function api_json_return($final_url){
//I used this function to work on `https://api.stackexchange.com`
// for example this url returns my stackoverflow data = 'https://api.stackexchange.com/2.2/users/4729243?order=desc&sort=reputation&site=stackoverflow'
$ch = curl_init($final_url);
if (! defined("CURL_HTTP_VERSION_2_0")) {
define("CURL_HTTP_VERSION_2_0", 3);
}
curl_setopt_array($ch,
[
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_HTTPHEADER => [
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language: en-US,en;q=0.5",
"Accept-Encoding: gzip, deflate, br",
"Connection: keep-alive",
"Upgrade-Insecure-Requests: 1",
"Cache-Control: max-age=0"
],
CURLOPT_USERAGENT => "Mozilla/5.0 (X11; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0",
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2_0
]
);
$out = gzdecode(curl_exec($ch));
$info = curl_getinfo($ch);
if ($ern = curl_errno($ch)) {
$err = curl_error($ch);
curl_close($ch);
throw new StackoverflowException(
"Error (".$ern."): ".$err
);
}
curl_close($ch);
return $out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment