Here's the PHP function that queries Google Images and returns an image URL:
Expand|Select|Wrap|Line Numbers
- function GetRandomImageURL($topic='', $min=0, $max=100)
- {
- // get random image from Google
- if ($topic=='') $topic='image';
- $ofs=mt_rand($min, $max);
- $geturl='http://www.google.ca/images?q=' . $topic . '&start=' . $ofs . '&gbv=1';
- $data=file_get_contents($geturl);
- $f1='<div id="center_col">';
- $f2='<a href="/imgres?imgurl=';
- $f3='&imgrefurl=';
- $pos1=strpos($data, $f1)+strlen($f1);
- if ($pos1==FALSE) return FALSE;
- $pos2=strpos($data, $f2, $pos1)+strlen($f2);
- if ($pos2==FALSE) return FALSE;
- $pos3=strpos($data, $f3, $pos2);
- if ($pos3==FALSE) return FALSE;
- return substr($data, $pos2, $pos3-$pos2);
- }
If any markers ($f1, $f2 or $f3) are not found, the function will return FALSE. Otherwise, the first image (from the "start" parameter) is parsed, and the corresponding URL is retrieved.
Note that Google may alter its HTML along the way, making this function obsolete. Also, large "start" values seem to exceed the number of images Google is willing to display. At the time of this writing, the maximum was about 980.
The $topic parameter allows the option of specifying a certain type of image. Pass 'vehicle' and an image of a vehicle is the target; pass 'balloon', and.. well, you get the idea. Note that this isn't guaranteed to focus on a topic, as someone may have posted a picture with 'balloon' as an image tag but without any balloons in the picture.
Although any randomiser function could be used, mt_rand() is used here due to its speed and reasonable randomness.
This example function demonstrates the use of the above GetRandomImageURL() function:
Expand|Select|Wrap|Line Numbers
- function ShowRandomImage($topic='')
- {
- echo('<table border="1"><tr><td>');
- $url=GetRandomImageURL($topic);
- if ($url==FALSE) echo('Error while searching');
- else {
- echo(htmlentities($url) . '<br />');
- echo('<img width="640" src="' . $url . '" />');
- }
- echo('</td></tr></table>');
- }
- ShowRandomImage();
- ShowRandomImage('rothschild');