#1
  1. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Location
    India
    Posts
    65
    Rep Power
    20

    How to delete cookie which is deleted on browser close ?


    Respected Friends,
    I have creating one offline website for my learning purpose. I have created Log in page. What I have planned to store username of the user to cookie after authenticating user from SQL Database. At the time of creating cookie I am passing validity argument as 0. This means the cookie is deleted when the client's browser is closed. Now I also want to delete the cookie when my user clicks the Log out button. Now here is the problem. I am unable to delete the cookie which is created by me with the validity argument 0. Can anyone help me to solve out this problem or are there any other methods to solve this problem. Kindly share your experience with me. Thank you.
    Following is my code.
    PHP Code:
    <?php

    require_once('SQL_Class.php');

    if ( isset ( 
    $_POST['button_logout']  ) ) {
        
    setcookie('username',NULL,-100);
        
    header 'Location : home_page.php');
    }

    $isUserAlive false;

    if ( isset ( 
    $_COOKIE['username']) ) {
        
    $isUserAlive $_COOKIE['username'];
    }
    else {
        
    $isUserAlive false;
    }

    $isWrongUsernameOrPassword false;
        
    if ( isset ( 
    $_POST['button_login'] ) and isset ($_POST['textbox_username'] ) and isset ( $_POST['textbox_password']) )    {
        
    $sqlConnection = new SQL('localhost','root','','radhe_electronics');
        
        if ( 
    $sqlConnection->IsUserValid$_POST['textbox_username'],md5($_POST['textbox_password']) ) ) {
            
            if (
    setcookie ('username',$_POST['textbox_username'],0) != true) {
                
    /*This is useless code. I have to think about the error message.My load function is not taking any arguments.------>>*/Load('There is Some problem with the Coockie. Kindly check your browser configuration and set allow Coockie to login successfully.');
            }
            
    Load();
        }
        else {
            
    $isWrongUsernameOrPassword true;
            
    Load();
        }
    }
    else {
        
    Load();
    }

    ob_start();
    ?>
    <!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>Untitled Document</title>

    <?php

    function Load()
    {

    ?>
    <div class="banner">

        <h1>    Radhe Electronics Bill searching page    </h1>

    </div>

    <div class="login">

        <form name="loginPannel" method="post" action="home_page.php">
        
        <?php
            
    if ( $GLOBALS['isWrongUsernameOrPassword'] == true )    {
                echo 
    '<dim class = "wrongUsernameOrPassword" >';
                echo 
    'Wrong Username or Password.<br/>';
                echo 
    '</dim>';
            }
            if (
    $GLOBALS['isUserAlive'] != false) {
                echo 
    'Welcome '.$GLOBALS['isUserAlive']." !";
        
    ?>
                <!--- The below code is inside the above If !--->
                 <br />
                <a href="welcome_page.php">    Home    </a>
                <input name="button_logout" id="button_logout" type="button" value="Logout" />
        
        <?php
            
    // <--- closing the If.
            
    else {
        
    ?>
                <!--- The following code is inside the Else !--->
                
                Username : <input name="textbox_username" id="textbox_username" type="text" size="20" maxlength="25" />
                <br />
                Password : <input name="textbox_password" id="textbox_password" type="password" size="20" maxlength="25" />
                <br />
                <input name="button_login"    onclick="return validateUsernameAndPassword()" type="submit" value="Login" />
                <input name="button_clear"  type="reset" value="Clear" />
                </form> 
      <?php
              
    }// <--- Closing the else.
        
    ?>
        
    </div>

    <div class="center_data">
        <!--- I am allowing the user to search call number even if they are not login. So kindly don't confuse. There are other task when the user login is required. Any user who visits page can search for the call number. !--->
        
        <form action="home_page.html" method="post" name="form_search">
        <p> 
            <h2> Enter Bill number here : </h2>
              
            <input name="textbox_searchNumber" id="textbox_searchNumber" class="large" type="text" size="25" maxlength="25" />
              <input name="button_search" onclick="IsText('textbox_searchNumber','Invalid search text.Please Enter number')" class="large" type="button" value="Search" />
       
       </p>
        
        </form>
      
          <p>&nbsp;</p>

    </div>

    <div class="footer">

        <p>    Created by Jaysinh Shukla    </p>

    </div>

    <?php

    // <-- Endinh Load function here.

    ?>

    </body>
    </html>

    <?php

    ob_flush
    ();

    ?>
    The SQL_Class.php is below.

    PHP Code:
    <?php
        
    class SQL
        
    {
            private 
    $userName$host$password$dataBaseName$connectionString;
            
            public function 
    SQL($Host,$user_name,$Password,$DBname)
            {
                
    $this->host $Host;
                
    $this->userName $user_name;
                
    $this->password $Password;
                
    $this->dataBaseName $DBname;
            
                
            }
            private function 
    Connect()
            {
                
    $this->connectionString mysqli_connect($this->host,$this->userName,$this->password,$this->dataBaseName);
                
                
                if (
    mysqli_connect_errno() == 0)
                {
                    
                    return 
    true;
                }
                else
                {
                    
    mysqli_close($connectionString);
                    return 
    false;
                }
            }
            private function 
    Disconnect()
            {
                
    mysqli_close($this->connectionString);
            }
            
            private function 
    ExecuteQuery($query)
            {
                if(
    $this->Connect())
                {
                    
                
                    
    $result mysqli_query($this->connectionString,$query);
                    
                    if ( 
    $result == 'FALSE' or $result == 'TRUE') {
                            
    $this->Disconnect();
                            
                            
    //echo 'Returning from true-false';
                            
                            
    return $result;    
                            
                    }
                    else {
                        
    $rows mysqli_fetch_array($result);
                
                    
    $this->Disconnect();
                    
                    
    //echo 'returning from array';
                    
    return $rows;
                    }
                }
                else
                {
                    
    //echo 'returning from null';
                    
    return NULL;
                }
            }
            public function 
    IsUserValid($user_name$password)
            {
                 
    $result $this->ExecuteQuery("SELECT COUNT(*) FROM USER WHERE username = '$user_name' and password = '$password'");
                
                    if ( 
    $result[0]> '0')
                    {
                        return 
    true;
                    }
                    else
                    {
                        return 
    false;
                    }
            }
            public function 
    IsUsernameExists ($username)
            {
                
    $users $this->ExecuteQuery("SELECT COUNT(*) FROM USER WHERE USERNAME = '$username'");
                
            if ( 
    $users[0] > '0' ) {
                    return 
    true;
                }
                else {
                    return 
    false;
                }
                
            }
            public function 
    CreateUser($firstName$lastName$gender$username$password)
            {
                
    $result $this->ExecuteQuery("INSERT INTO USER (`username`, `password`, `dateOfJoining`, `gender`, `typeOfUser`, `isUserContinue`, `firstname`, `lastname`) VALUES ('$username',  '$password', CURDATE(), '$gender', 2, 'YES', '$firstName', '$lastName') ");
                
                return 
    $result;
            }
        
        }
    ?>
  2. #2
  3. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    13,997
    Rep Power
    9397
    You can't technically guarantee that a cookie will be deleted (it's up to the browser) but you can change the value and give an expiration in the past. Which it looks like you're doing...

    Can you confirm that your cookie has the new value and expiration? Inspecting response headers and looking for Set-Cookie is the best way to see exactly what the browser is receiving.
  4. #3
  5. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1046
    Hi,

    there are several bugs and issues, so I'm not too surprised that you're not getting the expected result.

    First of all, what is the -100 in the setcookie() call supposed to do? Check the manual: You can either pass 0 or a Unix timestamp (e. g. 1378011600). The number 0 makes it a session cookie, a Unix timestamp sets the expires value to that point of time. Negative values are invalid and seem to result in a session cookie. If you wanna set the expiration to a point of time in the past, you must use the current timestamp and then subtract the duration from it. The manual again explains exactly how to do it:

    PHP Code:
    <?php

    // set the expiration date to one hour ago
    setcookie ("TestCookie"""time() - 3600);
    The next problem is that you don't stop the script after sending the Location header. This means it will keep running, and you might again send the cookie you just tried to delete.

    Apart from that, there are plenty of security issues: You don't do any escaping in your queries, which makes them wide open to SQL injections (which is kinda sad given that the MySQLi library has some great security features). You hash your passwords with the incredibly weak and long obsolete MD5 algorithm. And you connect to your database as root. Check The 6 worst sins of security to get a basic understanding of typical security risks and how to deal with them.
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  6. #4
  7. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Location
    India
    Posts
    65
    Rep Power
    20
    Originally Posted by Jacques1
    Hi,

    there are several bugs and issues, so I'm not too surprised that you're not getting the expected result.

    First of all, what is the -100 in the setcookie() call supposed to do? Check the manual: You can either pass 0 or a Unix timestamp (e. g. 1378011600). The number 0 makes it a session cookie, a Unix timestamp sets the expires value to that point of time. Negative values are invalid and seem to result in a session cookie. If you wanna set the expiration to a point of time in the past, you must use the current timestamp and then subtract the duration from it. The manual again explains exactly how to do it:

    PHP Code:
    <?php

    // set the expiration date to one hour ago
    setcookie ("TestCookie"""time() - 3600);
    The next problem is that you don't stop the script after sending the Location header. This means it will keep running, and you might again send the cookie you just tried to delete.

    Apart from that, there are plenty of security issues: You don't do any escaping in your queries, which makes them wide open to SQL injections (which is kinda sad given that the MySQLi library has some great security features). You hash your passwords with the incredibly weak and long obsolete MD5 algorithm. And you connect to your database as root. Check The 6 worst sins of security to get a basic understanding of typical security risks and how to deal with them.
    Thank you for Your deep comment. Well This is my first real world code in PHP. The reason behind passing " -100 " value in setcookie function is to remove it because I thought when I am creating Cookie with "0" when I will create with any minus argument I will be deleted but unfortunately it is not. So here I was unknown how to delete Session cookie. Is there any predefined PHP function to delete Session Cookie ?
    I know about the issue of security in my script. You can consider it to be week. But I was planning to create limited separate MySQL account for my script. I was also planning to create SALT in database and conforming it with the combination of the password. But this Session stuff irritates me so I postponed it.
  8. #5
  9. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1046
    Originally Posted by jaysinhp
    Is there any predefined PHP function to delete Session Cookie ?
    No, but you can use the code above.

    Note, however, that deleting the session cookie isn't enough. You also need to delete the session file on the server. Otherwise, anybody can continue to use the session by creating the cookie in their browser.

    Stopping a session consists of three actions:

    • Deleting the session file with session_destroy().
    • Asking the browser to delete the session cookie.
    • Emptying the $_SESSION array. This is not strictly necessary, but it's sensible to account for programming errors.

    The manual has a code example.



    Originally Posted by jaysinhp
    I know about the issue of security in my script. You can consider it to be week. But I was planning to create limited separate MySQL account for my script.
    Great. To make your queries secure, use prepared statements. This is by far the most reliable way of preventing SQL injections.



    Originally Posted by jaysinhp
    I was also planning to create SALT in database and conforming it with the combination of the password.
    Don't. Fumbling with your own salts and hashes is a bad idea, because there's a lot of mistakes you can make. And MD5 (or SHA, for that matter) is so weak that a salt simply won't help you.

    Instead, use a specialized password hashing algorithm. If you have PHP 5.5, you can take advantage of the new password API. It's very secure and easy to use. If you don't have PHP 5.5 but at least 5.3.7, you can use the password_compat library, which emulates the new API. If you don't even have PHP 5.3.7, it's time for an update.
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".

IMN logo majestic logo threadwatch logo seochat tools logo