random quotes with PHP
- Posted Wednesday, June 8th, 2005 at 11:26 PM
- |
- PHP
Note: If you enjoy this article, you might also check out the Geeky Stuff section.
So you want to display a randomly selected quote on your page, and you want to use PHP to do it. It’s dang simple, let me tell you.
Requirements
- You need PHP support on your server. An easy way to test this is to stick
<?php phpinfo(); ?>into a .php file, upload that file to your server, and load it in your browser. If you get a huge table with information about your PHP setup, then you know you have PHP support. If you get a blank page, then you don’t have PHP. :(
Howto
- Create a file with one quote per line. Save it as
quotes.txt. - The file in which you want to display your random quote must be a PHP file (i.e. it must end in .php). Open this file and stick in the following:
<?php
$quotes = “/the/full/path/to/your/file/quotes.txt”;
$quotes = file($quotes);
srand((double)microtime() * 1000000);
$ranNum = rand(0, count($quotes)-1);
?>
It doesn’t matter where you put that. - In the area where you want your random quote displayed, insert the following:
<?php echo ($quotes[$ranNum]); ?>
If you want, you may take a look at my random quotes file (if you just want to read the quotes, may I suggest this prettier version).
Other Uses
You don’t have to use this for just random quotes, you know. Maybe you want to display a random image of yourself. You might use the following code:
<?php
$images = “/the/full/path/to/your/file/images.txt”;
$images = file($images);
srand((double)microtime() * 1000000);
$ranNum = rand(0, count($images)-1);
echo “<img src=\”";
echo ($images[$ranNum]);
echo “\” alt=\”Random image\”>”;
?>
And in this case, your images.txt file wouldn’t contain one random quote per line, but one image name per line. Example:
/images/john.jpg
http://www.example.com/tom.png
me.gif
I wrote something very similar a while ago for showing random images/quotes (it’s super basic)..
$max = count($quote);
$count = rand(1,$max);
(and then obviously put the quotes in an array.)
I remember trying to do this with JavaScript last year and to me at the time it seemed much more complex. I love PHP, it is my friend.