Skip to main content

Tracking and Securing Downloads

If you want to report or track downloads from your website, try this script.   This script will send you an email every time you have a download.   The email will tell you what file was downloaded and who did the download.   You could change this script to keep counts (store them in flat file or MySQL) if you desire.

The variable $directory is the directory where the download files are located.   If you want the script in the same directory as the files then use "./" as the directory (you must always have the slash).

In your html page, use the following structure as your download link (where name.txt is the file name to download):

<a href="download.php?file=name.txt">download</a>
Then you use the following script (called download.php):

- - Start Script Here - -
<?php
$emailaddress 
"email@yourdomain.com";$filename $_GET['file'];$directory "downloads/";$path "$directory$filename";putenv('TZ=EST5EDT'); // eastern time$downloadtime = (date(" F d h:ia"));$browser $_SERVER['HTTP_USER_AGENT'];$domain $_SERVER['HTTP_HOST'];$page $_SERVER['REQUEST_URI'];$referer $_SERVER['HTTP_REFERER'];$IP $_SERVER['REMOTE_ADDR'];$message "";$message .= "File name: $filename\n\n";$message .= "Time of the download: $downloadtime\n\n";$message .= "browser: $browser\n\n";$message .= "Page Requested: $domain$page\n\n";$message .= "Referer: $referer\n\n";$message .= "IP Address: $IP\n\n";$name gethostbyaddr($IP);$message .= "Hostname: $name\n\n";
if( 
file_exists($path) AND substr_count($filename,"/") == "0") {
  
header("Content-type: application/");
  
header("Content-Disposition: attachment; filename=$filename");
  
header("Content-Length: ".filesize($path));
  
readfile("$path");
  
mail($emailaddress"Download notification" $message"From: Website <>");
} else {
  
mail($emailaddress"Download error" $message"From: Website <>");
}
?>

- - End Script Here - -

You can then make the download files inaccessible from direct links if you put the following lines in a .htaccess file in the directory with the files:

RewriteEngine On
RewriteRule \.(txt|zip)$ /error.gif [L]


This example will redirect any attempt to directly access any .txt or .zip file in that directory to the error image specified.

Then if you want to stop direct linking to the script as well (this will pretty much secure the download from any hot-linking), add these two lines at the top of the script:

session_start();
if ($_SESSION['allowed'] != "yes") die('Inavlid download attempt');


And on the main page of your website you must set the session variable $_SESSION['allowed'] = yes;   Then anyone who has not been to your site during the current browser session will not be allowed to access the script either.

Custom Download Page
You can use the script below to create a custom dircetory list page.   This is a basic script that can be customized to achieve the look you want.   The script will automatically generate and link list of all the files in the directory that are of the types specified in the array variable, and only those file types.   Populate the array with file types in lower case only, the script will match case insensitive.   This is a good companion script to the File Upload Upload script on this page.

