简体   繁体   中英

Request Cookie is not been deleted

I have a simple page where users will log in and the page checks if the cookie exist to either show the name or the login button, but the cookie is not been unset. Here is my code, where is the issue? I tried different pages but nothing worked so far.

<?php
$nombre_us = $_COOKIE['nombre_cookie'];
function logout() {
    if (isset($_COOKIE['nombre_cookie'])) {
        unset($_COOKIE['nombre_cookie']);
        setcookie('nombre_cookie', null, -1, '/');
        return true;
    } else {
        return false;
    }
}   
?>
<div class="sample">
    <?php
    if (!$nombre_us) {
        echo '<a class="smp_btn" href="login.php?pageURL=' . $url . '">Login</a>';
    }
    else {
        echo '<span class="smp_text">' . $nombre_us . '</span>';
        echo '<a class="smp_text" href="' . $url . '" onclick="logout()">Logout</a>';
    }
    ?>
</div>

Thank you!


So now I tried it with JavaScript instead of PHP but still nothing. Here is here is the sample code

<div class="sample">
<?php
$nombre_us = $_COOKIE['nombre_cookie'];
    if (!$members_name) {
        echo '<a class="smp_btn" href="sample_login.php?pageURL=' . $url . '">Login</a>';
    }
    else {
        echo '<span class="smp_text">' . $members_name . '</span>';
        ?>
        <a class="smp_text" href="<?php echo $url; ?>" onclick="delete_cookie('nombre_cookie')">Logout</a>
                <?php
                }
                ?>
            </div>
    <script>
        function delete_cookie(name) {
            document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
        }
    </script>
</div>

You can't set -1 to expire parameter in setcookie() . You can set it to 2147483647 , which is maximum value (expires 2038).

But the main problem is logout() in onclick attribute. logout() is PHP function. When clicking a tag, you are calling JavaScript logout() function. You need to use ajax ( XMLHttpRequest ), through which you can call it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM