Gapex
Gapex

Reputation: 15

php crypt password and postgresql database

I'm new in PHP. I'm doing authentication, where I'm checking password with password stored in database PostgreSQL. On db site i used this function to crypt my password:

update ucty set psswd =  crypt('some_pswd',gen_salt('md5')) where uid='1';

In my PHP srcipt I'm using this code:

$query = "SELECT meno, priezvisko, nickname, psswd, uid 
          FROM ucty 
          where nickname='$nickname' and psswd=crypt('$password', psswd)";

Everything works fine, but I'm not sure , that this is correct way to secure my password.

Any advice?

Upvotes: 0

Views: 2168

Answers (1)

Chris Forrence
Chris Forrence

Reputation: 10114

You're correct; this isn't the correct way to secure your password.

  • You're encrypting the password as part of the query. This can be logged (in plaintext), so it's very possible for intruders (or anyone listening to your traffic) to see users' passwords in plaintext.

    "How can I prevent this?" Do your hashing on the server-side, within your PHP code. You can read up on this in the PHP manual.

    Essentially, you want to have your query to set a password be something like this:

      UPDATE ucty SET psswd=$hashed WHERE uid=1;
    
  • You're putting variables directly into the SQL statement. You didn't mention what method you're using to query the database, but you'll want to use prepared statements. This is a safe way to slide in user-supplied data (which $nickname and $password are).

    This would be an example of a good way to use prepared statements:

      $query = "SELECT meno, priezvisko, nickname, psswd, uid"
         . " FROM ucty"
         . " WHERE nickname=? and psswd=?";
    
      $stmt = $dbh->prepare($query);
      $stmt->execute(array($nickname, $hashedPassword));
    

Upvotes: 2

Related Questions