I have a cookie set like this:
$_COOKIE['admin'] = 'foo';
Now the first time, I can see this cookie getting serialized using var_dump($_COOKIE['admin']) So, I removed that cookie and just placed this instead.
if(isset($_COOKIE['admin']){
echo 'hello admin';
}else{
echo 'hello visitor';
}
Normally this should work for all pages, but it only works once. Meaning, if I browse index page, it works, if I navigate to other page (same website) then comeback to the index page, the cookie gets lost. And there is nothing to destroy/unset any cookie/session in any page.
What could be the problem here
I think you're supposed to set cookie values like this:
setcookie("name","value", $time, "/");
This is covered here in the PHP docs.
To make cookie work in all pages, use like this
$value = 'foo';
setcookie('admin', $value, time() + (60 * 60 * 24));
Now, a cookie named 'admin' with value 'foo' will be available for 1 day. The path parameter is optional. But if you set it to "/", it will be availabel within entire domain.
Related
I'm about to write some code for mahara. I'm trying to store a variable in a cookie. If I do, it will disappear on the next page.
Example:
foo.php:
...
$myfoo = 'bar';
setcookie('mycookie', $myfoo)
var_dump($_COOKIE)
...
executing foo.php: all the mahara cookies & 'mycookie' is set. Like expected, everything's fine.
bar.php
...
var_dump($_COOKIE)
...
executing bar.php after foo.php: only mahara standard cookies set, but no 'mycookie'.
I can't really explain that.
Also $_SESSION does not work like intended.
My server is set up correctly, cookies generally work.
Has anyone an idea?
Edit: I see the cookies via var_dump in my foo.php. Even if I stop to set them. They are there. But not on other pages.
<?php
$myfoo = 'bar';
setcookie('mycookie', $myfoo, time() + (86400 * 30), "/"); // 86400 = 1 day
var_dump($_COOKIE);
?>
Your cookies are expiring because
Specifies when the cookie expires because if expiry time is omitted or set to 0, the cookie will expire at the end of the session (when the browser closes). Change it to some value like time()+86400*30
For more details: https://www.w3schools.com/php/func_network_setcookie.asp
So I'm currently making a site that includes purchases. Instead of signing up I want to set a cookie then every time a user clicks the buy button, it'll add 1 to the cookie name. Then when the cookie name = $_POST['user'] + 10 I want to echo 'too many right now' or something along those lines. I can't get this to work and have tried multiple times. There is no error in my html or anywhere else in my html. I just can't get this to work. Here is my code:
<?php
$cookie_name = $_POST['user'];
setcookie($cookie_name, time() + (86400 * 30), "/");
if(!isset($_COOKIE[$cookie_name])) {
print 'Cookie with name "' . $cookie_name . '" does not exist...';
} else {
print'Cookie with name "'. $cookie_name .'"value is:'.$_COOKIE[$cookie_name];
}
if(isset($_POST['button'])) {
setcookie($cookie_name, '+1', $cookie_value);
}
if (setcookie($cookie_name == $_POST['user'], +10)) {
echo 'to many right now';
}
?>
I obviously have a html form with the attributes name = 'button' and name = 'user' I just want to know how I can achieve what I said I was trying to do above. Any help is appreciated, thanks.
You are clearly out of your depth, and are hoping that somehow, setcookie will do all the work for you, reading, adjusting, and testing the cookie. As the manual makes clear it does only one thing:
setcookie() defines a cookie to be sent along with the rest of the HTTP headers.
It takes two main parameters: a string which is the name of the cookie to send to the browser, and a string which is the value to send; the other arguments are all optional, and change when and where it will be visible; just ignore them for now. Note that the second argument is not an equation, or an adjustment to be made, it's just a string of text to store.
As ever, the key is to break your problem down; go through each of these steps, and make sure it's working before you go to the next step:
Decide on your cookie's name (the part that won't change, because it's how you'll find it again later).
Test if the cookie has already been set on a previous request.
If it has, put its value into a new variable.
Increment that value by 1
If there is no existing cookie, set the variable to an initial value, like 0 or 1
Send a cookie to the browser with the new value, using setcookie
Test if the value has reached some threshold, and echo a message.
Note that in the above, there is only one call to setcookie; most of your logic is just working with numbers, and doesn't need to know about cookies at all.
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.
I am completely baffled by this problem. Setting a cookie should be the easiest thing in the world, but for whatever reason it's just not working. Currently I'm just trying to get a test-script to work. It looks like this:
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + 86400 * 30, "/");
setcookie("act", "sj", time() + 86400 * 365);
setcookie("bbba", "Hello", time() + 86400);
echo $_COOKIE['act'];
echo $_COOKIE['bbba'];
echo $_COOKIE['user'];
None of these cookies will set. Nothing will echo, and I can not find the cookies when using the inspector. I've tried the following:
- Placing the echo $_COOKIE in another file in the same directory.
- With and without ob_start() and ob_flush()
- Using "/", "/direcotry" and nothing at all as path
- Moving the file to the root directory to see if it works there.
Nothing seems to work, and I cannot see what could possibly be wrong. Other scripts using cookies are working on the same domain - which is located on a web hotel.
Can anyone see the problem here?
Cookies will not become visible until the next loading of a page that
the cookie should be visible for. To test if a cookie was successfully
set, check for the cookie on a next loading page before the cookie
expires. Expire time is set via the expire parameter. A nice way to
debug the existence of cookies is by simply calling
print_r($_COOKIE);.
It's from php manual. You can set the value in $_COOKIE array by manual if you really want it in same page which's declared.
$_COOKIE['key'] = 'value';
echo $_COOKIE['key'];
PHP Manual setcookie
The problem was caused by whitespace at the beginning of the document.
I'm using the following to save the current URI to a cookie:
$redirect_address = JURI::current();
Then setting the cookie like this:
setcookie('redirect_to', $redirect_address, time() + (86400 * 30), "/", ".domain.com");
Which is saving the value of the 'redirect_to' cookie as "http%3A%2F%2Fwww.domain.com/......"
The problem I'm having is that the page isn't redirecting when using:
$redirect = "<script type=\"text/javascript\">location.href = '";
$redirect .= $_COOKIE['redirect_to'];
$redirect .= "';</script>";
I think it's the funny characters it's replacing when saving the value in the cookie that's causing an issue? All of the resources I've found have said that this is the correct way to pass this to a cookie and perform the redirect, so I'm not sure what I'm doing wrong.
I changed the setcookie() line to use:
setrawcookie('redirect_to', $redirect_address, time() + (86400 * 30), "/", ".domain.com");
And that seems to have done the trick.
From http://php.net/manual/en/function.setcookie.php:
Note that the value portion of the cookie will automatically be urlencoded when you send the cookie, and when it is received, it is automatically decoded and assigned to a variable by the same name as the cookie name. If you don't want this, you can use setrawcookie() instead if you are using PHP 5.
So it is correct that the value is HTML encoded. But it should also be automatically decoded; i just tested your example code and it redirects fine. I guess the typo was elsewhere.
Of course you can just go on using setrawcookie