Posted on August 24, 2008 in PHP by Elliott Brueggeman3 Comments »

Having a secure area to a PHP site is a common website requirement. Implementing the secure area, on the other hand, can be difficult and confusing. I’ve put together a basic security framework that you can use for your PHP based website.

What this framework is:

  • Simply coded & easy to understand
  • Secure enough for most sites, blogs, and internally accessed (intranet) sites.

What this framework is NOT:

  • Secure enough for sites involving e-commerce transactions and sensitive personal information.

Note the “NOT” clause above - this implementation is not for securing sensitive data. Most people implementing this framework will be doing it on unsecure sites (sites NOT using the HTTPS secure socket layer), causing user passwords to be sent from script to script in plaintext, which is vulneable to intrusion.

How the PHP security flow works

This framework works as follows:

  • User submits login form containing name and passsword to login processor script
  • Login processor form compares name and password to stored value
  • If name and password do not match expected value, send user back to login form
  • If name and password match expected value, set a session variable containing a unique hash value, and forward user to secure page

When a user tries to access a secure page, this happens:

  • Security code checks session variable with user hash and compares to expected value.
  • If the hash values match, continue displaying page.
  • If the hash values do not match, send user to login form.

Seems simple right? It is! To implement the above workflow you’re going to need to use the code I have included below.

Login Form

Below is the login form code. Note that you must set the destination of the form to match the name of your check login script (login processor.)

<?php
/*
* FILE: login.php
*/
?>
<html>
<head>
  <title>Login</title>
</head>
<body>
  <form name="login-form" method="post" action="check_login.php">
    <p>User: <input type="textfield" id="user" name="user"/></p>
    <p>Password: <input type="password" id="pass" name="pass"/></p>
    <p><input type="submit" name="Submit" value="Submit"></p>
</form>
</body>
</html>

Login Processor

The login processor has the main chunk of your security code. This is the script that decides whether you have a correct username and password, and what to do after logging in. Note that this code uses an include of login functions to accompish its purpose. These login functions are shown later in this article.

<?php
/*
* FILE: check_login.php
*/
 
session_start();
 
//include our login functions.
require('login_functions.php');
 
//retrieve post data
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);
 
 
/*
* Basic Login Logic
*/
 
clear_login_state();
 
if (!empty($user) && !empty($pass)) {
 
  if (check_login_correct($user, $pass)) {
 
    //set appropiate session vars
    login_user($user);
 
    //redirect to secured page
    send_to_page('secure_page.php');
  }
  else {
    //wrong user or password supplied, send back to login
    send_to_page('login.php');
  }
}
else {
  //no user or password supplied, send back to login
  send_to_page('login.php');
}
?>

Login Functions

The above Login Processor code uses some important functions to accomplish the secure login. These functions are enclosed in their own file and included by the above code.

<?php
/*
* FILE: login_functions.php
*/
 
function check_login_correct($user, $pass) {
  /**
  * This function is for you to fill in.
  * Typically, you would compare the user's password 
  * to the password stored in the database, and then return
  * either true or false, depending on the result.
  */
 
  if ($user == 'admin' && $pass == 'Chelsea') { return true; }
 
  return false;
}
 
function login_user($user) {
  session_regenerate_id();
 
  //set the user session variable, for later app use
  $_SESSION['user'] = $user;
 
  //set the hash session variable
  $_SESSION['hash'] = calculate_secure_hash($user);
}
 
//function sends the user to a page. Note this must be called 
//in the header, before any page output (echo's, html, print, etc) 
function send_to_page($page) {
  header("Location: $page");
  die("Redirect Failed");
}
 
//clears login state (logs you out) by unsetting login variables
//must be called in header, before any page output (echo's, html, print, etc) 
function clear_login_state() {
  session_unset();
}
 
function calculate_secure_hash($user) {
  //the security of your system is based on the hash seed below - change often
  $hash_seed = 'this_is_a_secret';	
  return md5($_SERVER['HTTP_USER_AGENT'] . $hash_seed . $user);
}
 
function check_logged_in() {
 
  //retrieve session vars
  $found_hash = $_SESSION['hash'];
  $user = $_SESSION['user'];
 
  //must not be empty
  if (!empty($found_hash) && !empty($user)) {
 
    //recalculate the hash
    $calculated_hash = calculate_secure_hash($user);
 
    //if recalculated hash matches, we have a logged in user
    if ($calculated_hash != $found_hash) {
      send_to_page('login.php');
    }
  }
  else {
    send_to_page('login.php');
  }
}
 
?>

Secure Page Code

