'PHP cookie lost after closing browser

When I open my website on localhost on chrome or other browser it set cookie until I close my browser. When I close my Chrome or other browser it delete my cookie even I have specified expiry time also. But it not lost on fire-fox, in fire-fox cookie is working properly even after closing browser. Why chrome and other browser delete my cookie after closing browser.

the code I have used :

setcookie( "CookieName", "Cookievalue", time() + 3600, "/");


Solution 1:[1]

Hello and Welcome Lucky Jaiswal, Please first off check whether chrome clears all cookies on exit. You can do this by going to settings then to privacy and security and then click on cookies and site data, there will be a toggle button saying clear all cookies and site data on exit please check if it is toggled on if yes please toggle it off and try your code again. If the problem still persists I shall try to give you another solution.

(Edit_2) Try this:

<?php 

    if ( isset($_COOKIE['test']) ) {

        echo 'Cookie exists';

    } else {

        echo 'Cookie not found';

    }

    if (isset($_POST['login'])) {

        if ( $_POST['name'] /* Add your extra conditions for example $_POST['name'] && $_POST['email'] && $_POST['password'] something like that*/ ) {

            print_r($_POST);
        
            session_start(); 

            ob_start();
        
            $name = $_POST['name'] ?? '';
        
            $conn = mysqli_connect("localhost", "root", "", "trial") ;
        
            $query = "SELECT * FROM `trialtable` WHERE `name` = '".mysqli_real_escape_string($conn, $name)."'";
        
            $result = mysqli_query($conn, $query) or die("Error 3");
        
            $row = mysqli_fetch_assoc($result);
        
            if ($name == $row['name']) {
            
                setcookie("test", '"'.$row['id'].'"', time() + 3600, "/");
        
            } 
        
            mysqli_close($conn);

        }

    }

?>

P.S: Tested in Chrome, Microsoft Edge and Firefox!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1