Advertisement
zefie

Caching API Wrapper (Twitch.TV API v5 & Helix)

Apr 13th, 2018
414
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.44 KB | None | 0 0
  1. <?php
  2. class TwitchAPI {
  3.     public $url;
  4.     public $cachedir = "/home/user/somedir";
  5.     public $cachetime = 60;
  6.     public $oauth = null;
  7.     private $clientid = "";
  8.  
  9.     private function getFromTwitch($u,$f) {
  10.         // Last updated 2018-04-13 for v5 Kraken to v"New" Helix transition
  11.         $s = curl_init();
  12.         $headers[] = 'Client-ID: '.$this->clientid;
  13.         if ($this->oauth != null) {
  14.             $headers[] = 'Authorization: OAuth '.$this->oauth;
  15.             // clear after each use
  16.             $this->oauth = null;
  17.         }
  18.         if (preg_match('/\/kraken\//',$u)) {
  19.             $headers[] = 'Accept: application/vnd.twitchtv.v5+json';
  20.         }
  21.         curl_setopt($s,CURLOPT_HTTPHEADER,$headers);
  22.         // clear after each use
  23.         $headers = null;
  24.         curl_setopt($s,CURLOPT_URL,$u);
  25.         curl_setopt($s,CURLOPT_RETURNTRANSFER, 1);
  26.         $data = curl_exec($s);
  27.         curl_close($s);
  28.         $fp = fopen($f,"w");
  29.         fwrite($fp,$data);
  30.         fclose($fp);
  31.         return $data;
  32.     }
  33.  
  34.     function get($apiurl = "api.twitch.tv",$secure = true) {
  35.         $prefix = "http://";
  36.         if ($secure) { $prefix = "https://"; }
  37.         $inturl = $prefix.$apiurl."/".$this->url;
  38.         $md5 = md5($inturl);
  39.         $cachefile = $this->cachedir."/".$md5;
  40.         if (file_exists($cachefile)) {
  41.             $mtime = filemtime($cachefile);
  42.             $time = time();
  43.             if (($time - $mtime) > $this->cachetime) {
  44.                 return $this->getFromTwitch($inturl,$cachefile);
  45.             } else {
  46.                 return file_get_contents($cachefile);
  47.             }
  48.         } else {
  49.             return $this->getFromTwitch($inturl,$cachefile);
  50.         }
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement