SakhaliaNetHome PageHistory of the RailwayVorKutaAcceptance of cookiesAcceptance of cookies

PHP Tutorial :: Sessions (II)

PHP Example #82

User identification and connection

By default, a session sets an anonymous connection with a certain user. By allowing users to connect to the website we can identify them. The connection procedure usually consists of two data entries: an username (or e-mail address) and a password that verifies the user as legitimate. Once the user is connected, he/she has access to any functions that the website provides for their users. This process can be understood in five parts:

- Showing a form that asks for username and password

- Checking the values sent in the form

- Adding the username to the session if the credentials are correct

- Seeking for the username in the session to perform the available tasks

- Deleting the username from the session when the user logs out

This example shows how the three first tasks can be programmed. By sending matching pairs of the username/password provided in the array $users[], you can test how these are properly recognized by the program. Note that the error message is the same for username and password, to difficult the task of guessing the correct values to someone trying to get unauthorized access. The function htmlspecialchars() helps to avoid code injection in the form input.

<?php
// This is similar to the function input_text(), but prints a password field,
// on which asterisks hide the information facilitated
// This function is included as well in formhelpers.php
function input_password($element_name, $values) {
print '<input type="password" name="' . $element_name . '" value="';
print htmlspecialchars($values[$element_name]) . '">';
}

require 'scripts/formhelpers.php';
if ($_POST['_submit_check']) {
if ($form_errors = validate_form()) {
show_form($form_errors);
} else {
process_form();
}
} else {
show_form();
}
function show_form($errors = '') {
print '<form method="post" action="' . $_SERVER['PHP_SELF'] . '">';
if ($errors) {
print '<ul><li>';
print implode('</li><li>', $errors);
print '</li></ul>';
}
print 'Username: ';
input_text('username', $_POST);
print '<br/>';
print 'Password: ';
input_password('password', $_POST);
print '<br/>';
input_submit('submit', 'Log In');
print '<input type="hidden" name="_submit_check" value="1"/>';
print '</form>';
}
function validate_form() {
$errors = array();
$users = array('alice' => 'dog123',
'bob' => 'my^pwd', 'charlie' => '**fun**');
// Checks if the username is valid
$saved_user = htmlspecialchars($_POST['username']);
if (! array_key_exists($saved_user, $users)) {
$errors[] = 'Please enter a valid username.';
}
// Checks if the password matches
$saved_password = $users[htmlspecialchars($_POST['username'])];
if ($saved_password != htmlspecialchars($_POST['password'])) {
$errors[] = 'Please enter a valid password.';
}
return $errors;
}
function process_form() {
// Adds the username to the session
$_SESSION['username'] = htmlspecialchars($_POST['username']);
print "Welcome, $_SESSION[username].";
}
?>
Username:
Password:

PHP Example #83

Checking connected users

Once the user is included in the session (the array $_SESSION[]), we can use array_key_exists() to check the username in the pages where the connected user can perform actions.

<?php
if (array_key_exists('username', $_SESSION)) {
print "Hello, $_SESSION[username].";
} else {
print 'Howdy, stranger.';
}
?>
Howdy, stranger.

PHP Example #84

Password encryption

Storing passwords without encrypting them is an insecure practice. Passwords can be encrypted by using the crypt() function. For getting an encrypted string representing a certain password, just use something like: print crypt('dog123'). This will give you an encrypted string that corresponds with that password. If you run the command several times, you will see that the encrypted string changes each time, since there is not only one encrypted string for each possible password, but many, and crypt() recognizes when two different encrypted strings actually point to the same password.

By using crypt() with only a parameter, we obtain the encrypted string for any password that we pass, and by using crypt() with two parameters, we will be encrypting the first one and comparing it with the second one, which is already encrypted. You can see below how the previous login program can be greatly improved by using encrypted passwords.

Storing passwords in predefined arrays inside a program is good enough for simple websites where only one or some few persons that are already predetermined will login (for instance, the administrator or a workgroup), but usually usernames and passwords are contained in databases, which allows to introduce in the system new users automatically. This method works in a similar way, by just replacing the accesses to the array of users by SQL queries to the database (INSERT INTO to add a new user and SELECT FROM to verify an existing user).

<?php
require 'scripts/formhelpers.php';
if ($_POST['_submit_check2']) {
if ($form_errors = validate_form2()) {
show_form2($form_errors);
} else {
process_form2();
}
} else {
show_form2();
}
function show_form2($errors = '') {
print '<form method="post" action="' . $_SERVER['PHP_SELF'] . '">';
if ($errors) {
print '<ul><li>';
print implode('</li><li>', $errors);
print '</li></ul>';
}
print 'Username: ';
input_text('username2', $_POST);
print '<br/>';
print 'Password: ';
input_password('password2', $_POST);
print '<br/>';
input_submit('submit', 'Log In');
print '<input type="hidden" name="_submit_check2" value="1"/>';
print '</form>';
}
function validate_form2() {
$errors = array();
$users = array('alice' => '$1$zpZGwOhf$3RWngacP0Go1ruxcWldjU.',
'bob' => '$1$jt4klA7l$BZUHe9w.GPlMdR44o9ZQu.',
'charlie' => '$1$..lIHUDg$ET00ryiXu9kihZKjBBR9r1');
// Checks if the username is valid
$saved_user = htmlspecialchars($_POST['username2']);
if (! array_key_exists($saved_user, $users)) {
$errors[] = 'Please enter a valid username.';
}
// Checks if the password matches
$saved_password = $users[htmlspecialchars($_POST['username2'])];
if ($saved_password != crypt(htmlspecialchars($_POST['password2']), $saved_password)) {
$errors[] = 'Please enter a valid password.';
}
return $errors;
}
function process_form2() {
// Adds the username to the session
$_SESSION['username2'] = htmlspecialchars($_POST['username2']);
print "Welcome, $_SESSION[username2].";
}
?>
Username:
Password:

PHP Example #85

Ending a session

To disconnect (log out) an user we use the unset() function to delete a certain value (which represents an user) from the array $_SESSION[]. The user will remain disconnected (anonymous) until a new connection (log in) is executed for that user.

<?php
unset($_SESSION['alice']);
print 'Bye, bye.';
?>