How to embed YouTube videos in PHP?

PhpHtmlVideoYoutubeYoutube Api

Php Problem Overview


Can anyone give me an idea how can we show or embed a YouTube video if we just have the URL or the Embed code?

Php Solutions


Solution 1 - Php

You have to ask users to store the 11 character code from the youtube video.

For e.g. http://www.youtube.com/watch?v=Ahg6qcgoay4

The eleven character code is : Ahg6qcgoay4

You then take this code and place it in your database. Then wherever you want to place the youtube video in your page, load the character from the database and put the following code:-

e.g. for Ahg6qcgoay4 it will be :

<object width="425" height="350" data="http://www.youtube.com/v/Ahg6qcgoay4" type="application/x-shockwave-flash"><param name="src" value="http://www.youtube.com/v/Ahg6qcgoay4" /></object>

Solution 2 - Php

Do not store the embed code in your database -- YouTube may change the embed code and URL parameters from time to time. For example the <object> embed code has been retired in favor of <iframe> embed code. You should parse out the video id from the URL/embed code (using regular expressions, URL parsing functions or HTML parser) and store it. Then display it using whatever mechanism currently offered by YouTube API.

A naive PHP example for extracting the video id is as follows:

<?php
    preg_match(
        '/[\\?\\&]v=([^\\?\\&]+)/',
        'http://www.youtube.com/watch?v=OzHvVoUGTOM&feature=channel',
        $matches
    );
    // $matches[1] should contain the youtube id
?>

I suggest that you look at these articles to figure out what to do with these ids:

To create your own YouTube video player:

Solution 3 - Php

From both long and short youtube urls you can get the embed this way:

$ytarray=explode("/", $videolink);
$ytendstring=end($ytarray);
$ytendarray=explode("?v=", $ytendstring);
$ytendstring=end($ytendarray);
$ytendarray=explode("&", $ytendstring);
$ytcode=$ytendarray[0];
echo "<iframe width=\"420\" height=\"315\" src=\"http://www.youtube.com/embed/$ytcode\" frameborder=\"0\" allowfullscreen></iframe>";

Hope it helps someone

Solution 4 - Php

The <object> and <embed> tags are deprecated as per HTML Youtube Videos, it is preferable to use the <iframe> tag to do so.

<iframe width="420" height="315"
src="http://www.youtube.com/embed/XGSy3_Czz8k?autoplay=1">
</iframe>

In order for your users not spend their entire lifetime trying to find the video id in links to put it in your form field, let them post the link of the video they find on youtube and you can use the following regex to obtain the video id:

