PHP

Play Youtube video on repeat using PHP

Share Button

I coded this little useful utility few years back to overcome the pain caused by the lack of repeat button on Youtube. Hitting play button again and again really spoils the momentum of listening a song on repeat. Today I’ll share this code with you. This code requires basic understanding of PHP.

Understanding the logic

Each Youtube video has a video key, you can find this key in the video URL. Notice 11 jumbled characters after v=

1
https://www.youtube.com/watch?v=j1mxO-rL63k

Here j1mxO-rL63k is the video key.

Now comes the real trick – Create a Youtube playlist of two videos, play this on loop and if both the videos are same, then Youtube will end up playing the same video again and again. :)

Lets code now

For this utility first we need a simple html form to post Youtube URL, then we’ll extract the video id from the posted video URL.

  • isset($_POST['name']) is used to check whether user has submitted the form or not.
  • strpos($string1, $string2) finds the starting position of a substring in a given string.
  • substr($string1, x, y) finds the substring of a string starting from position x up to next yth character.

Here we are finding the position of v= and using this position to extract video id.

Now to generate a playlist with two same videos we are using a URL which is -

1
http://www.youtube.com/embed/VideoID?playlist=VideoID&autoplay=1&loop=1

This will create the desired playlist and loop=1 parameter will keep playing this playlist in loop. Finally I am using an iframe with some height and width to embed this video. And we are done. Voila :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<form method="post" action="">
    <input type="text" name="url" />
    <input type="submit" value="Submit" />
</form>

<?php

if(isset($_POST['url'])){
    $url = $_POST['url'];
}

$findme   = 'v=';
$pos = strpos($url, $findme);
$pos = $pos + 2;
$id = substr($url, $pos, 11);

if($pos!=2){
    echo '<iframe width="885" height="500" src="http://www.youtube.com/embed/' . $id . '?playlist=' . $id . '&autoplay=1&loop=1">';
}
else{
    echo 'Enter Youtube URL';
}

?>

A working example with added styling is here. I hope you learned something new. In case of any query, let me know in the comments. If you liked this article, share with friends.

Share Button