Okay, so we have successfully logged a user in - now what? Well, for each secure page accessed you have to reverify the hash value. On each secure page, you’re going to need to setup the top of your page (PHP script) like this:

<?php
/*
* FILE: secure_page.php
*/
 
session_start();
 
//include our login functions.
require('login_functions.php');
 
//do security check
check_logged_in();
 
//now, display the page's content...
echo "You are viewing a secured page!";
 
?>

Download the Above Code

You can download this zip of the above code, and run it on your server to test how the authentication code works. Remember, you’re going to need to customize the check_login_correct() function to fit your particular password storage method.

Posted on January 9, 2008 in AJAX, Javascript, PHP by Elliott Brueggeman2 Comments »

Background

One of the most useful new web technologies is AJAX, or Asynchronous JavaScript and XML. In short, AJAX allows you to send and receive server requests without a user having to reload the page. This allows pages to be more dynamic without interrupting the user experience.

AJAX is fairly easy to implement and use effectively, but finding a comprehensive start to finish tutorial for integration with PHP is not quite as easy. To make the task easier, I have put together a simple PHP AJAX framework that is flexible and easy to implement.

AJAX Workflow

The inner workings of AJAX are a mystery for some so I will go over the basics of how our framework will work with PHP.

  1. Using JavaScript, a call to your AJAX function is triggered by clicking somewhere, entering something, etc.
  2. Your AJAX function creates an XMLHttpRequest object.
  3. When ready, the object requests information from your server in the form of a URL, possibly with arguments such as myscript.php?name=jon&year=2007, etc.
  4. The server executes the PHP script and sends the result by echo[ing] it out.
  5. Instead of printing it to the screen, that information is instead returned to you as a JavaScript variable.
  6. Using JavaScript, that information can now be dynamically inserted in the page by using the innerHTML property or by assigning the result to the value of a form element.
  7. Rinse and Repeat… The value of AJAX is that you can repeat this process infinitely without having the user have to navigate away from the page!

PHP AJAX Framework

The PHP AJAX Framework shown below is structured into three parts. The part that stays the same every time is the JavaScript ajaxHelper() function. This is the core of our AJAX functionality. We also need to create two additional JavaScript functions. The code of these functions is different depending on what you want to do. These functions or hooks will be called by the ajaxHelper() function and their names must end in “_init” and “_ajax” which will be explained below.

The ajaxHelper() function

