How can i fix cookies in PHP? - 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?

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.

Related

Reading PHP Cookie is Impossible

I tried to read a PHP cookie but I couldn't, although I was able to see it in the Chrome console. I have found the solution myself, using debugging methods, but in case someone else is having the same problem, I'll answer this question myself, in order to save you time.
I was using this code:
if(!empty($_COOKIE['my.cookie'])) {
echo "cookie value: ".$_COOKIE['my.cookie'];
}
// fallback
else {
echo "cookie not set!";
}
Using the var_dump() function helped me identify the problem, because the cookie-name was changed by PHP, automatically. (Maybe a bug, or some kind of known limit - my version is PHP 7.0.33.)
var_dump($_COOKIE);
This resulted in the list of cookies printed on the web page, and the cookie name was changed from "my.page-LANG" to "my_page-LANG".
So I renamed my cookie and I was good:
if(!empty($_COOKIE['my_cookie'])) {
echo "cookie value: ".$_COOKIE['my_cookie'];
}
// fallback
else {
echo "cookie not set!";
}

Why the cookie value is not being set after omitting or adding blank white space('') as the 'expire' parameter in setcookie() function?

I'm using PHP 7.2.0
I want to omit the expire parameter in setcookie() function while setting the cookie, so I tried below code and got Parse error in output.
<!DOCTYPE html>
<?php
$cookie_n = "user";
$cookie_value = "John Doe";
setcookie($cookie_n, $cookie_value, , "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_n])) {
echo "Cookie named '" . $cookie_n . "' is not set!";
} else {
echo "Cookie '" . $cookie_n . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_n];
}
?>
<p><strong>Note:</strong> You might have to reload the page to see the value of the cookie.</p>
</body>
</html>
Output :
Parse error: syntax error, unexpected ',' in ... on line 5
Then I tried with below setcookie() code but I got Warning and the cookie didn't get set:
setcookie($cookie_n, $cookie_value, '' , "/");
Output :
Warning: setcookie() expects parameter 3 to be integer, string given in ... on line 5
Cookie named 'user' is not set!
Note: You might have to reload the page to see the value of the cookie.
From manual consider below text about expire parameter,
If set to 0, or omitted, the cookie will expire at the end of the
session (when the browser closes).
So, according to this I tried the code but it's not working and generating parse error and notice. Please someone help me and correct the mistake I'm making in my code.
I also want to know, whether the cookie value set by omitting expire parameter value will be alive after closing the respective browser tab only and not the entire web browser?
Can I set cookies from Command Line? If yes, how? If no, why?
Thank You.

PHP setcookie / cookies not working

I pulled this file from w3schools, it works perfectly fine through their editor but when I upload it on my hosting service it keeps showing up as "Cookie 'user' is not set". I checked my php.ini file and it seems like cookies are turned on, are there other settings that might be causing this problem?
<!DOCTYPE html>
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), ""); // 86400 = 1 day
?>
<html>
<body>
<?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];
}
?>
</body>
</html>
Thank you very much!
You have a line of HTML before your PHP code. I assume output buffering is off, so this line causes the response headers to be sent. Move the first line behind the PHP code.
You might not have cookies enabled on your browser. If you are using chrome, you can try the following steps:
Click the menu icon on the browser toolbar.
Select Settings.
Click the Show advanced settings
Click Content Settings
In the "Cookies" section of the dialog that appears, make sure Allow
local data to be set is selected to allow both first-party and
third-party cookies.
Click Close.
If you are using another browser, just google: "Allow coockies on [Browser Name]"

PHP :Session is not working for parent directory

I have my code for setting the session like:
if($found>0){
session_start();
$_SESSION['user_name']=$user;
session_set_cookie_params(24*60*1,'/','.localhost');
$expire=time()+60*60*24;
setcookie("cookiename", $user, $expire);
header("location:http://localhost/UI/user/userprofile.php");
} else{
$message = "Username or password is not correct.";
header("Location:index.php?message={$message}");
}
here is my header content where i put login and logout
session_start();
if (isset($_COOKIE["cookiename"])){
$unm = $_SESSION["user_name"];
echo "User : " . $_SESSION["user_name"] . "";
echo " <a href='http://localhost/UI/user/logout.php'>logout</a>";
echo " <a class='addmeeting' href='http://localhost/UI/user/createmeeting.php' title='Create New Meeting'>Create Meeting</a>";
} else{
echo "<li><a href='register.php'>Register</a></li>";
echo " User : Guest!<br />";
}
My session is working for subfolder but it is not working for the parent folder.
Here is the directory structure:
UI
user
userprofile.php
login.php
logout.php
index.php
headers.php
Please tell me what i am doing wrong ?
My guess is that it's the cookie that's not working, rather than the session (your session code is inside an if() block that checks the cookie first).
Cookies default to being limited to the current folder, so it won't apply to the parent folders.
If you want it to apply to the whole site, you need to specify a / in the cookie, like so:
setcookie("cookiename", $user, $expire, '/');
This will set the cookie across your entire site, so your code should work.
However, I don't really understand why you're not just using sessions here anyway; why have cookies and sessions in the same context? You may as well set everything in the session and be done with it. (sessions are cookie based anyway)

php cookie does not work at the first time reading

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.
When I open the page at the first time, the cookie will not work. It will work when I repeated to open that link. However, I still could not make it work after I use function include and header One of codes is :
One code cookie.php is :
<?php
setcookie("cookiename",$_REQUEST['name']);
if(isset($_COOKIE['cookiename'])){
$cookieSet = ' The Cookie is ' . $_COOKIE['cookiename'];
} else {
$cookieset = ' No Cookie has been set';
}
setcookie("cookiepwd",$_REQUEST['pwd']);
print_r($_COOKIE);
?>
When I run this code first time, it will does not show any thing. I can see cookie data at second time. From some website it is said that cookie would not be read at the same page.
So I moved print_r($_COOKIE) to second php file as well as added function include() or header() to above file, but both neither works.
Cookie2.php:
<?php
setcookie("cookiename",$_REQUEST['name']);
if(isset($_COOKIE['cookiename'])){
$cookieSet = ' The Cookie is ' . $_COOKIE['cookiename'];
} else {
$cookieset = ' No Cookie has been set';
}
setcookie("cookiepwd",$_REQUEST['pwd']);
include(‘printcookie.php’);
//or header("Location: printcookie.php")
?>
printcookie.php:
<?php
print_r($_COOKIE);
?>
Thank you very much for answering in advance!
Michelle
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
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.
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.

Categories