Create Random Text in PHP

by Scott Allen

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:

”I love it when a plan comes together.”

— Hannibal Smith, The A-Team 

Tags:
| | |

Bookmark, Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • StumbleUpon
  • del.icio.us
  • Sphinn
  • Digg
  • Reddit
  • Netscape
  • Technorati
  • Ma.gnolia
  • YahooMyWeb
  • Slashdot
  • Spurl
  • Fark
  • Furl
  • BlinkList


If you enjoyed this post, make sure you subscribe to the RSS feed!


Email This to a Friend Email This to a Friend

Print This Post Print This Post


Related Posts:

  • Lorem Ipsum
  • About
  • End Blog Spam - Let Others Know About WP-SpamFree!
  • Search Engine Optimization (SEO) Tools #2 - Robots.txt Generator
  • SES NY Day 4 - Wrapping It Up, Along With Some Random Thoughts


  • About This Entry