PHP $_COOKIE get cookie with preset variable - php

SOLUTION:
$_COOKIE was replacing periods with underscores.
str_replace('.','-',$cookie_name);
PROBLEM
I am setting a cookie like this.
$cookie_name = '_visited-'.$user_ip.'-'.$visted_link;
setcookie($cookie_name,'visited',time() + (86400 * 30), "/");
header('Location: '.$_SERVER['REQUEST_URI']);
exit;
then trying to see if cookie is set and unlink it from links array like this.
foreach($links['unique'] as $link){
$cookie_name = '_visited-'.$user_ip.'-'.$link;
if(isset($_COOKIE[$cookie_name])){
if(($key = array_search($l, $links['unique'])) !== false) {
unset($links['unique'][$key]);
}
}
}
odd thing is that even though the cookie is clearly set in the foreach using isset I am unable to detect that the cookie exist so I am unable to remove the visited link.

You can not access the cookie on the same page it is set.
As you can see in the manual it clearly states it:
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE array.

How do you transfer $links from one page to the other? Each call of the PHP is independent. That is why I save my cookies to a session table in the database. First step in each page is to load the sessions from the database.
I think your cookie is never found since $links is initiated at each execution. Add print_r($links) at the top of the page to see, and edit your question.

ok so found the issue. I was putting user IP in as part of the cookie name.
The . was being replaced by _ so just went ahead and replaced all . with - when setting the cookie. Works perfectly as I had intended now.

Related

Why can't I set a cookie in PHP which can be used in an If statement on the next page?

I'm trying to create a cookie within PHP.
By using the following code :
<?php
//Writing Cookie Data
setcookie("Enabled", "True", time()+3600);
setcookie("Username", $username);
//Test if cookie is set. / Just for test purposes.
echo $_COOKIE["Username"];
?>
After the cookie is set I've used a code to let users go to the next page by pressing an image (link).
This one :
<img src="image.png"></img>
And I've used a code on the next page which will check if the cookie exists.
This one :
<!-- Security Start -->
<?php
If (isset($_COOKIE["Enabled"])) {
}
else
{
header("Location: ../");
}
?>
<!-- Security Stop -->
And when the user goes to the next page he'll just be redirected to the folder specified if the security cookie doesn't exist.
I've probably setup everything correctly, and I've already checked many things, but I can't come up with a solution to this problem. The cookie should exist, and exsists.
Because the echo code works on the same page.
But after going to the next page; the cookie is suddenly gone, it doesn't exist.
Echo and using it in an If statement on the next page are both not possible.
Any ideas what might cause this?
Cookies
Some things I would do to debug this if you want cookies:
I would check the path as stated by Patrick
I would look at the return value of setcookie and see if it tells you it failed.
In your browser you should be able to see a list of all cookies, and you can check and see if the cookie was actually set. Again, look at the path here.
Using a session instead
However, I agree with the session recommendation by developerwjk, one way to do it is to make sure you call 'ob_start()' as one of the first things that happens on the page, it will then buffer the output and give you time to manipulate $_SESSION. Make sure you then call ob_flush(), to flush the buffer once you are finished with all session stuff.. I believe otherwise it will automatically flush the buffer at the end of the page but it might just discard everything..
You do not see the cookie because you have not set the PATH argument for setcookie
Using a path of "/" will enable the use of the cookie anywhere on the domain, otherwise the cookie can only be seen by scripts in the folder and sub folders of the executing script.
setcookie("Enabled", "True", time()+3600, "/");
setcookie("Username", $username,time()+3600,"/");
But as with the comments do not use cookies in place of sessions, as cookies can be easily faked.
If you already have session started you do not need to do session_start() again, if you have php 5.4 or higher you can check session status with session_status
if (session_status() !== PHP_SESSION_ACTIVE) {session_start();}
or if it is lower than 5.4
if (!isset($_SESSION)) { session_start(); }
As per the user submitted comment on the session_status page

My cookie is set but php can't read it

