I am a beginner for PHP and studying to use cookie for login. Would any body please check my code to see what is my problem, or let me how to fix this problem.
Wh
As a workaround you could use location() after checking the cookie to have access to the stored data.
But be aware that location() fails, if anything (including breaks and blanks in your script) already sent to the browser.
Give zerkms the answer, but I just want to reiterate:
Cookies are not bad for storing bits of info like the user's theme preferences or preferred start page, etc. They get their bad rep from being used for identity and authentication handling. There are cookies out there that basically have "isAdmin=0" in order to control user access. It is very easy to change that to isAdmin=1
and have a field day. Since you are new to PHP, take the time to learn about sessions now while it's all new to you.
When you set a cookie using setcookie
, you are sending an HTTP header to the browser with the cookie info. The browser will then pass back that cookie in any future requests to the server. The $_COOKIE
global variable holds the cookie info passed in from the browser to the server.
Since you are using $_REQUEST
to get the cookie name, you don't need to check the cookie (otherwise you wouldn't have the data to set it right?). So consider going this route:
if(!isset($_COOKIE['cookiename'])) {
$name = $_POST['name']);
setcookie("cookiename",$name);
} else {
$name = $_COOKIE['cookiename']);
}
echo "Welcome back $name!";
This will also help out if they clear cookies, etc.
But really, the safer route is:
session_start();
if(!isset($_SESSION['name'])){
$_SESSION['name'] = $_POST['name']);
}
if(!isset($_SESSION['pwd'])){
$_SESSION['pwd'] = $_POST['pwd']);
}
$name = $_SESSION['name'];
$pwd = $_SESSION['pwd'];
And even this would be frowned upon for serious web security, where you should simply check the password against a stored hash and then delete it, using other global variables to confirm session integrity. But there's now a whole StackExchange for that.
setcookie
only sets up the header, that is being sent to the client. It doesn't change the $_COOKIE
superglobal.
In other hand - $_COOKIE
is filled up with the cookies sent from the client
So at first step - you set the cookie with setcookie
and have nothing in $_COOKIE
because client hasn't sent it yet, and will only on the next request.
And there is no way of doing what you want, rather than modifying $_COOKIE
manually
PS: it is a bad idea to put user's password in the cookie