Thursday, 7 April 2016

Detect and Extract youtube videos using php



Hi my fellow web masters, here is another fresh tutorial, if sometime and now you want users to share youtube videos on your social website, this tutorial perhaps will meet your need, i know there are many people out there who really need this, just like facebook did, detect and extract youtube video from users update,

This tutorials is all about how we can detect and extract youtube video url using php and still play the video on third party site, to detect if user post is url we are going to use php preg_match function

 Download



This php line of code will just do fine

// user post
$postdata ="THE SOCIAL NETWORK APP V.1.0 https://youtu.be/PGpbVQsVyRc Build Your Own Social Network";
 //if Youtube url detected;
if(preg_match('~(?:https?://)?(?:www.)?(?:youtube.com|youtu.be)/(?:watch\?v=)?([^\s]+)~', $postdata, $match)){
echo "
<iframe width='560' height='315' src='http://www.youtube.com/embed/".$match[1]."' frameborder='0' allowfullscreen></iframe>
";
//print ($match[1]);
}


The code above will now chech the user post, if post contain url and if the url domain is youtube then past the video value to array $match[1]


I am using the jQuery Form Plugin which will allows me to easily send data without page load and refresh.
The Form Plugin API provides several methods that allow you to easily manage form data and form submission.
ajaxForm
Prepares a form to be submitted via AJAX by adding all of the necessary event listeners. It does not submit the form. Use ajaxForm in your document's ready function to prepare your form(s) for AJAX submission. ajaxForm takes zero or one argument. The single argument can be either a callback function or an Options Object.

Note: You can pass any of the standard $.ajax options to ajaxForm

Example:

$('#myFormId').ajaxForm();



Here is how you can get the YouTube Video ID from a URL no matter how many extra parameters get passed along with it.
I had implement this plugin on Wall Script Social Network Version 1.0,  let specify thing to do, first we are going to create database where it will hold and store all our post from users. Let’s call the database urldetect.


-- Database: `labs`

Source code for urldetect table, this table holds all our post from users


-- Database: `labs`
-- Table structure for table `urldetect`
--
CREATE TABLE IF NOT EXISTS `urldetect` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `post` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=90 ;


Code for index.html

Index.html is where we want to dispaly our post Let create our index.html page and add the code blow to it


<style>
body
{
font-family:Arial, Helvetica, sans-serif;
font-size:12px;
}
#contentbox
{
width:740px; height:100px;
border:solid 2px #dedede;
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
margin-bottom:6px;

}
.userbox
{
width:200px; height:20px;
border:solid 2px #dedede;
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
margin:6px;
padding: 4px;
font-style:italic;
}
</style>




Include these javascript file in your header file


// include at head
<!-- <script type="text/javascript" src="js/jquery.min.js"></script>
<script src="js/jquery.form.js"></script> 
<script src="jsload.js"></script>

Past it into your body section


<div id='container'>
  <h1>
Detect Youtube Url From User Updates 
  </h1>
<form id="myForm" action="addpost.php" method="post">
 
    <textarea id="contentbox" id="post" name="post" required="">
    </textarea>
    
<label>
      <strong>User Name: 
      </strong> 
    </label>
    <input type="text" name="name" class="userbox" required="" value="" /> 
    <input type="submit" class="button"  value="Post" /> 
  </form>
<div id="updates">
    <div align="center">
      <img src="loader2.gif">
    </div>
</div>
</div>


Content.php source code

The code below will fetch users updates from db and load the post to index.html

$query = $db->query("SELECT * FROM urldetect ORDER BY id DESC");
//Count total number of rows
$rowCount = $query->num_rows;
while($data=mysqli_fetch_array($query))
{
// ##############  post contain Youtube link ###########
$postdata = $data['post'];
// ##############  Extracting Youtube cntent from post link ###########
echo '
<div class="stbody">
  <span class="timeline_square">
  </span>
  <div class="stimg">
    <img src="blake.jpg" />
  </div>
<div class="sttext">
    <span class="stdelete" title="Delete">X
    </span>
    <b>'.$data['name'].'
    </b>
    
'.$postdata.'
    <div class="sttime">
3 mins ago
    </div>
<div class="stexpand">
      ';
      //if Youtube url detected do run the following script below: display video;
      if(preg_match('~(?:https?://)?(?:www.)?(?:youtube.com|youtu.be)/(?:watch\?v=)?([^\s]+)~', $postdata, $match)){
      echo "
      
<iframe width='560' height='315' src='http://www.youtube.com/embed/".$match[1]."' frameborder='0' allowfullscreen>
      </iframe>
      
";
      //print ($match[1]); get v value from link v=Nnn4jMCzIgk
      }
      echo "
    </div>
</div>
</div>
";
}


Ajaxpost.php source code

Here we want to insert user post content and name to database table urldetect


// include database connection

if (isset($_POST['post'])) {

$name=$_POST['name'];
$post=$_POST['post'];
//echo "$name $comment";

//insert post to table urldetect
$db->query("INSERT INTO urldetect (name, post) VALUES ('$name', '$post')")
}

Ajax load content source code jsload.js

pass form data to ajaspost.php without page refrest


// wait for the DOM to be loaded 
setTimeout('#updates', 3000)
$(document).ready(function() { 
// bind 'myForm' and provide a simple callback function 
$('#myForm').ajaxForm(function() { 
$('#updates').load('content.php').fadeIn(3000);
$('#post').val("");
}); 
$('#updates').load('content.php').fadeIn(3000);
}); 

CSS file

Download Animate.css
Download Style.css

Download Jquery.form.js
Download Jquery.min.js

Your database connection

Connect to your database using mysqli

<?php
session_start();
//db details
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'labs';
//Connect and select the database
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
?>


Enjoy…




No comments:

Post a Comment

Hit me with a comment!