1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Login script requires two attempts

Discussion in 'PHP' started by gilgil2, Sep 12, 2012.

  1. #1
    Hi

    I have a log in script that if successful starts a session. When you enter the correct info it days that you are logged in, but when you try to acces a restricted file it says that you are not logged in. If you then log in again it works fine. I am not sure even where to start looking for the problem, is it likely to be in the log in script or in the restricted file?

    Thanks
    Gilgil
     
    gilgil2, Sep 12, 2012 IP
  2. plussy

    plussy Peon

    Messages:
    152
    Likes Received:
    5
    Best Answers:
    9
    Trophy Points:
    0
    #2
    first thing to check would be that you use session_start(); on every page where you want to use the session. This has to happen before you send any output to the screen so right at the beginning would be best.
     
    plussy, Sep 12, 2012 IP
  3. ezprint2008

    ezprint2008 Well-Known Member

    Messages:
    611
    Likes Received:
    15
    Best Answers:
    2
    Trophy Points:
    140
    Digital Goods:
    1
    #3
    is the folder structure set up were there are two separate folders and its going up a level? Public and Private? so technically you'd be in the public side, and then it jumps to Private and has lost the session and then re-login there and it works because now you're on the correct folder level?

    Otherwise it would be a bad session setting. You're posting the login info they enter to form, and not turning them into $_SESSION in a handler which causes the page to reload with no session_start()
     
    ezprint2008, Sep 13, 2012 IP
  4. gilgil2

    gilgil2 Member

    Messages:
    71
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #4
    Hi, I have session_start() at the top of each page and it is in the same folder, here is the login script with $_SESSION part, is there a problem with this bit?

    
    $sql="SELECT `active` FROM `users` WHERE `username`='".$username."' AND `password`='".$realp."'";    $search = mysql_query($sql) or die(mysql_error());  
        $match  = mysql_num_rows($search);  
     
    if($match==1)
    {
    $_SESSION['authenticated'] = true ;
    $_SESSION['username']=$_POST['username']; 
    $_SESSION['password']=$_POST['password'];
    	$url = 'index.php'; // default page for 
    	if(isset($_SESSION['url']))
    	{
    		$url = strip_tags($_SESSION['url']);
    		unset($_SESSION['url']);
    	}
    
    header("Location: http://website.com/$url");
    	exit("<p>Authenticated variable is: " . $_SESSION['authenticated'] . "</p>");
    }
    
    
    Code (markup):
    Is this where the problem is?

    Thanks for any help
     
    gilgil2, Sep 13, 2012 IP
  5. Poppers

    Poppers Member

    Messages:
    61
    Likes Received:
    1
    Best Answers:
    1
    Trophy Points:
    28
    #5
    I can't see anything wrong with that code, have you tried just a simple echo of the session on a protected page to see if it exists?
     
    Poppers, Sep 17, 2012 IP
  6. gilgil2

    gilgil2 Member

    Messages:
    71
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #6
    Hi poppers I did what I think you meant and echoed the following:

    <? echo $_SESSION;
    echo $_SESSION['authenticated'];
    echo $_SESSION['username'];
    echo $_SESSION['password'];?>

    The result was:

    array
    1
    correct username
    correct password

    Not entirely sure what this means? Is there a problem with that?
    Is it perhaps that I need to delay it by a second or two, is going to index.php too soon for it to register that the user is logged in?
    Thanks
    Gilgil
     
    gilgil2, Sep 17, 2012 IP
  7. Poppers

    Poppers Member

    Messages:
    61
    Likes Received:
    1
    Best Answers:
    1
    Trophy Points:
    28
    #7
    Nope shouldn't be, session is getting set, if it was to delay the PHP script would hang on the creation of the session and wait until it was created before continuing the script and redirecting. It all looks good looking at them echo results, so what are you using to check if the session exists on the protected page?
     
    Poppers, Sep 17, 2012 IP
  8. gilgil2

    gilgil2 Member

    Messages:
    71
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #8
    Thanks,

    When they are redirected to index.php and it says login successful and echoes username (this always happens first time) they can then click to go to useradmin.php at the top of which is the following bit of code to check they are logged in:

    <? 
    session_start();
    if(!isset($_SESSION['authenticated']))
    header ("Location: myaccount.php") ;
    ?>
    Code (markup):
    However the first time that they click to go to useradmin they are redirected to myaccount.php which tells them that they are not logged in and need to log in, if they then log in again and do the same thing useradmin.php works and certain information is echoed from the database, I just don't know why it takes two attempts...

    Thanks for your help.
     
    gilgil2, Sep 17, 2012 IP
  9. Poppers

    Poppers Member

    Messages:
    61
    Likes Received:
    1
    Best Answers:
    1
    Trophy Points:
    28
    #9
    
    if(!isset($_SESSION['authenticated']))
    header ("Location: myaccount.php") ;
    
    Code (markup):
    ^^ That bit of code is saying, if the authentication session ISN'T set, redirect to myaccount.php - surely that's not correct? It should be:

    
    if(isset($_SESSION['authenticated']))
    header ("Location: myaccount.php") ;
    
    Code (markup):
     
    Poppers, Sep 17, 2012 IP
  10. gilgil2

    gilgil2 Member

    Messages:
    71
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #10
    Sorry I realise I have set this up in a really bad and confusing way, here is what is included in myaccount.php:

    
    <?php
    session_start();  
    if(isset($_SESSION['authenticated']))
    { 
    include 'accountadmin.php';
     }
    else
    {echo 'You are not currently logged in, you must <br> <a href="\unsignedgigs/login.php\">Log In</a> to see this page.'; }
     
    ?>
    
    Code (markup):
    So basically if you are redirected to myaccount.php you are told to log in again, but it is a very counter intuitive and it was so long ago I'm not sure why I set it up like this.
     
    gilgil2, Sep 17, 2012 IP
  11. Poppers

    Poppers Member

    Messages:
    61
    Likes Received:
    1
    Best Answers:
    1
    Trophy Points:
    28
    #11
    But surely you would never get to the point of including 'accountadmin.php' because you would only get to myaccount.php if you are not logged in, there doesn't seem to be any redirection to myaccount.php if the user IS logged in therefore you will be stuck with "echo: you are not currently logged in" blah blah, the only way a user would see the accountadmin.php section is by manually clicking his way to that page.

    You should have:

    
    if(isset($_SESSION['authenticated']))
    header ("Location: myaccount.php") ;
    
    Code (markup):
    In the first file you mentioned... and...

    
    <?php
    session_start();  
    if(!isset($_SESSION['authenticated'])) {
    echo 'You are not currently logged in, you must <br> <a href="\unsignedgigs/login.php\">Log In</a> to see this page.';
    die();
    }
    
    include 'accountadmin.php';
    ?>
    
    Code (markup):
    In the other.

    If that doesn't work, rather than naming the session "true", a real value may make a difference, for example: $_SESSION['authenticated'] = "1";
     
    Poppers, Sep 17, 2012 IP
    gilgil2 likes this.
  12. gilgil2

    gilgil2 Member

    Messages:
    71
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #12
    Ok thanks, I'll try that I have probably just made it too confusing and have no idea what is going on, I'll change it round now.
    Thanks for your help.
     
    gilgil2, Sep 17, 2012 IP
  13. Poppers

    Poppers Member

    Messages:
    61
    Likes Received:
    1
    Best Answers:
    1
    Trophy Points:
    28
    #13
    Yeah it seems to be getting stuck in a loop, no worries :)
     
    Poppers, Sep 17, 2012 IP
  14. gilgil2

    gilgil2 Member

    Messages:
    71
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #14
    Hi again,

    I have reorganised it so that if you login you go to index.php and it echo Your are logged in as $username and then you can go to myaccount.php etc. so it is now simpler. However the issue is still there but I have made a few changes to try and narrow down the problem.

    For login.php there is now a part that checks if you are logged in and this works, so you can't log in again if you are already logged in (this also checks that logout.php works). However once you log in again (if you use a different username/password to last time) on index.php it echos the old username/password even though that had been successfully unset. But then if you go to myaccount.php it echoes the new username and information db associated with that username.

    Any idea how this is happening?

    Thanks
     
    gilgil2, Sep 18, 2012 IP
  15. Poppers

    Poppers Member

    Messages:
    61
    Likes Received:
    1
    Best Answers:
    1
    Trophy Points:
    28
    #15
    On logout.php are you using session_destroy(); rather than just clearing individual sessions? I suggest doing so if you aren't already.

    Also, in my code rather than creating multiple individual sessions in files, I tend to create a PHP file called session-handler.php that contains all the session info and then include this file into any file that requires the use of the session data. It's not really necessary but it makes life easier.

    It's hard to tell without actually seeing all the actual code and playing about with it myself, but it definitely sounds like the old session aren't being cleared properly.
     
    Poppers, Sep 18, 2012 IP
  16. gilgil2

    gilgil2 Member

    Messages:
    71
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #16
    Ok thanks, I'll post all the code, if you could have a look that would be great. (Some of the html is outdated but just want to get it all working first).

    Login.php:
    
    <?phpsession_start();
    error_reporting(E_ALL ^ E_NOTICE);
     if(isset($_SESSION['authenticated']))
    { 
    echo 'You are already logged in as:';
    echo $username;
    echo '<a href="logout.php">Logout</a>';
     }
    
    
    else {
     
    $SELF=basename(__FILE__);
    $msg='';
    
    
    if(isset($_POST['submit']) && isset($_POST['username']) && !empty($_POST['username']) && isset($_POST['password']) && !empty($_POST['password']))
    {  
        $link = mysql_connect('' '' '') or die('Could not connect: ' . mysql_error()); 
        mysql_select_db('') or die(mysql_error()); 
     
        $username = mysql_real_escape_string($_POST['username']);  
        $password = mysql_real_escape_string($_POST['password']);  
    
    
    $realp = md5($password);
     
        $sql="SELECT * FROM `users` WHERE `username`='".$username."' AND `password`='".$realp."' AND `active` IS NULL";
        $search = mysql_query($sql) or die(mysql_error());  
        $match  = mysql_num_rows($search);  
    
    
     
    if($match==1)
    {
    $_SESSION['authenticated'] = 1 ;
    $_SESSION['username']=$_POST['username']; 
    $_SESSION['password']=$_POST['password'];
        
    
    
    if (isset($_POST['rememberme'])) {
                /* Set cookie to last 1 year */
    setcookie('username', $_POST['username'], time()+60*60*24*365, 'www.example.com');
    setcookie('password', $_POST['password'], time()+60*60*24*365, 'www.example.com');
            } else {
                setcookie('username', $_POST['username'], false, 'www.example.com');
                setcookie('password', $_POST['password'], false, 'www.example.com');
            }
    
    
    
    
        header("Location: http://example.com/index.php");
        exit("<p>Authenticated variable is: " . $_SESSION['authenticated'] . "</p>");
    }
    else
    { 
        $msg='<p>Login Failed! Please make sure that you enter the correct details and that you have activated your account.</p>';  
    }  
    }
              
    
    
    echo '<html><body><h1>Login Form</h1>';
        
            if(!empty($msg))
            {
                echo $msg;
            }
    
    
    echo '<p>Please enter your name and password to login</p>  
            <!-- start sign up form -->  
            <form action="login.php" method="post">  
                <div>
                    <label for="name">Name:</label>  
                    <input type="text" name="username" value="" />
                </div>
                <div>
                    <label for="password">Password:</label>
                    <input type="password" name="password" value="" />
                </div>
       Remember Me: <input type="checkbox" name="rememberme" value="1"><br>
    
    
     
                <div><input type="submit" name="submit" class="submit_button" value="Login" /></div>
            </form>  
    <a href="http://www.example.com/forgot.php">Forgot Password?</a><br>
    <a href="http://www.example.com/register.php">Register here</a>
     
    </body>
    </html>';
    echo $username;
    echo $_SESSION['username'];
    echo $_SESSION['authenticated'];
    }
    ?>
    
    Code (markup):

    Index.php (directed here after successful login)
    
    <?php 
    session_start();
    if(isset($_SESSION['authenticated']))
    { 
    include 'usermenu.php';
     }
    else
    {echo 'You are not currently logged in <br> <a href="login.php">Log In</a>'; }
     
    ?>
    <html>
    <body>
    
    
    
    
    </body>
    </html>
    
    Code (markup):

    Usermenu.php (included if logged in)

    
    <? echo $_SESSION;
    echo $_SESSION['authenticated'];
    echo $_SESSION['username'];
    echo $_SESSION['password'];
    ?>
    You are logged in as <? echo $username ?>  
    <a href="myaccount.php">My Account</a>
    <a href="logout.php">Log Out</a>
    
    Code (markup):
    Logout.php
    
    <?php
    session_start();  
    if(isset($_SESSION['authenticated'])) 
        unset($_SESSION['authenticated']); 
    
    
    if(isset($_SESSION['username'])) 
        unset($_SESSION['username']); 
    
    
    if(isset($_SESSION['password'])) 
        unset($_SESSION['password']); 
    
    
    $past = time() - 100;
    setcookie('username', $_POST['username'], $past, 'www.example.com');
    setcookie('password', $_POST['password'], $past, 'www.example.com');
    
    
    session_destroy();
    
    
    if(isset($_SESSION['authenticated']))
    { 
    echo 'logout unsuccessful';
     }
    elseif (isset($_COOKIE['username']))
    {
    echo 'cookie not removed';
    }
    else
    {
    echo 'logout successful';
    }
    
    
    echo $_COOKIE["username"];
    
    
    
    
    echo $_SESSION['authenticated'];
    echo $_SESSION['username'];
    echo $_SESSION['password'];
    ?> 
    <html>
    <body>
    Return to <a href="index.php">home page</a>
    </body>
    </html>
    
    Code (markup):
    I think this is all the relevant files, myaccount.php accesses mysql db and takes values etc. from there but I don't think there is a problem with that.

    Sorry there is so much to look at, but if you could work out what has gone wrong I would be very grateful
     
    gilgil2, Sep 18, 2012 IP
  17. Poppers

    Poppers Member

    Messages:
    61
    Likes Received:
    1
    Best Answers:
    1
    Trophy Points:
    28
    #17
    I'll take a look at it in the morning for you :)
     
    Poppers, Sep 18, 2012 IP
  18. wyfytangsh

    wyfytangsh Peon

    Messages:
    32
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #18
    first thing to check would be that you use session_start(); do you do that ?
     
    wyfytangsh, Sep 19, 2012 IP
  19. EricBruggema

    EricBruggema Well-Known Member

    Messages:
    1,740
    Likes Received:
    28
    Best Answers:
    13
    Trophy Points:
    175
    #19
    @wyfytangsh: start reading friend, the TS did that, see previous posts..

    @TS: Where is the code where you redirect to the file or want to access the file?
     
    EricBruggema, Sep 19, 2012 IP
  20. gilgil2

    gilgil2 Member

    Messages:
    71
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #20
    Hi Eric, the redirect (php header) is about halfway down login.php (sorry I didn't include line numbers), and it redirects to index.php, the top few lines of which check if the user is logged in and if they are includes a menu that non logged in people won't see.
     
    gilgil2, Sep 19, 2012 IP