PHP Wants To Be Your Web Language Of The Future – Part 2 – “Finally” and Password Hashing

PHP Password Hashing APIThis is part 2 of a 6 part series looking at the some of the wonderful features of PHP 5.5 and why it might remain a dominate web language for the future. This series was originally written for the Software Developer’s Journal.

Continuing on with our 6 part series, the next two items that make PHP the language of the future is the finally keyword (which is used in conjunction with the try-catch error handling statements introduced in earlier versions of PHP) and the simplified password hashing API. This API makes it easier, and more secure, for developers to deal with passwords and hashing them properly. One of the weakest points of many applications is their use of passwords with many developers attempting to develop their own insecure methods of creating passwords.

Exception Handling With the “Finally” Keyword

I believe this is one of those features that should have been included right from the start when they brought in the try catch mechanism. This feature fits into the grand scheme of PHP by rounding out the syntax to make it more complete. The finally keyword is the final piece to exception handling where certain code, mostly cleanup code, needs to be executed no matter if an exception was thrown or not. Where you would see this the most is around database connections or file handlers. Perhaps you opened a file with fopen() and for some reason you attempted to read from the file and it threw an exception. You need a mechanism to make sure that the file handle is properly closed whether or not the read was a success. In other words, if the read was successful, great! Read the file and close it in the finally clause. If the read failed, throw an exception to let the system know something wrong took place, but still close the file in the finally clause.

This mechanism is the same as many other languages with try catch handling like C# or Java. If you are familiar with those languages, this works the exact same way.

Simplified Password Hashing API

This feature fits into PHP’s theme by increasing security. One of the most compromised parts of a system is through its handling of passwords. Attackers look for issues with subsystems related to the passing, storage and transmission of password related data. This API makes it easier for developers to handle passwords and strengthen their hashing.

It does this by using the same underlying library as the crypt() function but wrapping it up in functions that are easier to use and implement. It takes into account things like salting and cost as well as being able to specify an algorithm of choice (two are currently supported, bcrypt and blowfish, but I expect more will be added in the future). Then it makes it easier for the developer to take that hash and verify it against a supplied password (given by the user during a login for example) for validity. This should be the go to code for hashing versus using insecure methods like MD5 or SHA-1 which have been proven to be vulnerable.

CreateUser.php

// User would supply a username (email address) and a password.
// This example demonstrates the use of password_hash() using the default bcrypt() hashing.
// On success we would store this in a database.

if (isset($_POST["usr"]) && isset($_POST["pwd"])) {
   $usr = $_POST["usr"];
   $pwd = $_POST["pwd"];

   // First check user doesn't already exist and username is proper format (like an email)
   if (!userExists($usr) && userValidate($usr)) {

      // Run the password through your own password requirements
      if (validate($pwd)) {

         // Create password hash using new PHP 5.5 password API
         $hash = password_hash($pwd, PASSWORD_DEFAULT);

         // Insert hash into database (zero is saying they are currently inactive)
         $db->inserUser($usr, $hash, 0);

         // Send user email with some confirm link to activate
         sendConfirmationEmail($usr);
      }
   }
   else {
      echo "Sorry but this user already exists. Please login.";
   }
}

In the code above we demonstrate the use of the password_hash() function that is part of the new PHP 5.5 password API. It simply takes the text to hash and the type of algorithm to use. Here we have chosen to use the default bcrypt() style algorithm. Next we will show how we could then retrieve that info and verify it.

Login.php

// Login page code where a user would provide username and password via a form
// This example uses PHP 5.5's password_verify() method to verify password.

if (isset($_POST["confirm_usr"]) && isset($_POST["verify_pwd"])) {
   $pwd = $_POST["verify_pwd"];

   // Get password for user from database
   $pwd_from_db = $db->getUser($confirm_usr);

   // Verify password with new PHP 5.5 password_verify() function.
   if (password_verify($pwd, $pwd_from_db)) {

      echo "Successfully logged in!";
      $_SESSION["auth"] = true;
      redirectUser("main");
   }
   else {
      echo "Sorry, your username or password was not correct. Please try again.";
   }
}

The password API makes verification easy. As seen in the code above, we take the username and password supplied by the user, use the username to pull the hash from the database, run the currently supplied password and the one from the database through the new password_verify() function for verification. If it returns true, the password is good. We can then go about setting them up with a session and redirecting them to our main account page.

This has reduced the boilerplate style code several lines by easily making sure that we securely hash the password and then verify it with a couple simple functions. Great addition to the language!

In part 3 of our 6 part series, we will discuss constant array/string dereferencing and the use of the empty() in expressions… a feature that I personally have wondered about for awhile now. Should make for more interesting discussion!

Thanks for reading! 🙂

If you haven’t already, visit our other parts of this series…

About The Author

Martyr2 is the founder of the Coders Lexicon and author of the new ebooks "The Programmers Idea Book" and "Diagnosing the Problem" . He has been a programmer for over 25 years. He works for a hot application development company in Vancouver Canada which service some of the biggest tech companies in the world. He has won numerous awards for his mentoring in software development and contributes regularly to several communities around the web. He is an expert in numerous languages including .NET, PHP, C/C++, Java and more.