Unit 7: Session Variables and Login Screens

advertisement
Instructor’s Notes
Web Data Management
Unit 7 - Session Variables and Login Forms
Web Data Management
152-155
Unit 7 - Session Variables and Login Forms
Notes
Activity
Quick Links & Text References






Session Variables
Search Session Variable
Password Encryption
Creating a Login Screen
Logging Out
Encrypting Other Data
Pages
Pages
Pages
Pages
Pages
Pages
348 – 375
348 – 375
688 – 689
690 – 699
692 – 693
700 – 703
Session Variables


Session variables are stored in a super-global, associative
array (like $_REQUEST) named $_SESSION.
 Each session variable’s name is used as the key
Actually, session variables are extra-super-global
variables because they can retain their value even after
you leave the web site and even after you shut down the
browser.
 Session variables are stored in a cookie that is saved
on the user’s computer until your program deletes it
or it times out.
 If the user has cookies turned off, session variables
don’t work.
 You might consider writing additional code to
retain variables like $search.
Page 1 of 10
Instructor’s Notes

Web Data Management
Unit 7 - Session Variables and Login Forms
You must instruct your website to use session variables
 By default, session variables are off
 This is normally done in the controller
 Works pretty good in connect.php too
$lifetime = 60 * 60;
//1 hour
session_set_cookie_params($lifetime,'/');
session_start();


The second line creates a set of session parameters
that tell the session how to behave. In this case, we’re
setting the cookie’s lifetime (defined in the statement
above in seconds) and designating that the cookie is
available to all pages in the web site.
The last line starts the session
 This creates a session ID that is used by the
server and the cookie to communicate that they
are linked
 If a session ID already exists, this command
does nothing
▪ Remember this command is in the controller
and the controller is called over and over
again.
▪ Only one session is created
Using Session Variables
to Remember a Search String


In the last unit, we passed a search variable from the list
view to the controller to the details view, etc. The search
variable needed to be handled in many differ locations so
the pages didn’t forget its value when it was needed
again.
A session variable can simplify this greatly.
Page 2 of 10
Instructor’s Notes

Unit 7 - Session Variables and Login Forms
In the appropriate case file, , check to see if a search
session variable already exists. If not, create it initializing
it to the empty string (search for all)
Search only used in
employee List case so put
this in that case file.
if(!isset($_SESSION['empSearch']))
$_SESSION['empSearch'] = "";
Replace REQUEST
employee filter with
command shown here
(SESSION).



Web Data Management
Note you use the $_SESSION array just like the
$_REQUEST array (yes, you could extract it)
I’ve added the emp prefix to my search key value.
Many websites will have numerous list pages and
you’ll want to keep the search variables for those
pages distinct.
Update call to
getEmployeeList
Next, we’ll transfer the search element from the
$_REQUEST array to the $_SESSION array
 The first time the controller loads, there won’t be a
$_REQUEST array, but after the list view has been
displayed, the $_REQUEST array will have a search
element
 So the search value will be remembered forever (or at
least until a new search value is defined), we transfer
it to the $_SESSION array
if(isset($_REQUEST['empSearch']))
$_SESSION['empSearch'] =
$_REQUEST['empSearch'];
Lines split to fit these notes



Again, I’ve named the variable coming from the
search box on the list view (empSearch) using a
prefix to distinguish it from search variables coming
from other list view.
That’s it. The application now captures and saves our
search selection in the $_SESSION array when we leave
the list view by clicking the Search button.
Now, we have to get the list view to use the session variable to fill in the
search textbox when the form displays.
<input type="text" name="empSearch" id="txtSearch" size="20"
value='<?php echo $_SESSION['empSearch'];?>'>

That should do it—you’re done. No more passing the
search variable from form to form. The controller saves
the search textbox contents (from the $_REQUEST array)
to the $_SESSION variable.
Page 3 of 10
Instructor’s Notes
Web Data Management

What’s the cookie look like?
 To view a cookie in IE9:
 Open IE and navigate to the page.
