PHP cookies instantly expire when set to value retrieved from the database

Hey, whenever i set a cookie to a value retrieved from my database, it expires instantly, regardless of how long i set the time parameter.

my code is below.

 <?php
            if(isset($_COOKIE['A001'])) { 
              $sessionID = $_COOKIE['A001'];
                $con = [code removed however I have checked that the connection is fine]
                $sql = "SELECT * FROM Users WHERE SessionID = '$sessionID' ";
                if($result = mysqli_query($con, $sql)) {
                    $row = mysqli_fetch_assoc($result);
                    setcookie("LName", $row['LastName'], time() + 1800, "/", "www.mywebsite.com");
                }
            } 
            mysqli_free_result($result);
            mysqli_close();
        ?>

Cookie A001 is set in another file and the code does detect this file and verifies its contents.
The cookie LName is set after this code is run but its expiry date is identical to its creation date and so its contents say “deleted” when i look at it in the browser.
This only occurs if the cookies value is set to either $row[‘column_name’] or another variable which is set to $row[‘column_name’]

My first guess would be that the value $row['LastName'] is empty. If you set a cookie with a value null, the browser may show it as deleted. Can you please debug the value in the code to make sure that isn’t the case?

I also see that there is no error handling to make sure that the session ID exists. Or input sanitation (remember that cookies can be changed at will by the visitor, which includes injecting SQL code into the value).

3 Likes

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.