C
C
Cat_usual2019-09-16 19:46:14
PHP
Cat_usual, 2019-09-16 19:46:14

How to delete cookies?

Actually, I got an error: Cannot modify header information - headers already sent

<?php
require 'db.php';
require 'database.php';


$id = $_SESSION['user_id'];
if ($result = $link->query("SELECT clicks FROM users WHERE id =".$_SESSION['user_id'])) {
    $row = $result->fetch_all();
    foreach ($row as &$value){
        $balance = $value[0];
        global $balance;
    }
    $result->close();
}

?>
<head>
    <title>Ваш аккаунт</title>
    <link rel="stylesheet" href="free.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>

<?php if ( isset($_COOKIE['user_hash'])) {
    $test = $link->query('SELECT COUNT(*) FROM users WHERE hash = "' . $_COOKIE['user_hash'] . '"');
    $rows = mysqli_fetch_row($test);
    $total = $rows[0]; // всего записей
    if ($total == 1) {
        $user_id = $link->query('SELECT id, login FROM users WHERE hash = "'. $_COOKIE['user_hash'].'"');
        foreach ($user_id as $values) {
            $_SESSION['user_id'] = $values['id'];
            $_SESSION['logged_user'] = $values['login'];
        };
    };
};?>

<?php if ( isset ($_COOKIE['user_hash']) ) : ?>
    <?php
//    $test = $link->query('SELECT id FROM users WHERE hash = "'.$_COOKIE['user_hash'].'"');
    $test = $link->query('SELECT COUNT(*) FROM users WHERE hash = "'.$_COOKIE['user_hash'].'"');
    $rows = mysqli_fetch_row($test);
    $total = $rows[0]; // всего записей
    if ($total == 0) {
        unset($_SESSION['logged_user']);
        $link->query('UPDATE users SET hash = "" WHERE ID ='.$_SESSION['user_id']);
        unset($_SESSION['user_id']);
        setcookie("user_hash", '', time() - 3600);
        header('Location: /');
};
    ?>
?>

I need to check if the cookie is not in the database, and the request returns 0, then delete everything, including cookies.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Talyan, 2019-09-16
@Cat_usual

cookies, sessions - all this must be done before the first appearance of the character on the page. You already have the HTML code out there, and only then you manipulate cookies. That won't work. First - cookies and sessions, and only then - HTML output /
If you had PHP error output turned on, you would see "Header already send"

B
Barmunk, 2019-09-16
@Barmunk

Before deciding Cannot modify header information , pay attention to sql injections. $_COOKIE['user_hash'] anyone can open a browser debug and change your hash to something worse. Read what this approach can lead to: https://habr.com/ru/post/148151/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question