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:

http://www.youtube.com/watch?v=yWsqTrDJ_gU

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:

5MQ0QX870FE
yWsqTrDJ_gU
JyTawuNvQi0
HwRQ9dbti-4
_ziv_WeBLvo

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.

<?php

// 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);

?>

<object width="425" height="350"><param name="movie" value="http://www.youtube.com/v/<?php echo $video;? >"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/<?php echo $video;?>" type="application/x-shockwave-flash" wmode="transparent" width="425" height="350"></embed></object>

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.

Featured Resources

How to choose the right Identity Protection service.
Read our comparison of identity protection options to help you pick the best one for your family.

Master Home Movie Editing
Read a detailed guide on how to improve your home movies.

Instantly Fix Driver Problems
Find missing drivers on your XP or Vista PC.

Back up your iPod
iPod Access backs up your iPod music library and transfer songs to a new computer.

Convert Vinyl to MP3 or CD
Convert your Vinyl LPs and Cassettes to CD or MP3 using a simple software solution.

Subscribe for Free!

Your E-mail Address:

Ads