Personal computing discussed

Moderators: renee, SecretSquirrel, just brew it!

 
StefanVonS
Gerbil Elite
Topic Author
Posts: 553
Joined: Mon Aug 14, 2006 2:51 pm
Location: Strong Badia

Something wrong with this script? PHP

Thu Aug 05, 2010 2:24 pm

For some reason the following script seems to loop no matter what is input. If I hit cancel, then it behaves as expected; however, inputting correct or incorrect information results in a brief pause before the user/pass prompt returns. I checked in IE, FF, & Safari with the same result.

<?php // authenticate.php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database)
   or die("Unable to select database: " . mysql_error());

if (isset($_SERVER['PHP_AUTH_USER']) &&
   isset($_SERVER['PHP_AUTH_PW']))
{
   $un_temp = mysql_entities_fix_string($_SERVER['PHP_AUTH_USER']);
   $pw_temp = mysql_entities_fix_string($_SERVER['PHP_AUTH_PW']);

   $query = "SELECT * FROM users WHERE username='$un_temp'";
   $result = mysql_query($query);
   if (!$result) die("Database access failed: " . mysql_error());
   elseif (mysql_num_rows($result))
   {
      $row = mysql_fetch_row($result);
      $salt1 = "qm&h*";
      $salt2 = "pg!@";
      $token = md5("$salt1$pw_temp$salt2");

      if ($token == $row[3])
                    echo "$row[0] $row[1] :
         Hi $row[0], you are now logged in as '$row[2]'";

      else die("Invalid username/password combination");
   }
   else die("Invalid username/password combination");
}
else
{
   header('WWW-Authenticate: Basic realm="Restricted Section"');
   header('HTTP/1.0 401 Unauthorized');
   die ("Please enter your username and password");
}

function mysql_entities_fix_string($string)
{
   return htmlentities(mysql_fix_string($string));
}

function mysql_fix_string($string)
{
   if (get_magic_quotes_gpc()) $string = stripslashes($string);
   return mysql_real_escape_string($string);
}


?>
 
Shining Arcanine
Gerbil Jedi
Posts: 1718
Joined: Wed Jun 11, 2003 11:30 am

Re: Something wrong with this script? PHP

Thu Aug 05, 2010 4:30 pm

Assuming that it is looping, have you tried modifying the script with things like echo "probe 1" to see what sections are executing, what sections are looping and what sections are not executing? Perhaps it is something in login.php, as I see no loops in that script.
Disclaimer: I over-analyze everything, so try not to be offended if I over-analyze something you wrote.
 
StefanVonS
Gerbil Elite
Topic Author
Posts: 553
Joined: Mon Aug 14, 2006 2:51 pm
Location: Strong Badia

Re: Something wrong with this script? PHP

Thu Aug 05, 2010 4:46 pm

I may have figured out the problem. Tell me if I'm right or wrong here. It appears this only works on an apache server and I get back CGI/FAST CGI back from phpinfo(). Could this be the problem?
 
