Tuesday, January 14, 2014

Validating and Embedding Youtube and Vimeo video dynamically using PHP

This function will help you to embed Youtube and Vimeo video dynamically. I made this for a project and now sharing it with you guys to use it in your projects or applications.
At the moment it's supporting Youtube and Vimeo URLs but soon i'll be adding support for other websites like Daliymotion etc.. When it will be completed i'll also share it with you through Github so follow me on Github https://github.com/thecodepress

Here's the function:
function v_embed($url) {
   $video = Array();
   $url = "video://".$url;
   if(strpos($url, "youtube")==true) {
      $host_pos = strpos($url, "youtube");
      $video["host"] = "youtube";
   }else if(strpos($url, "vimeo")==true) {
      $host_pos = strpos($url, "vimeo");
      $video["host"] = "vimeo";
   }else {
      $error = true;
   }

   if($video["host"]=="youtube") {
      $video["id"] = substr($url, strpos($url, "watch?v=")+8);
   }else if($video["host"]=="vimeo") {
      $video["id"] = substr($url, strpos($url, ".com/")+5);
   }else {
      $error = true;
   }

   if(isset($error)) {
      return false;
   }else {
      return $video;
   }
}

Example Usage:
After pasting the code it's looking non-indented so it's suggested to download the source files of this tutorial which contain the example.

Don't forget it's just a small piece of code which is used for a project..so if you find any changes then you can comment it below or if you want you can use it anywhere. Soon a repository will be available on Github which will support many other video platforms.

DOWNLOAD SOURCE FILES


Liked the post ? subscribe us with your email to get upcoming tutorials directly in your inbox:


1 comment:

Your Comment Will Be Visible After Approval, Thanks !