Re: Correct code ?? PHP Basic pw athentication with mysql

From: Date: Mon, 27 Jul 2009 06:40:59 +0000
Subject: Re: Correct code ?? PHP Basic pw athentication with mysql
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-295860@lists.php.net to get a copy of this message
Jason Guritz wrote:
I cant seem to get this to work. Any ideas?? And If I have post this to the wrong area.. My sincere apologies! Thank you in advance! Jason <?php
if ( !isset($_SERVER['PHP_AUTH_USER']) ) { header('WWW-Authenticate: Basic realm="My realm"'); header("HTTP/1.0 401 Unauthorized"); exit; } else { $cxn = mysql_connect("localhost","root","") or die ("You didnt get this right!"); $db = mysql_select_db("secretdb",$cxn) or die ("Couldn't connect"); $sql = "SELECT id FROM users WHERE username = '$_SERVER[PHP_AUTH_USER]' AND 'password' = '$_SERVER[PHP_AUTH_PW]'"; The select statement here needs to have backticks, not single quotes Plus, you should really look at sanitizing those variables before you stuff them in an SQL statement! Run them through mysql_real_escape_string() at least. $sql = "SELECT id FROM users WHERE username = '$_SERVER[PHP_AUTH_USER]' AND password = '$_SERVER[PHP_AUTH_PW]'"; $result = mysql_query($sql) or die ("Couldn't get results."); $num = mysql_numrows($result); The above function is actually named mysql_num_rows(). You're missing an underscore. if ( $num == 1 ) { echo "<P>You are a valid user<BR>"; echo "Your username is: {$_SERVER['PHP_AUTH_USER']}<BR>"; echo "Your password is: {$_SERVER['PHP_AUTH_PW']}<BR>"; Again, you should sanitize your input before you use it! } else { echo "You are not authorized!"; } } ?> Side question, what happens if you get 2 or more results? Are you expecting their to be a possibility that you could have more then two results? -- Jim Lucas "Some men are born to greatness, some achieve greatness, and some have greatness thrust upon them." Twelfth Night, Act II, Scene V by William Shakespeare

« previous php.general (#295860) next »