PDA

View Full Version : PHP - display random image(s) on your page.


mlseim
May 22 '06, 02:31 PM
Requirements:

1) Your webhost allows PHP scripting.
2) Your web page(s) have the extension .php
3) You have a directory with all of your photos uploaded
by number ... example: photo_1.jpg, photo_2.jpg, photo_3.jpg

At the beginning of your web page, right after <body>, insert this script:

<?php
srand(time());
$max=50; // This is the number of photo you have in your directory (eg. numbered 1-50)
$arr = array();
while ( count($arr) < $max ) {
$x = mt_rand(1,$max);
if ( !in_array($x,$arr) ) { $arr[] = $x; }
}
$p1 = "photo_".$arr[0].".jpg";
$p2 = "photo_".$arr[1].".jpg";
$p3 = "photo_".$arr[2].".jpg";
?>

In the script above, you have defined the number of photos you have in
your directory, in this case, there are 50 of them numbered 1-50 (photo_1.jpg, photo_2.jpg)

You will have 3 randomly picked photos ready to be used at any time.

You can display them by using any of the three $p variables ...
Giving the directory path, and then the PHP variable (which is the filename of your photo)...

<img src="./myphotos/<?=$p1?>" alt="my title">

or
<img src="./myphotos/<?=$p2?>" alt="my title">

Those three photos created in the script will all be different and random.
If you need more than 3 photos, add more:
$p4 = "photo_".$arr[3].".jpg";
$p5 = "photo_".$arr[4].".jpg";
$p6 = "photo_".$arr[5].".jpg";

Each time the page is refreshed or displayed, the 3 photos will randomly change.

Here's a working example:
http://www.pierreandclaudia.com

infiniti
May 24 '06, 04:09 PM
nice tut, easy to follow. Cool

hagen
May 30 '06, 07:27 AM
Though it's probably more than yo uare trying to demonstrate here, I do stuff like that like this:


$d = dir("gallery/$folder");
while (false !== ($entry = $d->read())) {
if (preg_match('/jpg/',$entry)) {
array_push($files, $entry);
}
}
$d->close();

IE get a list of the .jpg files in a folder then open them randomly as you have done above... you dont need to worry about the names then...

If you only wanted a specific number you could jump out of the loop...

:-)

-Hagen

dchesterton
June 5 '06, 08:27 PM
Hagen: That is a good idea in theory, probably won't work for many sites as it is very processor intensive, getting every file from a folder. :D

hagen
June 6 '06, 06:17 AM
Hi, dchesterton intresting... :-)

I guess you appreciate I am not getting the files but a file list....?

It's not something I had thought chould be significant...

Is this really going to be slow compared with connecting to a database for example?

Or with the internet latency itself?

Cheers

-H

hagen
June 6 '06, 06:51 AM
Here is a largish example with 70ish files....

http://www.taichiclub.co.uk/tai-chi-gallery.php

would you not expect the processor to make a single IO request to the "storage device"?

I guess it could be waiting around unable to do anything until the results come back...?

But then servers are multithreaded arn't they so would just run another job in the case of multiple users?

Let me know what you think! I know plenty about processors having worked on the design of a number of them, DSP's and microcontrollers over the years, but very little about system atchitecture... :nervous:

Cheers all


-Hagen

mlseim
June 7 '06, 10:42 AM
This is really a bandwidth issue?

If any PHP (or Perl) scripts are a burden, wouldn't the webhosts
find a way to charge the bandwidth ... that being my limitation to
how much system use I'm allowed?

Unless I'm amazon.com, or ebay, my site is probably not much of
a burden to a server, even if I get 1000 unique visitors per day.

If it was difficult for me to name my .jpegs in sequence, I would think
using Hagen's 'read directory' snippet would be a great way to grab
the list of .jpegs.

But then, that's what makes this forum the best ... an exchange of
ideas that get people thinking (and learning some new things).
This never ceases to amaze me.

dchesterton
June 7 '06, 01:03 PM
I'm not completely sure if there is a bandwidth issue. I was just trying to put ideas out there, I would guess it could get quite processor intensive with a lot of requests, to be completely honest i'm not sure :D but I would suspect it would be. Maybe someone knows for sure :confused:

hagen
June 7 '06, 01:33 PM
well it got me thinking!! :-)

...and if things started to grind to a halt and I had this kind of structure it would probably be one of the first places I could check now...

Cheers -H

P.S. I hope we will be designing sites on the same scale as eBay and friends very soon! :-)

