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 />

403<br />

To get the same output as the preceding script, you need to create two separate<br />

HTML files: one for the content <strong>and</strong> one for the rejection page.We skipped some<br />

HTML elements in the previous examples but really should include <strong>and</strong> <br />

tags when generating HTML.<br />

Listing 17.5, named content.html, contains the content that authorized users see.<br />

Listing 17.6, called rejection.html, contains the rejection page. Having a page to show<br />

in case of errors is optional, but it is a nice, professional touch if you put something useful<br />

on it. Given that this page will be shown when a user attempts to enter a protected<br />

area but is rejected, useful content might include instructions on how to register for a<br />

password, or how to get a password reset <strong>and</strong> emailed if it has been forgotten.<br />

Listing 17.5<br />

content.html— Sample Content<br />

<br />

Here it is!<br />

I bet you are glad you can see this secret page.<br />

<br />

Listing 17.6<br />

rejection.html—Sample 401 Error Page<br />

<br />

Go Away!<br />

You are not authorized to view this resource.<br />

<br />

There is nothing new in these files.The interesting file for this example is Listing 17.7.<br />

This file needs to be called .htaccess <strong>and</strong> will control accesses to files <strong>and</strong> any subdirectories<br />

in its directory.<br />

Listing 17.7 .htaccess— An .htaccess File Can Set Many Apache Configuration<br />

Settings, Including Activating Authentication<br />

ErrorDocument 401 /chapter17/rejection.html<br />

AuthUserFile /home/book/.htpass<br />

AuthGroupFile /dev/null<br />

AuthName “Realm-Name”<br />

AuthType Basic<br />

require valid-user<br />

Listing 17.7 is an .htaccess file to turn on basic authentication in a directory. Many<br />

settings can be made in an .htaccess file, but the six lines in this example all relate to<br />

authentication.<br />

The first line<br />

ErrorDocument 401 /chapter17/rejection.html

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

Saved successfully!

Ooh no, something went wrong!