Julienh / Sharrre

Make your sharing widget! Sharrre is a jQuery plugin that allows you to create nice widgets sharing for Facebook, Twitter, Google Plus (with PHP script) and more.
sharrre.com
MIT License
1.04k stars 413 forks source link

Add HTPP Cache Option for googlePlus #236

Open ewwink opened 9 years ago

ewwink commented 9 years ago

Too many (Million lol) HTTP request to googlePlus may decrease your server performance or even you get blocked, here I modify sharrre.php you only need to define cache life, by default it used 5 minutes and make sure sharrre-cache directory is exist and writable.

Change original code from

  $contents = parse('https://plusone.google.com/u/0/_/+1/fastbutton?url=' . $url . '&count=true');
  preg_match( '/window\.__SSR = {c: ([\d]+)/', $contents, $matches ); 
  if(isset($matches[0])){ 
      $json['count'] = (int)str_replace('window.__SSR = {c: ', '', $matches[0]); 
  }

with

if (!file_exists("sharrre-cache")) {
      mkdir("sharrre-cache");         
  } 
  $cache_file = "sharrre-cache/".base64_encode($_GET['url']);
  // cache for 5 minutes
  if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 60 * 5 ))) {
      $file = file_get_contents($cache_file);
      $json['count'] = $file;
  } else {
      $contents = parse('https://plusone.google.com/u/0/_/+1/fastbutton?url=' . $url . '&count=true');
      preg_match( '/window\.__SSR = {c: ([\d]+)/', $contents, $matches );
      if(isset($matches[0])){
          $json['count'] = (int)str_replace('window.__SSR = {c: ', '', $matches[0]);
          file_put_contents($cache_file, $json['count'], LOCK_EX);
      }
      else{
          file_put_contents($cache_file, "0", LOCK_EX);
      }

  }