PHP CURL hack to display random image from keyword

NimaiNimai Registered Users Posts: 564 Major grins
Well, since throwing the gauntlet down over [thread=42580]here[/thread] didn't have much of an effect, I made a replacement for random.mg that is for keywords, not galleries.
For those of you with PHP on your servers, save this code as "randomkw.php":

UPDATE: New version caches the templatechange.mg output from SmugMug on your server, doubling performance!
<?php
ini_set('display_errors','1');
ini_set('display_startup_errors','1');
error_reporting(E_ALL & ~E_NOTICE);

$cachefile = 'randomkw.cache.html';
$cacheretention = 20;	// in minutes
$smugmug = $_GET['homepage'];
$keyword = $_GET['keyword'];
$size = $_GET['size'];
$result = '';

$cacheexists = file_exists($cachefile);
$now = time();
$cachetime = filectime($cachefile);
$cacheage = ($now - $cachetime)/60;
if( $cacheexists && ($cacheage < $cacheretention) ) {
	$f = fopen($cachefile,'r');
	if( $f ) {
		$result = fread( $f, filesize($cachefile) );
		fclose( $f );
	}
}

if( empty($result) ) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, "$smugmug/homepage/templatechange.mg?origin=$smugmug%2Fkeyword%2F$keyword&TemplateID=8" );
	curl_setopt($ch, CURLOPT_FAILONERROR, 1);
	curl_setopt($ch, CURLOPT_COOKIEJAR, "curlcookies");
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);// allow redirects
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
	curl_setopt($ch, CURLOPT_TIMEOUT, 10); // times out after 11s
	$result = curl_exec($ch); // run the whole process
	curl_close($ch);
	$f = fopen($cachefile,'w');
	if( $f ) {
		fwrite( $f, $result );
		fclose( $f );
	}
}

preg_match_all( '/imageID\[\d+\]\s*=\s*"(\d+)";/mx', $result, $imageid );

$index = rand(0,count($imageid[1])-1);
$id = $imageid[1][$index];
$src = "$smugmug/photos/$id-$size.jpg";

$ch = curl_init($src);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
header("Content-type: image/jpeg");
print( $data );
?>

Original non-caching version
<?php
ini_set('display_errors','1');
ini_set('display_startup_errors','1');
error_reporting(E_ALL & ~E_NOTICE);

$smugmug = $_GET['homepage'];
$keyword = $_GET['keyword'];
$size = $_GET['size'];

$ch = curl_init();    // initialize curl handle
curl_setopt($ch, CURLOPT_URL, "$smugmug/homepage/templatechange.mg?origin=$smugmug%2Fkeyword%2F$keyword&TemplateID=8" );
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, "curlcookies");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);// allow redirects
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
curl_setopt($ch, CURLOPT_TIMEOUT, 10); // times out after 11s
$result = curl_exec($ch); // run the whole process
curl_close($ch); 

preg_match_all( '/imageID\[\d+\]\s*=\s*"(\d+)";/mx', $result, $imageid );

$index = rand(0,count($imageid[1])-1);
$id = $imageid[1][$index];
$src = "$smugmug/photos/$id-$size.jpg";

$ch = curl_init($src);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
header("Content-type: image/jpeg");
print( $data );
?>
On your website, or bio box, etc. use the randomkw.php as the src for your img, for example:
<table width="100%">
<tr>
<td width="33%" align="center" valign="middle">
  <img src="http://bceboosterclub.org/randomkw.php?homepage=http://nimai.smugmug.com&keyword=WHS-cheerleading-2007&size=150x150&i=1" /></td>
<td width="33%" align="center" valign="middle">
  <img src="http://bceboosterclub.org/randomkw.php?homepage=http://nimai.smugmug.com&keyword=WHS-cheerleading-2007&size=150x150&i=2" /></td>
<td width="33%" align="center" valign="middle">
  <img src="http://bceboosterclub.org/randomkw.php?homepage=http://nimai.smugmug.com&keyword=WHS-cheerleading-2007&size=150x150&i=3" /></td>