function ajaxHelper(functionName, additionalArgs) {
  var xmlHttp;
  // Firefox, Opera 8.0+, Safari, SeaMonkey
  try {
    xmlHttp=new XMLHttpRequest();
  }
  catch (e) {
    // Internet Explorer
    try {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {
      try {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e) {
        alert("Sorry, your browser does not support AJAX.");
        return false;
      }
    }
  }
 
  xmlHttp.onreadystatechange=function() {
    //The request is complete == state 4
    if (xmlHttp.readyState==4) {
      var response=xmlHttp.responseText;
      //Send reponse to _ajax hook of passed function name
      eval(functionName + "_ajax" + '(\'' + response + '\')');
    }
  }
 
  //Get request string from _setup hook of passed function name
  if (additionalArgs !== undefined && additionalArgs.length > 0) {
    var requestString = eval(functionName+"_init" + '(' + additionalArgs + ')');
  }
  else {
    var requestString = eval(functionName+"_init" + '()');
  } 
 
  if (requestString) {
    xmlHttp.open("GET", requestString, true);
    xmlHttp.send(null);
  }
}

The _init and _ajax functions

As stated above, these are functions are hooks, meaning that they will be called dynamically by the ajaxHelper() function depending on the argument you pass it. For example, on a button click you execute the ajaxHelper(’chat_update’) function. The ajaxHelper will call chat_update_init() and then chat_update_ajax() automatically, so you must have them defined. By making them dynamic hooks, you can have many different AJAX calls on the same page but use the same ajaxHelper() function each time. You pass the ajaxHelper() function the first part of the name of your two additional functions (minus the _init and _ajax), which is “chat_update” in the above example.

The _init hook function specifies the name of the PHP file and any arguments to be passed to the ajaxHelper() function. An example _init hook is as follows:

function my_first_try_init() {
  //retrieve username from html input box with the id "name_box"
  var username = document.getElementById('name_box');
  var script = 'myscript.php';
  var queryString = "?username=" + username;
  return script + queryString;
}

The _ajax function is passed the results of the PHP script specified in the _init hook as a JavaScript variable. Using JavaScript trickery, we can update the page that the user is viewing. You can use the .innerHTML property and change the contents of a div or other element. Or, you could even change the text of input boxes by changing the .value property. This may sound confusing, but study the below examples for a better understanding.

function my_first_try_ajax(results) {
  var targetDiv = document.getElementById('firstDiv');
  var resultHTML='<h1>' + results + '</h1>';
  targetDiv.innerHTML = resultHTML;
}

The above code replaces the html within a div with the id “firstDiv” with whatever has been returned by myscript.php wrapped in h1 tags. You could have an empty div and only insert html into it on AJAX calls. The div would look like this:

<div id="firstDiv"></div>

While declaring an _ajax hook function is required, adding JavaScript code inside the function is optional. Why? Because often you do not want to change content on the user’s page, but instead just update values in the database on your call to the script specified in the _init hook. In that case, nothing would need to be updated on the page.

Your PHP Script

Creating your PHP script that will be called by the AJAX framework is easy if you know PHP. You can have your PHP script do pretty much anything. You probably want to either return some value or values, update a database, or both. The only thing to note is that to return a value, you need to “echo” it out. Values printed to the screen from your PHP callback script are returned to the the JavaScript _ajax() hook function as the results variable, as seen above.

How do you return multiple results? Well the implementation differs depending on what you want to return, but if you want to return an array you simply echo out a comma separated list in your PHP script and then you split the returned JavaScript variable by the commas and loop through the values in your _ajax() function and do whatever. Here is an example of a php script that connects to a database and returns the current sales totals for the year:

<?php
//connect to database
$link = mysql_connect('localhost', 'username', 'password')
  or die('Could not connect: ' . mysql_error());
mysql_select_db('sales_db') or die('Could not select database');
 
$currentYear = date('Y');
 
//execute query
$sql = "SELECT SUM(sale_total) as `total`
  FROM sales_table WHERE year = $currentYear";
$result = mysql_query($sql);
 
//retrieve results
while ($row = mysql_fetch_assoc($result)) {
  $total = $row["total"];
}
 
//return via echo to our JavaScript _ajax function
echo $total;
?>

Here is another example that returns an array of values:

<?php
//[not shown] do a database call and retrieve an array
$valueArray = array(23, 231, 'roger 123', 26, 'Las Veags,
  Nevada', 'Washington', 77);
 
//replace commas with their html value so they do not
//get in the way of separating out the array
// values with commas via the implode statement
echo implode(', ', str_replace(',', '&#44;', $valueArray));
?>

Activating AJAX

Finally, the only thing we are missing is how we trigger our AJAX call. There are many ways to do this. The most common method is when a user interacts with an element on the page, triggering the AJAX helper function, but this is not the only way. You can also use a JavaScript timer and call the AJAX at a set interval. This method will be covered in a future article. Let’s look at some common examples of triggering AJAX through user interaction:

Button Click

<input type="button" id="trig" value="ClickMe" onClick="ajaxHelper('my_first_ajax');" >

Mouse-Over a Div

<div id="TriggerDiv" onMouseOver="ajaxHelper('sales_calculate');" ></div>

Click in a Text Box

<input type="text" name="datefield" onClick="ajaxHelper('update_date');" >

Conclusion

The uses for AJAX are endless, especially coupled with PHP. Explore, experiment, and see what’s best for your website.

Update - September 15th, 2009

I added an optional second parameter to the ajaxHelper() function call - this allows you to pass additional variables to the PHP script via Javascript. Below is an example of passing an array of three values to the php script.

Example Usage

<a href="#" onclick="ajaxHelper('track_click', new Array(1303432, 26));">Click Here</a>

To utilize these values, add parameters to your _init hook function for each value passed. The below _init hook function takes each of the passed values and then puts them into a url friendly format to be passed to your PHP script.

function track_click_init(arg0, arg1) {
 
	var script = 'onclick.php';
	var queryString = "?id=" + arg0 + "&age=" + arg1;
 
	return script + queryString;
}


Warning: include() [function.include]: URL file-access is disabled in the server configuration in /home/content/b/r/u/brueggemanwine/html/blog/wp-content/themes/ebrue_theme/footer.php on line 51

Warning: include(http://www.ebrueggeman.com/includes/include_ad_chooser.php) [function.include]: failed to open stream: no suitable wrapper could be found in /home/content/b/r/u/brueggemanwine/html/blog/wp-content/themes/ebrue_theme/footer.php on line 51

Warning: include() [function.include]: Failed opening 'http://www.ebrueggeman.com/includes/include_ad_chooser.php' for inclusion (include_path='.:/usr/local/php5/lib/php') in /home/content/b/r/u/brueggemanwine/html/blog/wp-content/themes/ebrue_theme/footer.php on line 51