Tutorials PHP Protect files using htaccess and htpasswd, and display using PHP

Protect files using htaccess and htpasswd, and display using PHP

Today's tutorial will be on how to serve and protect your files with PHP. Your server can only process code from PHP files so what about other kinds of files? Documents, PDFs, images and other files are all served as-is by the server. Anybody with the correct URL can get these files.

Securing your files

First step of is to secure the files on your server. You can put your files outside your public directory or you can use your .htaccess with Apache to restrict access to it.

If you're using Apache, create a folder on your server with a .htaccess file with the following code. This will prevent access to the folder and subfolders.

<Directory /folder_name>
Order Deny,Allow
Deny from all
</Directory> 

Retrieving the file

After verifying the user, you can use PHP to send the file. It uses the readfile function to deliver the file to the browser.

$file = 'private.jpg';

if (file_exists($file)) {
  header('Content-Description: File Transfer');
  header('Content-Type: application/octet-stream');
  header('Content-Disposition: attachment; filename='.basename($file));
  header('Content-Transfer-Encoding: binary');
  header('Expires: 0');
  header('Cache-Control: must-revalidate');
  header('Pragma: public');
  header('Content-Length: ' . filesize($file));
  ob_clean();
  flush();
  readfile($file);
  exit;
}

Demo:

http://www.phptrainee.com/files/private/index.html

Download: (You need to put these files on an Apache web server to work)

http://www.phptrainee.com/files/PHPtrainee.com_private-files.zip

That's it for this tutorial. Now you can allow or deny access to your files to different users.

Posted by on . Category: PHP


Comments

No comments posted yet

You need to register or login to post new comments.