This document describes a PHP function that retrieves a random image URL from Google Images. The function takes optional parameters to specify a topic for the images or a random number range. It generates a random number, queries Google Images with that number as the "start" parameter, and parses the HTML response to extract the URL of the first returned image. Specifying a topic will return an image related to that topic. The function returns FALSE if the HTML parsing fails to find the necessary markers.
2. Ron Poulton
A recent project involved me obtaining a random image from the Web and using it in
P: 1 some specific fashion. I chose to use PHP to access Google Images for a random
image URL. The image could be generic or related to a specific topic.
Here's the PHP function that queries Google Images and returns an image URL:
Expand|Select|Wrap|Line Numbers
1. function GetRandomImageURL($topic='', $min=0, $max=100)
2. {
3. // get random image from Google
4. if ($topic=='') $topic='image';
5. $ofs=mt_rand($min, $max);
6. $geturl='http://www.google.ca/images?q=' . $topic . '&star
t=' . $ofs . '&gbv=1';
7. $data=file_get_contents($geturl);
8.
9. $f1='<div id="center_col">';
10. $f2='<a href="/imgres?imgurl=';
11. $f3='&imgrefurl=';
12.
13. $pos1=strpos($data, $f1)+strlen($f1);
14. if ($pos1==FALSE) return FALSE;
15. $pos2=strpos($data, $f2, $pos1)+strlen($f2);
16. if ($pos2==FALSE) return FALSE;
17. $pos3=strpos($data, $f3, $pos2);
18. if ($pos3==FALSE) return FALSE;
19. return substr($data, $pos2, $pos3-$pos2);
20.}
21.
This function generates a random number, sends that off as a "start" parameter with
an image query to Google, and grabs the HTML code generated. The "gbv=1"
parameter is required - without it, Google will return a generic page instead of the
image results.
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