Skip to content

Instantly share code, notes, and snippets.

@sperelson
Created October 12, 2012 15:58
Show Gist options
  • Save sperelson/3879930 to your computer and use it in GitHub Desktop.
Save sperelson/3879930 to your computer and use it in GitHub Desktop.
Mixup PHP curl routines with memcache
<?php
// Copyright Stephen Perelson
//
// Example PHP script to get a banner from http://mixup.hapnic.com
// Adds a 1 minute cache of the banner using Memcache
// Untested code
//
// Mixup is a cross-Promotion Linksharing service for Mxit web apps
class ServeMixup {
// Call get_link to return a string with a new link
public function get_link($Mxit_Referral_ID) {
$url = "http://serve.mixup.hapnic.com/" . $Mxit_Referral_ID;
$memcache = $this->get_memcache();
if ($memcache === false) {
$link = $this->curl_get_link($url);
} else {
$key = "YOUR_MEMCACHE_KEY_mixup_banner";
$ttl = 60; // 1 minute
if ($memlink = $memcache->get($key)) {
$link = $memlink;
} else {
$link = $this->curl_get_link($url);
$memcache->replace($key, $link, false, $ttl) || $memcache->set($key, $link, false, $ttl);
}
}
return $link;
}
private function curl_get_link($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl, CURLOPT_TIMEOUT, 3);
$link = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$errno = curl_errno($curl);
curl_close($curl);
if ($errno == 0 && $httpcode == 200 && strlen($link) > 0) { // No curl errors
return $link;
}
return '';
}
private function get_memcache() {
$usemem = false;
if (extension_loaded('memcache')) {
$usemem = true;
}
if ($usemem) {
$memcache_server = 'Your_memcacheserver';
$memcache_port = '11211';
$memcache = new Memcache;
$memcache->addServer($memcache_server, $memcache_port);
return $memcache;
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment