Article

Write Secure Scripts with PHP 4.2!

Page: 1 2 3 4

How does this affect sessions?

The introduction of the special $_SESSION array actually helps to simplify session code. Instead of registering global variables as session variables and then having to keep track of which variables are registered when, simply refer to all your session variables as $_SESSION['varname'].

Let's consider another authorization example. This time, it will use sessions to mark a user as authorized for the remainder of his or her stay on your site. First, the PHP 4.0 version (with register_globals enabled):

<?php    
 session_start();    
   
 if ($username == 'kevin' and $password == 'secret')    
 {    
   $authorized = true;    
   session_register('authorized');    
 }    
?>    
<?php if (!$authorized): ?>    
 <!-- Display HTML Form prompting user to log in -->    
<?php else: ?>    
 <!-- Super-secret HTML content goes here -->    
<?php endif; ?>

Now, spot the security hole. As before, adding ?authorized=1 to the end of the URL bypasses the security measures and grants access to the page contents. The developer probably thought of $authorized as a session variable, and missed the fact that the same variable could easily be set by user input.

Here's how the script looks when we add our special arrays (PHP 4.1) and switch off register_globals (PHP 4.2):

<?php    
 session_start();    
   
 if ($_POST['username'] == 'kevin' and    
     $_POST['password'] == 'secret')    
   $_SESSION['authorized'] = true;    
?>    
<?php if (!$_SESSION['authorized']): ?>    
 <!-- Display HTML Form prompting user to log in -->    
<?php else: ?>    
 <!-- Super-secret HTML content goes here -->    
<?php endif; ?>

See? Much more straightforward! Instead of registering a normal variable as a session variable, we set the session variable (in the $_SESSION array) directly, and then use it the same way. There's no more confusion as to which variables are session variables and you'll notice the code is slightly shorter too!

Summary

In this article I explained the reasoning behind recent changes to the PHP scripting language. In PHP 4.1, a set of special arrays were added to the language to access external data values. These arrays are available in any scope to make external data access a more convenient. In PHP 4.2, register_globals was turned off by default to encourage migration to the new arrays and to reduce the tendency of inexperienced developers to write insecure PHP scripts.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links

Rate This Article

  • 1
    Poor
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
    Great

Comment on This Article

Have something to say?

Post A Comment

You need to be a member of the SitePoint Forums to comment on this post. Sign Up

Already a member? Post using your SitePoint Forums account: