When you have video, and /or audio on your Web site, someone else can steal the audio and video directly taking the URL and display on their websites. This is what we call hotlinking. It take advantage of your bandwidths. Because it’s called directly from your server, every time the file are loaded on their website it cost you bandwidths.
This tutorial shows you how to prevent hotlinking, to block external access to video and audio files using ".htaccess", and PHP.
- The idee presented in this tutorial it's to change frequently, automatically, the name of the directories in which you have those files.

• To download the files, and example with the codes presented bellow, click: Prevent Hotlinking.

First, we create a code in ".htaccess" that allows accessing to specified files only from our domain, and from blank referrers (because Mozilla Firefox not send referrers information), and redirects the URL for those files to a PHP script.

Code for .htaccess to prevent hotlinking video and audio

RewriteEngine On

# set allowed referer. Replace "coursesweb" with your domain name
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?coursesweb.net [NC]
RewriteRule .(flv|mp4|ogg|mp3) / [NC,L]

# Redirect URL for files specified above, to a PHP file
RewriteRule ^/(vi|au)_([^\.]+\.(flv|mp4|ogg|mp3))$ redirect_va.php?fn=$2&tp=$1 [NC,L]

# Blocks the external access to dirsuffix.txt
<files dirsuffix.txt>
 order allow,deny
 deny from all
</files>

- Line 4 ( RewriteCond %{HTTP_REFERER} !^$ ) – Allow blank referrers.
- Line 5 – Site allowed to link the files (here coursesweb.net), replace with your Website domain name.
- Line 6 – File format to block. In between the () are file-extensions you intended to block from hotlinking. To add more seperate them with "|".
- Next Line redirects the URL to "redirect_va.php", passing the file name, and the type ("vi" indice for video, or "au" for audio).
- The last lines block the external access to "dirsuffix.txt", a file that store the suffix-name (changed frequently) for directories in which audio and video files are stored.

- To be more sure that the file can be accessed only from your website, it is better to use session too. If the page that streams the video or audio is generated with a .php file, add the following code to the beginning of that file, to create a Session that will be checked in "redirect_va.php" (as you can see added in "index.php", in the archive from the download link above).
session_start();
$_SESSION['getva'] = '1';

The PHP script

Create on the server a PHP file named "redirect_va.php", in this file we write a PHP script that changes frequently (60 minutes) the name of the directories in which the video and audio files are stored, than it redirects to the requested file.
In the same folder, create another file, named "dirsuffix.txt". In this file is registered the suffix used to form the directories name, and the Timestamp when the name was changed (for more explanations, see the coments in code).

PHP must have writable permissions to can write data in the "dirsuffix.txt" file, and to change the directory name.

Code for redirect_va.php

<?php
// Prevent Hotlinking video /audio - http://coursesweb.net/php-mysql/
session_start();

$fstore = 'dirsuffix.txt';       // file to register: suffix^timestamp
$base_dir_vi = 'video';          // basename for directory with videos
$base_dir_au = 'audio';          // basename for directory with audios

// array with values used to form /change directory name
$suffix = array('xyz5', 'de18', 'ab85', 'ju7k', 'w2er', 'hws8', 'bnji', 'hgdmar');

// check if session "getva" exists, and URL with GET "fn", and "tp" (redirected from .htaccess)
if(isset($_SESSION['getva']) && isset($_GET['fn']) && isset($_GET['tp'])) {
  // removes tags from data in GET, and gets the name and the indice for type
  $_GET = array_map("strip_tags", $_GET);
  $fname = trim($_GET['fn']);
  $ftype = trim($_GET['tp']);

  // get the basename for directory name, for video or audio, acording to $ftype
  $dir = ($ftype == 'vi') ? $base_dir_vi : $base_dir_au;

  // read the TXT file, separate suffix and timestamp
  $ardata = file($fstore, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  $pf_tm = explode('^', $ardata[0]);
  $sfx = $pf_tm[0];

  // if data older than 60 min, choose /get random a new suffix to form the directory name
  if(($pf_tm[1] + 3600) < time()) {
    $isf = array_rand($suffix, 1);
    $sfx = $suffix[$isf];
    if($sfx == $pf_tm[0]) $sfx = 'files';         // if it's the same suffix, set 'files'

    // register the new suffix^timestamp in the TXT file
    if(file_put_contents($fstore, $sfx.'^'.time())) {
      // checks if the directories for video and audio exists, and rename them
      if(is_dir($base_dir_vi.$pf_tm[0])){
        rename($base_dir_vi.$pf_tm[0], $base_dir_vi.$sfx);
      }
      if(is_dir($base_dir_au.$pf_tm[0])){
        rename($base_dir_au.$pf_tm[0], $base_dir_au.$sfx);
      }
    }
  }

  header('Location: '. $dir.$sfx. '/'. $fname);          // redirect to the requested file
}
?>

IMPORTANT :
1) Initially, the directory names that store the video and audio files must have the names: videofiles, respectively audiofiles, with "files" as suffix (because the directory name is formed by the basename (audio, or video) and the suffix registered in "dirsuffix.txt" (initially "files")).
If you want to use other name /basename for these directories, you have to change in "redirect_va.php" the values of the variables: $base_dir_vi, and $base_dir_au.

