[X]Random Image from PHP file returns same image on one page

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
AngusL
Forum Contributor
Posts: 155
Joined: Fri Aug 20, 2004 4:28 am
Location: Falkirk, Scotland

[X]Random Image from PHP file returns same image on one page

Post by AngusL »

Perhaps not the most descriptive title, sorry.

I'm using a very simple php script to return random images for use in signatures on forums, and when it is loaded more than once on one page, it still displays the same one image. It randomises correctly, but I would like, if possible, for it to display a different image each time it is loaded, by clearing the cache or whatever is required.

Image
Image
http://ae.flightsimcenter.com/ASASigs/ASASigs.php

Like so.

Code:

Code: Select all

<?php 
srand ((double) microtime( )*1000000); 
$random_number = rand(1,4); 
if( $random_number == 1 ) 
{ 
echo( readfile ("1st Sig.jpg") ); 
header( 'Content-type: image/jpg' ); 
} 
elseif( $random_number == 2 ); 
{ 
echo( readfile ("2nd Sig.jpg") ); 
header( 'Content-type: image/jpg' ); 
}
elseif( $random_number == 3 );
{
echo( readfile ("VASMSig1.jpg") );
header( 'Content-type: image/jpg' );
}
elseif( $random_number == 4 );
{
echo( readfile ("Firefox.gif") );
header( 'Content-type: image/gif' );
}
?>
There may be easier ways to do this, and I know you can load any image from a folder, but I'm pretty much a complete newbie to PHP, so bear with me. :)
Last edited by AngusL on Fri Aug 20, 2004 9:42 am, edited 1 time in total.
ast3r3x
Forum Commoner
Posts: 95
Joined: Thu Aug 19, 2004 8:36 pm

Post by ast3r3x »

I've done something like that for a photographer's website I was working on. http://www.jacklongphotography.com/seniors.php

Code: Select all

<?php

function ImageSelect()
{	
	$success = false;
	
	
		while($success == false)
		{
			$pick = rand(1,6);
			
			$imgimg = "{$pick}.jpg";
			
			if(file_exists($imgimg))
			{
				$success = true;
			}
		}
	}
	return $pick;
}

?>
I deleted some stuff for it to be more relevant to you but you get the idea. I just call it then with something like:

Code: Select all

&lt;IMG SRC="images/seniors/&lt;?php $pick = ImageSelect(); echo $pick; ?&gt;.jpg" alt="f off" &gt;
What you could actually do which I think would be easier, is make an array at the top of your page with all the images in. Then with the number you pick you could just output it into an array, and that array slot would correspond with a string, so you wouldn't have to have an whole bunch of if statements.

My code I showed may have been a bad idea, but the 2nd part with advice isn't :D (...at least until someone comes and tells me differently)

I'm want to see why this is happening though. It seems like it's just not loading it a second time.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post by pickle »

The only way to stop an image from being displayed twice in a row, is to store the currently displayed image client-side.

Code: Select all

//no need to seed the randomizer unless you've got a really old version
//of PHP.  The newer builds do it automatically
srand ((double) microtime( )*1000000);

while(($random_number = rand(1,4)) && ($random_number ==  $_COOKIE['angusl_sig']))
{}
setcookie('angusl_sig',$random_number);

if( $random_number == 1 )
{
echo( readfile ("1st Sig.jpg") );
header( 'Content-type: image/jpg' );
}
elseif( $random_number == 2 );
{
echo( readfile ("2nd Sig.jpg") );
header( 'Content-type: image/jpg' );
}
elseif( $random_number == 3 );
{
echo( readfile ("VASMSig1.jpg") );
header( 'Content-type: image/jpg' );
}
elseif( $random_number == 4 );
{
echo( readfile ("Firefox.gif") );
header( 'Content-type: image/gif' );
}
Also, I would suggest modifying your script to just pick a random image out of a directory, rather than hardcoding in the filenames. That will allow you to just throw images into the directory, and have this script use them.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
AngusL
Forum Contributor
Posts: 155
Joined: Fri Aug 20, 2004 4:28 am
Location: Falkirk, Scotland

Post by AngusL »

Oh right, thanks both, I'll go update my script now!
ast3r3x
Forum Commoner
Posts: 95
Joined: Thu Aug 19, 2004 8:36 pm

