Skip to content

Instantly share code, notes, and snippets.

@brockriemenschneider
Created April 7, 2013 17:00
Show Gist options
  • Save brockriemenschneider/5331313 to your computer and use it in GitHub Desktop.
Save brockriemenschneider/5331313 to your computer and use it in GitHub Desktop.
Code Example
<?php
class Instagram
{
private $api_feed = "https://api.instagram.com/v1/users/%s/media/recent/?count=6&access_token=%s";
private $api_user = "https://api.instagram.com/v1/users/search/?q=%s&count=1&access_token=%s";
private $access_token = "XXXXX";
private $file = './instagram.txt';
/**
* Fetches a instagram feed
*
* @param string $username
* A instagram username
*
* @return object
*/
function fetch( $username )
{
// check for a cached version...
if ( ! $instagram_feed = $this->get_cache( $this->file )) {
// retrieve the instagram user
$user_url = sprintf( $this->api_user, $username, $this->access_token );
$user = $this->curl( $user_url );
// make sure the user exists
if( isset($user->data[0]->id)) {
// retrieve the instagram feed for the user
$feed_url = sprintf( $this->api_feed, $user->data[0]->id, $this->access_token );
$feed = $this->curl( $feed_url );
// cache the feed
$this->cache( $this->file, $feed );
return $feed;
}
return false;
}
return $instagram_feed;
}
/**
* Fetches the contents of a website
*
* @param string $url
* The website to curl
*
* @return json
*/
function curl( $url )
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result);
}
/**
* Caches content to a file
*
* @param string $file
* The path of the file
*
* @param string $content
* The content to put in the file
*
* @return bool
*/
function cache( $file, $content )
{
// open the file for writing
$f = @fopen($file, 'w+');
// file did not open
if (!$f) {
return false;
}
// write the content to the file
$bytes = fwrite($f, json_encode($content));
// close the file
@fclose($f);
return true;
}
/**
* Retrieves the cached file
*
* @param string $file
* The name of the file
*
* @param int $seconds
* The the number of seconds the cache is valid for
*
* @return mixed (object, bool)
*/
function get_cache( $file, $seconds = 300)
{
$current_time = time();
$expire_time = $seconds * 60;
$file_time = filemtime($file);
// is the cache still valid?
if(file_exists($file) && ($current_time - $expire_time < $file_time)) {
return json_decode(file_get_contents($file));
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment