Page 1 of 3 123 LastLast
Results 1 to 40 of 85

Thread: login problems

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2004
    Posts
    447

    login problems

    I'm having logging problems. It keeps logging out when I click on the url and entering. These are my pages. First it's the index page where the rest are include files found in it:
    index.php:
    PHP Code:
    <?php 
    //twotexts
    ob_start();
    session_start();//the only thing related to the login
    //...
    login page: index.php
    PHP Code:
    <?php
    ob_start
    ();
    include(
    "dbconnection.php");
    ?>
    <div style="float: left; width: 100%; margin: 0px 0px 0px 0px; background-color: #7C7C7C; border: 1px solid #A5A498; border-width: 1px 1px 0px 1px;">
        <span style="float: left; padding: 2px 10px 0px 12px; color: #FFFFFF; font-family: arial; font-weight:bold; font-size: 13px;">Login</span>
    </div>
    <div style="float: left; width: 100%; height: 120px; background-color: #B4B3A9; border: 1px solid #A5A498; margin: 0px 0px 0px 0px; overflow-x: hidden; overflow-y: auto;">
    <?php
    function login(){
    ?>
        <table border="0">
            <tr>
                <td>Administrator:</td><td><input type="checkbox" id="adminid" name="admin" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C;" value="no" onClick="if(this.value=='no'){this.value='yes'; document.getElementById('register').style.display = 'none';} else{this.value='no';document.getElementById('register').style.display = 'block';};" /></td>
            </tr>
            <tr>
                <td>Username:</td>
                <td><input type="text" name="<?php //vb_login_username?>username" id="username" style="float: left; border: 1px solid #7C7C7C; font: 9px verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" value="User Name" onBlur="if (this.value == '') this.value = 'User Name';" onFocus="if (this.value == 'User Name') this.value = '';" /></td>
            </tr>
            <tr>
                <td>Password:</td><td><input type="password" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" <?php //name="pass"?> name="<?php //vb_login_username?>pass" id="pass" /></td></tr>
            <tr>
                <td><a id="register" href="login/register.php" style="float: left; display: block; background-color: #7C7C7C; text-align: left; padding: 0px 0px 0px 5px; width: 80px; height: 20px; text-decoration: none; color: #ffffff; border: 1px solid #7C7C7C; font-weight: bold;" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'">Register</a></td><td align="right"><input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 100px; height: 20px;" name="submit" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Login" /></td>
            </tr>
        </table>
    <?php
    }

    //Checks if there is a login cookie
    if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directs you to the members page
        
    $myusername $_COOKIE['ID_my_site'];
        
    $pass $_COOKIE['Key_my_site'];
        
    $admin $_COOKIE['Admin_my_site'];
        
    $user $_COOKIE['User_my_site'];    
        
    $sql "SELECT * FROM ";
        if(
    $admin=="yes"){
            
    $sql .= $dbTable2;
        }else{
            
    $sql .= $dbTable;
        }
        
    $sql .= " WHERE username = '".mysql_real_escape_string($myusername)."'";
        
    $check mysql_query($sql)or die(mysql_error());
        while(
    $info mysql_fetch_array$check )){
            if (
    $pass != $info['password']){
            }else{
                
    //print("Welcome ".$myusername."! <br />Visit your <a href=\"login/member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>");
                //header("Location: login/member.php");
                //header("Location: ");
            
    }
        }
    }
    //if the login form is submitted
    if (isset($_POST['submit'])){ // if form has been submitted
        
    if(!$_POST['username'] | !$_POST['pass']) {// makes sure they filled it in
            //die('You did not fill in a required field.');
            
    print('You did not fill in a required field.');
        }
    // checks it against the database
        
    if (!get_magic_quotes_gpc()){
            
    $_POST['email'] = addslashes($_POST['email']);
        }
        
    $sql "SELECT * FROM ";
        if(
    $admin=="yes"){
            
    $sql .= $dbTable2;
        }else{
            
    $sql .= $dbTable;
        }
        
    $sql .= " WHERE username = '".$_POST['username']."'";
        
    $check mysql_query($sql)or die(mysql_error());
        
    //Gives error if user dosen't exist
        
    $check2 mysql_num_rows($check);
        if (
    $check2 == 0) {
            
    //die('That user does not exist in our database. <a href=login/register.php>Click Here to Register</a>');
            
    print('That user does not exist in our database.');
            
    login();
        }
        while(
    $info mysql_fetch_array$check )){
            
    $_POST['pass'] = stripslashes($_POST['pass']);
            
    $info['password'] = stripslashes($info['password']);
            
    $_POST['pass'] = md5($_POST['pass']);

            
    //gives error if the password is wrong
            
    if ($_POST['pass'] != $info['password']){
                
    //die('Incorrect password, please try again.');
                
    print('Incorrect password, please try again.');
                
    login();
            }else{
                
    // if login is ok then we add a cookie
                
    $_POST['username'] = stripslashes($_POST['username']);
                
    $hour time() + 3600;
                
    setcookie(ID_my_site$_POST['username'], $hour);
                
    setcookie(Key_my_site$_POST['pass'], $hour);
                if(
    $_POST["admin"]=="yes"){
                    
    setcookie(Admin_my_site$_POST['admin'], $hour);
                    print(
    "<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome ".$myusername."! <br />Visit your <a style=\"text-decoration: none;\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" href=\"login/member.php\">member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
                }else{
                    
    setcookie(User_my_site$_POST['admin'], $hour);
                    print(
    "<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome <span id=\"myusername\">".$myusername."</span>! <br />Visit your <a style=\"text-decoration: none;\" href=\"login/member.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
                }
                
    //then redirect them to the members area
                //header("Location: login/member.php");
                //print("Welcome".$username);
                //header("Location: login/member.php");
                //header("Location: ");
                
            
    }
        }
    }else{
        
    // if they are not logged in
        
    login();
    }
    ?>
    </div>
    logout.php
    PHP Code:
    <?php
    ob_start
    ();
    include(
    "dbconnection.php");
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Logout</title>
    </head>

    <body>
    <?php
    $past 
    time() - 100;
    //this makes the time in the past to destroy the cookie
    setcookie(ID_my_sitegone$past);
    setcookie(Key_my_sitegone$past);
    setcookie(Admin_my_sitegone$past);
    header("Location: ../index.php");
    ?> 
    </body>
    </html>
    Compare bible texts (and other tools):
    TheWheelofGod

  2. #2

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2004
    Posts
    447

    Re: login problems

    register.php
    PHP Code:
    <?php
    include("dbconnection.php");
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Register</title>
    </head>

    <body bgcolor="#505050" text="#000000" link="#363636" vlink="#363636" alink="#d5ae83">
            <div id="master" style="width: 1240px; height: 780px; margin: 0px auto; overflow: hidden; text-align: center;">
                <div id="logo" style="float: left; margin: 0px; border: none; background-color: #ECECEC; width: 100%; height: 120px; padding: 0px 5px 0px 0px;">
                    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="655" height="120" id="wheelofgod2" align="middle">
                        <param name="allowScriptAccess" value="sameDomain" />
                        <param name="movie" value="flashclips/wheelofgod2.swf" />
                        <param name="quality" value="high" />
                        <param name="bgcolor" value="#ECECEC" />
                        <embed src="../../flashclips/wheelofgod2.swf" quality="high" bgcolor="#ECECEC" width="655" height="120" name="wheelofgod" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
                    </object>
                </div>
                <div id="leftbar" style="float: left; width: 200px; height: 1200px; margin: 5px 0px 0px 0px; background-color: #505050;">
        <?php //$Colors = Array("FF0000", "0000FF", "009900", "FF9900", "660099", "00FFFF");
            
    include("../../getFiles/links.php");
            include(
    "../../getFiles/updates.php");?>
                </div>
                <div id="main" style="float: left; margin: 5px 5px 5px 5px; background-color: #D2C5A0; border: 1px solid #B5A26F; width: 810px; height: 640px; padding: 5px 5px 5px 5px; overflow-y: auto;">
    <?php
    //This code runs if the form has been submitted
    if (isset($_POST['submit'])){//This makes sure they did not leave any fields blank
        
    if (!$_POST['username'] | !$_POST['pass'] | !$_POST['pass2']){
            
    //die('You did not complete all of the required fields');
            
    print('You did not complete all of the required fields');
        }
        
    // checks if the username is in use
        
    if (!get_magic_quotes_gpc()){
            
    $_POST['username'] = addslashes($_POST['username']);
        }
        
    $usercheck $_POST['username'];
        
    $check mysql_query("SELECT username FROM ".$dbTable." WHERE username = '$usercheck'") or die(mysql_error());
        
    $check2 mysql_num_rows($check);

        
    //if the name exists it gives an error
        
    if ($check2 != 0) {
            
    //die('Sorry, the username '.$_POST['username'].' is already in use.');
            
    print('Sorry, the username '.$_POST['username'].' is already in use.');
        }

        
    // this makes sure both passwords entered match
        
    if ($_POST['pass'] != $_POST['pass2']) {
            
    //die('Your passwords did not match. ');
            
    print('Your passwords did not match. ');
        }
        
        
    // here we encrypt the password and add slashes if needed
        
    $_POST['pass'] = md5($_POST['pass']);
        if (!
    get_magic_quotes_gpc()) {
            
    $_POST['pass'] = addslashes($_POST['pass']);
            
    $_POST['username'] = addslashes($_POST['username']);
        }

    // now we insert it into the database
    $insert "INSERT INTO ".$dbTable." (
    ...// ...
    )"
    ;
    //echo $insert;
    //$add_member = mysql_query($insert);
    ?>
    <div style="float: left; width: 100%; margin: 5px 0px 0px 0px; background: #7C7C7C; border: 1px solid #A5A498; border-width: 1px 1px 0px 1px;">
        <span style="float: left; padding: 2px 10px 0px 12px; color: #FFFFFF; font-family: arial; font-weight:bold; font-size: 13px">Registered</span>
    </div>

    <p>Thank you <?php echo "<span style=\"font-weight: bold; font-style: italic;\">".$_POST['username']."</span>"?>, you have registered - you may now <a href="../index.php">login</a>.</p>
    <?php
    }else{
    ?>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
        <table border="0">
            <tr><td>*Username:</td><td><input type="text" name="username" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 200px; height: 15px;" maxlength="60" /></td></tr>
            <tr><td>*Password (10 characters):</td><td><input type="password" name="pass" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 200px; height: 15px;" maxlength="10" /></td></tr>
            <tr><td>*Confirm Password (10 characters):</td><td><input type="password" name="pass2" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 200px; height: 15px;" maxlength="10" /></td></tr>
            <tr>
                <td>*First Name:</td>
                <td><input name="fname" size="29" maxlength="30" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 200px; height: 15px;" /></td>
            </tr>
            <tr>
                <td>*Last Name:</td>
                <td><input name="lname" size="29" maxlength="40" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 200px; height: 15px;" /></td>
            </tr>
            <tr>
                <td>*Your e-mail:</td>
                <td><input name="email" size="29" maxlength="40" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 200px; height: 15px;" /></td>
            </tr>
            <tr>
                <td>Your URL:</td>
                <td><input name="url" size="29" maxlength="100" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 200px; height: 15px;" /></td>
            </tr>
            <tr>
                <td>Additional URL:</td>
                <td><input name="addnlurl" size="29" maxlength="100" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 200px; height: 15px;" /></td>
            </tr>
            <tr>
                <td>
                    <input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 200px; height: 20px; margin: 5px 5px 5px 5px;"  onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" name="submit" value="Register" />
                </td>
                <td>
                    <input type="reset" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 200px; height: 20px; margin: 5px 5px 5px 5px;"  onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Reset" name="reset" />
                </td>        
            </tr>
        </table>
    </form>
    <?php
    }
    ?>
                </div>
                <div id="rightbar" style="float: left; width: 200px; height: 1200px; margin: 5px 0px 0px 5px; background-color: #505050;">
    <?php 
    include("index.php");
    //include("../../getFiles/whattodo.php");
    include("../../getFiles/posts.php");
    ?>
                </div>
            </div>
        </div>
    </body>
    </html>
    Compare bible texts (and other tools):
    TheWheelofGod

  3. #3

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2004
    Posts
    447

    Re: login problems

    member.php
    PHP Code:
    <?php
    ob_start
    ();
    include(
    "dbconnection.php");
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Members Page</title>
    </head>

    <body bgcolor="#505050" text="#000000" link="#363636" vlink="#363636" alink="#d5ae83">
            <div id="master" style="width: 1240px; height: 780px; margin: 0px auto; overflow: hidden; text-align: center;">
                <div id="logo" style="float: left; margin: 0px; border: none; background-color: #ECECEC; width: 100%; height: 120px; padding: 0px 5px 0px 0px;">
                    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="655" height="120" id="wheelofgod2" align="middle">
                        <param name="allowScriptAccess" value="sameDomain" />
                        <param name="movie" value="flashclips/wheelofgod2.swf" />
                        <param name="quality" value="high" />
                        <param name="bgcolor" value="#ECECEC" />
                        <embed src="../../flashclips/wheelofgod2.swf" quality="high" bgcolor="#ECECEC" width="655" height="120" name="wheelofgod" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
                    </object>
                </div>
                <div id="leftbar" style="float: left; width: 200px; height: 1200px; margin: 5px 0px 0px 0px; background-color: #505050;">
        <?php //$Colors = Array("FF0000", "0000FF", "009900", "FF9900", "660099", "00FFFF");
            
    include("../../getFiles/links.php"); ?>
                </div>
                <div id="main" style="float: left; margin: 5px 5px 5px 5px; background-color: #D2C5A0; border: 1px solid #B5A26F; width: 810px; height: 640px; padding: 5px 5px 5px 5px; overflow-y: auto;">
    <?php
    //checks cookies to make sure they are logged in
    if(isset($_COOKIE['ID_my_site'])){
        
    $myusername $_COOKIE['ID_my_site'];
        
    $pass $_COOKIE['Key_my_site'];
        
    $admin $_COOKIE['Admin_my_site'];
        
    $user $_COOKIE['User_my_site'];
        
    $sql "SELECT * FROM ";
        if(
    $admin=="yes"){
            
    $sql .= $dbTable2;
        }else{
            
    $sql .= $dbTable;
        }
        
    $sql .= " WHERE username = '".mysql_real_escape_string($myusername)."'";
        
    //echo $sql;

        
    $check mysql_query($sql)or die(mysql_error());
        while(
    $info mysql_fetch_array$check )){//if the cookie has the wrong password, they are taken to the login page
            
    if ($pass != $info['password']){
                
    header("Location: ../index.php");
            }else{
    //otherwise they are shown the admin area
            
    ?>
            <div style="float: left; width: 100%; margin: 5px 0px 0px 0px; background: #7C7C7C; border: 1px solid #A5A498; border-width: 1px 1px 0px 1px;">
        <span style="float: left; padding: 2px 10px 0px 12px; color: #FFFFFF; font-family: arial; font-weight:bold; font-style: italic; font-size: 13px"><?php echo mysql_real_escape_string(strtoupper($myusername)); ?>'s Member Stat.</span>
    </div>
                <?php
                
    include("memberStat.php");
                echo 
    "<a href=\"logout.php\">Logout</a>";
            }
        }
    }else{
    //if the cookie does not exist, they are taken to the login screen
        
    header("Location: ../index.php");
    }
    ?>
                </div>
                <div id="rightbar" style="float: left; width: 200px; height: 1200px; margin: 5px 0px 0px 5px; background-color: #505050;">
    <?php 
    include("index.php");
    //include("../../getFiles/whattodo.php");
    include("../../getFiles/updates.php");
    include(
    "../../getFiles/posts.php");
    ?>
                </div>
            </div>
        </body>
    </html>
    Compare bible texts (and other tools):
    TheWheelofGod

  4. #4
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: login problems

    cookies are a type of header; this means that they must be sent to the browser before any output is sent. you're sending output, and then trying to set cookies later on in your login script. move your login logic to the top of the script, and echo stuff later on. a separation of logic and presentation is always good practice, anyway. oh yeah, and it looks like you're trying to use constants for the name of your cookies (in your setcookie() calls), but the first parameter of this function should be a string. if this wasn't a modification you made accidentally when posting, your cookies would never get set properly because those constants don't exist.

    also, I'd recommend not using addslashes() and using mysql_real_escape_string() instead. I do see that you've used the latter at least somewhere in your script, but it's best to pretty much never use the former, I'd say -- at least when you're dealing with raw data that will be used in a database situation.

    I might also suggest that you only use cookies to store user information, and use sessions to store any temporary login information (like whether or not that person is an administrator -- cookies can be modified, after all). sessions will persist for 20 minutes by default (which can be changed), and so generally I store a cookie of the user's username and encrypted password to act as a "remember me" function.

    and lastly, I would suggest that for development you run PHP in a strict environment so that you can easily see any warnings and errors that might be thrown at you -- to not catch some of these would seem like you're running on a production environment.

  5. #5

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2004
    Posts
    447

    Re: login problems

    Quote Originally Posted by kows View Post
    cookies are a type of header; this means that they must be sent to the browser before any output is sent. you're sending output, and then trying to set cookies later on in your login script. move your login logic to the top of the script, and echo stuff later on. a separation of logic and presentation is always good practice, anyway. oh yeah, and it looks like you're trying to use constants for the name of your cookies (in your setcookie() calls), but the first parameter of this function should be a string. if this wasn't a modification you made accidentally when posting, your cookies would never get set properly because those constants don't exist.

    also, I'd recommend not using addslashes() and using mysql_real_escape_string() instead. I do see that you've used the latter at least somewhere in your script, but it's best to pretty much never use the former, I'd say -- at least when you're dealing with raw data that will be used in a database situation.

    I might also suggest that you only use cookies to store user information, and use sessions to store any temporary login information (like whether or not that person is an administrator -- cookies can be modified, after all). sessions will persist for 20 minutes by default (which can be changed), and so generally I store a cookie of the user's username and encrypted password to act as a "remember me" function.

    and lastly, I would suggest that for development you run PHP in a strict environment so that you can easily see any warnings and errors that might be thrown at you -- to not catch some of these would seem like you're running on a production environment.
    Ok can you give me an example of how the login should be coded? Is there a good tutorial that you would recommend?

    I got this tutorial from:
    http://php.about.com/od/finishedphp1...gin_code_2.htm
    Compare bible texts (and other tools):
    TheWheelofGod

  6. #6
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: login problems

    well, my post goes through a few details of how you might go about fixing your current code.

  7. #7
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    Re: login problems

    Please read kows' post and take his suggestions seriously. This will do more to improve your PHP skill than copying from an example or tutorial.

  8. #8

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2004
    Posts
    447

    Re: login problems

    Quote Originally Posted by penagate View Post
    Please read kows' post and take his suggestions seriously. This will do more to improve your PHP skill than copying from an example or tutorial.
    I appreciate what he's saying but I don't know in what order to set things up. I have headers within if statements. Are those correct?

    It's been a few weeks I've been struggling in this.
    Compare bible texts (and other tools):
    TheWheelofGod

  9. #9
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: login problems

    I only said that you could not send headers after you've sent output to the browser. every time you echo or print something, or display HTML, you're sending output to the browser. if you wish to send cookies on a page, your logic for deciding whether or not these cookies should be set (or destroyed) must be done before you send any output to the browser. in your logout script, for example, you start outputting your HTML and then you try to destroy your cookies by calling setcookie() with a time stamp in the past -- normally, this would throw some sort of error that told you that you could not send headers after output is sent ...

    ... and then, I realized you were using output buffering (ob_start()). I would firmly suggest against using output buffering unless you actually have a reason to use it (which you don't in this case). it promotes improper coding by letting you get away with certain things (and that may seem like it makes things convenient for you, but I would argue against that). properly written and formatted scripts will be easier to maintain in the future -- in this case, properly written/formatted would mean that the majority of your login/logout logic should happen at the beginning of all of your scripts (which is what I mentioned before and above).

    so, to answer your question -- headers can be called within IF statements, yes.

    but, there are still other issues with your script that I've discussed in my previous post; for example, this snippet of code from index.php:
    PHP Code:
                setcookie(ID_my_site$_POST['username'], $hour);
                
    setcookie(Key_my_site$_POST['pass'], $hour);
                if(
    $_POST["admin"]=="yes"){
                    
    setcookie(Admin_my_site$_POST['admin'], $hour);
                    print(
    "<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome ".$myusername."! <br />Visit your <a style=\"text-decoration: none;\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" href=\"login/member.php\">member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
                }else{
                    
    setcookie(User_my_site$_POST['admin'], $hour);
                    print(
    "<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome <span id=\"myusername\">".$myusername."</span>! <br />Visit your <a style=\"text-decoration: none;\" href=\"login/member.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
                } 
    ignoring the horrendous HTML (you shouldn't use echo/print to emit HTML), you're calling setcookie() four times and you're using constants to define the names of these cookies. however, the constants don't exist (and I'm not even sure you know what a constant is) and when PHP looks for these constants they will be null, which means you're setting cookies with null names. this means there is no possible way for you to reference them, so that isn't very helpful. briefly, here is the extremely simple difference between how to call or use constants, variables, strings, and functions:
    Code:
    CONSTANT
    
    $variable
    
    "string"
    
    'string'
    
    function()
    so, in your code, you can see that you're trying to use a constant to define a cookie name (ID_my_site), but you need to use strings:
    PHP Code:
    setcookie("my_cookie_name""my_cookie_value"time() + 3600); 
    then, I could reference $_COOKIE['my_cookie_name'] to get the value "my_cookie_value" after a full reload of the current page (cookies don't take affect until you've loaded a new page).

    and then, there's the thing I mentioned about sessions. sessions would be better than cookies in your case (in my opinion) simply because you're setting a cookie for just an hour. cookies are generally used to store long term information -- not short term. sessions will persist for up to 20 minutes by default and will store any data on the server rather than the client (which is good for information that may need a bit more security), and a user doesn't need anything enabled in their browser to make sessions work. I would suggest that you read up on them here through the simple example.

    however, as a final note, if you are not really understanding PHP and this tutorial/script is your first step into it, I would highly suggest you take a step back and look into some beginner tutorials -- perhaps the ones from W3Schools would be a good start.

    and don't be afraid to ask questions if you don't understand anything I just wrote!

  10. #10

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2004
    Posts
    447

    Re: login problems

    I understand php. I've been working on it for at least 3 years now. That part of the tutorial didn't make sense where the quotes "" should appear but I left it there anyways for the time being.

    But the login is new to me.

    So I blocked the ob_start(). The session_start() stays in the main index file. The code below is the include file for logging in.

    I added quotes setcookie("ID_my_site"....

    But the rest I'm not sure how to put in order. There is so many nested if statements that I'm afraid I could ruin the code if I were to play around.

    Do you mean this should be set in the beginning:
    PHP Code:
            //gives error if the password is wrong
            
    if ($_POST['pass'] != $info['password']){
                
    //die('Incorrect password, please try again.');
                
    print('Incorrect password, please try again.');
                
    login();
            }else{
                
    // if login is ok then we add a cookie
                
    $_POST['username'] = stripslashes($_POST['username']);
                
    $hour time() + 3600;
                
    setcookie("ID_my_site"$_POST['username'], $hour);
                
    setcookie("Key_my_site"$_POST['pass'], $hour);... 
    ?
    My code updated:
    PHP Code:
    <?php
    //ob_start();
    include("dbconnection.php");
    function 
    login(){
    ?>
        <table border="0">
            <tr>
                <td>Administrator:</td><td><input type="checkbox" id="adminid" name="admin" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C;" value="no" onClick="if(this.value=='no'){this.value='yes'; document.getElementById('register').style.display = 'none';} else{this.value='no';document.getElementById('register').style.display = 'block';};" /></td>
            </tr>
            <tr>
                <td>Username:</td>
                <td><input type="text" name="<?php //vb_login_username?>username" id="username" style="float: left; border: 1px solid #7C7C7C; font: 9px verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" value="User Name" onBlur="if (this.value == '') this.value = 'User Name';" onFocus="if (this.value == 'User Name') this.value = '';" /></td>
            </tr>
            <tr>
                <td>Password:</td><td><input type="password" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" <?php //name="pass"?> name="<?php //vb_login_username?>pass" id="pass" /></td></tr>
            <tr>
                <td><a id="register" href="login/register.php" style="float: left; display: block; background-color: #7C7C7C; text-align: left; padding: 0px 0px 0px 5px; width: 80px; height: 20px; text-decoration: none; color: #ffffff; border: 1px solid #7C7C7C; font-weight: bold;" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'">Register</a></td><td align="right"><input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 100px; height: 20px;" name="submit" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Login" /></td>
            </tr>
        </table>
    <?php
    }
    ?>
    <div style="float: left; width: 100%; margin: 0px 0px 0px 0px; background-color: #7C7C7C; border: 1px solid #A5A498; border-width: 1px 1px 0px 1px;">
        <span style="float: left; padding: 2px 10px 0px 12px; color: #FFFFFF; font-family: arial; font-weight:bold; font-size: 13px;">Login</span>
    </div>
    <div style="float: left; width: 100%; height: 120px; background-color: #B4B3A9; border: 1px solid #A5A498; margin: 0px 0px 0px 0px; overflow-x: hidden; overflow-y: auto;">
    <?php

    //Checks if there is a login cookie
    if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directs you to the members page
        
    $myusername $_COOKIE['ID_my_site'];
        
    $pass $_COOKIE['Key_my_site'];
        
    $admin $_COOKIE['Admin_my_site'];
        
    $user $_COOKIE['User_my_site'];    
        
    $sql "SELECT * FROM ";
        if(
    $admin=="yes"){
            
    $sql .= $dbTable2;
        }else{
            
    $sql .= $dbTable;
        }
        
    $sql .= " WHERE username = '".mysql_real_escape_string($myusername)."'";
        
    $check mysql_query($sql)or die(mysql_error());
        while(
    $info mysql_fetch_array$check )){
            if (
    $pass != $info['password']){
            }else{
                
    //print("Welcome ".$myusername."! <br />Visit your <a href=\"login/member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>");
                //header("Location: login/member.php");
                //header("Location: ");
            
    }
        }
    }
    //if the login form is submitted
    if (isset($_POST['submit'])){ // if form has been submitted
        
    if(!$_POST['username'] || !$_POST['pass']) {// makes sure they filled it in
            //die('You did not fill in a required field.');
            
    print('You did not fill in a required field.');
        }
    // checks it against the database
        
    if (!get_magic_quotes_gpc()){
            
    $_POST['email'] = addslashes($_POST['email']);
        }
        
    $sql "SELECT * FROM ";
        if(
    $admin=="yes"){
            
    $sql .= $dbTable2;
        }else{
            
    $sql .= $dbTable;
        }
        
    $sql .= " WHERE username = '".$_POST['username']."'";
        
    $check mysql_query($sql)or die(mysql_error());
        
    //Gives error if user dosen't exist
        
    $check2 mysql_num_rows($check);
        if (
    $check2 == 0) {
            
    //die('That user does not exist in our database. <a href=login/register.php>Click Here to Register</a>');
            
    print('That user does not exist in our database.');
            
    login();
        }
        while(
    $info mysql_fetch_array$check )){
            
    $_POST['pass'] = stripslashes($_POST['pass']);
            
    $info['password'] = stripslashes($info['password']);
            
    $_POST['pass'] = md5($_POST['pass']);

            
    //gives error if the password is wrong
            
    if ($_POST['pass'] != $info['password']){
                
    //die('Incorrect password, please try again.');
                
    print('Incorrect password, please try again.');
                
    login();
            }else{
                
    // if login is ok then we add a cookie
                
    $_POST['username'] = stripslashes($_POST['username']);
                
    $hour time() + 3600;
                
    setcookie("ID_my_site"$_POST['username'], $hour);
                
    setcookie("Key_my_site"$_POST['pass'], $hour);
                if(
    $_POST["admin"]=="yes"){
                    
    setcookie("Admin_my_site"$_POST['admin'], $hour);
                    print(
    "<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome ".$myusername."! <br />Visit your <a style=\"text-decoration: none;\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" href=\"login/member.php\">member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
                }else{
                    
    setcookie("User_my_site"$_POST['admin'], $hour);
                    print(
    "<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome <span id=\"myusername\">".$myusername."</span>! <br />Visit your <a style=\"text-decoration: none;\" href=\"login/member.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
                }
                
    //then redirect them to the members area
                //header("Location: login/member.php");
                //print("Welcome".$username);
                //header("Location: login/member.php");
                //header("Location: ");
                
            
    }
        }
    }else{
        
    // if they are not logged in
        
    login();
    }
    ?>
    </div>
    Compare bible texts (and other tools):
    TheWheelofGod

  11. #11
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: login problems

    not really. here, I've made some small changes all over the place (they're highlighted in red), feel free to take a look:
    Code:
    <?php
    
      //say goodbye to magic_quotes_gpc! no false security.
      
      //fix magic_quotes_gpc() being on
      if(get_magic_quotes_gpc())
      {
        foreach($_GET as $k => $v)
        {
          $_GET[$k] = stripslashes($v);
        }
        foreach($_POST as $k => $v)
        {
          $_POST[$k] = stripslashes($v);
        }
        foreach($_COOKIE as $k => $v)
        {
          $_COOKIE[$k] = stripslashes($v);
        }
      }
      
      //ob_start();
      include("dbconnection.php");
    
      //I got rid of your function. no need for it
      
      //Checks if there is a login cookie
      if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directs you to the members page
          $myusername = $_COOKIE['ID_my_site'];
          $pass = $_COOKIE['Key_my_site'];
          $admin = $_COOKIE['Admin_my_site'];
          $user = $_COOKIE['User_my_site'];    
          $sql = "SELECT * FROM ";
          if($admin=="yes"){
              $sql .= $dbTable2;
          }else{
              $sql .= $dbTable;
          }
          $sql .= " WHERE username = '".mysql_real_escape_string($myusername)."'";
          $check = mysql_query($sql)or die(mysql_error());
          while($info = mysql_fetch_array( $check )){
              //you don't need to check if the passwords do not match, just check if they DO match
              /*
              if ($pass != $info['password']){
              }else{
              */
              
              if($pass == $info['password']){
                
                //you can uncomment these headers now if you'd like
                
              
                  //print("Welcome ".$myusername."! <br />Visit your <a href=\"login/member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>");
                  //header("Location: login/member.php");
                  //header("Location: ");
              }
          }
      }
      
      //variable to keep track of whether to show the user the login form or not
      $showlogin = true; //we show the form by default, -unless- we know they have logged in
      
      //if the login form is submitted
      if (isset($_POST['submit'])){ // if form has been submitted
          if(!$_POST['username'] || !$_POST['pass']) {// makes sure they filled it in
              //die('You did not fill in a required field.');
              print('You did not fill in a required field.');
          }// checks it against the database
          //don't need this if anymore, but we need the stuff inside of it
          //if (!get_magic_quotes_gpc()){
              //$_POST['email'] = addslashes($_POST['email']);
              
              //we use mysql_real_escape_string(), not addslashes()
              $_POST['email'] = mysql_real_escape_string($_POST['email']);
              
              //we also need to sanitize the username! but use a variable:
              $db['username'] = mysql_real_escape_string($_POST['username']);
              
          //end of the if we no longer need
          //}
          
          $sql = "SELECT * FROM ";
          if($admin=="yes"){
              $sql .= $dbTable2;
          }else{
              $sql .= $dbTable;
          }
          $sql .= " WHERE username = '".$db['username']."'";
          $check = mysql_query($sql) or die(mysql_error());
          //Gives error if user dosen't exist
          $check2 = mysql_num_rows($check);
          if ($check2 == 0) {
              //die('That user does not exist in our database. <a href=login/register.php>Click Here to Register</a>');
              print('That user does not exist in our database.');
              //login(); //we don't want to echo out a form right away!
          }
          while($info = mysql_fetch_array( $check )){
              
              /* you don't need to do this anymore.
              
              $_POST['pass'] = stripslashes($_POST['pass']);
              $info['password'] = stripslashes($info['password']); //you should have never needed to do this. the database doesn't store extra slashes.
              */
              
              $_POST['pass'] = md5($_POST['pass']);
    
              //gives error if the password is wrong
              if ($_POST['pass'] != $info['password']){
                  //die('Incorrect password, please try again.');
                  print('Incorrect password, please try again.');
                  //login(); //we don't want to echo out a form right away!
              }else{
                  // if login is ok then we add a cookie
                  //$_POST['username'] = stripslashes($_POST['username']); //no more stripslashes
                  $hour = time() + 3600;
                  setcookie("ID_my_site", $_POST['username'], $hour);
                  setcookie("Key_my_site", $_POST['pass'], $hour);
                  
                  //they are logged in. no need to show the login form
                  $showlogin = false;
                  
                  if($_POST["admin"]=="yes"){
                      setcookie("Admin_my_site", $_POST['admin'], $hour);
                      
                      //no printing! this is -logic- time
                      //print("<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome ".$myusername."! <br />Visit your <a style=\"text-decoration: none;\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" href=\"login/member.php\">member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
                      
                  }else{
                      setcookie("User_my_site", $_POST['admin'], $hour);
                      
                      //no printing! this is -logic- time
                      //print("<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome <span id=\"myusername\">".$myusername."</span>! <br />Visit your <a style=\"text-decoration: none;\" href=\"login/member.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
                      
                  }
                  
                  //you can uncomment these redirects now
                  //then redirect them to the members area
                  //header("Location: login/member.php");
                  //print("Welcome".$username);
                  //header("Location: login/member.php");
                  
              }
          }
      }
      //commented this out
      /*else{
          // if they are not logged in
          login();
      }*/
      
      
      //if we are supposed to show the login form, then let's show it
      if($showlogin){
    ?>
    <div style="float: left; width: 100&#37;; margin: 0px 0px 0px 0px; background-color: #7C7C7C; border: 1px solid #A5A498; border-width: 1px 1px 0px 1px;">
        <span style="float: left; padding: 2px 10px 0px 12px; color: #FFFFFF; font-family: arial; font-weight:bold; font-size: 13px;">Login</span>
    </div>
    <div style="float: left; width: 100%; height: 120px; background-color: #B4B3A9; border: 1px solid #A5A498; margin: 0px 0px 0px 0px; overflow-x: hidden; overflow-y: auto;">
        <table border="0">
            <tr>
                <td>Administrator:</td><td><input type="checkbox" id="adminid" name="admin" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C;" value="no" onClick="if(this.value=='no'){this.value='yes'; document.getElementById('register').style.display = 'none';} else{this.value='no';document.getElementById('register').style.display = 'block';};" /></td>
            </tr>
            <tr>
                <td>Username:</td>
                <td><input type="text" name="<?php //vb_login_username?>username" id="username" style="float: left; border: 1px solid #7C7C7C; font: 9px verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" value="User Name" onBlur="if (this.value == '') this.value = 'User Name';" onFocus="if (this.value == 'User Name') this.value = '';" /></td>
            </tr>
            <tr>
                <td>Password:</td><td><input type="password" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" <?php //name="pass"?> name="<?php //vb_login_username?>pass" id="pass" /></td></tr>
            <tr>
                <td><a id="register" href="login/register.php" style="float: left; display: block; background-color: #7C7C7C; text-align: left; padding: 0px 0px 0px 5px; width: 80px; height: 20px; text-decoration: none; color: #ffffff; border: 1px solid #7C7C7C; font-weight: bold;" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'">Register</a></td><td align="right"><input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 100px; height: 20px;" name="submit" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Login" /></td>
            </tr>
        </table>
    </div>
    <?php } //end if $showlogin ?>
    Last edited by kows; Apr 10th, 2010 at 02:27 PM.

  12. #12
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: login problems

    and because my post was too long to make a comment afterward, here it is:

    of course, that's all untested, but it should be okay. other than the things I mentioned in that code, there are plenty of other things you can do to better this code. for example, when you query the database to see if the user exists you already know you should only be returning one result (one user per username), but you have a while looping through the results of the query. all you need to do is fetch them once, like so:
    PHP Code:
    $info mysql_fetch_assoc($query); 
    hope that at least gives you a bit of insight, or something!

    edit: oh yeah, almost forgot! instead of just printing out your errors as they happen (I didn't comment them out), consider something like this (this would be within your login validation [or just general form validation]):
    PHP Code:
    $errors = array();

    if(
    $_SERVER['REQUEST_METHOD'] == "POST"){

      if(empty(
    $_POST['username'])){
        
    $errors[] = "username was empty";
      }

      if(empty(
    $_POST['password'])){
        
    $errors[] = "password was empty";
      }

      if(empty(
    $_POST['email'])){
        
    $errors[] = "e-mail was empty";
      }

      if(
    count($errors) == 0){

        
    /* put the rest of your login logic in here, and continue checking if
         * count($errors) is 0 before you go to the next "level" of validation
         */

      
    }

    then, later on (presumably on your form):
    PHP Code:
    <h1>Login</h1>
    <?php if(count($errors)): ?>
    <h2>The following errors occurred:</h2>
    <ul>
    <?php foreach($errors as $error): ?>
      <li><?php echo $error?></li>
    <?php endforeach; ?>
    </ul>
    <?php endif; ?>
    <!-- now your form goes here -->
    Last edited by kows; Apr 10th, 2010 at 02:28 PM.

  13. #13
    Frenzied Member TheBigB's Avatar
    Join Date
    Mar 2006
    Location
    *Stack Trace*
    Posts
    1,511

    Re: login problems

    A little thing I've noticed is that you give specific feedback when the username does not exist.
    This can be risky. It makes the job of a bruteforcer a heck of a lot easier when it can validate the username.
    Delete it. They just clutter threads anyway.

  14. #14

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2004
    Posts
    447

    Re: login problems

    Quote Originally Posted by TheBigB View Post
    A little thing I've noticed is that you give specific feedback when the username does not exist.
    This can be risky. It makes the job of a bruteforcer a heck of a lot easier when it can validate the username.
    What do you mean? Kows, give me some time to look at your posting.
    Compare bible texts (and other tools):
    TheWheelofGod

  15. #15
    Frenzied Member TheBigB's Avatar
    Join Date
    Mar 2006
    Location
    *Stack Trace*
    Posts
    1,511

    Re: login problems

    I was aiming at a part in index.php
    PHP Code:
        $sql .= " WHERE username = '".$_POST['username']."'";
        
    $check mysql_query($sql)or die(mysql_error());
        
    //Gives error if user dosen't exist
        
    $check2 mysql_num_rows($check);
        if (
    $check2 == 0) {
            
    //die('That user does not exist in our database. <a href=login/register.php>Click Here to Register</a>');
            
    print('That user does not exist in our database.');
            
    login();
        } 
    You should give the same message for username and password errors.
    Like: "Username or password incorrect."
    Delete it. They just clutter threads anyway.

  16. #16

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2004
    Posts
    447

    Re: login problems

    Quote Originally Posted by kows View Post
    not really. here, I've made some small changes all over the place (they're highlighted in red), feel free to take a look:
    PHP Code:
    <?php

      
    //say goodbye to magic_quotes_gpc! no false security.
      
      //fix magic_quotes_gpc() being on
      
    if(get_magic_quotes_gpc())
      {
        foreach(
    $_GET as $k => $v)
        {
          
    $_GET[$k] = stripslashes($v);
        }
        foreach(
    $_POST as $k => $v)
        {
          
    $_POST[$k] = stripslashes($v);
        }
        foreach(
    $_COOKIE as $k => $v)
        {
          
    $_COOKIE[$k] = stripslashes($v);
        }
      }
      
      
    //ob_start();
      
    include("dbconnection.php");

      
    //I got rid of your function. no need for it
      
      //Checks if there is a login cookie
      
    if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directs you to the members page
          
    $myusername $_COOKIE['ID_my_site'];
          
    $pass $_COOKIE['Key_my_site'];
          
    $admin $_COOKIE['Admin_my_site'];
          
    $user $_COOKIE['User_my_site'];    
          
    $sql "SELECT * FROM ";
          if(
    $admin=="yes"){
              
    $sql .= $dbTable2;
          }else{
              
    $sql .= $dbTable;
          }
          
    $sql .= " WHERE username = '".mysql_real_escape_string($myusername)."'";
          
    $check mysql_query($sql)or die(mysql_error());
          while(
    $info mysql_fetch_array$check )){
              
    //you don't need to check if the passwords do not match, just check if they DO match
              /*
              if ($pass != $info['password']){
              }else{
              */
              
              
    if($pass == $info['password']){
                
                
    //you can uncomment these headers now if you'd like
                
              
                  //print("Welcome ".$myusername."! <br />Visit your <a href=\"login/member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>");
                  //header("Location: login/member.php");
                  //header("Location: ");
              
    }
          }
      }
      
      
    //variable to keep track of whether to show the user the login form or not
      
    $showlogin true//we show the form by default, -unless- we know they have logged in
      
      //if the login form is submitted
      
    if (isset($_POST['submit'])){ // if form has been submitted
          
    if(!$_POST['username'] || !$_POST['pass']) {// makes sure they filled it in
              //die('You did not fill in a required field.');
              
    print('You did not fill in a required field.');
          }
    // checks it against the database
          //don't need this if anymore, but we need the stuff inside of it
          //if (!get_magic_quotes_gpc()){
              //$_POST['email'] = addslashes($_POST['email']);
              
              //we use mysql_real_escape_string(), not addslashes()
              
    $_POST['email'] = mysql_real_escape_string($_POST['email']);
              
              
    //we also need to sanitize the username! but use a variable:
              
    $db['username'] = mysql_real_escape_string($_POST['username']);
              
          
    //end of the if we no longer need
          //}
          
          
    $sql "SELECT * FROM ";
          if(
    $admin=="yes"){
              
    $sql .= $dbTable2;
          }else{
              
    $sql .= $dbTable;
          }
          
    $sql .= " WHERE username = '".$db['username']."'";
          
    $check mysql_query($sql) or die(mysql_error());
          
    //Gives error if user dosen't exist
          
    $check2 mysql_num_rows($check);
          if (
    $check2 == 0) {
              
    //die('That user does not exist in our database. <a href=login/register.php>Click Here to Register</a>');
              
    print('That user does not exist in our database.');
              
    //login(); //we don't want to echo out a form right away!
          
    }
          while(
    $info mysql_fetch_array$check )){
              
              
    /* you don't need to do this anymore.
              
              $_POST['pass'] = stripslashes($_POST['pass']);
              $info['password'] = stripslashes($info['password']); //you should have never needed to do this. the database doesn't store extra slashes.
              */
              
              
    $_POST['pass'] = md5($_POST['pass']);

              
    //gives error if the password is wrong
              
    if ($_POST['pass'] != $info['password']){
                  
    //die('Incorrect password, please try again.');
                  
    print('Incorrect password, please try again.');
                  
    //login(); //we don't want to echo out a form right away!
              
    }else{
                  
    // if login is ok then we add a cookie
                  //$_POST['username'] = stripslashes($_POST['username']); //no more stripslashes
                  
    $hour time() + 3600;
                  
    setcookie("ID_my_site"$_POST['username'], $hour);//line 116
                  
    setcookie("Key_my_site"$_POST['pass'], $hour);//line 117
                  
                  //they are logged in. no need to show the login form
                  
    $showlogin false;
                  
                  if(
    $_POST["admin"]=="yes"){
                      
    setcookie("Admin_my_site"$_POST['admin'], $hour);
                      
                      
    //no printing! this is -logic- time
                      //print("<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome ".$myusername."! <br />Visit your <a style=\"text-decoration: none;\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" href=\"login/member.php\">member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
                      
                  
    }else{
                      
    setcookie("User_my_site"$_POST['admin'], $hour);//line 129
                      
                      //no printing! this is -logic- time
                      //print("<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome <span id=\"myusername\">".$myusername."</span>! <br />Visit your <a style=\"text-decoration: none;\" href=\"login/member.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
                      
                  
    }
                  
                  
    //you can uncomment these redirects now
                  //then redirect them to the members area
                  //header("Location: login/member.php");
                  //print("Welcome".$username);
                  //header("Location: login/member.php");
                  
              
    }
          }
      }
      
    //commented this out
      /*else{
          // if they are not logged in
          login();
      }*/
      
      
      //if we are supposed to show the login form, then let's show it
      
    if($showlogin){
    ?>
    <div style="float: left; width: 100%; margin: 0px 0px 0px 0px; background-color: #7C7C7C; border: 1px solid #A5A498; border-width: 1px 1px 0px 1px;">
        <span style="float: left; padding: 2px 10px 0px 12px; color: #FFFFFF; font-family: arial; font-weight:bold; font-size: 13px;">Login</span>
    </div>
    <div style="float: left; width: 100%; height: 120px; background-color: #B4B3A9; border: 1px solid #A5A498; margin: 0px 0px 0px 0px; overflow-x: hidden; overflow-y: auto;">
        <table border="0">
            <tr>
                <td>Administrator:</td><td><input type="checkbox" id="adminid" name="admin" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C;" value="no" onClick="if(this.value=='no'){this.value='yes'; document.getElementById('register').style.display = 'none';} else{this.value='no';document.getElementById('register').style.display = 'block';};" /></td>
            </tr>
            <tr>
                <td>Username:</td>
                <td><input type="text" name="<?php //vb_login_username?>username" id="username" style="float: left; border: 1px solid #7C7C7C; font: 9px verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" value="User Name" onBlur="if (this.value == '') this.value = 'User Name';" onFocus="if (this.value == 'User Name') this.value = '';" /></td>
            </tr>
            <tr>
                <td>Password:</td><td><input type="password" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" <?php //name="pass"?> name="<?php //vb_login_username?>pass" id="pass" /></td></tr>
            <tr>
                <td><a id="register" href="login/register.php" style="float: left; display: block; background-color: #7C7C7C; text-align: left; padding: 0px 0px 0px 5px; width: 80px; height: 20px; text-decoration: none; color: #ffffff; border: 1px solid #7C7C7C; font-weight: bold;" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'">Register</a></td><td align="right"><input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 100px; height: 20px;" name="submit" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Login" /></td>
            </tr>
        </table>
    </div>
    <?php //end if $showlogin ?>
    There's a problem with the header:
    Warning: Cannot modify header information - headers already sent by (output started at C:...index.php:13) in C:...login\index.php on line 116

    Warning: Cannot modify header information - headers already sent by (output started at C:...index.php:13) in C:...login\index.php on line 117

    Warning: Cannot modify header information - headers already sent by (output started at C:...index.php:13) in C:...login\index.php on line 129
    Compare bible texts (and other tools):
    TheWheelofGod

  17. #17
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    Re: login problems

    Quote Originally Posted by kows View Post
    //fix magic_quotes_gpc() being on
    Magic quotes is recursive so you should use something like array_walk_recursive to reverse it.

  18. #18
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    Re: login problems

    Quote Originally Posted by gilgalbiblewhee View Post
    There's a problem with the header:
    Why can't I send headers?

  19. #19
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: login problems

    so you have to make sure there is no output before those cookies are sent. extra spaces, print statements, etc. I didn't exactly say to just take what I had changed and try to directly use that, either. it was to give you an idea of what I meant. there doesn't seem to be (at a glance) anything wrong with what I gave you though. if this is a page you are including somewhere it won't work, either.

    edit: and penagate's link about sending headers would be an excellent start to learning to debug!

  20. #20

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2004
    Posts
    447

    Re: login problems

    Quote Originally Posted by penagate View Post
    Ok I'm looking at your posting.
    (output started at D:\dev\php\test.php:3)
    Does that mean that it's line 3 of test.php that's causing the error?

    So the setting of cookies has to be before the <head>. How about before <html>?
    Compare bible texts (and other tools):
    TheWheelofGod

  21. #21
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    Re: login problems

    Perhaps the wording of my post is not clear enough. The headers must be sent before the response body. The response body is what appears when you "View source" in the browser, including all HTML and any characters (even spaces) before the HTML.

    A complete response looks something like this:
    Code:
    HTTP/1.1 200 OK
    Content-type: text/html
    Set-Cookie: foo=bar
    
    <!DOCTYPE html>
    <!-- ... -->

  22. #22

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2004
    Posts
    447

    Re: login problems

    Quote Originally Posted by penagate View Post
    Perhaps the wording of my post is not clear enough. The headers must be sent before the response body. The response body is what appears when you "View source" in the browser, including all HTML and any characters (even spaces) before the HTML.

    A complete response looks something like this:
    Code:
    HTTP/1.1 200 OK
    Content-type: text/html
    Set-Cookie: foo=bar
    
    <!DOCTYPE html>
    <!-- ... -->
    Ok. Just wanted to make sure. Now there is no header warning but when I log in the login box disappears:
    PHP Code:
    <?php 
    //twotexts
    //ob_start();
    session_start();

      
    //say goodbye to magic_quotes_gpc! no false security.
      
      //fix magic_quotes_gpc() being on
      
    if(get_magic_quotes_gpc())
      {
        foreach(
    $_GET as $k => $v)
        {
          
    $_GET[$k] = stripslashes($v);
        }
        foreach(
    $_POST as $k => $v)
        {
          
    $_POST[$k] = stripslashes($v);
        }
        foreach(
    $_COOKIE as $k => $v)
        {
          
    $_COOKIE[$k] = stripslashes($v);
        }
      }
      
      
    //ob_start();
      
    include("dbconnection.php");

      
    //I got rid of your function. no need for it
      
      //Checks if there is a login cookie
      
    if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directs you to the members page
          
    $myusername $_COOKIE['ID_my_site'];
          
    $pass $_COOKIE['Key_my_site'];
          
    $admin $_COOKIE['Admin_my_site'];
          
    $user $_COOKIE['User_my_site'];    
          
    $sql "SELECT * FROM ";
          if(
    $admin=="yes"){
              
    $sql .= $dbTable2;
          }else{
              
    $sql .= $dbTable;
          }
          
    $sql .= " WHERE username = '".mysql_real_escape_string($myusername)."'";
          
    $check mysql_query($sql)or die(mysql_error());
          while(
    $info mysql_fetch_array$check )){
              
    //you don't need to check if the passwords do not match, just check if they DO match
              /*
              if ($pass != $info['password']){
              }else{
              */
              
              
    if($pass == $info['password']){
                
                
    //you can uncomment these headers now if you'd like
                
              
                  //print("Welcome ".$myusername."! <br />Visit your <a href=\"login/member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>");
                  //header("Location: login/member.php");
                  //header("Location: ");
              
    }
          }
      }
      
      
    //variable to keep track of whether to show the user the login form or not
      
    $showlogin true//we show the form by default, -unless- we know they have logged in
      
      //if the login form is submitted
      
    if (isset($_POST['submit'])){ // if form has been submitted
          
    if(!$_POST['username'] || !$_POST['pass']) {// makes sure they filled it in
              //die('You did not fill in a required field.');
              
    print('You did not fill in a required field.');
          }
    // checks it against the database
          //don't need this if anymore, but we need the stuff inside of it
          //if (!get_magic_quotes_gpc()){
              //$_POST['email'] = addslashes($_POST['email']);
              
              //we use mysql_real_escape_string(), not addslashes()
              
    $_POST['email'] = mysql_real_escape_string($_POST['email']);
              
              
    //we also need to sanitize the username! but use a variable:
              
    $db['username'] = mysql_real_escape_string($_POST['username']);
              
          
    //end of the if we no longer need
          //}
          
          
    $sql "SELECT * FROM ";
          if(
    $admin=="yes"){
              
    $sql .= $dbTable2;
          }else{
              
    $sql .= $dbTable;
          }
          
    $sql .= " WHERE username = '".$db['username']."'";
          
    $check mysql_query($sql) or die(mysql_error());
          
    //Gives error if user dosen't exist
          
    $check2 mysql_num_rows($check);
          if (
    $check2 == 0) {
              
    //die('That user does not exist in our database. <a href=login/register.php>Click Here to Register</a>');
              
    print('That user does not exist in our database.');
              
    //login(); //we don't want to echo out a form right away!
          
    }
          while(
    $info mysql_fetch_array$check )){
              
              
    /* you don't need to do this anymore.
              
              $_POST['pass'] = stripslashes($_POST['pass']);
              $info['password'] = stripslashes($info['password']); //you should have never needed to do this. the database doesn't store extra slashes.
              */
              
              
    $_POST['pass'] = md5($_POST['pass']);

              
    //gives error if the password is wrong
              
    if ($_POST['pass'] != $info['password']){
                  
    //die('Incorrect password, please try again.');
                  
    print('Incorrect password, please try again.');
                  
    //login(); //we don't want to echo out a form right away!
              
    }else{
                  
    // if login is ok then we add a cookie
                  //$_POST['username'] = stripslashes($_POST['username']); //no more stripslashes
                  
    $hour time() + 3600;
                  
    setcookie("ID_my_site"$_POST['username'], $hour);
                  
    setcookie("Key_my_site"$_POST['pass'], $hour);
                  
                  
    //they are logged in. no need to show the login form
                  
    $showlogin false;
                  
                  if(
    $_POST["admin"]=="yes"){
                      
    setcookie("Admin_my_site"$_POST['admin'], $hour);
                      
                      
    //no printing! this is -logic- time
                      //print("<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome ".$myusername."! <br />Visit your <a style=\"text-decoration: none;\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" href=\"login/member.php\">member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
                      
                  
    }else{
                      
    setcookie("User_my_site"$_POST['admin'], $hour);
                      
                      
    //no printing! this is -logic- time
                      //print("<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome <span id=\"myusername\">".$myusername."</span>! <br />Visit your <a style=\"text-decoration: none;\" href=\"login/member.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
                      
                  
    }
                  
                  
    //you can uncomment these redirects now
                  //then redirect them to the members area
                  //header("Location: login/member.php");
                  //print("Welcome".$username);
                  //header("Location: login/member.php");
                  
              
    }
          }
      }
      
    //commented this out
      /*else{
          // if they are not logged in
          login();
      }*/
    $_SESSION['logged_in'] = 1;

    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    Compare bible texts (and other tools):
    TheWheelofGod

  23. #23
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: login problems

    yes, that's because you aren't telling your script to do anything once you are logged in. all of your redirect headers are commented out. the login isn't supposed to show once you're logged in. that's when you would be redirecting to a "successfully logged in" page, or something.

  24. #24

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2004
    Posts
    447

    Re: login problems

    Quote Originally Posted by kows View Post
    yes, that's because you aren't telling your script to do anything once you are logged in. all of your redirect headers are commented out. the login isn't supposed to show once you're logged in. that's when you would be redirecting to a "successfully logged in" page, or something.
    What confuses me are the if statements. Since I've put most of the code at the top the welcome appears at the top. But if I cut off and paste the if statements which contain the prints I'm afraid of messing up the code.
    Compare bible texts (and other tools):
    TheWheelofGod

  25. #25
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: login problems

    if you're afraid of screwing stuff up, you might be in the wrong line of work. make a back-up of the file and just play with it. you won't learn how things work if you don't get your hands dirty.

    in your case, instead of all of those prints and stuff, use a variable to display a message. then, you can later embed this message into your mark-up. take the error displaying example I showed you here and try to apply that to your code; you'll have an $errors array and continually add onto it instead of print()ing out messages. then, later on in your mark-up (where ever you deem appropriate), you check if the errors array has anything in it -- if so, you display those errors. otherwise, you do nothing. keep in mind also that it's only an example -- you don't have to only check for empty variables. the point of it is using an array to record all of your error messages and then displaying them later. then, you'll have a simple way of checking whether or not an error occurred on this page by checking the count() of the $errors array (if it's above 0, an error occurred).

    as penagate said, separation of presentation and logic is good practice, and enforcing this style of programming now will make you a better programmer. it also makes easier-to-maintain code, especially if you're working with a team of some kind.

  26. #26

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2004
    Posts
    447

    Re: login problems

    Ok thanks I'm working on it. The logout is giving the header problems as well:
    PHP Code:
    <?php
    //ob_start();
    include("dbconnection.php");
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Logout</title>
    </head>

    <body>
    <?php
    $past 
    time() - 100;
    //this makes the time in the past to destroy the cookie
    setcookie("ID_my_site"gone$past);
    setcookie("Key_my_site"gone$past);
    setcookie("Admin_my_site"gone$past);
    header("Location: ../index.php");
    ?> 
    </body>
    </html>
    Compare bible texts (and other tools):
    TheWheelofGod

  27. #27
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: login problems

    I really don't see what you're not understanding (there have been 3 or 4 posts in this thread alone about this [and a link to a comprehensive post made by penagate about why you might not be able to send headers]): you cannot send headers after you have sent output. output is defined in this case as ANYTHING that you echo out to be sent to the browser. you are echoing out a ton of HTML, and in the middle of this HTML you're then trying to set cookies (aka send headers).

    the bottom line: you cannot set cookies (send headers) after you have sent output (echoed/printed anything). place your logic (setting cookies, sending headers) at the top of your script (away from your presentation [or mark-up (or HTML)]).

    hope that helps. :/

  28. #28

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2004
    Posts
    447

    Re: login problems

    Quote Originally Posted by kows View Post
    I really don't see what you're not understanding (there have been 3 or 4 posts in this thread alone about this [and a link to a comprehensive post made by penagate about why you might not be able to send headers]): you cannot send headers after you have sent output. output is defined in this case as ANYTHING that you echo out to be sent to the browser. you are echoing out a ton of HTML, and in the middle of this HTML you're then trying to set cookies (aka send headers).

    the bottom line: you cannot set cookies (send headers) after you have sent output (echoed/printed anything). place your logic (setting cookies, sending headers) at the top of your script (away from your presentation [or mark-up (or HTML)]).

    hope that helps. :/
    That's right. Like this:
    PHP Code:
    <?php
    //ob_start();
    include("dbconnection.php");
    $past time() - 100;
    //this makes the time in the past to destroy the cookie
    setcookie("ID_my_site"gone$past);
    setcookie("Key_my_site"gone$past);
    setcookie("Admin_my_site"gone$past);
    header("Location: ../index.php");
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Logout</title>
    </head>

    <body>
    <?php

    ?>
     
    </body>
    </html>
    Compare bible texts (and other tools):
    TheWheelofGod

  29. #29

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2004
    Posts
    447

    Re: login problems

    But going back to the login I'm trying to put together the print within the <div> and it gives me this error:
    Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in C:\...\login\index.php on line 35
    PHP Code:
    <div style="float: left; width: 100%; margin: 0px 0px 0px 0px; background-color: #7C7C7C; border: 1px solid #A5A498; border-width: 1px 1px 0px 1px;">
        <span style="float: left; padding: 2px 10px 0px 12px; color: #FFFFFF; font-family: arial; font-weight:bold; font-size: 13px;">Login</span>
    </div>
    <div style="float: left; width: 100%; height: 120px; background-color: #B4B3A9; border: 1px solid #A5A498; margin: 0px 0px 0px 0px; overflow-x: hidden; overflow-y: auto;"><?php
      
    //if we are supposed to show the login form, then let's show it
      
    if($showlogin=false){
    ?>
        <table border="0">
            <tr>
                <td>Administrator:</td><td><input type="checkbox" id="adminid" name="admin" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C;" value="no" onClick="if(this.value=='no'){this.value='yes'; document.getElementById('register').style.display = 'none';} else{this.value='no';document.getElementById('register').style.display = 'block';};" /></td>
            </tr><?php 
    $check2 
    mysql_num_rows($check);
    if (
    $check2 == 0){
        print(
    "<tr><td colspan=2 style=\"float: left; text-align: left; color: red; height: 20px; width: 100%; display: block; border: 1px solid black; overflow: hidden;\">That username does not exist in our database.</td></tr>");
    }
            
    ?><tr>
                <td>Username:</td>
                <td><input type="text" name="username" id="username" style="float: left; border: 1px solid #7C7C7C; font: 9px verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" value="User Name" onBlur="if (this.value == '') this.value = 'User Name';" onFocus="if (this.value == 'User Name') this.value = '';" /></td>
            </tr><?php 
    while($info mysql_fetch_array($check)){
        if (
    $_POST['pass'] != $info['password']){
            print(
    "<tr><td colspan=2 style=\"float: left; text-align: left; color: red; height: 20px; width: 100%; display: block; border: 1px solid black; overflow: hidden;\">Incorrect password, please try again.</td></tr>");
        }
    }
            
    ?>
            <tr>
                <td>Password:</td><td><input type="password" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" name="pass" id="pass" /></td></tr>
            <tr>
                <td><a id="register" href="login/register.php" style="float: left; display: block; background-color: #7C7C7C; text-align: left; padding: 0px 0px 0px 5px; width: 80px; height: 20px; text-decoration: none; color: #ffffff; border: 1px solid #7C7C7C; font-weight: bold;" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'">Register</a></td><td align="right"><input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 100px; height: 20px;" name="submit" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Login" /></td>
            </tr>
        </table>
    <?php 
    }else{
        
    //if(isset($_POST['submit'])){
            
    while($info mysql_fetch_array($check)){
                if(
    $pass == $info['password']){
                    print(
    "Welcome ".$myusername."! <br />Visit your <a href=\"login/member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>");
                }else{print(
    "Welcome ".$myusername."! <br />Visit your <a href=\"login/member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>");}
            }
        
    //}
    }
    ?></div>
    The while part was broken (taken) from:
    PHP Code:
      //Checks if there is a login cookie
    if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directs you to the members page
        
    $myusername $_COOKIE['ID_my_site'];
        
    $pass $_COOKIE['Key_my_site'];
        
    $admin $_COOKIE['Admin_my_site'];
        
    $user $_COOKIE['User_my_site'];    
        
    $sql "SELECT * FROM ";
        if(
    $admin=="yes"){
            
    $sql .= $dbTable2;
        }else{
            
    $sql .= $dbTable;
        }
        
    $sql .= " WHERE username = '".mysql_real_escape_string($myusername)."'";
        
    $check mysql_query($sql)or die(mysql_error());
    /*    while($info = mysql_fetch_array( $check )){
            if($pass == $info['password']){
                //you can uncomment these headers now if you'd like
                print("Welcome ".$myusername."! <br />Visit your <a href=\"login/member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>");
                //header("Location: login/member.php");
                //header("Location: ");
            }
        }*/

    Compare bible texts (and other tools):
    TheWheelofGod

  30. #30
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: login problems

    you never define $check in the code you posted that has an error. the parameter passed to mysql_fetch_array() needs to be a result from mysql_query(). you're also trying to use a while loop where you are only returning one record (and thus don't need to use a loop. you just need to make a call to mysql_fetch_array() or mysql_fetch_assoc()).

  31. #31

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2004
    Posts
    447

    Re: login problems

    Quote Originally Posted by kows View Post
    you never define $check in the code you posted that has an error. the parameter passed to mysql_fetch_array() needs to be a result from mysql_query(). you're also trying to use a while loop where you are only returning one record (and thus don't need to use a loop. you just need to make a call to mysql_fetch_array() or mysql_fetch_assoc()).
    But it makes me wonder if the following should be brought down as well within the <div> or left above since it involves cookies:
    PHP Code:
        while($info mysql_fetch_array($check)){
            
    $_POST['pass'] = md5($_POST['pass']);
            
    //gives error if the password is wrong
            
    if ($_POST['pass'] != $info['password']){
                
    //die('Incorrect password, please try again.');
                
    print('Incorrect password, please try again.');
                
    //login(); //we don't want to echo out a form right away!
            
    }else{
                
    // if login is ok then we add a cookie
                //$_POST['username'] = stripslashes($_POST['username']); //no more stripslashes
                
    $hour time() + 3600;
                
    setcookie("ID_my_site"$_POST['username'], $hour);
                
    setcookie("Key_my_site"$_POST['pass'], $hour);
                
    //they are logged in. no need to show the login form
                
    $showlogin false;
              
                  if(
    $_POST["admin"]=="yes"){
                    
    setcookie("Admin_my_site"$_POST['admin'], $hour);
                    
    //no printing! this is -logic- time
                    //print("<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome ".$myusername."! <br />Visit your <a style=\"text-decoration: none;\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" href=\"login/member.php\">member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
                
    }else{
                    
    setcookie("User_my_site"$_POST['admin'], $hour);
                    
    //no printing! this is -logic- time
                    //print("<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome <span id=\"myusername\">".$myusername."</span>! <br />Visit your <a style=\"text-decoration: none;\" href=\"login/member.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
                
    }
              
    //you can uncomment these redirects now
              //then redirect them to the members area
              //header("Location: login/member.php");
              //print("Welcome".$username);
              //header("Location: login/member.php");
          
    }
      } 
    Compare bible texts (and other tools):
    TheWheelofGod

  32. #32
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: login problems

    as I've tried to tell you -- use a variable of some sort (or an array of errors like I mentioned) to figure out where the errors are. you can set a flag variable for password if the password was wrong and then check whether that flag is set later on when you're displaying your form.

  33. #33

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2004
    Posts
    447

    Re: login problems

    Quote Originally Posted by kows View Post
    as I've tried to tell you -- use a variable of some sort (or an array of errors like I mentioned) to figure out where the errors are. you can set a flag variable for password if the password was wrong and then check whether that flag is set later on when you're displaying your form.
    Ok I did that:
    PHP Code:
    <?php 
    //twotexts

    session_start();
      
    //say goodbye to magic_quotes_gpc! no false security.
      
      //fix magic_quotes_gpc() being on
    if(get_magic_quotes_gpc()){
        foreach(
    $_GET as $k => $v){
            
    $_GET[$k] = stripslashes($v);
        }
        foreach(
    $_POST as $k => $v){
            
    $_POST[$k] = stripslashes($v);
        }
        foreach(
    $_COOKIE as $k => $v){
            
    $_COOKIE[$k] = stripslashes($v);
        }
    }

    include(
    "dbconnection.php");

      
    //I got rid of your function. no need for it
      
      //Checks if there is a login cookie
    if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directs you to the members page
        
    $myusername $_COOKIE['ID_my_site'];
        
    $pass $_COOKIE['Key_my_site'];
        
    $admin $_COOKIE['Admin_my_site'];
        
    $user $_COOKIE['User_my_site'];    
        
    $sql "SELECT * FROM ";
        if(
    $admin=="yes"){
            
    $sql .= $dbTable2;
        }else{
            
    $sql .= $dbTable;
        }
        
    $sql .= " WHERE username = '".mysql_real_escape_string($myusername)."'";
        
    $check mysql_query($sql)or die(mysql_error());
        while(
    $info mysql_fetch_array$check )){
            if(
    $pass == $info['password']){
                
    $writeusername "Welcome ".$myusername."! <br />Visit your <a href=\"login/member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>";
            }
        }
    }
    //variable to keep track of whether to show the user the login form or not
    $showlogin true//we show the form by default, -unless- we know they have logged in
      
    //if the login form is submitted
    if (isset($_POST['submit'])){ // if form has been submitted
        
    if(!$_POST['username'] || !$_POST['pass']) {// makes sure they filled it in
              
    $writeemptyfield "<tr><td>You did not fill in a required field.</td></tr>";
          }
    // checks it against the database
        
    $_POST['email'] = mysql_real_escape_string($_POST['email']);
        
    $db['username'] = mysql_real_escape_string($_POST['username']);
        
    $sql "SELECT * FROM ";
        if(
    $admin=="yes"){
            
    $sql .= $dbTable2;
        }else{
            
    $sql .= $dbTable;
        }
        
    $sql .= " WHERE username = '".$db['username']."'";
        
    $check mysql_query($sql) or die(mysql_error());
        
    //Gives error if user dosen't exist
        
    $check2 mysql_num_rows($check);
        if (
    $check2 == 0) {
            
    $writeusernoexist "<tr><td>That user does not exist in our database.</td></tr>";
        }
        while(
    $info mysql_fetch_array$check )){
            
    $_POST['pass'] = md5($_POST['pass']);
            
    //gives error if the password is wrong
            
    if ($_POST['pass'] != $info['password']){
                
    $writewrongpassword "<tr><td>Incorrect password, please try again.</td></tr>";
            }else{
                
    // if login is ok then we add a cookie
                
    $hour time() + 3600;
                
    setcookie("ID_my_site"$_POST['username'], $hour);
                
    setcookie("Key_my_site"$_POST['pass'], $hour);

            
    //they are logged in. no need to show the login form
            
    $showlogin false;
              
              if(
    $_POST["admin"]=="yes"){
                  
    setcookie("Admin_my_site"$_POST['admin'], $hour);
              }else{
                  
    setcookie("User_my_site"$_POST['admin'], $hour);
              }
          }
      }
    }

    $_SESSION['logged_in'] = 1;
    ...
    ?>
    and
    PHP Code:
    <?php
    //ob_start();
    include("dbconnection.php");
    if(isset(
    $_COOKIE['ID_my_site'])){
        function 
    login(){
            print(
    "<span style=\"float: left; text-align: left; padding: 5px 5px 5px 5px;\">Welcome <span id=\"myusername\">".$myusername."</span>! <br />Visit your <a style=\"text-decoration: none;\" href=\"login/member.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >member's stat</a> <br /><a style=\"text-decoration: none;\" href=\"login/logout.php\" onmouseover=\"this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" >Logout</a></span>");
        }
    }else{
        function 
    login(){
    ?>
        <table border="0">
            <tr>
                <td>Administrator:</td><td><input type="checkbox" id="adminid" name="admin" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C;" value="no" onClick="if(this.value=='no'){this.value='yes'; document.getElementById('register').style.display = 'none';} else{this.value='no';document.getElementById('register').style.display = 'block';};" /></td>
            </tr>
    <?php echo $writeemptyfield?>
    <?php 
    echo $writeusernoexist?>
            <tr>
                <td>Username:</td>
                <td><input type="text" name="username" id="username" style="float: left; border: 1px solid #7C7C7C; font: 9px verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" value="User Name" onBlur="if (this.value == '') this.value = 'User Name';" onFocus="if (this.value == 'User Name') this.value = '';" /></td>
            </tr>
    <?php echo $writewrongpassword?>        
            <tr>
                <td>Password:</td><td><input type="password" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" name="pass" id="pass" /></td></tr>
            <tr>
                <td><a id="register" href="login/register.php" style="float: left; display: block; background-color: #7C7C7C; text-align: left; padding: 0px 0px 0px 5px; width: 80px; height: 20px; text-decoration: none; color: #ffffff; border: 1px solid #7C7C7C; font-weight: bold;" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'">Register</a></td><td align="right"><input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 100px; height: 20px;" name="submit" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Login" /></td>
            </tr>
        </table>
    <?php
        
    }
    }
    ?>
    <div style="float: left; width: 100%; margin: 0px 0px 0px 0px; background-color: #7C7C7C; border: 1px solid #A5A498; border-width: 1px 1px 0px 1px;">
        <span style="float: left; padding: 2px 10px 0px 12px; color: #FFFFFF; font-family: arial; font-weight:bold; font-size: 13px;">Login</span>
    </div>
    <div style="float: left; width: 100%; height: 120px; background-color: #B4B3A9; border: 1px solid #A5A498; margin: 0px 0px 0px 0px; overflow-x: hidden; overflow-y: auto;">
    <?php login(); ?>
    </div>
    But it's not functioning properly. When I log in it doesn't show "Welcome $username". The $username shows blank.
    Last edited by gilgalbiblewhee; Apr 17th, 2010 at 12:56 AM.
    Compare bible texts (and other tools):
    TheWheelofGod

  34. #34
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: login problems

    ack! why are you using a function to display all of this again? quit that ;) you only need the original IF statement you have, you don't need to create a function to echo anything.

    functions are useful when you're going to be re-using code. they're unnecessary in your case. also, on why your variable wouldn't work -- you need to learn a little about variable scope. if you define a variable in the global scope (outside of a function), then it isn't available inside of the function. you could use the global keyword to make it available, but you'll have to read the link if you want to continue doing that.

    anyway, this is what you should be trying to do -- I've removed your function once again and I've even cleaned up the print statement you have to make it readable.

    PHP Code:
    <?php include("dbconnection.php"); ?>
    <div style="float: left; width: 100%; margin: 0px 0px 0px 0px; background-color: #7C7C7C; border: 1px solid #A5A498; border-width: 1px 1px 0px 1px;">
        <span style="float: left; padding: 2px 10px 0px 12px; color: #FFFFFF; font-family: arial; font-weight:bold; font-size: 13px;">Login</span>
    </div>
    <div style="float: left; width: 100%; height: 120px; background-color: #B4B3A9; border: 1px solid #A5A498; margin: 0px 0px 0px 0px; overflow-x: hidden; overflow-y: auto;">

    <?php if(isset($_COOKIE['ID_my_site'])){ ?>
    <span style="float: left; text-align: left; padding: 5px 5px 5px 5px;">
      Welcome <span id="myusername">{$myusername}</span>!<br />
      Visit your <a style="text-decoration: none;" href="login/member.php" onmouseover="this.style.textDecoration='underline';" onmouseout="this.style.textDecoration='none';" >member's stat</a><br />
      <a style="text-decoration: none;" href="login/logout.php" onmouseover="this.style.textDecoration='underline';" onmouseout="this.style.textDecoration='none';" >Logout</a>
    </span>
    <?php }else { ?>
    <table border="0">
            <tr>
                <td>Administrator:</td><td><input type="checkbox" id="adminid" name="admin" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C;" value="no" onClick="if(this.value=='no'){this.value='yes'; document.getElementById('register').style.display = 'none';} else{this.value='no';document.getElementById('register').style.display = 'block';};" /></td>
           </tr>
    <?php echo $writeemptyfield?>
    <?php 
    echo $writeusernoexist?>
            <tr>
                <td>Username:</td>
                <td><input type="text" name="username" id="username" style="float: left; border: 1px solid #7C7C7C; font: 9px verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" value="User Name" onBlur="if (this.value == '') this.value = 'User Name';" onFocus="if (this.value == 'User Name') this.value = '';" /></td>
           </tr>
    <?php echo $writewrongpassword?>        
            <tr>
                <td>Password:</td><td><input type="password" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" name="pass" id="pass" /></td></tr>
            <tr>
                <td><a id="register" href="login/register.php" style="float: left; display: block; background-color: #7C7C7C; text-align: left; padding: 0px 0px 0px 5px; width: 80px; height: 20px; text-decoration: none; color: #ffffff; border: 1px solid #7C7C7C; font-weight: bold;" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'">Register</a></td><td align="right"><input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 100px; height: 20px;" name="submit" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Login" /></td>
            </tr>
        </table>
    <?php ?>
    </div>
    logically, this will do exactly what you've done before. it's just better structured and written in a way that should be more maintainable than what you have done.

    you may also want to look into using a stylesheet instead of having all of that inline CSS. as far as maintainability goes, your HTML will be incredibly difficult to change in the future if you choose to do so.

  35. #35

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2004
    Posts
    447

    Re: login problems

    Quote Originally Posted by kows View Post
    ack! why are you using a function to display all of this again? quit that ;) you only need the original IF statement you have, you don't need to create a function to echo anything.

    functions are useful when you're going to be re-using code. they're unnecessary in your case. also, on why your variable wouldn't work -- you need to learn a little about variable scope. if you define a variable in the global scope (outside of a function), then it isn't available inside of the function. you could use the global keyword to make it available, but you'll have to read the link if you want to continue doing that.

    anyway, this is what you should be trying to do -- I've removed your function once again and I've even cleaned up the print statement you have to make it readable.

    PHP Code:
    <?php include("dbconnection.php"); ?>
    <div style="float: left; width: 100%; margin: 0px 0px 0px 0px; background-color: #7C7C7C; border: 1px solid #A5A498; border-width: 1px 1px 0px 1px;">
        <span style="float: left; padding: 2px 10px 0px 12px; color: #FFFFFF; font-family: arial; font-weight:bold; font-size: 13px;">Login</span>
    </div>
    <div style="float: left; width: 100%; height: 120px; background-color: #B4B3A9; border: 1px solid #A5A498; margin: 0px 0px 0px 0px; overflow-x: hidden; overflow-y: auto;">

    <?php if(isset($_COOKIE['ID_my_site'])){ ?>
    <span style="float: left; text-align: left; padding: 5px 5px 5px 5px;">
      Welcome <span id="myusername">{$myusername}</span>!<br />
      Visit your <a style="text-decoration: none;" href="login/member.php" onmouseover="this.style.textDecoration='underline';" onmouseout="this.style.textDecoration='none';" >member's stat</a><br />
      <a style="text-decoration: none;" href="login/logout.php" onmouseover="this.style.textDecoration='underline';" onmouseout="this.style.textDecoration='none';" >Logout</a>
    </span>
    <?php }else { ?>
    <table border="0">
            <tr>
                <td>Administrator:</td><td><input type="checkbox" id="adminid" name="admin" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C;" value="no" onClick="if(this.value=='no'){this.value='yes'; document.getElementById('register').style.display = 'none';} else{this.value='no';document.getElementById('register').style.display = 'block';};" /></td>
           </tr>
    <?php echo $writeemptyfield?>
    <?php 
    echo $writeusernoexist?>
            <tr>
                <td>Username:</td>
                <td><input type="text" name="username" id="username" style="float: left; border: 1px solid #7C7C7C; font: 9px verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" value="User Name" onBlur="if (this.value == '') this.value = 'User Name';" onFocus="if (this.value == 'User Name') this.value = '';" /></td>
           </tr>
    <?php echo $writewrongpassword?>        
            <tr>
                <td>Password:</td><td><input type="password" style="float: left; border: 1px solid #7C7C7C; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; width: 100px; height: 15px;" name="pass" id="pass" /></td></tr>
            <tr>
                <td><a id="register" href="login/register.php" style="float: left; display: block; background-color: #7C7C7C; text-align: left; padding: 0px 0px 0px 5px; width: 80px; height: 20px; text-decoration: none; color: #ffffff; border: 1px solid #7C7C7C; font-weight: bold;" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'">Register</a></td><td align="right"><input type="submit" style="float: left; border: 1px solid #7C7C7C; background-color: #7C7C7C; color: #ffffff; font: 9pt verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif; font-weight: bold; width: 100px; height: 20px;" name="submit" onMouseOver="this.style.backgroundColor='#B4B3A9'" onMouseOut="this.style.backgroundColor='#7C7C7C'" value="Login" /></td>
            </tr>
        </table>
    <?php ?>
    </div>
    logically, this will do exactly what you've done before. it's just better structured and written in a way that should be more maintainable than what you have done.

    you may also want to look into using a stylesheet instead of having all of that inline CSS. as far as maintainability goes, your HTML will be incredibly difficult to change in the future if you choose to do so.
    Welcome {$myusername}! It doesn't show the username. I don't understand. Once I log in it refreshes and makes me log in a 2nd time. The 2nd time it refreshes it shows Welcome {$myusername}!.
    Compare bible texts (and other tools):
    TheWheelofGod

  36. #36
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: login problems

    err. of course, that's because I was in a hurry and when I removed your print I didn't update that. {$myusername} is in HTML now; you'd need to replace that with:
    PHP Code:
    <?php echo $myusername?>
    your login is showing you as not logged on because you're using cookies. the cookie is being set, however a cookie doesn't actually become usable until you've loaded a new page. this can be gotten around by you having a redirect (to the "members" page) after the cookies are set (using the header() function). if you were to use sessions (as I recommended previously), this wouldn't be an issue.

  37. #37

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2004
    Posts
    447

    Re: login problems

    Quote Originally Posted by kows View Post
    err. of course, that's because I was in a hurry and when I removed your print I didn't update that. {$myusername} is in HTML now; you'd need to replace that with:
    PHP Code:
    <?php echo $myusername?>
    your login is showing you as not logged on because you're using cookies. the cookie is being set, however a cookie doesn't actually become usable until you've loaded a new page. this can be gotten around by you having a redirect (to the "members" page) after the cookies are set (using the header() function). if you were to use sessions (as I recommended previously), this wouldn't be an issue.
    Why isn't it logging out?
    PHP Code:
    <?php
    //ob_start();
    include("dbconnection.php");
    $past time() - 100;
    //this makes the time in the past to destroy the cookie
    setcookie("ID_my_site"gone$past);
    setcookie("Key_my_site"gone$past);
    setcookie("Admin_my_site"gone$past);
    header("Location: ../index.php");
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Logout</title>
    </head>

    <body>
    <?php

    ?>
     
    </body>
    </html>
    I put the header in the login and it worked. I forgot that this was excluded. But what's replacing the ob_start that it worked?
    Compare bible texts (and other tools):
    TheWheelofGod

  38. #38

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2004
    Posts
    447

    Re: login problems

    Quote Originally Posted by kows View Post
    and because my post was too long to make a comment afterward, here it is:

    of course, that's all untested, but it should be okay. other than the things I mentioned in that code, there are plenty of other things you can do to better this code. for example, when you query the database to see if the user exists you already know you should only be returning one result (one user per username), but you have a while looping through the results of the query. all you need to do is fetch them once, like so:
    PHP Code:
    $info mysql_fetch_assoc($query); 
    hope that at least gives you a bit of insight, or something!

    edit: oh yeah, almost forgot! instead of just printing out your errors as they happen (I didn't comment them out), consider something like this (this would be within your login validation [or just general form validation]):
    PHP Code:
    $errors = array();

    if(
    $_SERVER['REQUEST_METHOD'] == "POST"){

      if(empty(
    $_POST['username'])){
        
    $errors[] = "username was empty";
      }

      if(empty(
    $_POST['password'])){
        
    $errors[] = "password was empty";
      }

      if(empty(
    $_POST['email'])){
        
    $errors[] = "e-mail was empty";
      }

      if(
    count($errors) == 0){

        
    /* put the rest of your login logic in here, and continue checking if
         * count($errors) is 0 before you go to the next "level" of validation
         */

      
    }

    then, later on (presumably on your form):
    PHP Code:
    <h1>Login</h1>
    <?php if(count($errors)): ?>
    <h2>The following errors occurred:</h2>
    <ul>
    <?php foreach($errors as $error): ?>
      <li><?php echo $error?></li>
    <?php endforeach; ?>
    </ul>
    <?php endif; ?>
    <!-- now your form goes here -->
    Should I include this?
    Compare bible texts (and other tools):
    TheWheelofGod

  39. #39
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: login problems

    Should I include this?
    .. you can't just "include it." it's an example of the logic behind displaying errors. it isn't something that will just work for you. you'd need to apply it to work for your situation.

    I put the header in the login and it worked. I forgot that this was excluded. But what's replacing the ob_start that it worked?
    but, I don't understand what you mean. nothing is replacing ob_start(). output buffering is not needed to send headers. output buffering stops all output from going to the browser until you tell it to. this shouldn't be used as a way to get around having to send headers before output, though.

    Why isn't it logging out?
    possibly because you're trying to set the value of the cookie to a constant that doesn't exist (you need to use strings, as I've mentioned before). this may or may not be a problem.

  40. #40

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2004
    Posts
    447

    Re: login problems

    Quote Originally Posted by kows View Post
    .. you can't just "include it." it's an example of the logic behind displaying errors. it isn't something that will just work for you. you'd need to apply it to work for your situation.


    but, I don't understand what you mean. nothing is replacing ob_start(). output buffering is not needed to send headers. output buffering stops all output from going to the browser until you tell it to. this shouldn't be used as a way to get around having to send headers before output, though.


    possibly because you're trying to set the value of the cookie to a constant that doesn't exist (you need to use strings, as I've mentioned before). this may or may not be a problem.
    Ok the first part didn't work when I enserted the errors:
    index.php
    PHP Code:
    session_start();
    include(
    "dbconnection.php");
    //say goodbye to magic_quotes_gpc! no false security.
    /*
    $errors = array();

    if($_SERVER['REQUEST_METHOD'] == "POST"){
        if(empty($_POST['username'])){
            $errors[] = "username was empty";
        }
        if(empty($_POST['password'])){
            $errors[] = "password was empty";
        }
        if(empty($_POST['email'])){
            $errors[] = "e-mail was empty";
        }
        if(count($errors) == 0){*/
            //fix magic_quotes_gpc() being on
            
    if(get_magic_quotes_gpc()){
                foreach(
    $_GET as $k => $v){
                    
    $_GET[$k] = stripslashes($v);
                }
                foreach(
    $_POST as $k => $v){
                    
    $_POST[$k] = stripslashes($v);
                }
                foreach(
    $_COOKIE as $k => $v){
                    
    $_COOKIE[$k] = stripslashes($v);
                }
            }
        
    //Checks if there is a login cookie
        
    if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directs you to the members page
            
    $myusername $_COOKIE['ID_my_site'];
            
    $pass $_COOKIE['Key_my_site'];
            
    $admin $_COOKIE['Admin_my_site'];
            
    $user $_COOKIE['User_my_site'];    
            
    $sql "SELECT * FROM ";
            if(
    $admin=="yes"){
                
    $sql .= $dbTable2;
            }else{
                
    $sql .= $dbTable;
            }
            
    $sql .= " WHERE username = '".mysql_real_escape_string($myusername)."'";
            
    $check mysql_query($sql)or die(mysql_error());
            while(
    $info mysql_fetch_array$check )){
                if(
    $pass == $info['password']){
                    
    $writeusername "Welcome ".$myusername."! <br />Visit your <a href=\"login/member.php\">member's stat</a> <br /><a href=\"login/logout.php\">Logout</a>";
                }
            }
        }
        
    //variable to keep track of whether to show the user the login form or not
        
    $showlogin true//we show the form by default, -unless- we know they have logged in
          
        //if the login form is submitted
        
    if (isset($_POST['submit'])){ // if form has been submitted
            
    if(!$_POST['username'] || !$_POST['pass']) {// makes sure they filled it in
                
    $writeemptyfield "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">You did not fill in a required field.</td></tr>";
            }
    // checks it against the database
            
    $_POST['email'] = mysql_real_escape_string($_POST['email']);
            
    $db['username'] = mysql_real_escape_string($_POST['username']);
            
    $sql "SELECT * FROM ";
            if(
    $admin=="yes"){
                
    $sql .= $dbTable2;
            }else{
                
    $sql .= $dbTable;
            }
            
    $sql .= " WHERE username = '".$db['username']."'";
            
    $check mysql_query($sql) or die(mysql_error());
            
    //Gives error if user dosen't exist
            
    $check2 mysql_num_rows($check);
            if (
    $check2 == 0) {
                
    $writeusernoexist "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">That user does not exist in our database.</td></tr>";
            }
            while(
    $info mysql_fetch_array$check )){
                
    $_POST['pass'] = md5($_POST['pass']);
                
    //gives error if the password is wrong
                
    if ($_POST['pass'] != $info['password']){
                    
    $writewrongpassword "<tr><td colspan=\"2\" style=\"text-align: left; color: red;\">Incorrect password, please try again.</td></tr>";
                }else{
                    
    // if login is ok then we add a cookie
                    
    $hour time() + 3600;
                    
    setcookie("ID_my_site"$_POST['username'], $hour);
                    
    setcookie("Key_my_site"$_POST['pass'], $hour);
        
                
    //they are logged in. no need to show the login form
                
    $showlogin false;
                  
                  if(
    $_POST["admin"]=="yes"){
                      
    setcookie("Admin_my_site"$_POST['admin'], $hour);
                  }else{
                      
    setcookie("User_my_site"$_POST['admin'], $hour);
                  }
                  
    header("Location: ../index.php");
              }
          }
        }
    /*  }
    }*/

    $_SESSION['logged_in'] = 1;
    ?> 
    I don't understand what's missing in this logout script? It's redirecting back to the index page where you have the script above.
    logout.php
    PHP Code:
    <?php
    //ob_start();
    include("dbconnection.php");
    $past time() - 100;
    //this makes the time in the past to destroy the cookie
    setcookie("ID_my_site"gone$past);
    setcookie("Key_my_site"gone$past);
    setcookie("Admin_my_site"gone$past);

    header("Location: ../index.php");
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Logout</title>
    </head>

    <body>
    <?php

    ?>
     
    </body>
    </html>
    Compare bible texts (and other tools):
    TheWheelofGod

Page 1 of 3 123 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width