Ahamed
Ahamed

Reputation: 59

PHP setCookie and getCookie

I am working on this PHP application, and I set a cookie and then redirect to another pager after after when I set my cookie.

When I got to my new page and try to access my cookie, it telling me that

if ($num > 0) {
            $row = mysqli_fetch_array($result, MYSQLI_NUM);

            setcookie("userid", $row[0]);
            setcookie("username", $username);

            header("Location: ../direction/Exist.php");
            exit();
        } else {
            setcookie("username", $username);
            setcookie("password", $pass);
            header("Location: ../direction/NewMember.php");
            exit();
        }
    }

    mysqli_close(checkConnection());
}

And I my NewMember.php page, I am accessing the cookie with this code.

$username = $_COOKIE["username"];
$password = $_COOKIE["password"];

Undefined index: username in line 5

This is the line I am trying to access my cookie on.

Below is the code of how I set my cookie.

Any help please.

Upvotes: 0

Views: 4128

Answers (1)

Petr Hejda
Petr Hejda

Reputation: 43481

Your code suggests that the cookie is created and read in different URL paths. You'll need to override the path (4th argument) in which the cookie will be available on.

setcookie("username", $username, 0, "/");

From the setcookie() path argument documentation:

The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in.

Upvotes: 1

Related Questions