▪ If you haven’t done so already, access the
list view and designate a search value
 Press F12 to open IE developer view
 From the menu, select CacheView Cookie
Information
 Since we didn’t designate a name, PHPSESSID
is used. Scroll to locate the cookie.
▪ Note the expiration date/time
▪ Note the content
 To view a cookie in Firefox (FF)
 Open FF and navigate to the page.
▪ If you haven’t done so already, access the
list view and designate a search value
 Click the orange Firefox button and select
Options
 Select the Privacy tab
 Click the remove individual cookies link
 Search for localhost
▪ Note the expiration date
▪ Note the content
 The cookie contains the session ID, but not the
$_SESSION array. That is actually stored on the
server and is tied to (linked to) this session ID.

To clear a cookie (for further session variable testing)
 In FF
 Navigate away from the localhost
 Access the cookies (see above)
 Delete the localhost cookie
 Return to the list view (search should be blank)
 In IE,
 Navigate TO the list view, set a search
 Navigate away, and then go back to the list view
 Access cookies (see above)
 Clear Session Cookies
 Close IE, reopen, access list view
Unit 7 - Session Variables and Login Forms
Page 4 of 10
Instructor’s Notes
Web Data Management
Unit 7 - Session Variables and Login Forms
Password Encryption



Normally, before you store a user’s password you’ll want
to encrypt it so others (even the database admin) won’t be
able to read it.
PHP provides the sha1 function
 sha1 has recently become vulnerable because of
increased computing speed and readily available
hashing tables. PHP no longer recommends its use. .
Read about it.
The PHP provides the password_hash function to
securely encrypt passwords.
$statement->bindValue(":password",
password_hash($password,PASSWORD_DEFAULT));


This creates a 60-character password hash, regardless
of the size of the password the user entered.
 This is a one-way hash, it cannot be decrypted.
When checking to see if a person is an authorized user
 Get the user’s name and password from the database.
 If no records are returned (bad user name), return
false.
 Use password_verify (returns Boolean) to ensure the
passwords match
$results = password_verify($password,
$passwordFromDatabase);



$password is the password entered by the user
$passwordFromDatabase is the password your query
retrieved from the database.
Note the password from the user does not need to be
hashed (the function does it).
Creating a Login Screen


PHP includes two ways to get the user’s login
information
 PHP (HTML) input form
 Standard PHP login dialog box
Since the PHP input form provides the most flexibility,
we’ll use that.
 You can read about the PHP standard login dialog
box in the text (pages 698-9)
Page 5 of 10
Instructor’s Notes

Unit 7 - Session Variables and Login Forms
The basic PHP login form (view) includes
 Text box to get the username
 Password box (input type=password) the get the
user’s raw password
 Note unless a secure connection is used, a
cracker could still intercept the password as it is
being sent to the server.
 Login button
 Message line (label)


Web Data Management
The form could also include links/buttons that allow
the user to
 Request that their password be reset
▪ Note using sha1 encryption, there is no way
to decrypt the user’s password and send it to
them.
 Change their password (after correctly inserting
the correct password)
▪ This option might be included on a separate
form that is only accessible after successful
login.
As with all other forms, the controller includes a case for
login.
case 'login':
$userName = (isset($_REQUEST['userName']))?$_REQUEST['userName']:"";
$password = (isset($_REQUEST['password']))?$_REQUEST['password']:"";
if($userName == "") {
$loginMessage = "You must login to use this website.";
include('views/login.php');
}else if(isAuthorized($userName, $password)) {
$_SESSION['authorizedUser'] = true;
header("Location: ?action=myList");
} else {
$loginMessage = "Invalid username or password.";
include('views/login.php');
}//end if
break;
Page 6 of 10
Instructor’s Notes






Web Data Management
Unit 7 - Session Variables and Login Forms
Note Murach’s examples are not for PHP 5.3.8 which
requires variables be set before they are used.
The first time the web site is accessed, there won’t be a
username or password, which will cause the login view to
be displayed.
Note you must define the isAuthorizedUser function in
a model file for the database user table and require this
model file in the controller
 This function accepts two parameters (username, raw
password) and returns either true or false
 The function encrypts the raw password and checks
