Mega Code Archive

 
Categories / Php / Authentication
 

PHP3 Authentication using MySQL (also has nice query_db() function

to return an array of arrays from a MySQL query result). <? // All of this SHOULD go into an .inc file function query_db($query) { // connect and get row(s) $mysql = mysql_pconnect('host', 'sqluser', 'sqlpass'); $success = mysql_select_db('database'); $result = mysql_query($query, $mysql); if ($err) { // return empty array :P echo "Error querying database<BR>\n"; echo "$err<BR>\n"; echo "Please alert <A HREF=\"root@yoursite.com\">admin</A><BR>\n"; return array(); } else { // make the array $ret_array = array(); // do we have something? if (mysql_num_rows($result) > 0) { // yes get each one and stuff it in while ($row = mysql_fetch_array($result)) { $ret_array[] = $row; } } // returns arrays of rows, or array() if no rows return $ret_array; } } function authenticate() { // not authenticated, or previously failed authentication Header('WWW-authenticate: basic realm="Realm name"); Header('HTTP/1.0 410 Unauthorized'); echo "You must have a valid login and password to access this page\n"; } function LoginIsValid($uname, $passwd) { // don't even bother if they're empty if ($uname == "" | $passwd == "") return 0; // query the database $query = "SELECT userid,password FROM users WHERE username='$uname'"; $result = query_db($query); // did we get anything back if (count($result) != 0) { // let's get 'each one' (just for showing how to get multiple rows w/ my query_db) while (list($key, $arr) = each($result)) { $row = $arr; // get a row $uid = $row['userid']; $pass = $row['password']; if ( (crypt($passwd, $pass) == $pass) and ($pass != "") ) { return $uid; // valid login } else { return 0; // invalid login } } // end while() } else { return 0; // not even a user by that name! } // end if (count($result) != 0) } // end function ?> <? // THIS part goes in your page require('db.inc'); // or where ever you have the above code if (LoginIsValid($PHP_AUTH_USER,$PHP_AUTH_PW) == 0) authenticate(); // if I need an else or the like, let me know! ?>