How to Randomize YouTube Videos with PHP

I recently got a question from someone about how to randomly display one of many YouTube videos in a player using PHP. I’m a hack when it comes to programming, but I came up with something that should do the trick in most cases. Basically, you put a YouTube video file on a single line of a text file, for as many videos as you want to randomize, then you use a couple lines of PHP to pick one of those IDs at random from the text file.

Here’s how to Randomize YouTube Videos with PHP:

I’m going to use a bunch of videos from Chris Pirillo’s Lockergnome channel on YouTube for my example, because he’s got a ton of stuff to choose from. Each of the video pages on YouTube has a URL that looks something like this:

The part you’re going to want to copy is everything after the equals sign, or in the example above: yWsqTrDJ_gU

Copy on that text into a text file, hit Enter and paste everything after the equals sign of the URL on the next video page on the following line. You’ll end up with a series of lines that look something like this:


Save this text file with a meaningful name and upload it to your Web server. Next you need to build the code to display your video. If you copy the following and paste it onto a page that supports PHP, replacing only the YourVideoList.txt with the path to your file, you should get a YouTube player with a randomized set of videos.


// Build an array from the list of YouTube videos
// Replace YourVideoList.txt with the path to your text file
// This will likely be something like /home/accountname/public_html/foldername/etc
$video_array = file('YourVideoList.txt');

// Randomly pick one video from the array
$video = $video_array[rand(0, count($video_array) - 1)];
$video = trim($video);


Note: Don’t copy anything beyond this point for your code.

Here’s an example of the whole thing in action. Hit refresh on your browser to see the video change.

<param name="movie"
type=”application/x-shockwave-flash” wmode=”transparent”
width=”425″ height=”350″>