preg_match("/^(?:http(?:s)?:\/\/)?
    (?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|
    (?:embed|v|vi|user)\/))([^\?&\"'>]+)/", $url, $matches);

To get the video id you can fetch it $matches[1], these will match:

Part of this answer is referred by @shawn's answer in this question.

Solution 5 - Php

Use a regex to extract the "video id" after watch?v=

Store the video id in a variable, let's call this variable vid

Get the embed code from a random video, remove the video id from the embed code and replace it with the vid you got.

I don't know how to deal with regex in php, but it shouldn't be too hard

Here's example code in python:

>>> ytlink = 'http://www.youtube.com/watch?v=7-dXUEbBz70'
>>> import re
>>> vid = re.findall( r'v\=([\-\w]+)', ytlink )[0]
>>> vid
'7-dXUEbBz70'
>>> print '''<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/%s&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/%s&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object>''' % (vid,vid)
<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/7-dXUEbBz70&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/7-dXUEbBz70&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object>
>>>

The regular expression v\=([\-\w]+) captures a (sub)string of characters and dashes that comes after v=

Solution 6 - Php

Here is some code I've wrote to automatically turn URL's into links and automatically embed any video urls from youtube. I made it for a chat room I'm working on and it works pretty well. I'm sure it will work just fine for any other purpose as well like a blog for instance.

All you have to do is call the function "autolink()" and pass it the string to be parsed.

For example include the function below and then echo this code.

`
echo '<div id="chat_message">'.autolink($string).'</div>';

/****************Function to include****************/

<?php

function autolink($string){
    // force http: on www.
    $string = str_ireplace( "www.", "http://www.", $string );
    // eliminate duplicates after force
    $string = str_ireplace( "http://http://www.", "http://www.", $string );
    $string = str_ireplace( "https://http://www.", "https://www.", $string );

    // The Regular Expression filter
    $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
    // Check if there is a url in the text

$m = preg_match_all($reg_exUrl, $string, $match); 

if ($m) { 
$links=$match[0]; 
for ($j=0;$j<$m;$j++) { 
            
    if(substr($links[$j], 0, 18) == 'http://www.youtube'){
    
    $string=str_replace($links[$j],'<a href="'.$links[$j].'" rel="nofollow" target="_blank">'.$links[$j].'</a>',$string).'<br /><iframe title="YouTube video player" class="youtube-player" type="text/html" width="320" height="185" src="http://www.youtube.com/embed/'.substr($links[$j], -11).'" frameborder="0" allowFullScreen></iframe><br />';
     
    
    }else{
    
    $string=str_replace($links[$j],'<a href="'.$links[$j].'" rel="nofollow" target="_blank">'.$links[$j].'</a>',$string);
    
        } 
     
    } 
} 




               return ($string);
 }

?>

`

Solution 7 - Php

If you want to upload videos programatically, check the YouTube Data API for PHP

Solution 8 - Php

Searching for this same topic I found another method using Javascript an Youtube API's

Directly from: <http://code.google.com/apis/ajax/playground/#simple_embed>

Loading the API

<script src="http://www.google.com/jsapi" type="text/javascript"></script>

And executing the following javascript code:

  google.load("swfobject", "2.1");
  function _run() {

    var videoID = "ylLzyHk54Z0"
    var params = { allowScriptAccess: "always" };
    var atts = { id: "ytPlayer" };
    // All of the magic handled by SWFObject (http://code.google.com/p/swfobject/)
    swfobject.embedSWF("http://www.youtube.com/v/" + videoID + "&enablejsapi=1&playerapiid=player1",
                       "videoDiv", "480", "295", "8", null, null, params, atts);
    
    
  }
  google.setOnLoadCallback(_run);

The complete sample is in the previously referred page <http://code.google.com/apis/ajax/playground>

Solution 9 - Php

You can do this simple with Joomla. Let me assume a sample YouTube URL - https://www.youtube.com/watch?v=ndmXkyohT1M

<?php 
$youtubeUrl =  JUri::getInstance('https://www.youtube.com/watch?v=ndmXkyohT1M');
$videoId = $youtubeUrl->getVar('v'); ?>
		
<iframe id="ytplayer" type="text/html" width="640" height="390"  src="http://www.youtube.com/embed/<?php echo $videoId; ?>"  frameborder="0"/>

Solution 10 - Php

You can simply create a php input form for Varchar date,give it a varchar length of lets say 300. Then ask the users to copy and paste the Embed code.When you view the records, you will view the streamed video.

Solution 11 - Php

Just a small update to Alec Smart's answer: since AS2 is deprecated now, the '?version=3' is required to get his example to work. See the Youtube reference at [YouTube Embedded Players and Player Parameters][1] under "Selecting content to play" for details.

In other words:

<object width="425" height="350" data="http://www.youtube.com/v/Ahg6qcgoay4?version=3" type="application/x-shockwave-flash"><param name="src" value="http://www.youtube.com/v/Ahg6qcgoay4?version=3" /></object>

Apparently, the Youtube reference above does this as follows (the inner embed presumably used as a fallback for browsers that don't yet support the object tag):

<object width="640" height="390">
  <param name="movie"
         value="https://www.youtube.com/v/u1zgFlCw8Aw?version=3&autoplay=1"></param>
  <param name="allowScriptAccess" value="always"></param>
  <embed src="https://www.youtube.com/v/u1zgFlCw8Aw?version=3&autoplay=1"
         type="application/x-shockwave-flash"
         allowscriptaccess="always"
         width="640" height="390"></embed>
</object>

Or using iframes (replace http://example.com with your site's domain):

<iframe id="ytplayer" type="text/html" width="640" height="390" src="http://www.youtube.com/embed/u1zgFlCw8Aw?autoplay=1&origin=http://example.com" frameborder="0"/>

[1]: https://developers.google.com/youtube/player_parameters, "YouTube Embedded Players and Player Parameters"

Solution 12 - Php

luvboy,

If i understand clearly, user provides the URL/code of the Youtube video and then that video is displayed on the page.

For that, just write a simple page, with layout etc.. Copy video embed code from youtube and paste it in your page. Replace embed code with some field, say VideoID. Set this VideoId to code provided by your user.

edit: see answer by Alec Smart.

Solution 13 - Php

This YouTube embed generator solve all my problems with video embedding.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSatish RavipatiView Question on Stackoverflow
Solution 1 - PhpAlec SmartView Answer on Stackoverflow
Solution 2 - PhpSalman AView Answer on Stackoverflow
Solution 3 - PhpfankyView Answer on Stackoverflow
Solution 4 - PhpKADView Answer on Stackoverflow
Solution 5 - PhphasenView Answer on Stackoverflow
Solution 6 - PhpRossView Answer on Stackoverflow
Solution 7 - PhpChristian C. SalvadóView Answer on Stackoverflow
Solution 8 - PhpOscarRyzView Answer on Stackoverflow
Solution 9 - PhpakfaiselView Answer on Stackoverflow
Solution 10 - PhphaiderView Answer on Stackoverflow
Solution 11 - PhpRyan ShihView Answer on Stackoverflow
Solution 12 - PhpAkshayView Answer on Stackoverflow
Solution 13 - PhpPatartics MilánView Answer on Stackoverflow