Cant create cookies when website is online - php

when i try to create a cookie with PHP they are not saved when the website is online.
When i'm on the localhost, its all okay.
For example:
setcookie('user_register', 'username', time() + 3600, '/');
How can i troubleshoot this? Is there any config in cpanel to disable cookie creation ?
Thankyou

You say it works on localhost, which alerts me to think that you have placed the setcookie below output like this for example:
<?php
// top of file
Echo "saving cookie";
setcookie('user', 'username', 3600, '/');
?>
This may work on localhost but will always fail on a real php server.
Setcookie is a header and must be placed before any output as stated in the manual http://php.net/manual/en/function.setcookie.php
To make the code above work you need to chaange place of the echo and setcookie so that it first sets the cookie and then outputs the text:
<?php
// top of file
setcookie('user', 'username', 3600, '/');
Echo "saving cookie";
?>
Then to read the cookie you need to go to a new page or refresh the page.
Cookies can't be set and read at the same time in php.
So to complete the code we can do like this:
<?php
// top of file
If($_COOKIE(['user']){
Echo $_COOKIE(['user']);
}Else{
setcookie('user', 'username', 3600, '/');
Echo "saving cookie";
}
?>
Now you can set the cookie and read it on the same page if you refresh the page.

Cookies are used next time you visit the page. So there are 3 general solutions: 1. Save it to cookie and for first time, just echo POST variables instead of COOKIE. Code will look like this:
setcookie('user', $_POST['user'], time()+3600); // notice time() function
setcookie('pass', $_POST['pass'], time()+3600); // you cant use absolute value here
if (!isset($_COOKIE['user'])) echo $_POST['user'] . ' ' . $_POST['pass'];
else echo $_COOKIE['user'] . ' ' . $_COOKIE['pass'];
, but if you really want to store password in cookie (very bad idea), then at least hash it. Code with hashing could look like this:
setcookie('pass', hash(whirlpool/*algorithm*/, $_POST['pass']/*text*/), time()+3600);
, then when you check the password, just hash it and compare hashes.

You cannot send and receive cookie in the same request. Here is a modification you should try
if(isset($_POST['user']) && isset($_POST['pass'])){
setcookie("user",$_POST['user'],3600);
setcookie("pass",$_POST['pass'],3600);
header("location:".$_SERVER['PHP_SELF']);
}
if(isset($_COOKIE['user']) && isset($_COOKIE['user']))
{
echo $_COOKIE["user"] . " " . $_COOKIE["pass"]; // This is line 28
}
However, it advisable to use sessions instead. Start by going through PHP_SESSION

Related

PHP, Login, cookie not found

I have tried to find a solution here, and worked out some issues with Cookies (such as the problem with setting the cookie before the HTML/Header is created). I have checked my browser, and the cookie is set.
However, when I use code like the following, the value is not showing:
echo "cookie name: " . $cookie_name . "<br>";
if( isset( $_COOKIE[$cookie_name] ) )
{
echo "Cookie set: " . $_COOKIE[$cookie_name] . "<br>";
The value of the variable $cookie_name is coming from a configuration file that is included, and is returning the correct value. The problem is that isset() is not seeing the cookie. This is probably a very simple issue, but I'm not seeing it. Thanks in advance -- Ken
Per request, adding code to question for readability:
The two variables being used are set to this (at least for now):
// for login cookies
$cookie_name = 'GSPCMS_Id';
$cookie_time = (3600 * 24 * 10); // 10 days
The command that sets the cookie (in the login routine) is:
setcookie( $cookie_name, $_SESSION['user_name'], time()+$cookie_time );

can not retrieve a cookie value from echo $_COOKIE['name'] in php

setcookie(name, value, expire, path, domain, secure, httponly);
When I try to echo $_COOKIE['name'], it print a blank
This should work for you:
<?php
if(!isset($_COOKIE['action'])) {
$cookie_value = "menuopen";
setcookie("action", $cookie_value, time()+3600, "/", ".acvd.com");
}
if(!empty($_COOKIE['action']))
echo $_COOKIE['action'];
?>
You have to look that your using the right name of the cookie also that acvd.com is your domain! And you can't have a secure connection but httponly!
<?php
$cookie_value = "menuopen";
if(!empty($cookie_value))
{
setcookie("action", $cookie_value, time()+3600, "/", "acvd.com", 1, 1); ?>
}
?>
I hope it will work for you.
first Check the cookie name you have used during setcookie method
You can also check your cookie value in browser following are the steps:
1 open debugger tool
2 go to resource tab
3 then go to cookies
4 then go to your domain name
there you will find the cookie name with corresponding value, check for your name is it there and what is the name whether it is name or action.
if name then echo $_COOKIE['name']
if action then echo $_COOKIE['action']

Can't make users login for long period of time

I have this platform which you can login and do your tests (this is a test link): www.mf.pt.la
I can't understand why this isn't working... first I tried this on top of my config.php file:
ini_set('session.cookie_lifetime', 864000);
ini_set('session.gc_maxlifetime', 864000);
Than I tried this with a cookie:
$year = time() + 31536000;
if($_POST['remember']=="1")
{
setcookie("remember_me", $_SESSION[LOGIN_USER], $year);
}
elseif($_POST['remember']=="")
{
if(isset($_COOKIE['remember_me']))
{
$tendays = time() + 864000;
setcookie("remember_me", $_SESSION[LOGIN_USER], $tendays);
}
}
None seem to work because after 30mins/1h user is logged out! :(
This is very frustrating because inside this website users are usually getting in a out more than once per day, and having always to login is making me lose users actually! :(
EDIT 1:
Ok, so let's see where we are at this point.
After a lot of tests, I have noticed the problem was that I was trying to save an array directly into the cookie and it doesn't work like that. I have searched a lot and created a very simple cookie with name "test" and content "text" and it worked, so if what was working I did created a cookie!
Then I searched for a way to put it working all together on the same cookie instead of save one cookie for each information I needed.
So this is the conclusion. To create the cookie, this is what I've made:
$cookie_name = "remember_me";
$userinfo = $_SESSION[LOGIN_USER]['user_id']."_".$_SESSION[LOGIN_USER]['user_type']."_".$_SESSION[LOGIN_USER]['name']."_".$_SESSION[LOGIN_USER]['email'];
if($_POST['remember']=="1"){
setcookie($cookie_name, $userinfo, time() + 31536000, '/');
}else{
setcookie($cookie_name, $userinfo, time() + 864000, '/');
}
And to call the cookie this is what I have made:
if(isset($_COOKIE["remember_me"])) {
$usercookie = explode("_",$_COOKIE["remember_me"]);
$_SESSION[LOGIN_USER]['user_id'] = $usercookie[0];
$_SESSION[LOGIN_USER]['user_type'] = $usercookie[1];
$_SESSION[LOGIN_USER]['name'] = $usercookie[2];
$_SESSION[LOGIN_USER]['email'] = $usercookie[3];
}
So far, it seems to work, but... let's see if in some more hours the login is done automatically after I enter the website again.
EDIT 2:
Just noticed that spaces are saved into cookie as + and # as %40
EDIT 3:
FINALLY! I did it and here's what I did in order to help future users:
First, let's start by creating the cookie. I inserted a new colum in my users table to save a token, and assigned that token as an encription in MD5 to a variable, like this:
$tokenuser = md5(uniqid(rand(), true));
Once the table was updated, we must create the cookie, and here it is:
$cookie_name = "mfrm";
if($_POST['remember']=="1"){
setcookie($cookie_name, $tokenuser, time() + 31536000, '/');
}else{
setcookie($cookie_name, $tokenuser, time() + 864000, '/');
}
For those who didn't understood that "if" condition, that's simply to check if the user have selected the "checkbox" in order to be remembered "forever" (one year in this case).
So far so good, the next part was the one that was "try and error" until I finally did it! You should put this code BEFORE your headers, because otherwise it might not work and will probably give you an error:
if(isset($_COOKIE["mfrm"])) {
$usercookie = $_COOKIE["mfrm"];
}
So, this way your variable $usercookie now has the content of your cookie (the unique token we created).
"Later" on your code, you simply do a call to your database, check for which user that token is valid and then just asign user_id and all other things you want in order for user to have his login. :)
I hope whoever sees this can solve the problem, I did a LOT of Google search before I finally get this working.
My suggestion is, do a lot of "print" and "echo" in PHP so you can see where is your problem, if needed stop your code by inserting sleep(2); (where 2 means two seconds)
Good luck! :)
This won't suffice, cookies are saved in user's browser, so every time she connects, you check her cookies and and set set up her session accordingly.
Hope this helps
=== EDIT ===
This may help you: http://www.pontikis.net/blog/create-cookies-php-javascript
Let's say that the user ID is '12345', and he is logging in
You set the cookie with:
setcookie('user_id', '12345', time() + (86400 * 30), '/');
Then, then if the user logs in tomorrow, and his session has expired, you check if his user_id exists in DB from the cookies:
if(isset($_COOKIE['user_id'])) {
// check the user_id in DB and create session if exists
}else{
// User has no cookies, then he has to login
}
Hope this makes sense.
This is a very simple example, so of course, do not just put a user_id in your cookies, but a more rigorous form of authentication, like the last session id and a token you'd have generated.
=== EDIT2 ===
Is 'remember' the name of a checkbox? Because in which case, if it is not checked, $_POST['remember'] is not set. So instead of checking the value of $_POST['remember'], you should check if it is set or not
Assuming that 'remember' is the name of a checkbox:
$year = time() + 31536000;
if(isset($_POST['remember']))
{
setcookie("remember_me", $_SESSION[LOGIN_USER], $year);
}
else
{
if(isset($_COOKIE['remember_me']))
{
$tendays = time() + 864000;
setcookie("remember_me", $_SESSION[LOGIN_USER], $tendays);
}
}

Cookies will not set

setcookie("test","sonali",time()+3600,"../php/"," ",false,false);
echo $_COOKIE["test"];
Notice:Undefined index:test in
D:\projects\Trainee2014\Sonali\php\cookiedemo.php on line 3
if possible please give me solution
<?php
setcookie("test","sonali",time()+3600,"../php/"," ",false,false);
$check = $_COOKIE["test"];
if (isset($check)){
echo 'Cookie not set';
}
else{
echo 'Cookie set';
}
?>
Try the above code to handle the notice.
Change your code to this and try,
setcookie("test","sonali",time()+3600,"../php/"," ",false,false);
echo isset($_COOKIE["test"]) ? $_COOKIE["test"] : '';
Problem is at the first time $_COO KIE["test"] is not set. so you need to refresh. in order to avoid this problem you should simply use the if condition with isset().
Try like this:
Syntax setcookie(name,value,expire,path,domain,secure);
Use like this in page :
<?php
$value = "cookie value";
// send a simple cookie
setcookie("user",$value);
OR
// send a cookie that expires in 24 hours
setcookie("user",$value, time()+3600*24);
?>
Access it on page like this :
<?php
echo $_COOKIE["user"];
OR
echo $HTTP_COOKIE_VARS["user"];
// Print all cookies
print_r($_COOKIE);
?>
Try this :
setcookie("test","sonali",time()+3600,"../php/",false,false);
print_r($_COOKIE);
echo $_COOKIE["test"];
Please set setcookes function only 5 parameter
setcookie(name, value, expire, path, domain);
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 '/php/', the cookie will only be available within the /php/ directory and all sub-directories such as /php/../ of domain. The default value is the current directory that the cookie is being set in.
Ref: http://php.net/setcookie
setcookie("test","sonali",time()+3600,"/"," ",false,false);
echo $_COOKIE["test"];

PHP can't remove cookie that was set by JavaScript

Is it possible to remove cookie that was set on front via JS with PHP?
I'm doing this:
*FRONT (JS):
if ($.cookie('myCookie'))
{
console.log('Cookie.. :( ');
}
else
{
console.log('Yaay! No cookie!');
$.cookie('myCookie', '123');
}
BACK (PHP):
if (isset($_REQUEST['removeCookie']))
{
setcookie("myCookie", "", time()-3600);
unset($_COOKIE['myCookie']);
}
Result:
Seems like it's a mistery
You can't force the browser to delete the cookie file. You can, however, delete the contents of the cookie and expire it. Which is exactly what you're doing with your code above. I would probably tweak it slightly:
setcookie('myCookie', '', 1, '/'); // no need to calculate one hour ago.
If client time is wrong, setting cookie expire with time() function may not work as expected.
To unset cookie try,
setcookie('myCookie', 'blah blah', 1);
Source: A Comment in php setcookie docs
It would depend on the users PC deleting the cookie after the timeout. Personally I wouldn't trust that. I'd set the cookie to an empty value, or set it to DELETED then in your test code check if it is set and then check if the value is not blank or not DELETED
To completely remove cookie from browser by PHP, Try this code
$name = 'exists_cookie';
unset($_COOKIE[$name]);
// Set empty value
$blank = setcookie($name, '', time() - 3600);
Can someone run up this code on a test machine I'm a tad confused as to why cookie can be "unset" but cannot be value changed or expired etc in php it seems like setcookie() isn't working at all.
<script type="text/javascript" src="jquery.js"></script>
<script src="jquery.cookie.js"></script>
<script>
$.cookie('myCookie', '123' ,'/');
console.log("Created myCookie");
</script>
<?php
echo $_COOKIE['myCookie'];
//Comment/uncomment below as required
//setcookie("myCookie", "BLAH", time()-430000);
//$_COOKIE['myCookie'] = "BLAH";
setcookie('myCookie', '', 1, '/');
echo "<br />unset myCookie";
echo "<br />".$_COOKIE['myCookie'];
?>
<script>
console.log($.cookie('myCookie').length);
if ($.cookie('myCookie').length>0)
{
console.log('Cookie exists ');
console.log($.cookie('myCookie'));
}
else
{
console.log('Yaay! No cookie!');
}
</script>
You seem to be able to create a php <> JS cookie mismatch ie: 2 cookies called exactly the same but storing different data.

Categories