Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It is so important that new programmers learn to do username/password authentication properly I felt it necessary to write this longer post.</p> <p>Firstly, as eicto pointed out, the mysql extension is both deprecated and should really not even be used ever.</p> <p>So to the metal.<br> visit php.net and learn about <a href="http://ca1.php.net/pdo" rel="nofollow">PDO</a></p> <p>Never store unencoded passwords.</p> <p>here is what you should do:</p> <p>set up PDO:</p> <pre><code>// you need to store $link somewhere. in a class preferrably function InitPDO(&amp;$link) { // havet the database handle all strings as UTF-8. $options = array('PDO::MYSQL_ATTR_INIT_COMMAND' =&gt; 'set names utf8'); $link = new PDO ( 'mysql:host='.$config['dsn_host'].';dbname='.$config['dsn_db'], $config['username'], $config['password'], $options ) ; // If there is an error executing database queries, have PDO to throw an exception. $link-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $link-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false); } </code></pre> <p>upon registration of user.</p> <pre><code>function RegisterUser($username, $password, $company) { // hash the pwd $hpwd = hash('sha256',$password); $q ='insert into users values(username, password, company) values(?,?,?)'; $stmt = $link-&gt;prepare($q); $stmt-&gt;execute(array( $username, $hpwd, $company)); } </code></pre> <p>// validate user and return the company if successfull</p> <pre><code>function ValidateUser($username, $password, &amp;$company) { $hpwd = hash('sha256',$password); $q ='select company from users where username=? AND password=?'; $stmt = $link-&gt;prepare($q); $stmt-&gt;execute(array( $username, $hpwd)); if( ($company = $stmt-&gt;fetch(PDO::FETCH_COLUMN)) === false ) { $company = 'invalid'; // because user auth failed'; } //else all is good } </code></pre> <p>example test usage.</p> <pre><code>// assumes there is a 'login.php' and a 'invalid.php' file $link = null; InitPDO( $link ); RegisterUser('tester','password','login'); VerifyUser('tester','password', $redir ); if( file_exists( $redir . '.php' ) ) { header( 'Location: '. $redir . '.php' ); exit; } echo 'error. no valid page found to fullfill query'; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload