Avg. Rating 5.0

Problem

I have set up a login page to restrict access to certain parts of my website, but I want to greet the user by name. I would also like users to be able to update their own information.

Solution

Use the Dreamweaver Log In User server behavior for the login page. The server behavior creates a PHP session variable called $_SESSION['MM_Username'], which you can use as a filter in a recordset to retrieve the user's details. If you store the results of the recordset in your own session variables, that information will be available in any page where a PHP session has been enabled (including pages that use the Restrict Access to Page server behavior).

Detailed explanation

The Dreamweaver Log In User server behavior automatically creates two PHP session variables: $_SESSION['MM_Username'] and $_SESSION['MM_UserGroup']. These variables are used by the Restrict Access to Page server behavior to determine whether the user is authorized to view the page.

$_SESSION['MM_UserGroup'] stores the user's access level (or an empty string if you use only username and password for authentication), and tells you nothing about the individual user. However, as its name suggests, $_SESSION['MM_Username'] stores the user's username, enabling you  to identify exactly who is accessing the page. You can use this to control what each individual user sees.

PHP session variables are available on all pages that begin with a call to session_start(). This includes pages that use the Restrict Access to Page server behavior. If you want access to the user's details, it's a good idea to create a recordset on the first page the user visits after logging in.

Getting the user's details

To get the user's details, open the page that the user will be sent to after logging in successfully, and apply the Restrict Access to Page server behavior. Then create a recordset using the Recordset dialog box in Simple mode. You can call the recordset whatever you like, but this recipe uses "userDets". Set the Filter fields in the recordset dialog box to username = Session Variable MM_Username. The first three values are selected from pop-up menus, but you need to type MM_Username into the final field manually. PHP is case sensitive, so make sure you get the combination of uppercase and lowercase correct.

This inserts the following recordset code immediately above the DOCTYPE declaration in the page:

$colname_userDets = "-1";
if (isset($_SESSION['MM_Username'])) {
  $colname_userDets = $_SESSION['MM_Username'];
}
mysql_select_db($database_cookbook, $cookbook);
$query_userDets = sprintf("SELECT * FROM users 
                          WHERE username = %s",
  GetSQLValueString($colname_userDets, "text"));
$userDets = mysql_query($query_userDets, $cookbook) or
die(mysql_error());
$row_userDets = mysql_fetch_assoc($userDets);
$totalRows_userDets = mysql_num_rows($userDets);

This assumes the user's details are in a single table called users. If you need to join tables to get certain details, use the Recordset dialog box in Advanced mode, and set the Runtime Value of the variable for the username column to $_SESSION['MM_Username'].

The user's details will be stored in the userDets recordset. What you do with the user's details is entirely up to you.

Updating the user's details

If you just want users to be able to update their own information, create an update form in the body of the page, and use the Bindings panel to bind the existing value to each input field. Then apply an Update Record server behavior to the page. Because each user is identified by $_SESSION['MM_Username'], only information associated with the person who logged in will be updated. Of course, the level of security depends entirely on users creating strong passwords, and making sure they keep them secret.

Storing the user's details in session variables

If you want to be able to refer to the user's details in other pages, loop through the recordset result to assign the values to session variables. As long as each username is unique, there should be only one row in the recordset. Its values are already stored as an associative array in $row_userDets. Use a loop to assign the values to session variables by adding the following code immediately after the line of code that begins with $totalRows_userDets:

foreach ($row_userDets as $col => $val) {
  $_SESSION[$col] = $val;
}

This assigns the name of each column (field) as the session variable's index (key), and then assigns the value to the session variable. So, if you have a column called "company" and the value is "Adobe", the value of $_SESSION['company'] will be "Adobe".

Anywhere you want to use the user's details, make sure the page begins with session_start(), and just use $_SESSION['col_name'], replacing col_name with the name of the relevant database column (field).

If you don't want to use the database column names, just assign the values in $row_userDets to variables individually. For example:

$_SESSION['full_name'] = $row_userDets['first_name'] . ' ' .
$row_userDets['family_name'];

NOTE: You can't access the values in $row_userDets if you have already used it in a loop. To reuse the recordset row after running it through a loop, you must first reset it like this:

reset($row_userDets);

What if the user doesn't always go to the same page after logging in?

If the user has tried to access a restricted page before logging in, the Restrict Access to Page server behavior redirects the user to the login page. However, the Log In User server behavior has an option to redirect the user to the previous URL if it exists. If this option has been selected, you have no idea which page the user will be sent to after logging in.

Adding a recordset to retrieve the user's details on every page is inefficient, not to mention a lot of coding. The solution is to cut the previous code and paste it into an include file so that the session variables are created only if they don't already exist. The include file also needs to include the file that contains your MySQL connection. Assuming that your user details contain a column called "company", this is what the include file should look like:

<?php
// get the user's details if an expected variable doesn't exist
if (!isset($_SESSION['company'])) {
  // get the MySQL connection
  require_once('Connections/cookbook.php');

  // the recordset code cut and pasted into the include file
  $colname_userDets = "-1";
  if (isset($_SESSION['MM_Username'])) {
    $colname_userDets = $_SESSION['MM_Username'];
  }
  mysql_select_db($database_cookbook, $cookbook);
  $query_userDets = sprintf("SELECT * FROM users 
                            WHERE username = %s",
    GetSQLValueString($colname_userDets, "text"));
  $userDets = mysql_query($query_userDets, $cookbook) or
die(mysql_error());
  $row_userDets = mysql_fetch_assoc($userDets);
  $totalRows_userDets = mysql_num_rows($userDets);

  // assign the recordset result to the session variables
  foreach ($row_userDets as $col => $val) {
    $_SESSION[$col] = $val;
  }
}
?>

Include this file in each page where you want to access the user's details. Place the include command immediately before the DOCTYPE declaration.

Destroying the session variables when the user logs out

The Log Out User server behavior unsets only those session variables created by the Log In User server behavior. For security, you need to unset your own session variables. In the page that contains the Log Out User server behavior code, locate the following code:

$_SESSION['MM_Username'] = NULL;
$_SESSION['MM_UserGroup'] = NULL;
$_SESSION['PrevUrl'] = NULL;
unset($_SESSION['MM_Username']);
unset($_SESSION['MM_UserGroup']);
unset($_SESSION['PrevUrl']);

Immediately after this code block, add the following lines:

$_SESSION = array();
$params = session_get_cookie_params();
setcookie(session_name(), '', time() -42000,
  $params["path"], $params["domain"],
  $params["secure"], $params["httponly"]);
session_destroy();

This turns the $_SESSION array into an empty array, destroys the session cookie, and then destroys the session itself.


+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes