Software, your way.
burger menu icon
WillMaster

WillMaster > LibrarySecurity and Blocking

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

Authorized PDF Download

Sometimes a person wants to put a PDF on their website, but only for one person — not for search engine spiders or for anyone other than that one person.

The software with this article makes it possible by requiring a username and password. It can be used in either of two ways (these are live demonstration links):

  1. Provide a link to the PHP script with ?document.pdf appended to the URL. http://example.com/docs/downloadPDF.php?document.pdf is the link URL format.

    Live download PDF example link (horizontal scroll to see the entire URL):

    https://www.willmaster.com/possibilities/demo/downloadPDF/downloadPDF.php?document.pdf

    The username and the password for this demonstration are both the word "replace" (without the quotes).

  2. Provide what appears to be a link directly to the PDF file, but still requires a username and password before the file can be downloaded. http://example.com/docs/document.pdf is the link URL format.

    Live download PDF example link (horizontal scroll to see the entire URL):

    https://www.willmaster.com/possibilities/demo/downloadPDF/document.pdf

    The username and the password are the same as for the other method, the word "replace" (without the quotes).

Of the two methods, only the second requires an entry in the .htaccess file.

No separate password-protected directory is required.

Installing the Authorized PDF Download Software

Here is the source code for the authorized PDF download software. Customization information follows.

<?php
/*
   Authorized PDF Download
   Version 1.0
   January 7, 2018

   Will Bontrager Software LLC
   https://www.willmaster.com/
   Copyright 2018 Will Bontrager Software LLC

   This software is provided "AS IS," without 
   any warranty of any kind, without even any 
   implied warranty such as merchantability 
   or fitness for a particular purpose.
   Will Bontrager Software LLC grants 
   you a royalty free license to use or 
   modify this software provided this 
   notice appears on all copies.
*/

/* Customization area */
// See Willmaster Library article for additional information.
// Three places to customize.

// Place 1.
// Location relative to document root.

$LocationOfPDFdocs = "/location";

// Place 2.
// The username.

$Username = "replace";

// Place 3.
// The password may be plain text or 40-character sha1 encrypted. 
//   If plain text it may NOT be exactly 40 characters in length. 
//   (See https://www.willmaster.com/secure/encrypt.php to encrypt.)

$Password = "3cacc7bfac0a382c669a884c953d0401a689785d";

/* End of customization area */
/*****************************/

if( empty($_SERVER['QUERY_STRING']) ) { ExitWithMessage('Inappropriate access.'); }
$downloadfile = preg_replace('!^.*/!','',trim(urldecode($_SERVER['QUERY_STRING'])));
$LocationOfPDFdocs = preg_replace('!/$!','',$LocationOfPDFdocs);
$fileLocation = "{$_SERVER['DOCUMENT_ROOT']}$LocationOfPDFdocs/$downloadfile";
if( ! file_exists($fileLocation) ) { ExitWithMessage('Invalid file.'); }
if( ! ($filesize = filesize($fileLocation)) ) { ExitWithMessage('File is empty.'); }
$Username = trim(strtolower($Username));
$Password = trim($Password);
if( isset($_POST['un']) and isset($_POST['pw']) )
{
   $ok2proceed = true;
   $_POST['un'] = trim(stripslashes(strtolower($_POST['un'])));
   $_POST['pw'] = trim(stripslashes($_POST['pw']));
   if( $_POST['un'] != $Username ) { $ok2proceed = false; }
   else
   {
      if( strlen($Password) == 40 )
      {
         if( $Password != sha1($_POST['pw']) ) { $ok2proceed = false; }
      }
      else
      {
         if( $Password != $_POST['pw'] ) { $ok2proceed = false; }
      }
   }
   if( $ok2proceed )
   {
      header("Pragma: private");
      header("Expires: 0");
      header("Cache-Control: private, must-revalidate");
      header("Content-Type: application/octet-stream");
      header("Content-Disposition: attachment; filename=\"".$downloadfile."\"");
      header("Content-Transfer-Encoding: binary");
      header("Content-Length: $filesize");
      readfile($fileLocation);
      exit;
   }
}
function ExitWithMessage($s)
{
   echo $s;
   exit;
}
?><!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Authorized PDF Download</title>
<style type="text/css">
html, body { font-size:100%; font-family:sans-serif; }
p, input { box-sizing:border-box; }
input { font-size:100%; width:100%; }
#content { max-width:5in; margin:.5in auto; }
</style>
</head>
<body><div id="content">
<form method="post" enctype="multipart/form-data" accept-charset="utf-8" action="<?php echo(htmlspecialchars($_SERVER['PHP_SELF'])); ?>?<?php echo($downloadfile) ?>">
<p>
Provide credentials to download the <strong><?php echo($downloadfile) ?></strong> document.
</p>
<p>
Username:<br>
<input type="text" name="un">
</p>
<p>
Username:<br>
<input type="password" name="pw">
</p>
<p>
<input type="submit" value="Download PDF Document">
</p>
</form>
</div>
</body>
</html>

Three places in the above source code need to be customized.

  1. At about line 28:

    $LocationOfPDFdocs = "/location";

    Replace /location with the location of the downloadable PDF file. Make the location relative to document root (which would be its URL minus the leading http or https, ://, and domain name).

  2. At about line 33:

    $Username = "replace";

    Replace replace with the username for downloading the PDF document. The username is case-insensitive.

  3. At about line 40:

    $Password = "3cacc7bfac0a382c669a884c953d0401a689785d";

    Determine a password for downloading the PDF document. (The password is case-sensitive.) Then replace 3cacc7bfac0a382c669a884c953d0401a689785d with either:

    • The plain text of the password you determined. (The plain text password may not be exactly 40 characters long, else the software will think it's encrypted.)

    • The exactly 40-characters long sha1-encrypted version of the password. (You can get the encryption with the 40-character sha1 encryption form.)

When the customization has been done, upload the PHP source code to your server. Name it downloadPDF.php or any other name with .php file name extension.

Using the Authorized PDF Download Software

The following assumes you uploaded the PHP source code with file name downloadPDF.php, into a subdirectory named /docs, and that your domain is example.com.

To use the software, first upload your PDF document into the directory you specified in the first step of the customization notes. The following assumes the PDF file name is document.pdf.

As stated earlier, there are two ways the software can be used.

  1. A link URL that ends with /docs/downloadPDF.php?document.pdf.

  2. A link URL that ends with /docs/document.pdf.

The /docs/downloadPDF.php?document.pdf method —

This URL will download the PDF document:

http://example.com/docs/downloadPDF.php?document.pdf

The /docs/document.pdf method —

The .htaccess file in the /docs subdirectory needs these lines:

RewriteEngine on
RewriteCond %{REQUEST_URI} \.pdf$
RewriteRule ^(.*)$ /docs/downloadPDF.php?$1 [L]

If the subdirectory where you installed the PHP script is not /docs or the PHP script file name is not downloadPDF.php, then adjust /docs/downloadPDF.php accordingly.

With those lines in the .htaccess file, this URL will download the PDF document:

http://example.com/docs/document.pdf

Whichever method you use, the link will request a username and password to authorized the download.

(This article first appeared with an issue of the Possibilities newsletter.)

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2024 Will Bontrager Software LLC