views:

617

answers:

4

I put "username" and "password" to a form of mine. The action starts up a handler.php. The user sees then only a white page (handler.page) if he does not reload his browser at handler.php. If he does, the handler puts him to back to index.php.

I would like to put the user automatically back to the homepage after being at handler.php where he gets a login -cookie.

I have the following in my handler.php

$email = $_POST['email'];
$username = $_POST['username'];
$passhash_md5 = $_POST['passhash_md5']; 

 // COOKIE setting

 /* $cookie may look like this
   variables
        $username = "username"$
        $passhash_md5 = "password"$
        $email ="email"$
        $_SERVER['REMOTE_ADDR']=11.44.23.94$
   before md5:$
        "usernamepasshash_md5email11.44.23.94"$
   after md5:$
        "a08d367f31feb0eb6fb51123b4cd3cb7"$
 */

$login_cookie = md5(                                                                                                                                                                           
    $username .
    $password .
    $email .
    $_SERVER['REMOTE_ADDR']
);

setcookie ("login", $login_cookie);    

if (isset($_COOKIE['login']) )
{

    $sql2 = "SELECT * from users";
    $raw_user_list = pg_query($dbconn, $sql2);
    $user_list = pg_fetch_all($raw_user_list);

    // to process each user in the user-list that has a password 
    foreach ($user_list as $user => $passhash_md5)
    {                                                                                                                                                                                               
        //match the user list with the cookie$
        if ( $login_cookie == $_COOKIE['login'] )
        {
            header("Location: index.php"); 
            die("logged in");
        }
    }
    header("Location: index.php");   
    die("wrong username/password");
}
?>

I have a form which uses the POST -method and the action is handler.php.

My form

<form method="post" action="handler.php">
    <p>Username:
        <input name="username" type="text" size="40" />
    </p>

    <p>Email:
        <input name="email" type="text" size="230" />
    </p>

    <p>Password:
        <input name="password" type="password" size="230" />
    </p> 

    <input type="submit" value="OK" />
</form>

The handler page is not being called by AJAX.

I run the handler page unsuccessfully with the HEAD:

<head>
<meta http-equiv="refresh" content="5; URL=inedx.php">
</head>

However, I cannot include the HEAD because PHP does not allow to have output when you use header -commands.

How can you put the user automatically to the index.php if the login is successful?

+3  A: 

This should be your basic setup

First, the user comes to a login page and puts in their username/password. We'll call this login.php. It then sends the stuff to handler.php

HTML

<form method="POST" action="handler.php">
<input type="text" name="login[user]">
<input type="password" name="login[password]">
</form>

Then, the handler script recieves the POST data, processes if, and if the password hashes match, set a cookie and redirect back to the index page.

Login Script

// Check for a Login Form
if (isset($_POST['login']) )
{
    // Get the Data
    $sql2 = "SELECT * from users";
    $raw_user_list = pg_query($dbconn, $sql2);
    $user_list = pg_fetch_all($raw_user_list);

    // Go through each User 
    foreach ($user_list as $user => $passhash_md5)
    {   
        // Check if the passwords match
        if ( $passhash_md5 == md5($_POST['login']['password'] ))
        {
      // YOU NEED TO CREATE A COOKIE HERE  

            header("Location: index.php"); 
            die("logged in");
        }
    }
    header("Location: index.php");   
    die("wrong username/password");
}

Then, on every page you want to check for login, you redirect someone away if they don't have a login cookie set. You could expand this to check for a correct login cookie.

Every Page

// Check for a Cookie
if(!$_COOKIE['login'])
{
    header('Location: login.php');
    die("User Required");
}

I'm not too certain what you were trying to do there, but this is the basic set up for how to create a basic login form.


If you are try to check if the combination passed into the form is the same as the cookie try this:

// Set the Variables
$email = $_POST['email'];
$username = $_POST['username'];
$passhash_md5 = $_POST['passhash_md5']; 

 // COOKIE setting

 /* $cookie may look like this
   variables
        $username = "username"$
        $passhash_md5 = "password"$
        $email ="email"$
        $_SERVER['REMOTE_ADDR']=11.44.23.94$
   before md5:$
        "usernamepasshash_md5email11.44.23.94"$
   after md5:$
        "a08d367f31feb0eb6fb51123b4cd3cb7"$
 */

// Set what the cookie should look like
$login_cookie = md5(                                                                                                                                                                           
    $username .
    $password .
    $email .
    $_SERVER['REMOTE_ADDR']
);

