Jump to content

Help with login script


xkrja

Recommended Posts

First of all, I am a php beginner.

 

I've been working on a login script for a members area but I can't get it to work. I've spent hours trying to figure out what's wrong with it. Much of the code is from a tutorial but that didn't work either but the code was very easy to understand and that's why I wanted to use it. Please take a look at the code below. This is the "login.php" page:

 

<?php
//Connect to database
mysql_connect("localhost", "root", "my_password");
mysql_select_db("my_database");

function login($username, $password){
$username = addslashes($username);
$password = md5($password);
$query = mysql_query("SELECT * FROM user_accounts WHERE username='$username' AND password='$password'");
if(mysql_num_rows($query) == 1) {
    $info = mysql_fetch_array($query);
    $userid = $info['userid'];
    //echo "userid  =  " . $userid . "<br>";
    $sessionid = md5($userid . time());
    echo "sessionid från login: " . $sessionid . "<br/>";
    //echo "sessionid = " . $sessionid;
    $time = time();
    @setcookie("test_account", $sessionid, $time + 3600, '/', '');
    mysql_query("DELETE FROM user_sessions WHERE userid = '$userid'");
    mysql_query("INSERT INTO user_sessions (sessionid, userid, timestamp) VALUES('$sessionid','$userid','$time')");
    return $userid;
}
else{
    return 0;
}
}

function status() {
$sessionid = $_COOKIE["test_account"];
        echo "sessionid från cookie: " . $sessionid . "<br/>";
$oldtime = time() - 3600;
        echo "oldtime: " . $oldtime . "<br/>";
$query = mysql_query("SELECT * FROM user_sessions WHERE sessionid='$sessionid' AND timestamp>'$oldtime'");
echo "match: " . mysql_num_rows($query) . "<br/>";
        
        if(mysql_num_rows($query) == 1) {
	$info = mysql_fetch_array($query);
                echo "  info = " . $info . "<br/>";
	return $info['userid'];
}
        else {
return 0;
        }
}

if (isset($_POST["submit"])) {
    echo "SUBMIT <br/>";
if((strcmp($_POST["username"],'') != 0) && (strcmp($_POST["password"],'') != 0)){
    $login_status = login($_POST["username"], $_POST["password"]);
} 
elseif($_GET["logout"]){
    logout();
}
$userid = status();
}



if($userid > 0){
    //header("Location: area.php");
    echo "login correct <br/>";
}
else{
    if($login_status != '' && $login_status == 0){
        echo "invalid username/password combination<br>";
    }
?>
<h1>Login</h1>
<form action="login.php" method="POST">
Username <input type="text" name="username" />
Password <input type="password" name="password" />
<input type="submit" name="submit" value="Log In" />
</form>
No account? <a href="register.php">Register</a>
<?php } ?>

 

The database connection is correct. I can register new users with another form and they are added in the database. The problem seems to be with the cookies. For debugging purposes I echo the cookie value when using "setcookie" and the cookie value when reading the cookie with $_COOKIE. It seems they don't match. Why is that? There is a "lag" meaning that if I enter a username and password a cookie value is printed out which is the setcookie()-value but I get no value from the $_COOKIE and that check should be made after.

 

However, if I enter a user/password again the setcookie()-value is printed and the $_COOKIE-value is printed BUT it is the previous setcookie()-value. So that's what I mean with a lag. Why don't the $_COOKIE get the value that setcookie() sets?

 

Thanks for help!

Link to comment
Share on other sites

Thanks for the replies guys,

 

The session_start() didn't help. What should that do?

 

I must be getting something wrong with how this works. When a username and password is added a session is started and added to the database. After that the $_COOKIE tries to read the session from the database but it gets the previous one. Does that mean that a session cannot be created and then read during the same postback of the page?

 

Thanks for help!

Link to comment
Share on other sites

The code is not using sessions, so a session_start() would be pointless. You are setting a variable named $sessionid and saving it in the cookie and database, but that code is not using sessions of any kind.

 

You have an @ in front of the setcookie() statement. You probably did that because it was generating a header error due to the output from your echo statement.

 

A) Hiding error messages does not remove the error. You still have the error, the code still does not work, and now it is not telling you why it is not working. Never use @ in any code. There is no valid reason to do so. On a development system, you want to see all the errors because they tell you something is wrong and help you find and fix what is wrong. On a live server the display_errors setting would be off and any unexpected errors (finished, tested code does not normally generate any errors during its' execution) that did happen to occur would not be displayed.

 

B) The error message that got hidden by the @ was telling you that the output on the line where the echo statement is at, is preventing the header from being sent that is necessary for the cookie to work.

 

And yes, a $_COOKIE variable in delayed from the setcookie() statement. A $_COOKIE variable only gets set when the browser requests a page and sends the matching cookie to the web server. On the page that uses setcookie(), the corresponding $_COOKIE won't get set. You can 'fake' this by actually assigning the same value to the $_COOKIE variable that you just used in the setcookie() statement.

Link to comment
Share on other sites

Thanks, finally I get some things cleared out.

 

About the '@'-character; I more or less copied that from a tutorial I found so that wasn't my intention to hide any errors :-)

 

But if that is the case with that the $_COOKIE cannot read at the same time as the cookie is created. What is the alternative then? If this does not work, what is the standard approach?

 

Thanks again.

Link to comment
Share on other sites

If your setting a cookie on login redirect after successful login

 

header("Location: success.php");

 

Sessions wont need redirection but only last as long as the browser is open

 

You can set a session with any value

 

$sessionid = $_SESSION['loggedin']=1;

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.