36 wiersze
1,5 KiB
PHP
36 wiersze
1,5 KiB
PHP
<?php
|
|
function ckratelimit($headers,$echofun,$onlyret=false,$verbose=false) {//$echofun has to be the name of a defined function to pass messages to
|
|
$ret=null;
|
|
if (is_array($headers)) {
|
|
//echo "ckratelimit: {$headers}: ".print_r($headers,true));
|
|
$buff=[];
|
|
array_shift($headers);
|
|
foreach ($headers as $header)
|
|
if (preg_match('/^([^:]+):(.*)$/Uu',$header,$matches)===1)
|
|
$buff[$matches[1]]=trim($matches[2]);
|
|
$headers=$buff;
|
|
//print_r($headers);
|
|
if (isset($headers['Date']) && isset($headers['X-RateLimit-Reset']) && isset($headers['X-RateLimit-Remaining'])) {
|
|
//Wed, 30 Mar 2022 21:27:22 GMT
|
|
$srvnow=strtotime($headers['Date']);
|
|
//2022-03-31T04:05:00.058705Z
|
|
$srvrlreset=strtotime($headers['X-RateLimit-Reset']);
|
|
$srvrlremain=$headers['X-RateLimit-Remaining'];
|
|
$secstoreset=$srvrlreset-$srvnow;
|
|
$ret=['remaining'=>$srvrlremain,'secstoreset'=>$secstoreset];
|
|
if ($onlyret)
|
|
return $ret;
|
|
if ($verbose) $echofun("ckratelimit: X-RateLimit-Remaining: {$srvrlremain}; server time: {$srvnow}: ".gmdate('c',$srvnow).'; X-RateLimit-Reset: '.gmdate('c',$srvrlreset).'; current seconds before reset: '.$secstoreset.".\n");
|
|
if ($srvrlremain==0) {
|
|
$echofun("Reached rate limit, waiting {$secstoreset} seconds for rate limit reset ...\n");
|
|
sleep($secstoreset);
|
|
}
|
|
} else {
|
|
if ($verbose) $echofun("ckratelimit: no «Date» / «X-RateLimit-Reset» / «X-RateLimit-Remaining» header(s)!\n");
|
|
}
|
|
} else {
|
|
if ($verbose) $echofun("ckratelimit: headers is not an array!\n");
|
|
}
|
|
return $ret;
|
|
}
|
|
?>
|