// Check For the Cookie
if (isset($_COOKIE['login']) )
{
    // Check if the Login Form is the same as the cookie
    if ( $login_cookie == $_COOKIE['login'] )
    {
        header("Location: index.php"); 
        die("logged in");
    }
    header("Location: index.php");   
    die("wrong username/password");
}

I took out the database part because you aren't using the database part in any of the code, so it doesn't matter. It looks like you aren't trying to log someone in, but rather check that the cookie they have set to their machine contains the same string that they passed in on the form.


Ok, final edition, hopefully

// Set the Variables
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password']; 

 // COOKIE setting

 /* $cookie may look like this
   variables
        $username = "username"$
        $passhash_md5 = "password"$
        $email ="email"$
        $_SERVER['REMOTE_ADDR']=11.44.23.94$
   before md5:$
        "usernamepasshash_md5email11.44.23.94"$
   after md5:$
        "a08d367f31feb0eb6fb51123b4cd3cb7"$
 */

// Set what the cookie should look like
$login_cookie = md5(                                                                                                                                                                           
    $username .
    $password .
    $email .
    $_SERVER['REMOTE_ADDR']
);

// Check For the Cookie
if (isset($_COOKIE['login']) )
{
    // Check if the Login Form is the same as the cookie
    if ( $login_cookie == $_COOKIE['login'] )
    {
        header("Location: index.php"); 
        die("logged in");
    }
    header("Location: index.php");   
    die("wrong username/password");
}
// If no cookie, try logging them in
else
{
    $sql2 = sprintf("SELECT * from users WHERE passhash_md5='%s',
    pg_escape_string($login_cookie));
    $raw_user_list = pg_query($dbconn, $sql2);
    if ($user = pg_fetch_row($raw_user_list)) {.
        setcookie('login', $login_cookie);
        header("Location: index.php"); 
        die("logged in");
    } else {
    header("Location: index.php");   
    die("wrong username/password");
    }
}

Sprintf and Where clause provided by Rezzif

