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.

Implementing Authentication with Session Control<br />

521<br />

The first thing you do in the script is call session_start().This call loads in the<br />

session variable valid_user if it has been created.<br />

In the first pass through the script, none of the if conditions apply, so the user falls<br />

through to the end of the script, where you tell her that she is not logged in <strong>and</strong> provide<br />

her with a form to do so:<br />

echo ‘’;<br />

echo ‘’;<br />

echo ‘Userid:’;<br />

echo ‘’;<br />

echo ‘Password:’;<br />

echo ‘’;<br />

echo ‘’;<br />

echo ‘’;<br />

echo ‘’;<br />

When the user clicks the submit button on the form, this script is reinvoked, <strong>and</strong> you<br />

start again from the top.This time, you will have a userid <strong>and</strong> password to authenticate,<br />

stored as $_POST[‘userid’] <strong>and</strong> $_POST[‘password’]. If these variables are set, you go<br />

into the authentication block:<br />

if (isset($_POST[‘userid’]) && isset($_POST[‘password’]))<br />

{<br />

// if the user has just tried to log in<br />

$userid = $_POST[‘userid’];<br />

$password = $_POST[‘password’];<br />

$db_conn = new mysqli(‘localhost’, ‘webauth’, ‘webauth’, ‘auth’);<br />

if (mysqli_connect_errno()) {<br />

echo ‘Connection to database failed:’.mysqli_connect_error();<br />

exit();<br />

}<br />

$query = ‘select * from authorized_users ‘<br />

.”where name=’$userid’ “<br />

.” <strong>and</strong> password=sha1(‘$password’)”;<br />

$result = $db_conn->query($query);<br />

You connect to a <strong>MySQL</strong> database <strong>and</strong> check the userid <strong>and</strong> password. If they are a<br />

matching pair in the database, you create the variable $_SESSION[‘valid_user’], which<br />

contains the userid for this particular user, so you know who is logged in further down<br />

the track:<br />

if ($result->num_rows >0 )

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

Saved successfully!

Ooh no, something went wrong!