ablaye
June 13 '06, 01:33 AM
You could also store the names of the images in your database and pick one randomly using this mysql statement:
select * from my_image_table order by rand() limit 1

hagen
June 13 '06, 05:02 AM
yes is a good plan or simply use a file...

in fact if you were worried about the server load you could run the above code I suggested and pipe the results into a file say once a day then use that...

put the results into an array then use php "shuffle($array)" to randomise...

:-)

-Hagen

mlseim
June 13 '06, 08:21 AM
See, I never thought of the MySQL approach ...

About getting a random image .... what if you wanted to get 3 images at
one time. Can you get 3 random numbers without repeating one of the
numbers?

hagen
June 19 '06, 09:14 AM
Yes MySQL... doesnt repeat with the following kind of access:

$result = mysql_query("SELECT * FROM huts ORDER BY rand($seed)") or die(mysql_error());

If your'e intrested here is how I make a daily seed for the psudo random number....
$seed = str_replace("0", "", date("d")) + (100 * str_replace("0", "", date("m")));


however you do it, it's really easy to just throw the file away and get another one even if it has already been displayed...

I do this by adding the filename to a string then using a preg_patch.... Or you could just use an array.... (The reason I use a string is I tend to pass it between pages....)

-Hagen

smoseley
June 19 '06, 01:01 PM
File-system access is inately slower than Database access. It is not significantly more processor intensive. It is, however, dependant on hard drive speed, vs. solid-state memory, and is therefore slower.

Accessing a file-list from your machine vs. an array list or database will therefore be slower, but recognizably so on a typical website. I use file-access for my homepage photo gallery, with no problems whatsoever.

You could alternatively store your file list into an array (in a php file referenced as an include, perhaps) and update that list daily. Then you'd have the best of both worlds.

:)

hagen
June 19 '06, 01:40 PM
Hi Steve, ahhhh yes of course the database is running in the DRAM.... thanks for the reminder...

Is it not going to get the photoes from the hard drive anyway? What about the pages? Guess there could be some caching... But an entire photo gallery? Spose its no different from haveing an entire database....

Even better, put your actual photo binaries, instead of the file names into the database, then pull them out from there...

(I know the ISP also caches pages to speed things up, because it can be very annoying for a designer!!...)

The multi user question still stands... A key question for me is: is the processor waiting while it has made a request to the memory device? I would think it would be busy working on other requests...

I would love some difinitive answers to this stuff, because its fairly core to what we do.... :-)

Shadowfiend
June 19 '06, 03:25 PM
Well, the benefits of having the database in RAM only manifest themselves while it stays in RAM. The second your data becomes too big and parts of the database start to get swapped onto the hard drive, the benefits start to decrease significantly.

On a related note, do databases really sit in RAM? I know the data itself is definitely stored on the hard drive, but I'm guessing the database uses algorithms to determine what parts of the db it should be keeping in RAM, since keeping everything there would be less than efficient. The biggest advantage with a database isn't, if I remember correctly, that it sits in RAM, but rather that, by analyzing your query, and by being able to load, for example, indices into RAM, it can look for the actual data on your hard drive in a more optimized fashion rather than just hunt through it to try and find what you need.

Moreover, let's not forget the overhead that is network communications when dealing with a database server on a separate computer. While in general it's definitely true that db access is faster, it's not always as simple as that, I daresay. I'm sure certain contexts lend themselves to flat files better than to databases, just as many contexts play nice with databases.

hagen
June 19 '06, 07:27 PM
The MySQL server should normally be tuned using the: key_buffer_size to avoid the system having to page.... Sorry I dont know exactly how the key buffer relates to the database size...

Should be less than 50% of the memory on a shared system...

My server has 4G.... Thats a 2G key buffer.... Anyway it is BIG before swapping occurs.... obviously BIG is a term which is relative to what you normally design....

I guess you would expect the server to go at least some times onto the hard drive to back things up, but also not entirely true.... There is a --memlock command to stop the system comming out of ram... I guess when you shut the server down it must save a restore point of some kind onto another device...

:-)

-Hagen

mlseim
June 20 '06, 09:55 AM
Well ... that is all informative ... but ...

My site doesn't quite get the number of visitors that Google, Ebay, or Amazon.com get.

I'm pretty sure that accessing a few images with each refresh isn't going to kill my server.

The scope of this tutorial was for PHP beginners that were interested in randomly
displaying some images. So, unless you're working for Ebay, feel free to use this tutorial.