Chacha102
Your answer is excellent. I added the beginning of my handler to my message. It seems that you use a much shorter way for user authentication.
Masi
@Cha: Thank you for pointing out the logical mistake in my code! I am trying to log someone in, but I am confused with PHP, since it is new to me. In other words, I am trying to use the database too, since this is my first db-project.
Masi
Find it disappointing that you haven't corrected the issue that he is going through every user in the table to find the right one!
rezzif
I will... give me one second.
Chacha102
There you go. Added in with credit.
Chacha102
@Cha: Is `set_cookie` the same as `setcookie` in PHP? You use `set_cookie`. -- This line `$passhash_md5 = $_POST['passhash_md5'];` should apparently be `passhash_md5 = md5($_POST['passhash_md5']; since there is no value *passhash_md5* in the login form.
Masi
Fixed.
Chacha102
I created a new code based on your code and other answerers' codes. I added a while -loop to check the password in the Db, since I do not know how you can shortly check the value of one specific column. The variable $sql3 does not only contain the `passhash_md5`.
Masi
What is the column name?
Chacha102
@Cha: I mean by column name the name of a column in the table, for instance, *username* in the table *users*.
Masi
Right, when you use pg_fetch_row it creates an array of columns, so you would access the column username with $array['username'];
Chacha102
Do you mean like `echo $pg_fetch_row($data)['passhash_md5'];`? It gives me `Parse error: syntax error, unexpected '{' in /var/www/masi.php on line 20`. This suggests me that there is some problem with in reading the array.
Masi
You have to do it in two lines. Assign `pg_fetch_row($data)` to a variable, and then get the data using `$variable['passhash_md5']`. There was a long discussion about how PHP can't use the array returned by a function like that.
Chacha102
I run unsuccessfully the following code `$data = pg_query($dbconn, $sql); $result = $pg_fetch_row($data); $passhash = $result['passhash_md5'];`. Could you, please, clarify your last comment.
Masi
* where $sql is `$sql = "SELECT passhash_md5 FROM users WHERE username='a';";`, while I have dummy data in my db.
Masi
+1  A: 

Can't tell since you left out everything above the if statement. But it looks like you need a case for when $_COOKIE['login'] isn't set

Edit

Looks like your logic is a bit messed up. Your not setting any type of session variable to indicate when a user is authenticated. so you have nothing to check against on your other pages, to say that the user is logged in. Also, your foreach is overwriting the $passhash_md5 value with the result row:

foreach ($user_list as $user => $passhash_md5)

What you would need to do is probably:

foreach ($user_list as $user)

And then check the cookie against the column (ex: $user['md5hash'] == $login_cookie) which contains the md5 hash in the database. How you have it now, you are just checking to see if 1=1 since you are *$COOKIE['login'] to *$login_cookie* and then checking later on to see if those same variables equal each other.

Your whole usage of *$COOKIE seems to be unnecessary. You really should be using *$SESSION variables instead of everything you have in your script. First you'll need to query the database against the posted information using where statements. And if the user is authenticated, you should be setting a session variable to indicate they are authenticated. Something like: *$SESSION['loggedin'] = true; That way you can check on other pages to see *if($SESSION['loggedin'] === true), and if that is false, then redirect them to the login page. I suggest rewriting your login system using these suggestions instead of using what you have now.

Mark
Thank you for pointing that out! I updated my question.
Masi
updated to reflect the new code you posted
Mark
Thank you Mark for showing me the bug in the function `foreach` and the other bugs!
Masi
+2  A: 

As a side note are you really going through your entire users table to see if the person has a valid login?

You should really be using a where clause!


    $sql2 = sprintf("SELECT * from users WHERE UserName = '%s' AND UserPass = '%s'",
    pg_escape_string($_COOKIE['login']),
    pg_escape_string($passhash_md5));
    $raw_user_list = pg_query($dbconn, $sql2);
    if ($user = pg_fetch_row($raw_user_list)) {
       //Login valid
    } else {
      //Login invalid
    }

Not familair with pg but i hope that helps.

rezzif
Could you, please, explain why you use the function `sprintf`. It seems that it allows you to do some special formatting. --- **Where do the expressions '%s' point to?**
Masi
http://au.php.net/manual/en/function.sprintf.php %s is a place holder in a string that allows you to substitute values. so the first %s is the first value after the comma and so on. pg_escape_string escapes the sting in your sql so that it is safe from sql injection.
rezzif
@rezzif: Thank you for pointing that out! I did not know about the sql injection.
Masi
A: 

This is an answer based on Cha, Mark and rezzif's answers.

<?php

// independent variables
$dbHost = "localhost";
$dbPort = 5432;
$dbName = "masi";
$dbUser = "masi";
$dbPassword = "123456";

$conn = "host=$dbHost port=$dbPort dbname=$dbName user=$dbUser password=$dbPassword";

$dbconn = pg_connect($conn);

if(!$dbconn) {
    exit;
}

$sql = "SELECT username, passhash_md5, email
    FROM users
    WHERE username = '{$_POST['username']}'
    AND email = '{$_POST['email']}'
    AND passhash_md5 = '{$_POST['password']}';";

$result = pg_query($dbconn, $sql);
if(!$result) {
    exit;
}

$username = $_POST['username'];
$password = $_POST['password'];
$passhash_md5 = md5($_POST['password']);


 // COOKIE setting

 /* $cookie may look like this:
   variables
        $username = "username"
        $passhash_md5 = "password"
   before md5:
        "usernamepasshash_md5"
   after md5:
        "a08d367f31feb0eb6fb51123b4cd3cb7"
 */

$login_cookie = md5(
    $username .
    $password
);

$sql3 = "SELECT passhash_md5

            FROM users 
            WHERE username=$_POST['username'];";

$password_data_original = pg_query($dbconn, $sql3);

while ($row = pg_fetch_row($data)) {
    $password_original = $row[0];
}

$login_cookie_original = md5(
    $username .
    $password_original
);


// Check for the Cookie
if (isset($_COOKIE['login']) )
{

    // Check if the Login Form is the same as the cookie
    if ( $login_cookie_original == $login_cookie )
    {
        header("Location: index.php");
        die("logged in");
    }
    header("Location: index.php");
    die("wrong username/password");
}
    // If no cookie, try logging them in
else {
    // we do not want SQL injection so we use pg_escape_string
    $sql2 = sprintf("SELECT * from users
                    WHERE passhash_md5='%s',
                    pg_escape_string($login_cookie));
    $raw_user_list = pg_query($dbconn, $sql2);

    if ($user = pg_fetch_row($row_user_list)) {
        setcookie ("login", $login_cookie);
        header("Location: index.php");
        die("logged in");
    } else {
        header("Location: index.php");
        die("wrong username/password");
    }
}

pg_close($dbconn);
?>
Masi
This code gives me the error `Parse error: syntax error, unexpected '{' in /var/www/sivusto/handler.php on line [line: // Check for the Cookie]`
Masi