- - Start Script Here - -
<?php
$type 
= array(".jpg",".gif",".txt");
if (
$dir = @opendir("./")) {
  while ((
$file_select readdir($dir)) !== false) {
    
$type_test strtolower(strstr($file_select'.'));
    if (
in_array($type_test$type)) echo "<a href='$file_select'>$file_select</a><br>";
  }  
  
closedir($dir);
?>

- - End Script Here - -

You can reverse the file type test so all files except those with the specified file types are included in the list by changing the if test line to use this test:

if (!in_array($type_test,$type))

You can combine this with the Tracking and Securing Downloads Script by changing the <a href= in the script to this:

<a href='download.php?file=$file_select'>

This is a simple file upload script. It is a good starter example which can be customized to meet your needs.   This script will allow you to specify an upload directory, allowed file types, max file size and max space allowed to be used in the upload directory.   It will even send you an email letting you know there has been an upload to your website.   You need to change the variables at the top of the script as needed.

The specified upload directory can either be a directory relative to the location of the script (in the example the directory "./" is the directory where the script is located, "subdirectory/" would be one directory down from the script) or you can use the full Unix path.   Be sure to include a trailing slash on the directory.

If you want to upload files larger than 2MB there are changes required to the php.ini file.   See the Tip "Using a custom php.ini file" on this Tips & Scripts page.

- - Start Script Here - -
<?php
$emailaddress 
"mail@yourdomain.com";$this_script "upload.php";$home_page "home.htm";$uploaddir "./";$type = array(".jpg",".gif",".txt");  // enter in all lower case$maxSize 100000;$maxDisplay $maxSize 1000;$maxFileSpace 50000000;?><html><head></head><body>
<div style="text-align: center; left: 30%; top: 50px; position: absolute; border: 1px black solid; width:400px; height:300px;">
<?php// print_r($_FILES);  // can be used for debugging$file_name $_FILES['file']['name'];$file_size $_FILES['file']['size'];$file_tmp_name $_FILES['file']['tmp_name'];
if (
$file_name) {
  
$error "";
  echo 
"<br>File Name: $file_name<br><br>";
  echo 
"File Size: $file_size<br><br>";
  
// file size test
  
if ($file_size == $error .= "<font color=red>Invalid file</font><br>";
  if (
$file_size $maxSize $error .= "<font color=red>Your file exceeds $maxDisplay K.</font><br>";
  
// file type test
  
$type_test strtolower(strstr($file_name'.'));
  if (!
in_array($type_test$type) ) $error .= "<font color=red>Your file is not a valid file type.</font><br>";
  
// max directory size test
  
if ($dir = @opendir("$uploaddir")) {
    while ((
$file_select readdir($dir)) !== false) {
      
$type_test strtolower(strstr($file_select'.'));
      if (
in_array($type_test,$type)) {
        
$file_size_accum filesize("$uploaddir$file_select");
        
$total_size $total_size $file_size_accum;
      }
    } 
    
closedir($dir);
  }
  if ((
$total_size+$file_size) >= $maxFileSpace)  $error .= "<font color=red>Total file space limits have been exceeded.</font><br>";
  
// eliminate bad characters from the file name
  
$file_name stripslashes($file_name);
  
$file_name preg_replace("#[ ]#","_",$file_name);  // change spaces to underscore
  
$file_name preg_replace('#[^()\.\-,\w]#','_',$file_name);  //only parenthesis, underscore, letters, numbers, comma, hyphen, period - others to underscore
  
$file_name preg_replace('#(_)+#','_',$file_name);  //eliminate duplicate underscore
  // check for file already exists
  
if (file_exists("$uploaddir$file_name")) $error .= "<font color=red>File already exists.</font><br>";
  
// if all is valid, do the upload
  
if ($error == "") {
    if (
move_uploaded_file($file_tmp_name"$uploaddir$file_name")) {
      
chmod("$uploaddir$file_name"0644);
      echo 
"<font color=green>Your file was successfully uploaded!</font>";
      
mail($emailaddress"You have a file upload" $file_name"From: Upload <>");
    } else {
      echo 
"<font color=red>Your file could not be uploaded.</font>";
    }
  }
  echo 
"$error<hr>";
} else {
  echo 
"<br><br><br><br>";
}
?>Upload a <font color='blue'>
<?phpforeach($type as $print_type) { echo $print_type; }?></font> file to our server<br>
Maximum file size is <?=$maxDisplay?> K
<form action="<?=$this_script?>" method="post" enctype="multipart/form-data">
File: <input type=file name="file" size=30><br>
<input type=submit name="submit" value="Upload File"></form>
<a href="<?=$home_page?>">Return to the Home Page</a>
</div></body></html>

- - End Script Here - -

Comments

Popular posts from this blog

21 "teure" Arbeitsplätze in der Zukunft, vielversprechend und nur schwer durch künstliche Intelligenz zu ersetzen

Bei der Suche nach einem Arbeitsplatz sind die beiden Top-Belange, die Sie oft in Betracht ziehen,: Gehalt und Aussichten für die Zukunft. Vor kurzem hat das Bureau of Labor Statistics eine Zweijahresprognose der Entwicklung von Hunderten von Karrieren zwischen 2016 und 2026 veröffentlicht.


Auf der Grundlage der Prognosen und Schätzungen des durchschnittlichen Jahreseinkommens dieser Arbeitsplätze haben Forscher eine Rangliste der teuersten Berufe in der Zukunft veröffentlicht.
Hier werden 21 Stellen mit den höchsten Gehältern in den kommenden Jahrzehnten erwartet.
21. Landwirte, Viehzüchter, landwirtschaftliche Manager
20 Hauptaufgaben: Planen, verwalten, betreiben Sie den Betrieb, Gewächshaus, Aquakultur, Baumschule, Wald oder andere landwirtschaftliche Anlagen.
Anzahl der offenen Stellen im Jahr 2026: 68.700.
Durchschnittliches Einkommen im Jahr 2016: 66.360 USD.
Voraussetzungen: Abitur oder gleichwertig.
Computersystem-Analysator

Hauptaufgaben: Analyse von Datenverarbeitungsfrage…

The Flame Breathers

I write this narrative, not with the idea of contributing any additional scientific data to the discovery of Vulcan, but to put upon the record the real facts of our truly-amazing space voyage. The newscasters have hailed me as a modern Columbus. Surely I would not want to appear ungracious, unappreciative of all the applause that has been heaped upon me. But I do not deserve it. I did my job for my employers. The Society sent me to make a landing upon Vulcan—if the little planet existed. I found that it does exist; it was exactly where I was told it ought to be. I carried out my instructions, returned and made my report. There is no great heroism in that. So I am writing the facts of what happened. Just a bald, factual account, without the imaginative trimmings. The real hero of the discovery of Vulcan was young Jan Holden. He did his job—did it well—and he did something just a little extra. I'm Bob Grant, which of course you have guessed by now. Peter Torrence—the third member …

Der verschwindende Baum

Die Palme war einst am Stadtrand von Madurai reichlich vorhanden. Leider verschwindet der üppige Baum dank der raschen Verstädterung vom Horizont.
Raju legt seine Hände fest um den dunklen Kofferraum. Er befestigt den Knoten des Vadam um seine Beine und hüpft in weniger als fünf Minuten wie ein Frosch den 25 Fuß hohen Baum hinauf. Diese Bäume liegen mir sehr am Herzen. Ich umarme sie jeden Tag “, sagt Raju. Der Nungu-Verkäufer spricht von den Palmen, die für die Nungu-Verkäufer eine Einkommens- und Lebensgrundlage waren. Aber jetzt erscheint ihnen die Zukunft düster, da die Palmen rapide abnehmen. Die Stadt wächst und die Bäume werden gefällt, um Platz für Grundstücke zu machen, sagt Raju. „Früher war die Sivaganga Road von Palmen gesäumt, heute sind nur noch wenige übrig. Dies ist der Grund, warum der Preis für Palmen gestiegen ist. “

Umweltschützer sind auch besorgt über die sinkenden Zahlen. Die Panai Marams stammen aus dem südlichen Tamil Nadu und sind auch der Staatsbaum. "…