13.09.2016 Views

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

580 Chapter 27 Building User Authentication <strong>and</strong> Personalization<br />

This is the first script with any complexity to it that we have looked at in this application.<br />

It begins by including the application’s function files <strong>and</strong> starting a session. (When<br />

the user is registered, you create his username as a session variable, as you did in<br />

Chapter 23,“Using Session Control in <strong>PHP</strong>.”)<br />

The body of the script takes place in a try block because you check a number of<br />

conditions. If any of them fail, execution will fall through to the catch block, which we<br />

look at shortly.<br />

Next, you validate the input data from the user. Here, you must test for the following<br />

conditions:<br />

n Check that the form is filled out.You test this with a call to the function<br />

filled_out(), as follows:<br />

n<br />

if (!filled_out($_POST))<br />

We wrote this function ourselves. It is in the function library in the file<br />

data_valid_fns.php.We look at this function shortly.<br />

Check that the email address supplied is valid.You test this as follows:<br />

if (valid_email($email))<br />

n<br />

Again, this is a function we wrote; it’s in the data_valid_fns.php library.<br />

Check that the two passwords the user has suggested are the same, as follows:<br />

if ($passwd != $passwd2)<br />

n<br />

Check that the username <strong>and</strong> password are the appropriate length, as follows:<br />

if ((strlen($passwd) < 6)<br />

<strong>and</strong><br />

if ((strlen($passwd) > 16)<br />

In the example, the password should be at least 6 characters long to make it harder<br />

to guess, <strong>and</strong> the username should be fewer than 17 characters so that it will fit in<br />

the database. Note that the maximum length of the password is not restricted in<br />

this way because it is stored as an SHA1 hash, which will always be 40 characters<br />

long no matter the length of the password.<br />

The data validation functions used here, filled_out() <strong>and</strong> valid_email(), are shown<br />

in Listings 27.7 <strong>and</strong> 27.8, respectively.

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

Saved successfully!

Ooh no, something went wrong!