Video Streaming PHP Script Tutorial

One of the most important features in a website is the ability to show videos to your visitors. There are a lot of video hosting solutions nowadays, with YouTube as the most popular. However, due to its popularity, there are lots of services — even free services — that let viewers download your video files after you’ve uploaded them to YouTube. If you need to restrict downloading of your files, keep reading.

If your videos are for viewing purposes only and you need to strictly restrict downloading, then this tutorial can help you. Unlike YouTube, where all your uploaded videos are viewable in a single channel (thus any infringer can easily locate and download all of them), if you use the technique discussed in this tutorial then viewers cannot locate where you have saved all of your videos.

The benefits of using this application include:

  • Obfuscation of the real URL path to your video file.
  • Saving the bandwidth that would otherwise be expended from massive amounts of downloading due to an exposed directory.
  • Increased protection of your copyrighted video content online.

This is not a perfect solution, but it will add an extra layer of security which makes it very hard for ordinary surfers to download your protected video content. If you are interested, then keep reading.

Important Requirements

This PHP script application will NOT work in all hosting scenarios. Before you will implement this in your web server, consider the following requirements carefully to make sure your hosting features supports it.

  • Enable readfile/fopen PHP functions. You can use your phpinfo or ask your web hosting support about this. In my experience, these are only disabled in free web hosting accounts for security reasons.
  • You must be able to use FTP and MySQL databases. Some web hosting companies, particularly the free ones, will not support FTP or even MySQL databases, so you cannot implement this script.
  • Your hosting account must allow you to upload video files such as MPG, WMV or MOV, etc.
  • You must have a LAMPP hosting configuration. This means your server will be using the Linux operating system in Apache and a MySQL environment, using the PHP server side scripting language.

{mospagebreak title=Design of the Application}

The way basic HTML web tutorials teach us to embed videos is VERY basic and does not protect your content. The techniques taught pose a lot of risks for having your protected content easily snatched. (If you do NOT care that your video gets downloaded without your permission, then this tutorial is not for you).

For example, in this HTML embed code:


<embed src="http://www.yourwebsite.com/video/cute.mpg"

autostart="false" />


If you use that method of embedding videos, then any user can view the source code of your web page (using a browser) and look for the video path URL designated by SRC. One thing is obvious; you are placing videos in the “yourvideofolder” directory. The worst will happen if you allowed “directory listing” in your website. This means all of your precious videos can be seen in a single glance, for example below:


What if you disable directory listing using .htaccess? It is still obvious; hackers will only make a slight guess at your file names, and can do so by examining your naming conventions and content (even determined ordinary web surfers can do this). If you make nonsense filenames, it might work, but a lot of determined infringers will query your folder path for nonsense reasons, which consumes a lot of server bandwidth.

The best way is to NOT provide them a clue as to where you have saved your videos in the server. The moment they view the source code and see a PHP file in your SRC tag instead of .mpg, most of them will turn back, but again, this is not a perfect solution.

You can use the PHP language and MySQL to do this; your goal is to transform the real path URL, say http://www.yourwebsite.com/video/cute.mpg, into http://www.yourwebsite.com/phpvideostreaming.php?ID=34fdgf56ghghg5656534

The PHP file effectively obfuscates the real path of your video URL. However, the real URL path will be stored in the MySQL database. How will PHP fetch the correct real URL path for a specific request? The answer is, by using an “ID” system.

The ID (in my example, it uses 20 alphanumeric characters) is unique and corresponds to a certain URL saved in the MySQL database. You can use this tool to generate characters. Remember to uncheck “include symbols in password.” For an example of an ID and Real URL path MySQL table (rough design, actual MySQL table screenshot in the next section), look at this:

PHP will query  the MySQL database using the ID to get the equivalent real URL path to stream. This will be discussed in detail later.

{mospagebreak title=Upload video files and create a MySQL table}

Create a folder in your FTP server using a NOT so common name (the name of your pet maybe). And then upload your files to this folder. When it’s done, create a new MySQL table consisting of the following three important fields:

1. id

2. realurl

3. videotitle


For security purposes, it is important restrict the number of characters in your field. Read the article at the link for some MySQL database design tips.

