Using cookies to check if logged in
<p>Hi I'm trying to fetch the cookie I successfully created, and compare it to a string.</p>

<p>The problem is that, if the user access the page directly, all the content is shown, and I don't want that to happen, I want to redirect the user to the login page.</p>

<p>Basically if it says yes, it will simply show me the page, and if either there is no cookie or is set to no, it will redirect me to the login.</p>

<p>I'm trying to use PHP. This is what I tried.</p>

<pre><code>&lt;?php
        $value = "Yes";
        if(isset($_COOKIE['user']) &amp;&amp; $_COOKIE['user'] == $value)
        {
?&gt;

&lt;!------- HTML code goes here -------&gt;

&lt;?php

        }
        else{
            $cookie_name = "user";
            $cookie_value = "No";
            setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); 
            header("Location: index1.html");
        }

?&gt;
</code></pre>

<p>This is the php I'm calling to basically check the details inputted with an SQL database.</p>

<pre><code>&lt;?php
    $username = $_POST['username'];
    $password = $_POST['password'];

    $conn = mysqli_connect("localhost", "root", "", "accounts");
    if (mysqli_connect_errno()){
        echo "Error: Could not connect to database. Please try again later";
        exit;
    }

    $query="SELECT * FROM accounts WHERE username='$username' AND password='$password'";

    $result = mysqli_query($conn, $query)
    or die("Error in query: ". mysqli_error($conn));

    $number_of_rows = mysqli_num_rows($result);

    if($number_of_rows == 1 ){
        $cookie_name = "user";
        $cookie_value = "Yes";
        setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day

        header("Location: main.html");
        exit;
    }
    else{
        $cookie_name = "user";
        $cookie_value = "No";
        setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
        header("Location: index2.html");
    }
?&gt;
</code></pre>

<p>Can someone help me figure out how to do this? I tried different code, and also tried sessions instead but with no luck. I have successfully stored the cookie, but can't seem to solve this part.</p>

<p>Thanks</p>