I've been trying to make a cookie autologin, but although the cookie is set, php can't read it. I know it is set because I can see it with Cookie Monster, I don't know what's wrong...
Need help! It's driving me crazy!
The code to set the cookie (I do it before any HTML tag)
setcookie("autologin", $_SESSION['user'], time()+5184000, "/");
the code to retrieve it:
if (!isset($_SESSION['user']) && isset($_COOKIE['autologin'])) {
$_SESSION['user']=$_COOKIE['autologin'];
}
UPDATE: I don't use the code above in the same script. I do login, close the browser, reopen it and try to get the cookie, cookie is in Cookie Monster but php can't see it.
FIX: My problem was I was trying to save a serialized object, $_SESSION['user'], in the cookie, it has been fixed with that:
setcookie("autologin", base64_encode($_SESSION['user']), time()+5184000, "/");
and retrieving with:
if (!isset($_SESSION['user']) && isset($_COOKIE['autologin'])) {
$_SESSION['user']=base64_decode($_COOKIE['autologin']);
}
This cookie will available on next page loading. In this page you can define it yourself.
My problem was I was trying to save a serialized object, $_SESSION['user'], in the cookie, it has been fixed with that:
setcookie("autologin", base64_encode($_SESSION['user']), time()+5184000, "/");
and retrieving with:
if (!isset($_SESSION['user']) && isset($_COOKIE['autologin'])) {
$_SESSION['user']=base64_decode($_COOKIE['autologin']);
}

php session pass with setcookie and unset

i have a strange problem, when i use setcookie in PHP with session, while my browser is open, everything work fine, but when I close it, then I can't pass $_SESSION from page to another page!
in login page I have:
$_SESSION['name'] = $_POST['name'];
$_SESSION['pass'] = $_POST['pass'];
$life=2592000;//1 month
setcookie(session_name(),session_id(),time()+$life);
header("location:administrator/");
die();
I used session_start(); in every page on top of them, also I used this code for logout:
session_start();
unset($_SESSION['name']);
unset($_SESSION['pass']);
session_destroy();
header("location:../");
an important note is when I checked browser cookies, before closing browser there are tow cookie and their contents value is exactly same like each other, one expire at the end of session but another expire one month latter, which I like to be, but then I close browser and return back, there are tow cookie but with different values! which I think case problem and session variables don't pass from page to page.
Apart from the problem mentioned by #Matt (you may need some custom mechanism to restore or reinstantinate session using cookies), keep in mind that using mod_rewrite or actual directories messes with cookies path! To make sure the cookie is available when and where you need it, add additional parameter / (PHP setcookie(), $path parameter)

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.

Can't set PHP cookie on the same page

I'm having trouble setting cookies on the same page. I used cookies on my site and it works fine, I tend to set make the php in separate file. Now, I'm setting a cookie on the same page but it doesn't seem to work.
$expire = time()+5;
setcookie("rb_vote", 1, $expire);
then check if it is set
if(isset($_COOKIE["rb_vote"])) {
echo "IS SET";}
else {
echo "IS NOT SET"; }
It always says is not set. I tried doing this in page load but still doesn't work.
See the manual on setcookie() (emphasis mine):
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, superglobals such as $_COOKIE became available in PHP 4.1.0. Cookie values also exist in $_REQUEST
Here is a workaround suggestion. It's imperfect because it can't guarantee the cookie actually gets set, but might do in your case.
I've just encountered this issue in Vanilla Forum. On the first page load, before a session has been established, a session cookie is created, but then every time the application wants to access the session variables (to add to them) it looks for the current session ID in $_COOKIE, which is not set until the next page load.
My workaround is to set the $_COOKIE element manually when the cookie is created.
// Create a cookie to identify the session.
// This line already exists. $Name is the cookie name.
// $SessionID is a random md5 ID that has just been generated.
setcookie($Name, $SessionID, $Expire, $Path, $Domain);
// Set the cookie for the remainder of the page. This is a workaround.
if (!isset($_COOKIE[$Name])) $_COOKIE[$Name] = $SessionID;
I've raised this as a fault with Vanilla (https://github.com/vanillaforums/Garden/issues/1568), as this workaround feels like a bit of a hack, but it certainly gets around the problem for now.
PHP5.3 Vanilla Forum Version 2.0.18.4

Categories