13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Using Basic Authentication with Apache’s .htaccess Files<br />

405<br />

Listing 17.8 .htpass— The Password File Stores Usernames <strong>and</strong> Each User’s<br />

Encrypted Password<br />

user1:0nRp9M80GS7zM<br />

user2:nC13sOTOhp.ow<br />

user3:yjQMCPWjXFTzU<br />

user4:LOmlMEi/hAme2<br />

Each line in the .htpass file contains a username, a colon, <strong>and</strong> that user’s encrypted<br />

password.<br />

The exact contents of your .htpass file will vary.To create it, you use a small program<br />

called htpasswd that comes in the Apache distribution.<br />

The htpasswd program is used in one of the following ways:<br />

htpasswd [-cmdps] passwordfile username<br />

or<br />

htpasswd -b[cmdps] passwordfile username password<br />

The only switch that you need to use is -c. Using -c tells htpasswd to create the file.<br />

You must use this for the first user you add. Be careful not to use it for other users<br />

because, if the file exists, htpasswd will delete it <strong>and</strong> create a new one.<br />

The optional m, d, p, or s switches can be used if you want to specify which encryption<br />

algorithm (including no encryption) you would like to use.<br />

The b switch tells the program to expect the password as a parameter rather than<br />

prompt for it.This feature is useful if you want to call htpasswd noninteractively as part<br />

of a batch process, but you should not use it if you are calling htpasswd from the comm<strong>and</strong><br />

line.<br />

The following comm<strong>and</strong>s created the file shown in Listing 17.8:<br />

htpasswd -bc /home/book/.htpass user1 pass1<br />

htpasswd -b /home/book/.htpass user2 pass2<br />

htpasswd -b /home/book/.htpass user4 pass3<br />

htpasswd -b /home/book/.htpass user4 pass4<br />

Note that htpasswd may not be in your path: If it is not, you may need to supply the<br />

full path to it. On many systems, you will find it in the /usr/local/apache/bin<br />

directory.<br />

This sort of authentication is easy to set up, but there are a few problems with using<br />

an .htaccess file this way.<br />

Users <strong>and</strong> passwords are stored in a text file. Each time a browser requests a file that is<br />

protected by the .htaccess file, the server must parse the .htaccess file <strong>and</strong> then parse<br />

the password file, attempting to match the username <strong>and</strong> password. Instead of using an<br />

.htaccess file, you could specify the same things in your httpd.conf file—the main

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!