How to Change a Password Script in PHP

Written by andy carr
  • Share
  • Tweet
  • Share
  • Pin
  • Email
How to Change a Password Script in PHP
Change passwords in a secure manner. (access denied image by dead_account from

PHP is used widely across the Web to provide dynamic websites and to authenticate logon information. A good PHP script hides the data so that it can't be deciphered by potential hackers. The password should never be visible and ideally should have some form of encryption to protect the information from prying eyes. PHP provides several ways of securing password data while at the same time providing the ability to automate the login process.

Skill level:


  1. 1

    Confirm how the password is accessed in the existing PHP code. If the information with the full user name and password is visible in the programming code in the text, remove it immediately. Anyone having access to the PHP code could use the information to login otherwise.

  2. 2

    Create a separate login file containing the login information for the password script as follows:


    $host = "<hostname>";

    $user = "<user>";

    $passwd = "";

    $dbname = "<dbname>";


    Fill in the fields identified by "<>" as required. Note the password part is deliberately left blank to add another layer of security.

  3. 3

    Include the new login script in the main code by making it into an include file. For example, if the login script in Step 2 is called "," include it in the main PHP code as follows:




  4. 4

    Set the password variable "$passwd" by extracting it from a MySQL table. Ideally, this is encrypted before it is inserted into the table by using an appropriate encryption function. One such function is "md5," which is part of the standard PHP library:

    $passwd = md5($_POST['passwd']);

    $sql = "insert into usertable values('$user','$userpass')";

    $result = mysql_query($sql);

    To extract the password, this would be coded as:

    $passwd = md5($_POST['passwd']);

    $sql = "select * from usertable where username='$user' and password='$passwd'";

    $result = mysql_query($sql);

Tips and warnings

  • Encryption of passwords is potentially dangerous. If a user forgets a password and it is encrypted in the database, it may prove difficult or impossible even for an administrator to recover the details. Therefore, it is ideal to keep a backup copy of passwords in a separate table in readable form.

Don't Miss

  • All types
  • Articles
  • Slideshows
  • Videos
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the site, you consent to the use of cookies. For more information, please see our Cookie policy.