Post by ast3r3x »

THAT's how I did it. Good thinking. I forgot...and my example was, well basically completely useless. I actually made different directories and only selected one image from each, because I was doing something slightly different. Psh, shouldn't have been that hard to think of.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post by pickle »

~ast3r3x, most random image scripts are run a little differently than yours. The one I've made is just called like this:

Code: Select all

&lt;img src = "image.php?id=3"&gt;
Then, the image.php script loads and outputs the image. It makes your function a little longer, but makes your XHTML much cleaner.

image.php

Code: Select all

<?
//create connection to DB
$check_session = false;
require_once('/path/to/security/file');
$DBSession = new DB();//db abstraction class

$image_id = $_GET['image_id'];
$table = ($_GET['thumb'] == 'true') ? "thumbnails" : "images";

$query = <<<SQL
SELECT
*
FROM
$table
WHERE
entry_id = '$image_id'
SQL;

$result = $DBSession->sql_query($query,' retrieving image data');//maps to mysql_query($query)
$row = $DBSession->get_data($result);//equivalent to mysql_fetch_assoc();

header('Content-length: '.strlen($row[data]));//this line is important
header("Content-type: .$row[mime]");//this could be assumed if you didn't want to have multiple different filetypes.
echo $row[data];
?>
Keep in mind, this function takes the image data right from the db, not from the filestructure. It could be modified however, to load the image data from an address stored in the db.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
ast3r3x
Forum Commoner
Posts: 95
Joined: Thu Aug 19, 2004 8:36 pm

Post by ast3r3x »

pickle wrote:~ast3r3x, most random image scripts are run a little differently than yours. The one I've made is just called like this:

Code: Select all

&lt;img src = "image.php?id=3"&gt;
Then, the image.php script loads and outputs the image. It makes your function a little longer, but makes your XHTML much cleaner.

image.php

Code: Select all

<?
//create connection to DB
$check_session = false;
require_once('/path/to/security/file');
$DBSession = new DB();//db abstraction class

$image_id = $_GET['image_id'];
$table = ($_GET['thumb'] == 'true') ? "thumbnails" : "images";

$query = <<<SQL
SELECT
*
FROM
$table
WHERE
entry_id = '$image_id'
SQL;

$result = $DBSession->sql_query($query,' retrieving image data');//maps to mysql_query($query)
$row = $DBSession->get_data($result);//equivalent to mysql_fetch_assoc();

header('Content-length: '.strlen($row[data]));//this line is important
header("Content-type: .$row[mime]");//this could be assumed if you didn't want to have multiple different filetypes.
echo $row[data];
?>
Keep in mind, this function takes the image data right from the db, not from the filestructure. It could be modified however, to load the image data from an address stored in the db.
While I do like the idea better of just having the image source be a php script and having it choose an image rather then inserting PHP code into the XHTML page (your right, it's a lot cleaner), I'm not sure how your script is a random script. You seem to be calling a specific image.

Also I'm using MySQL which I don't believe supports storing images. Or else I need to redo my registering page for avatars.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post by pickle »

That script was just meant as an example of another way to output an image. This script should do the same thing from a file structure, and make it a random image. It's untested, but all the code here is from other functions I've written, so there shouldn't be a problem.

Code: Select all

//rand_image.php

$pic_dir = "/path/to/image/directory/on/server/"; 

  $handle = opendir($pic_dir);
  if ($handle = opendir($pic_dir))
    {
      while (false !== ($file = readdir($handle)))
        {
          if ($file != "." && $file != ".." && !is_dir($file))
            {
              $file_array[] = $file;
            }
        }
      closedir($handle);
       $file_path = $pic_dir . $file_array[array_rand($file_array)];
    }
  else
    {
      $file_path = $pic_dir . "01.jpg";
    }
}

  $filehandle = fopen($file_path,'rb');
  $image_data = fread($filehandle,filesize($file_path));
  fclose($filehandle);

  header('Content-length: '.strlen($image_data);
  header('Content-type: image/jpeg');
  echo $image_data;
}
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
ast3r3x
Forum Commoner
Posts: 95
Joined: Thu Aug 19, 2004 8:36 pm

Post by ast3r3x »

Oh ok. Well regaurdless, I like your way better, but because the photographers website is already ugly, I don't care about it enough to change it.
Post Reply