2) To can make the difference between requests to access video or audio file in ".htaccess", and "redirect_va.php", use in your player these prefixes to file name: the "vi_" for video, and the "au_" prefix for audio, like in these examples.
- For video:
<video controls="controls"width="200" height="150">
 <source src="vi_video_filename.mp4" type="video/mp4" />
 <source src="vi_video_filename.ogg" type="video/ogg" />
 Video not playing? <a href="vi_video_filename.mp4">Download file</a> instead.
</video>

- For audio:
<audio controls="controls">
 <source src="au_audio_filename.ogg" type="audio/ogg" />
 <source src="au_audio_filename.mp3" type="audio/mp3" />
 Your browser does not support the audio tag,
 <a href="au_audio_filename.mp3">Download file</a> instead.
</audio>
These prefixes must be added only to the file name in player, not to files on server. The file name on the server will be, for example: "video_filename.mp4", without "vi_".

Notice that the directory name isn't added in the player, so, the user can't see the location of the files. .htaccess will redirect to the PHP script ("redirect_va.php"), that will redirect to the location of the file.


• If in the page with the player you can't set a session (for example, because it is ".html" file), write this code in "redirect_va.php" (to not work with session). But the server must run PHP.
<?php
// Prevent Hotlinking video /audio - http://coursesweb.net/php-mysql/

$fstore = 'dirsuffix.txt';       // file to register: suffix^timestamp
$base_dir_vi = 'video';          // basename for directory with videos
$base_dir_au = 'audio';          // basename for directory with audios

// array with values used to form /change directory name
$suffix = array('xyz5', 'de18', 'ab85', 'ju7k', 'w2er', 'hws8', 'bnji', 'hgdmar');

// check if URL with GET "fn", and "tp" (redirected from .htaccess)
if(isset($_GET['fn']) && isset($_GET['tp'])) {
  // removes tags from data in GET, and gets the name and the indice for type
  $_GET = array_map("strip_tags", $_GET);
  $fname = trim($_GET['fn']);
  $ftype = trim($_GET['tp']);

  // get the basename for directory name, for video or audio, acording to $ftype
  $dir = ($ftype == 'vi') ? $base_dir_vi : $base_dir_au;

  // read the TXT file, separate suffix and timestamp
  $ardata = file($fstore, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  $pf_tm = explode('^', $ardata[0]);
  $sfx = $pf_tm[0];

  // if data older than 60 min, choose /get random a new suffix to form the directory name
  if(($pf_tm[1] + 3600) < time()) {
    $isf = array_rand($suffix, 1);
    $sfx = $suffix[$isf];
    if($sfx == $pf_tm[0]) $sfx = 'files';         // if it's the same suffix, set 'files'

    // register the new suffix^timestamp in the TXT file
    if(file_put_contents($fstore, $sfx.'^'.time())) {
      // checks if the directories for video and audio exists, and rename them
      if(is_dir($base_dir_vi.$pf_tm[0])){
        rename($base_dir_vi.$pf_tm[0], $base_dir_vi.$sfx);
      }
      if(is_dir($base_dir_au.$pf_tm[0])){
        rename($base_dir_au.$pf_tm[0], $base_dir_au.$sfx);
      }
    }
  }

  header('Location: '. $dir.$sfx. '/'. $fname);          // redirect to the requested file
}
?>

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag create a highlighted bolded text?
<q> <strong> <em>
<p>Address: <strong>http://CoursesWeb.net/</strong> - Tutorials.</p>
Which of these CSS codes displays the text bolded?
text-size: 18px; font-style: italic; font-weight: 800;
#id {
  font-weight: 800;
}
What JavaScript function can be used to call another function multiple times, to a specified time interval?
setInterval() setTimeout() push()
function someFunction() { alert("CoursesWeb.net"); }
setInterval("someFunction()", 2000);
Click on the correctly defined variable in PHP.
var vname = 8; $vname = 8; $vname == 8;
$vname = 8;
echo $vname;
Prevent Hotlinking / Block External Access to Video and Audio files

Last accessed pages

  1. Strategy Games (6364)
  2. Countdown Timer until specified Date-Time (3697)
  3. The Rise Of Atlantis (8188)
  4. PHP Laravel Tutorials (75)
  5. CSS Rhombus Shape (3249)

Popular pages this month

  1. Bubbles3 (3679)
  2. Butterfly Kyodai (3286)
  3. Zuma Deluxe (2405)
  4. Qwop (1692)
  5. Backgammon (1412)