473,779 Members | 2,078 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Retrieve a Random Image URL From Google With PHP

1 New Member
A recent project involved me obtaining a random image from the Web and using it in 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 . '&start=' . $ofs . '&gbv=1';
  7.   $data=file_get_contents($geturl);
  8.  
  9.   $f1='<div id="center_col">';
  10.   $f2='<a href="/imgres?imgurl=';
  11.   $f3='&amp;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 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 GetRandomImageU RL() function:
Expand|Select|Wrap|Line Numbers
  1. function ShowRandomImage($topic='')
  2. {
  3.   echo('<table border="1"><tr><td>');
  4.   $url=GetRandomImageURL($topic);
  5.   if ($url==FALSE) echo('Error while searching');
  6.   else {
  7.     echo(htmlentities($url) . '<br />');
  8.     echo('<img width="640" src="' . $url . '" />');
  9.   }
  10.   echo('</td></tr></table>');
  11. }
  12.  
  13. ShowRandomImage();
  14. ShowRandomImage('rothschild');
  15.  
Enjoy!
Apr 12 '11 #1
2 17636
dgreenhouse
250 Recognized Expert Contributor
Although I haven't tested it, it looks pretty cool.
May 25 '11 #2
makakee
1 New Member
Hmmm, this doesn't seem to work anymore. Any ideas why?
Dec 11 '13 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

4
3418
by: kingofkolt | last post by:
I have a directory of images, called "random". In it are the following files: 1.gif 2.gif 3.gif 4.gif I use this script to choose a random image and display it:
6
3537
by: Olly | last post by:
I've found a basic script, however I also need to add alt and title attributes as well, how would I go about doing this? Here's the script I found: Thanks <script language="JavaScript"> <!-- /*
5
2595
by: Linda | last post by:
Greetings: I have found a random image script that I like. It is located here: http://www.javascriptcity.com/scripts/local/simage3.htm I'd like to edit this to have 4 different slots for images with a different set of 5 images for each slot, something like this page: http://www.uchsc.edu The script says /* no need to edit past this point (unless you want to
5
2194
by: Haydnw | last post by:
Hi, I have the code below as code-behind for a page which displays two images. My problem is with the second bit of code, commented as " 'Portfolio image section". Basically, the SQL query gets details of a random image from an access database. I know this works because when I run the query in access, it picks a different image each time (or close enough). However, when I view the .aspx page that this code-behind is for, it always picks...
2
2890
by: Jim in Arizona | last post by:
I was trying to create a random image generator. I'm using visual web dev express with 2.0 framework. On the web form page (mypage.aspx), I have an image control: <asp:Image ID="Image1" runat="server" /> On the codebehind, (mypage.aspx.vb), I have this code when a button is clicked:
6
3077
by: comp.lang.php | last post by:
/** * Generate the random security image * * @access public * @param $willUseFilePath (default false) boolean to determine if you will be using a file path * @param mixed $filePath (optional) file path to store image resource object contents * @see actual_path */
7
2350
by: Spartanicus | last post by:
Afaik the use of a <noscriptelement is frowned upon nowadays. For a JS random image changer I tried to use a replacement by having the script change the HTML src attribute value of an img element. The trouble is that in some situations like over slow connections (on initial load when the JS is in an external file), or with a slow client the image specified in the HTML starts to load and display before it's changed by the script. This I'm...
4
3083
by: Kim | last post by:
Random image downloader for specified newsgroup. Hi I'm writing a small script that will download random images from a specified newsgroup. I've imported yenc into the script but I can't open the image or save it. This is my first script so be gentle! Heres the script ####random group downloader#### import nntplib import string, random import mimetools import StringIO
3
3591
by: fran7 | last post by:
Hi, I have this nice code that returns a random image database record. It works great. What I am trying to do now is to be able to get the "alt" description for the image from another field. If I add another field to the query it returns two images. I was making the alt alt=""" & recordset(i) & """ but I know that must be wrong. well it works but returns the image name, ie images/friday.jpg. Anyone know how I can get it to return the image...
0
9474
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10306
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10139
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10075
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9931
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7485
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5504
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4037
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2869
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.