to see if a record exists in the table with this
username and (encrypted) password combination. If a
record exists, the function returns true. Otherwise, it
returns false.
 See sample in book.
Remember, the variables ($username, $password,
$loginMessage) are all available to the login view so you
could display the original entries if the user makes a login
mistake.
Replace mainview.php with the name of the main view
of your web site
One final touch is to include a statement in the controller
to see if the authorizedUser session variable is set
 Note you can name this session variable whatever
you want.
 Remember it is possible for a user (cracker) to access
your website and send in their own action variable.
www.whatever.com/employees?action=employeeList


This would effectively bypass our login screen
(assuming employeeList is a valid action)
To prevent this, we add an if statement to the
controller that checks to see if the session variable is
set
 Murach places this under the if statement that
sets the default action. If the session variable is
not set, the action is set to login.
if(!isset($_SESSION['authorizedUser']))
$action='login';
Page 7 of 10
Instructor’s Notes

Web Data Management
Unit 7 - Session Variables and Login Forms
There’s no need to check to see if the session
variable is true. If it’s set, it will be true.
Logging Out

If possible, your website (menu?) should include an
option that allows the user to log out.
 If the user doesn’t log out, the session variables will
remain on the user’s computer until they expire.
 Another person could (conceivably) use this
computer and access the website without logging in
because the authorizedUser session variable is still
set.
case 'logout': //In the login cases
$_SESSION = array();
session_destroy();
$loginMessage = "You have been logged out.";
include('views/login.php');
break;



Add a log out link to the
employee list page.
The first line refines the $_SESSION array as an empty
array, effectively removing all session variables from the
server.
The second line wipes out the session ID.
Finally, the login page is redisplayed (you have to send
the user somewhere).
Encrypting Other Data



sha1 works well for passwords, especially if you don’t
need to decrypt them.
Other data in a database like social security numbers,
credit card numbers, account numbers, etc. should always
be stored encrypted, but will have to be decrypted when
displayed in an update view (for example).
Though encryption/decryption is not terribly complicated,
Murach provides a convenient Crypt class that takes care
of the dirty work.
 You can copy the class code from below
Page 8 of 10
Instructor’s Notes



Web Data Management
Unit 7 - Session Variables and Login Forms
Using the Crypt class couldn’t be simpler.
require (import) the Crypt class file where appropriate
(controller? details view?)
Create a new instance of the class
$crypt = new Crypt();

Use the encrypt or decrypt methods of the class where
appropriate.

Note: encrypted values seem to be 24 characters long
regardless of the original string length.
$data = $crypt->encrypt($_REQUEST['userEntry']);
//Save $data to the database instead of original user entry
echo "Credit Card Number: " . $crypt->decrypt($results['CCN']);
//Obviously don’t have to echo
Page 9 of 10
Instructor’s Notes

Web Data Management
Unit 7 - Session Variables and Login Forms
Crypt Class code
<?php
class Crypt
//Class
private
private
private
private
private
{
members
$key;
$ivs;
$iv;
$cipher;
$mode;
//Encrypt/decrypt key
//Initialization vector size
//Initialization vector
//Encryption technique code
//CBC mode of operation
public function __construct() {
$this->cipher = MCRYPT_RIJNDAEL_128;
$this->mode
= MCRYPT_MODE_CBC;
$this->key
= sha1('justSomeStuff', true); //Binary key
$this->ivs
= mcrypt_get_iv_size($this->cipher, $this->mode);
$this->iv
= mcrypt_create_iv($this->ivs);
}//end constructor
public function encrypt($data) {
$data = mcrypt_encrypt($this->cipher, $this->key, $data,
$this->mode, $this->iv);
$data = base64_encode($data);
return $data;
}//end encrypt
public function decrypt($data) {
$data = base64_decode($data);
$data = mcrypt_decrypt($this->cipher, $this->key, $data,
$this->mode, $this->iv);
return $data;
}//end decrypt
}//end class
?>
Page 10 of 10
Download