sokaran
sokaran

Reputation: 11

How can i fix cookies in PHP?

i want to include cookies in my website in php but i don't know how to do this.

i've tried to include them with sessions but it didn't work.

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

i expected to keep me connected but it didn't. What else do i need to add in my code to make this work?

Upvotes: 0

Views: 97

Answers (1)

Jacob S
Jacob S

Reputation: 1703

You're looking for setcookie()

Take a look at the PHP documentation for examples.

Edit:

To explain, before you can read a cookie, you need to set the cookie somewhere. You must call setcookie() before you output any information (e.g. echo or html before the php script tags) or there will be an error.

setcookie() also does not determine whether a user accepted the cookie. If a user has cookies disabled in browser, you would not be able to set or retrieve a cookie.

Since cookies can be manipulated, they tend to be a very bad place to store whether a user is logged in. Generally, sessions are better for that.

Upvotes: 1

Related Questions