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


This php line of code will just do fine

// user post
$postdata ="THE SOCIAL NETWORK APP V.1.0 Build Your Own Social Network";
 //if Youtube url detected;
if(preg_match('~(?:https?://)?(?:www.)?(?|\?v=)?([^\s]+)~', $postdata, $match)){
echo "
<iframe width='560' height='315' src='".$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.
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



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`
  `name` varchar(100) NOT NULL,
  `post` text NOT NULL,
  PRIMARY KEY (`id`)

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

font-family:Arial, Helvetica, sans-serif;
width:740px; height:100px;
border:solid 2px #dedede;
font-family:Arial, Helvetica, sans-serif;

width:200px; height:20px;
border:solid 2px #dedede;
font-family:Arial, Helvetica, sans-serif;
padding: 4px;

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

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;
// ##############  post contain Youtube link ###########
$postdata = $data['post'];
// ##############  Extracting Youtube cntent from post link ###########
echo '
<div class="stbody">
  <span class="timeline_square">
  <div class="stimg">
    <img src="blake.jpg" />
<div class="sttext">
    <span class="stdelete" title="Delete">X
    <div class="sttime">
3 mins ago
<div class="stexpand">
      //if Youtube url detected do run the following script below: display video;
      if(preg_match('~(?:https?://)?(?:www.)?(?|\?v=)?([^\s]+)~', $postdata, $match)){
      echo "
<iframe width='560' height='315' src='".$match[1]."' frameborder='0' allowfullscreen>
      //print ($match[1]); get v value from link v=Nnn4jMCzIgk
      echo "

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'])) {

//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() { 

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

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


No comments:

Post a Comment

Hit me with a comment!