Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

Making Sure Your Users' Passwords Are Secure

One way to improve the security of your sites is to beef up your methodologies for storing and handling user passwords. In this article, web developer Larry Ullman explains how to more securely store passwords and properly allow users to access your site when they’ve forgotten their password.
Like this article? We recommend

If your website has users that can log in, you are either storing the user’s credentials in some manner or using OpenID (or the like) to put that burden elsewhere. If you are storing the user’s credentials, you must secure the password to an appropriate level for your site. Towards that end, this article specifically discusses two aspects of password management: how to properly hash passwords for storage, and how to securely handle the forgotten password situation. But first, I want to rehash (pun!) what security is.

Understanding Security

The first thing everyone needs to understand about security is that it’s not a binary thing that can be turned on and off like a switch. Security is a sliding scale. You cannot make a website “secure”—you can only make it “more secure” or “less secure.” Thinking that your site is 100% secure is the kind of attitude that gets you into trouble.

As an analogy, think about where you live: a house, an apartment, a dorm room, whatever. Presumably, you lock the door(s) when you leave. Maybe you even have two locks. But does that mean the house or apartment or whatever is secure? No. Someone could break a window or pick the lock. So does that mean your home is not secure? Again, no. The locked door(s) only mean that it’s not easy for someone to get in.

This apparent contradiction leads me to my second point: Understanding that security is a scale—not an on/off state—you have to implement the appropriate level of security for the application. Depending upon many factors, your abode may be secure enough with just a locked door. For someone else, a monitored security system provides the correct level of security. The same is true for a website: Find the right security tools for the site in question. A content management system (CMS) does not require the same level of security as an e-commerce site, which still does not need to be as secure as an online banking or investing site.

Why wouldn’t you always implement the highest level of security, you may ask. Remember that security comes at a price. First, more security requires more of your time and effort. It also requires more of the end user. Second, more security normally has an adverse affect on performance. For example, requiring users to log in is an imposition on them, but is often a reasonable imposition to make.

The reason I’m explaining all this is that you need to decide when and how to implement the following specific ideas based upon the particulars of your site and its sensitivities.

Selecting a Hashing Algorithm

The first thing you should make sure your site is doing is storing passwords in a secure manner. On most sites these days, the password itself is not stored but rather a “hashed” version of the password is. A hash is just a mathematically computed representation. Storing a hash is more secure than storing a password, but how securely hashing is done depends upon two things:

  • The hashing algorithm used
  • The use and choice of salts

The hashing algorithm is the bit of programming that generates a hash of a value. For years, MD5 was commonly used, but it has been cracked for some time (i.e., it’s been proven to be less secure). Next, people turned to SHA1. While more secure than MD5, SHA1 has also been cracked. Again, this doesn’t mean you should never use SHA1, but it means that’s a less secure solution than some others.

If you’re using MySQL as your database application, you can use SHA2. Support for it was added in MySQL 5.5.5, and it is more secure than MD5 or SHA1. Here’s how you would use SHA2 to store a hashed version of a password:

INSERT INTO some_table (pass) VALUES (SHA2('actual password'))

That’s the short version of the applicable INSERT query; obviously, the real-world use would depend upon the particulars of the application. To verify that the correct credentials were supplied upon login, you would again use SHA2():

SELECT some_columns FROM some_table WHERE email='provided email address' AND pass=SHA2('provided password')

If that query returned one record, then the proper credentials were entered.

For an even more secure hashing algorithm, you can turn to the HASH Message Digest Framework in PHP. This toolset, built into PHP as of version 5.1.2, allows you to choose from a range of hashing algorithms to hash passwords on a security level of your specific choosing. It does require a bit more knowledge of security and algorithms in general, though.

To use this route, invoke the hash_hmac() function in PHP:

$pass = hash_hmac('sha512', 'actual password', 'secret key');

The first argument to this function is the hashing algorithm. Depending upon your operating system and version of PHP, there may be 40 or more to choose from. You’ll need to do some research to select an appropriate one for your situation. As with everything in security, the most secure algorithms will take longer to hash the data.

The ‘secret key’ value needs to be kept in a safe place, such as a secure file in which it’s defined as a PHP constant. Of course, the same secret key and algorithm must be used to hash the user’s password upon registration and to compare the password during login attempts.

Salting Passwords

Storing hashed versions of passwords is far, far more secure than storing passwords in plain text, but that alone is not secure enough under many situations. Better security can be attained by adding a “salt” to a password prior to hashing it. A salt is just a random collection of characters. Adding a salt has two benefits:

  • It makes the password longer, and longer passwords are always more secure (e.g., the salt can help atone for users who provide short passwords).
  • It results in different hashed versions of the same password by multiple users.

