PHP – password protect folder/page etc

Problem
You need to password protect content in PHP simply using .htaccess

Solution
You will require two files, the .htaccess and the .htpasswd files that needs to be in the location (directory) of the protected data.

In the .htaccess in side of the protected directory enter the following code

AuthType Basic
AuthName “restricted area”
AuthUserFile /home/site/html/confidential-dir/.htpasswd
require valid-user

If you are not sure what the full path is use the phpinfo() and locate the DOCUMENT_ROOT value
When done create the .htpasswd file with the user name and password MD5 hash for the accounts allowed to access the content

mike:sngUJ0KlPVjwY
danny:fl4puWp0zz52

In the example above mike’s password is snowball and danny is flower. To generate this hash use one of the following links (all not tested):

  • in section .htpasswd Username & Password Generator (https://davidwalsh.name/web-development-tools)
  • http://tools.dynamicdrive.com/password/
  • http://www.htaccesstools.com/htpasswd-generator/

Tested Platform
PHP 5.6

Leave a Reply