[PHP]My ultimate challenge, usage of $_SESSIONS

Results 1 to 14 of 14
  1. #1
    Sorcerer Supreme Hidden is offline
    Member +Rank
    Apr 2008 Join Date
    .Location
    367Posts

    [PHP]My ultimate challenge, usage of $_SESSIONS

    So im trying to make a login system, everything works fine. They can login and it will show the $_SESSION['username']; when i echo it.
    But once they go back to the same page, or any other page. They have to login again..
    here's the script:
    Login.php
    PHP Code:
    <?php 
    session_start
    ();
    include(
    "includes/header.php");
    if(
    $_SESSION['password'] && $_SESSION['username'] > 1){
    header("Location: usercp.php");
    }
    if(isset(
    $_POST['submit'])){
    $username=sql($_POST['username']);
    $password=sql($_POST['password']);
    $logincheck=mysql_query("SELECT * FROM users WHERE username='$username'");
    while(
    $login=mysql_fetch_assoc($logincheck)){
    $sql_username=$login['username'];
    $sql_password=$login['password'];
    if((
    $username==$sql_username) && ($password==$sql_password)){
    $_SESSION['username']=$username;
    $_SESSION['password']=$password;
    echo
    "".$_SESSION['username']."<--username";
    if(
    $password !=$sql_password){
    echo
    "<strong>Login Failed, either your username or your password is incorrect!<br>If you forgot your password click <a href='forgotpass.php'>here</a>";
    unset(
    $_SESSION['username'],$_SESSION['password']);
    }
    }
    }
    }
    else{
    ?>
    <script type="text/javascript">
    formchecker(formname,field1,field2,reason1,reason2){
    if(document.formname.field1.value.length < 1){
    alert(reason1);
    document.formname.field1.focus();
    return false;
    }
    if(document.formname.field2.value.length < 1){
    alert(reason2);
    document.formname.field2.focus();
    return false;
    }
    return true;
    }
    </script>
    <form action='' name='login' method="POST" onSubmit="javascript:formchecker(login,username,password,Please fill out your username!,Please fill out your password!);">
    Username:<input type="text" name="username" value="<?php if(isset($_POST['username'])){
    echo 
    $_POST['username'];}?>" /><br />
    Password:<input type="password" name="password" value="<?php if(isset($_POST['password'])){
    echo 
    $_POST['password'];}?>" /><br />
    <input type="submit" name="submit"  />
    </form>
    <? } include("includes/footer.php");?>
    Some of it doesn't work yet, like the automatic javascript form checker.


  2. #2
    Elite Member andrew951 is offline
    Member +Rank
    Dec 2006 Join Date
    207Posts

    Re: [PHP]My ultimate challenge, usage of $_SESSIONS

    try
    if(isset($_SESSION['password'] && $_SESSION['username']){

  3. #3
    Sorcerer Supreme admLoki is offline
    Member +Rank
    Apr 2005 Join Date
    www.codenetwork.ruLocation
    345Posts

    Re: [PHP]My ultimate challenge, usage of $_SESSIONS

    PHP Code:
    if(isset($_SESSION['password'] && isset($_SESSION['username'])){ 
    And this :
    PHP Code:
    include("includes/header.php");
    if(
    $_SESSION['password'] && $_SESSION['username'] > 1){
    header("Location: usercp.php"); 
    willn't work if header.php outputs any content.

  4. #4
    The Gamma..? EliteGM is offline
    Grand MasterRank
    Jul 2006 Join Date
    NandolandLocation
    4,077Posts

    Re: [PHP]My ultimate challenge, usage of $_SESSIONS

    For the js;
    You have:
    Code:
    formchecker(formname,field1,field2,reason1,reason2){
    Make it:
    Code:
    function formchecker(formname,field1,field2,reason1,reason2){

  5. #5
    Member fook3d is offline
    MemberRank
    Sep 2007 Join Date
    Leicester, UKLocation
    65Posts

    Re: [PHP]My ultimate challenge, usage of $_SESSIONS

    A couple things to note here, javascript is not needed and processing of data was poorly written, but thats a given since I believe you are new to PHP.

    Anyway, I re-wrote it and commented it, you may need to slightly adjust, but the majority is there and should work without error.

    PHP Code:
    <?php  
    session_start
    (); 
    // Check if form is posted
    // Check username and password is set and neither fields are empty - buh bye JS thats not needed!
    if(isset($_POST['username']) AND !empty($_POST['username']) AND isset($_POST['password']) AND !empty($_POST['password']))
    {
        
    // Its posted if its here, so secure the data before its put into a database string - I suggest learning security and doing better than simply MRES
        
    $username mysql_real_escape_string($_POST['username']); 
        
    $password mysql_real_escape_string($_POST['password']); 
        
    // Check the database for both username and password relation to given details.
        
    $logincheck mysql_query("SELECT * FROM `users` WHERE `username` = '$username' AND `password` = '$password' LIMIT 1") or die (mysql_error()); 
        
    // If the record doesnt exist, error and tell them.
        
    if(!mysql_num_rows($logincheck)
        {
            
    // Include the header here, so no html is output previously, so if the details are correct, you can redirect with header()
            
    include_once('includes/header.php');
            echo 
    '<strong>';
            echo 
    'Login Failed, either your username or your password is incorrect!';
            echo 
    '<br /><br />';
            echo 
    'If you forgot your password click <a href="forgotpass.php">here</a>';
            echo 
    '</strong>';
        }
        else
        {
            
    // Given details match a user in the database, so set the query into a variable.
            
    $login mysql_fetch_assoc($logincheck);
            
    // Set sessions...
            
    $_SESSION['username'] = $login['username']; 
            
    // This is crazy to have a session simply containing a raw password string, add it to md5 and add a salt, for simplicity, I will use password with a salt of the username.
            
    $_SESSION['password'] = md5($login['password'] . $login['username']); 
            echo 
    $_SESSION['username'];
            
    header('Location: usercp.php');
        } 
    }
    else 
    // Else if form is not submitted... - PHP does the checking when you submit, JS not needed!
    {
        
    // Include header - again, cant be at the top because if the user gives correct username and password, it redirects - Wont work with header() if there is any output previously on the page.
        
    include_once('includes/header.php');
        
    // The form.
        
    echo '<form name="login" action="' $_SERVER['PHP_SELF'] . '" method="POST">';
        echo 
    'Username: <input type="text" name="username" value="'; if(isset($_POST['username'])) { echo $_POST['username']; } echo '" />';
        echo 
    '<br />';
        echo 
    'Password:<input type="password" name="password" value="'; if(isset($_POST['password'])) { echo $_POST['password']; } echo '" />';
        echo 
    '<br />';
        echo 
    '<input type="submit" name="submit" value="Log In">';
        echo 
    '</form>'
    }
    include(
    'includes/footer.php');
    ?>
    Also, every page where you want it to keep hold of the sessions, needs session_start(); at the top of the file.

    PHP Code:
    <?php
    session_start
    ();

  6. #6
    Grand Master Schfoo is offline
    Grand MasterRank
    May 2007 Join Date
    Georgia, USLocation
    746Posts

    Re: [PHP]My ultimate challenge, usage of $_SESSIONS

    Quote Originally Posted by andrew951 View Post
    PHP Code:
    if(isset($_SESSION['password'] && $_SESSION['username']){ 
    Isset doesn't work like that, try this:
    PHP Code:
    <?php
    if(isset($_SESSION['username'], $_SESSION['password'])){
        
    //Etc...
    }
    ?>
    Also, are you sure that you're calling session_start() at the begining of every page?

  7. #7
    Sorcerer Supreme Hidden is offline
    Member +Rank
    Apr 2008 Join Date
    .Location
    367Posts

    Re: [PHP]My ultimate challenge, usage of $_SESSIONS

    Quote Originally Posted by fook3d View Post
    A couple things to note here, javascript is not needed and processing of data was poorly written, but thats a given since I believe you are new to PHP.

    Anyway, I re-wrote it and commented it, you may need to slightly adjust, but the majority is there and should work without error.

    PHP Code:
    <?php  
    session_start
    (); 
    // Check if form is posted
    // Check username and password is set and neither fields are empty - buh bye JS thats not needed!
    if(isset($_POST['username']) AND !empty($_POST['username']) AND isset($_POST['password']) AND !empty($_POST['password']))
    {
        
    // Its posted if its here, so secure the data before its put into a database string - I suggest learning security and doing better than simply MRES
        
    $username mysql_real_escape_string($_POST['username']); 
        
    $password mysql_real_escape_string($_POST['password']); 
        
    // Check the database for both username and password relation to given details.
        
    $logincheck mysql_query("SELECT * FROM `users` WHERE `username` = '$username' AND `password` = '$password' LIMIT 1") or die (mysql_error()); 
        
    // If the record doesnt exist, error and tell them.
        
    if(!mysql_num_rows($logincheck)
        {
            
    // Include the header here, so no html is output previously, so if the details are correct, you can redirect with header()
            
    include_once('includes/header.php');
            echo 
    '<strong>';
            echo 
    'Login Failed, either your username or your password is incorrect!';
            echo 
    '<br /><br />';
            echo 
    'If you forgot your password click <a href="forgotpass.php">here</a>';
            echo 
    '</strong>';
        }
        else
        {
            
    // Given details match a user in the database, so set the query into a variable.
            
    $login mysql_fetch_assoc($logincheck);
            
    // Set sessions...
            
    $_SESSION['username'] = $login['username']; 
            
    // This is crazy to have a session simply containing a raw password string, add it to md5 and add a salt, for simplicity, I will use password with a salt of the username.
            
    $_SESSION['password'] = md5($login['password'] . $login['username']); 
            echo 
    $_SESSION['username'];
            
    header('Location: usercp.php');
        } 
    }
    else 
    // Else if form is not submitted... - PHP does the checking when you submit, JS not needed!
    {
        
    // Include header - again, cant be at the top because if the user gives correct username and password, it redirects - Wont work with header() if there is any output previously on the page.
        
    include_once('includes/header.php');
        
    // The form.
        
    echo '<form name="login" action="' $_SERVER['PHP_SELF'] . '" method="POST">';
        echo 
    'Username: <input type="text" name="username" value="'; if(isset($_POST['username'])) { echo $_POST['username']; } echo '" />';
        echo 
    '<br />';
        echo 
    'Password:<input type="password" name="password" value="'; if(isset($_POST['password'])) { echo $_POST['password']; } echo '" />';
        echo 
    '<br />';
        echo 
    '<input type="submit" name="submit" value="Log In">';
        echo 
    '</form>'
    }
    include(
    'includes/footer.php');
    ?>
    Also, every page where you want it to keep hold of the sessions, needs session_start(); at the top of the file.

    PHP Code:
    <?php
    session_start
    ();
    generally i would use js+php to check
    since javascript is a instant check.

  8. #8
    Grand Master FragFrog is offline
    Grand MasterRank
    Aug 2004 Join Date
    The NetherlandsLocation
    5,629Posts

    Re: [PHP]My ultimate challenge, usage of $_SESSIONS

    PHP Code:
    if(isset($_POST['username']) AND !empty($_POST['username'])) 
    This is, in PHP, equivalent to
    PHP Code:
    if($_POST['username']) 
    Don't burden yourself with too many redundant checks.

    As for your script:
    PHP Code:
    if($_SESSION['password'] && $_SESSION['username'] > 1){ 
    header("Location: usercp.php"); 

    What does usercp.php do? Try instead a var_dump of SESSION, see what has been set and what hasn't. Also, $_SESSION['username'] > 1 will return false if your username does not contain a number. Leave out the > 1.

  9. #9
    Sorcerer Supreme admLoki is offline
    Member +Rank
    Apr 2005 Join Date
    www.codenetwork.ruLocation
    345Posts

    Re: [PHP]My ultimate challenge, usage of $_SESSIONS

    Quote Originally Posted by FragFrog View Post
    PHP Code:
    if(isset($_POST['username']) AND !empty($_POST['username'])) 
    This is, in PHP, equivalent to
    PHP Code:
    if($_POST['username']) 
    lolwhat?
    PHP Code:
    $var ""//Defined but empty

    if(empty($var)) echo 'empty check'."\n"//Outputs text
    if(isset($var)) echo 'isset check'."\n"//Outputs text
    if($var) echo 'if() statement check'//Outputs nothing 
    If variable already defined but empty if() statement will return false, so this is usable when variable not defined.
    Also, empty() function is too slow on undefined variables.

  10. #10
    Grand Master Daevius is offline
    Grand MasterRank
    Jun 2007 Join Date
    NetherlandsLocation
    3,252Posts

    Re: [PHP]My ultimate challenge, usage of $_SESSIONS

    You have different functions for different things, but most of these function include others, so you should try and limit that redundancy.

    What he meaned, was that if a string is not empty, it must be set. So checking with isset() is redundant. And, if the string is not empty, it equals to true in a boolean...though I am unsure what happens if the string contains a zero...

    I would've done:
    if (strlen($_POST['username']))

    But generally I use regex's to include much more functionality in just one statement ;)

  11. #11
    :-) s-p-n is offline
    DeveloperRank
    Jun 2007 Join Date
    Next DoorLocation
    2,097Posts

    Re: [PHP]My ultimate challenge, usage of $_SESSIONS

    Quote Originally Posted by Daevius View Post
    You have different functions for different things, but most of these function include others, so you should try and limit that redundancy.

    What he meaned, was that if a string is not empty, it must be set. So checking with isset() is redundant. And, if the string is not empty, it equals to true in a boolean...though I am unsure what happens if the string contains a zero...

    I would've done:
    if (strlen($_POST['username']))

    But generally I use regex's to include much more functionality in just one statement ;)
    Yes, I agree. Though I actually use this script since strlen checks how many characters are inside the string within the parenthesis..
    PHP Code:
    if (strlen($_POST['username'])>0) {} 
    Using >0 is probably redundant since the null probably checks for that anyway. I usually use something like strlen($string)>2 to check and make sure the username is at least 3 characters; Only because I made sure all of my users had at least 3 chars before they registered..

    This way I check if the field is empty and if it has above the minimum chars all in one shot. Though it's not necessary to check that in a login form.. I write redundant code too.. haha

  12. #12
    Elite Member andrew951 is offline
    Member +Rank
    Dec 2006 Join Date
    207Posts

    Re: [PHP]My ultimate challenge, usage of $_SESSIONS

    but, arent you setting the session anyways. so you can just check isset.

  13. #13
    :-) s-p-n is offline
    DeveloperRank
    Jun 2007 Join Date
    Next DoorLocation
    2,097Posts

    Re: [PHP]My ultimate challenge, usage of $_SESSIONS

    Quote Originally Posted by andrew951 View Post
    but, arent you setting the session anyways. so you can just check isset.
    To be perfectly honest, checking to see if the username field is empty would be redundant.. As long as all users in the database have a username, all you'd have to do is check to make sure the username and password match up. No need to check if they're empty or full.

    So really, this should be sufficient in checking user log-in:
    PHP Code:
    $password $_POST['password'];
    $username $_POST['username'];

    $userQuery=mysql_query('SELECT FROM `users` WHERE `username` = '.$username.' AND `password` = '.$password.' LIMIT 1') or die('Username and Password do not match.<br>Please go <a href="'.$_SERVER['HTTP_REQUEST'].'" target="_self">back</a> and try again.');
    while(
    $userRow=mysql_fetch_array($userQuery)) { 
         
    //... get data...
        
    $rank=strip_tags($userRow['rank']);

        
    $_SESSION['username'] = $username;
        
    $_SESSION['password'] = $password;
        
    $_SESSION['rank'] = $rank;


    The session will only be started if the username and password match. Therefore, it should be safe.

  14. #14
    :drools: GriffinHeart is offline
    Grand MasterRank
    Sep 2003 Join Date
    With u :)Location
    1,451Posts

    Re: [PHP]My ultimate challenge, usage of $_SESSIONS

    Quote Originally Posted by s-p-n View Post
    To be perfectly honest, checking to see if the username field is empty would be redundant.. As long as all users in the database have a username, all you'd have to do is check to make sure the username and password match up. No need to check if they're empty or full.
    Redundant code is a computer programming term for code that is executed but has no effect on the output of a program
    "oh shit! the username is empty, you can't login, now i won't have to do a useless query to my db"
    Wanna bet wich one is faster?
    isset or a query

    anyways

    for admLoki
    PHP Code:
    $x "";

    if(isset(
    $x) && !(empty($x))); //evaluates for false
    if($x); //evaluates for false

    if(isset($y) && !(empty($y))); //evaluates for false
    if($y); //evaluates for false

    $z "foo";

    if(isset(
    $z) && !(empty($z)) //evaluates for true
    if($z//evaluates for true 



Advertisement