</tr>
</table>
This renders a table with three random images based on the set of keywords supplied. I had to add something to make each img src different, so I tacked on i=n, where n is a unique number. That way the browser doesn't just try to reuse the same picture since the URL is the same.

So, the syntax is:

randomkw.php?homepage=xxx&size=yyy&i=zzz

homepage is your smugmug url, i.e. http://nimai.smugmug.com
size is the maximum X and Y dimensions, or S for Small, M for Medium, L for Large
i is just anything to uniquify the url

I hope this is useful to someone! Big thanks to Big Web Guy and DevBoBo for their trail-blazing.

Comments

  • SpeedieSpeedie Registered Users Posts: 173 Major grins
    edited September 24, 2007
    Hi,
    This looks great and just what I'm after but I can't get it to work for me. The URL I'm using is:
    http://www.mgpages.co.uk/misc/randomkw.php?homepage=http://digitalnature.smugmug.com&keyword=portfolio&size=100x100&i=1

    but as you can see it just shows me a page with the same URL in it. Not sure what I'm doing wrong - any ideas? (My web space supports php by the way).
  • NimaiNimai Registered Users Posts: 564 Major grins
    edited September 26, 2007
    Yikes!!

    Sorry- Looks like I had a copy/paste bug in there.
    The slashes in the CURLOPT_URL are represented (escaped) as %2F, so keyword/portfolio should have turned into keyword%2Fportfolio. I was missing the F! And then, in my sample, I had an extra F as the first letter of my keyword, so it worked for my case!

    11doh.gif

    How embarrasing. Thanks for reporting the problem. I'll fix the first post.
  • SpeedieSpeedie Registered Users Posts: 173 Major grins
    edited September 26, 2007
    Nimai wrote:
    How embarrasing. Thanks for reporting the problem. I'll fix the first post.
    No worries - works a treat now, many thanks. For the icing on the cake, is there any way to make the image a clickable link that takes you to the big version in your gallery?
  • NimaiNimai Registered Users Posts: 564 Major grins
    edited September 26, 2007
    Speedie wrote:
    No worries - works a treat now, many thanks. For the icing on the cake, is there any way to make the image a clickable link that takes you to the big version in your gallery?
    I made mine just take you to the keyword-gallery. In order to make one that has a link which takes you to that particular photo in it's gallery, you'd need some php code that returns the link <a href="..."> and the <img src="..."/>. The web page would need to use javascript and something like AJAX to call the PHP code, and change the href and src in unison. So, it's possible, but it's not a small step.
  • NimaiNimai Registered Users Posts: 564 Major grins
    edited September 28, 2007
    I added a new version of the PHP code that caches the response to the templatechange.mg SmugMug call on your server. If the file is over 20 minutes old, it reloads the data from SmugMug. Big performance increase! And it just feels better. :D

    It uses a file called "randomkw.cache.html" which I needed to create and give the proper permissions to make it writeable.

    Let me know if this works for you!
  • SpeedieSpeedie Registered Users Posts: 173 Major grins
    edited February 11, 2008
    Nimai wrote:
    I added a new version of the PHP code that caches the response to the templatechange.mg SmugMug call on your server. If the file is over 20 minutes old, it reloads the data from SmugMug. Big performance increase! And it just feels better. :D

    It uses a file called "randomkw.cache.html" which I needed to create and give the proper permissions to make it writeable.

    Let me know if this works for you!

    Thanks Nimai. I was still using the original version but this has now stopped working. I switched to the cached version but still no joy. Any chance of taking a look - I assume something has changed at SmugMug which has broken it. Is it to do with this?
  • SamirDSamirD Registered Users Posts: 3,474 Major grins
    edited July 22, 2009
    I'm interested in this if someone can get it working.
    Pictures and Videos of the Huntsville Car Scene: www.huntsvillecarscene.com
    Want faster uploading? Vote for FTP!
Sign In or Register to comment.