morphine
TR Staff
Posts: 11600
Joined: Fri Dec 27, 2002 8:51 pm
Location: Portugal (that's next to Spain)

Re: Something wrong with this script? PHP

Thu Aug 05, 2010 6:57 pm

Can we take a look at login.php? I don't see anything inherently wrong with your script as well.

As for your CGI question, per the PHP manual:

PHP manual wrote:
The HTTP Authentication hooks in PHP are only available when it is running as an Apache module and is hence not available in the CGI version.


I did find something odd: it appears that you're double-checking the user/pw through mysql *after* they authenticated? Isn't it redundant, or am I missing something?
There is a fixed amount of intelligence on the planet, and the population keeps growing :(
 
balzi
Gerbil XP
Posts: 357
Joined: Thu Aug 29, 2002 7:13 pm
Location: VIC, Australia

Re: Something wrong with this script? PHP

Thu Aug 05, 2010 7:12 pm

morphine wrote:
I did find something odd: it appears that you're double-checking the user/pw through mysql *after* they authenticated? Isn't it redundant, or am I missing something?


perhaps $db_username and $db_password are a fixed set (maybe root and ??? ) that will let the script access mysql to check the username and pwd provided by the browsing person?

of course, its still simpler to just try and login with the user provided user/pwd pair.. could be an even more obtuse table permission thing that Stefan is trying to get around. :-?
Japanese officer from Goons: "Honourable English Soldier - have unexplectedly run out of ammunition, could please borrow two boxes?"
Bloodnok: "What? what? .. No!!! You haven't returned our lawn-mower yet!?!"
 
Shining Arcanine
Gerbil Jedi
Posts: 1718
Joined: Wed Jun 11, 2003 11:30 am

Re: Something wrong with this script? PHP

Thu Aug 05, 2010 7:22 pm

morphine wrote:
Can we take a look at login.php? I don't see anything inherently wrong with your script as well.

As for your CGI question, per the PHP manual:

PHP manual wrote:
The HTTP Authentication hooks in PHP are only available when it is running as an Apache module and is hence not available in the CGI version.


I did find something odd: it appears that you're double-checking the user/pw through mysql *after* they authenticated? Isn't it redundant, or am I missing something?


http://en.wikipedia.org/wiki/Basic_acce ... entication

Programmers need to write their own authentication mechanisms to verify that the HTTP authorization information is correct. PHP has no way of knowing how to do that for them.

Unfortunately, I think that the way that this script is implemented would mean that an incorrect username and password would force a user to start a new session before he could try again. It would be better to use the same code for the unset state and the invalid username/password states.
Disclaimer: I over-analyze everything, so try not to be offended if I over-analyze something you wrote.
 
morphine
TR Staff
Posts: 11600
Joined: Fri Dec 27, 2002 8:51 pm
Location: Portugal (that's next to Spain)

Re: Something wrong with this script? PHP

Thu Aug 05, 2010 7:43 pm

Shining Arcanine wrote:
Programmers need to write their own authentication mechanisms to verify that the HTTP authorization information is correct. PHP has no way of knowing how to do that for them.

That's not correct. You can have a bog-standard HTTP authentication set on a directory, and PHP scripts inside that directory that can read the set username/password after the user has authenticated via plain HTTP auth. That's what the PHP_AUTH_USER and PHP_AUTH_PW server variables are for.

Having said that, it appears that I misread the script, as its intent seems to be doing the HTTP auth itself, and not just checking if it's already been done via other means.
Last edited by morphine on Thu Aug 05, 2010 8:59 pm, edited 1 time in total.
There is a fixed amount of intelligence on the planet, and the population keeps growing :(
 
StefanVonS
Gerbil Elite
Topic Author
Posts: 553
Joined: Mon Aug 14, 2006 2:51 pm
Location: Strong Badia

Re: Something wrong with this script? PHP

Thu Aug 05, 2010 8:11 pm

I'm posting the login.php page. For obvious security reasons, some data is redacted and will be show as # signs.

        <?php //login.php
        $db_hostname = '###.178.146.##';
        $db_database = 'publications';
        $db_username = '########';
        $db_password = '#########';
        ?>


I'm fairly certain there is nothing wrong here as I have other SQL scripts, including one that writes user names and passwords, that work properly.
 
morphine
TR Staff
Posts: 11600
Joined: Fri Dec 27, 2002 8:51 pm
Location: Portugal (that's next to Spain)

Re: Something wrong with this script? PHP

Thu Aug 05, 2010 9:15 pm

Several things you want to check/change:

- "SELECT *" is bad, bad mojo, because when you change your database schema and add or remove a field, you're going to end up with more or less columns in your result row, some of them probably useless and just wasting memory. Always do your SELECTs specifying exactly which fields you want.
- Also, I noticed that you're using numerical indexes for fetching rows with MySQL. Also not ideal because you have to remember and work with row indexes. Instead use mysql_fetch_assoc() instead of mysql_fetch_row() so that you're returned an associative array with the column names. Example:
$result= mysql_query("SELECT user_id FROM users WHERE password='awesome'");
$row = mysql_fetch_assoc($result);
echo "Your password is correct, your user ID is: $row[user_id]";

- You should use the mysqli_* functions instead of the regular mysql_* functions. The mysqli functions are the new versions, and they'll eventually replace the old ones.
- Even better, you should use a database abstraction class like PDO or ADODB. But keep it simple for now, you can change this later.
There is a fixed amount of intelligence on the planet, and the population keeps growing :(
 
StefanVonS
Gerbil Elite
Topic Author
Posts: 553
Joined: Mon Aug 14, 2006 2:51 pm
Location: Strong Badia

Re: Something wrong with this script? PHP

Fri Aug 06, 2010 6:07 am

Are the new mysqli commands version dependent? Using version 5. Thanks for the assoc command, hadn't learned that one yet.
 
morphine
TR Staff
Posts: 11600
Joined: Fri Dec 27, 2002 8:51 pm
Location: Portugal (that's next to Spain)

Re: Something wrong with this script? PHP

Fri Aug 06, 2010 11:03 am

StefanVonS wrote:
Are the new mysqli commands version dependent? Using version 5. Thanks for the assoc command, hadn't learned that one yet.

Yeah, but they're available in version 5.0.x at earliest, and I think even back on 4.3. It shouldn't be a concern, it's not cutting-edge stuff.
There is a fixed amount of intelligence on the planet, and the population keeps growing :(
 
StefanVonS
Gerbil Elite
Topic Author
Posts: 553
Joined: Mon Aug 14, 2006 2:51 pm
Location: Strong Badia

Re: Something wrong with this script? PHP

Fri Aug 06, 2010 11:25 am

I was able to work around the problem by using forms rather than HTTP authentication.

<?php // authenticate.php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database)
   or die("Unable to select database: " . mysql_error());

if (isset($_POST['user']) && isset($_POST['pass']))
{

    $un_temp = mysql_entities_fix_string($_POST['user']);
   $pw_temp = mysql_entities_fix_string($_POST['pass']);

   $query = "SELECT * FROM users WHERE username='$un_temp'";
   $result = mysql_query($query);
   if (!$result) die("Database access failed: " . mysql_error());
   elseif (mysql_num_rows($result))
   {
      $row = mysql_fetch_row($result);
      $salt1 = "qm&h*";
      $salt2 = "pg!@";
      $token = md5("$salt1$pw_temp$salt2");
         
      if ($token == $row[3])
                    echo "$row[0] $row[1] :
         Hi $row[0], you are now logged in as '$row[2]'";

      else die("Invalid username/password combination");
   }
   else die("Invalid username/password combination");
}
else
{
   echo <<<_END
    <form method="post" action="authenticate.php"><pre>
    Username: <input type="text" name="user" />
    Password: <input type="text" name="pass" />
    <input type="submit" />
    </pre>
    </form>
_END;
}

function mysql_entities_fix_string($string)
{
   return htmlentities(mysql_fix_string($string));
}

function mysql_fix_string($string)
{
   if (get_magic_quotes_gpc()) $string = stripslashes($string);
   return mysql_real_escape_string($string);
}


?>

Who is online

Users browsing this forum: No registered users and 1 guest
GZIP: On