Create Random Text in PHP
Want to put a random quote on your site? Or randomize some other aspect of your site? It’s easy. You’ll want to use PHP or some other server-side scripting language instead of a client-side scripting language like JavaScript. Server-side languages write the content to the page in html before it ever leaves the server. Search engines will be able to read the content on your page, but with JavaScript they cannot, so you lose any content value of the random code. Also, if a user turns off JavaScript, that random content is lost. Google, MSN, and Yahoo will see that the content is changing often, and that may help your rankings (depending on your implementation).
Here’s how to put the random elements into your page, using PHP.
Step 1:
Create a text file called “myData.txtâ€. Open the file and put in your random elements, placing each random element on its own line, (whether text, images or html). Then place “myData.txt†in the same directory as your page containing the PHP script.
Step 2:
Place the following PHP code into your page where you want the random element:
<?php
// Read text file
$myData ="myData.txt";
// Replace "myData.txt" with your file
// Read Text file
$myText = file("$myData");
// Generate random text
$myTexts = rand(0, sizeof($myText)-1);
// Print out text
$myRandomText=$myText[$myTexts];
echo $myRandomText;
?>
You’re done! See an example of it in action below. (Reload the page to see another quote.)
Random Quote:
“Character is like a tree and reputation like its shadow. The shadow is what we think of it; the tree is the real thing.”
– Abraham Lincoln