This second fact is the most important, particularly as your site has more users. Knowing why this is beneficial requires some knowledge of how systems are hacked, but the short description is this: If multiple users register with the same password, which can easily happen (just look online for lists of common passwords), then the hash of that password for all of those users will be exactly the same (when not using salts). This makes it easier for a hacker to break into the system using rainbow or lookup tables.

The solution is to add a randomly generated salt to each password. By doing so, even if multiple users have the same password, the stored hashed versions differ.

A common mistake is to think that the salts have to be secret—they don’t. They just need to be random, relatively unique, and the longer the salt is, the better. A single-character salt is better than none at all, but ideally the salt should be the same length as the output of the hash itself. For example, SHA1 results in a string 40 characters long, so you should use a 40-character salt.

So how do you make a good salt? In PHP, the most secure solution is to use the openssl_random_pseudo_bytes() function, added in version 5.3. Provide it with a length argument, which is the number of bytes that should be returned:

$salt = openssl_random_pseudo_bytes(20);

Keep in mind that this function returns bytes of data (i.e., binary data). To convert the binary salt to a character string, apply bin2hex():

$salt = bin2hex(openssl_random_pseudo_bytes(20));

Now the salt can be appended to the password, and the combination salted:

$pass = hash_hmac('sha512', 'actual password' . $salt, 'secret key') ;

Be sure to store the salt in the database record, too, so that it can be used again during verification of the credentials.

Handling Forgotten Passwords

If your site stores user credentials, then you inevitably have users who forget their passwords. As a hash of the password is stored, not the password itself, you cannot resend the registered password to the user. One solution is to reset the password in the system to something random, and then send that in an email to the registered email address. Using the new password, the user can log in (and hopefully change their password upon doing so). For some sites, this approach may be okay, but email is not a secure protocol (normally), so sending passwords in emails is not ideal. Second, such systems put no time limit on when the new password can be used.

Offering a non-password solution to the forgotten password scenario can mitigate both of these problems. This alternative is a token-based solution, that works like so:

  1. When the user submits the lost password form, a token is generated by the system.
  2. The token is sent to the user’s email address as part of a link.
  3. When the user clicks that link, the user is taken to a specific page on the site that validates the token.
  4. If the token is valid, the user is immediately asked to change his or her password.

This may sound similar to the new password approach, but note that no password is being sent in an email. Second, and more importantly, the token should have a limited life to it (i.e., set to expire within X number of minutes). The token should also expire once used.

The token needs to be associated with the user’s account, but should not be reflective of the user’s information. In other words, you can’t just use the user’s ID or email address as the token. One idea would be to create a hash of a combination of the user’s ID, email address, and perhaps registration date. Salt the value, too, and you have a nice, unique token.

In terms of code, the page that handles the forgotten password request would validate the submitted username or email address and then use that to retrieve the pertinent information from the database:

$q = "SELECT CONCAT(id, email, date_registered), id FROM users WHERE email='actual email'";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) === 1) {
    list($data, $id) = mysqli_fetch_array($r);
} else {
    // Report problem.

That information can be used to create the token:

$salt = bin2hex(openssl_random_pseudo_bytes(20));
$token = hash_hmac('sha512', $data . $salt, 'secret key');

Store this token in a separate database table, along with an expiration date and time. Here’s that query:

INSERT INTO password_tokens (token, id, expiration)
 VALUES ('$token', $id, DATE_ADD(NOW(), INTERVAL 15 MINUTE))

And, again, this token is sent to the user’s email address, as part of a link:$token

The reset.php page would first confirm that a token was received in the URL, and that it’s of the correct length.

The page would then check the token against the stored tokens. That query is:

SELECT id FROM password_tokens WHERE token='$token' AND expiration<NOW()

As you can see, the query uses an extra conditional that confirms that the expiration date and time is less than the current moment. This prevents password reset attempts that take too long (which can be suspicious).

If that query returns one record, the user should be presented with the option to change his or her password to a new one. The token record should also be deleted from the database:

DELETE FROM password_tokens WHERE token='$token'

If the SELECT query did not return a record, then either the token is invalid or it has expired. In either case, simply explain to the user that the password reset process must be started again, and that the user must act upon the email within the time limitation.

And that’s how you would implement this token-based system. As an added benefit, this approach allows users to ignore unwanted password resets. For example, if I were to go to X website and enter someone else’s email address in the lost password form, this token-based system would not actually change the user’s password. Yes, the user would get an unrequested email (as far as he or she could tell), but the user can ignore that email and continue logging in with his or her current password.


There is always more to be learned about security, and this article should have added another trick or two to your arsenal. Consider implementing these ideas on your next new project, and perhaps even go back to an older site and see if it could stand to be improved. Most importantly, make sure that you’re adhering to an appropriate level of security for each project, based upon that project’s needs and sensitivities.

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive:

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020