Your objective is to make sure that your MySQL table at least looks like the one below:



Create a page for your embedded content

Okay, now you have database tables for your ID and equivalent real URL video path. You will need to create a page where you will embed your content. Currently this is the one I use (replace with your own URL where appropriate):

<OBJECT id=WindowsMediaPlayer1 width=320 height=264 hspace=5

vspace=5 classid=clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6 border="5" align="middle">

<param name="URL" value="http://www.php-developer.org/streamthisvideo.php?ID=snN0CuN5WDwV26331loq8" ref>

<param name="rate" value="1">

<param name="balance" value="0">

<param name="currentPosition" value="0">

<param name="defaultFrame" value>

<param name="playCount" value="1">

<param name="autoStart" value="-1">

<param name="currentMarker" value="0">

<param name="invokeURLs" value="-1">

<param name="baseURL" value>

<param name="volume" value="50">

<param name="mute" value="0">

<param name="uiMode" value="full">

<param name="stretchToFit" value="-1">

<param name="windowlessVideo" value="0">

<param name="enabled" value="-1">

<param name="enableContextMenu" value="-1">

<param name="fullScreen" value="0">

<param name="SAMIStyle" value>

<param name="SAMILang" value>

<param name="SAMIFilename" value>

<param name="captioningID" value>

<param name="enableErrorDialogs" value="0">

<param name="_cx" value="9260">

<param name="_cy" value="9790">

<EMBED type=’application/x-mplayer2′

pluginspage=’http://microsoft.com/windows/mediaplayer/en/download/’

id=’mediaPlayer’ name=’mediaPlayer’ displaysize=’4′ autosize=’-1′

bgcolor=’darkblue’ showcontrols="true" showtracker=’-1′

showdisplay=’0′ showstatusbar=’-1′ videoborder3d=’-1′ width="320" height="264"

src="http://www.php-developer.org/streamthisvideo.php?ID=snN0CuN5WDwV26331loq8" autostart="true" designtimesp=’5311′>

</EMBED>

</OBJECT>


Important: Do not forget to save the file with a .php extension.

{mospagebreak title=The PHP script: Streamvideo.php}

The video PHP is very similar to the PHP MP3 streaming script.

The things that are changed are the following:

1. Database table field names (though they are still very similar).

2. Minor parts of PHP validation.

3. The content type header, from the mp3 format to: header(‘Content-type: video/mpeg’);


The third item is the most important change. If you are using this script for other video file types, use the appropriate content type header.

The revised PHP script is shown below:


<?php


//Validate text input

if (! preg_match(‘/^[-a-z.-@,'s]*$/i’,$_GET['ID']))

{

die(‘Invalid name proved, the name may only contain a-z, A-Z, 0-9, "-", "_" and spaces.’);

}

else

$empty=strlen($_GET['ID']);

if ($empty==0)

{

die(‘The text field cannot be empty’);

}

else

{

//the input data is clean, retrieve text data input

$ID = $_GET['ID'];

}

//Connect to MySQL database after sanitizing the data

$username = "**********";

$password = "**********";

$hostname = "**********";

$database = "**********";

$dbhandle = mysql_connect($hostname, $username, $password)

or die("Unable to connect to MySQL");

//select a database to work with

$selected = mysql_select_db($database,$dbhandle)

or die("Could not select $database");

//Escape variables for use in MySQL

$ID = mysql_real_escape_string(stripslashes($ID));

// sending query

$result = mysql_query("SELECT `realurl` FROM `videostreaming` WHERE `id`=’$ID’")

or die(mysql_error());

// store the record of the "example" table into $row

$row = mysql_fetch_array( $result )

or die("Invalid query: " . mysql_error());

// Print out the contents of the entry

$direction = $row['realurl'];

//close the connection

$path=’http://’.$direction;

header(‘Content-type: video/mpeg’);

header(‘Content-Length: ‘.filesize($path)); // provide file size

header("Expires: -1");

header("Cache-Control: no-store, no-cache, must-revalidate");

header("Cache-Control: post-check=0, pre-check=0", false);

readfile($path);

mysql_close($dbhandle);

?>


You can download the script and view the demo.

[gp-comments width="770" linklove="off" ]

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort