I'm trying to access cookie value into html using jquery or ajax ,I'm new to ajax so I don't know how to access json values. I tried with $.getJSON() but it not working. When I execute same code into localhost, it showing john.
test.php
<?php
$cookie_name = "user";
$cookie_value = "john";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
echo json_encode($_COOKIE[$cookie_name]);
?>
Not sure how you are planning on using the value on the client side, but the issue as to why you are not getting output is the fourth parameter option you have in setcookie() function. I'm not sure why you have this as the documentation I found does not list a fourth option. The function accepts the name, value, and time to live.
Also, if all you want to do is return the name of the user value, you don't need to use json_encode(). You can simply echo the name as the response:
<?php
$cookie_name = "user";
$cookie_value = "john";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30));
echo $_COOKIE[$cookie_name];
?>
Related
I know this has been asked many times before, and I've read and tried every suggestion I've found.
I set a cookie in a separate file with the following code:
<?php
session_start();
$q = $_SESSION['qty'];
setcookie ("quantity", $q, time() + (86400 * 30), "/");
$_COOKIE['quantity'] = $qty;
if(isset($_COOKIE['quantity'])) {
print_r("set");
}
else print_r("not set");
?>
It print's "set" every time, indicating to me it has been set. However, in a different php page I test for the cookie with the following code...
if(!isset($_COOKIE["quantity"])) {
include("functions/setQty.php");
}
...and it always takes me to the setQty page, indicating to me that it isn't set (which other issues verify that it's not). What am I missing?
I am trying to set a cookie like so:
<?php
$cookie_name = "user";
$cookie_value = "James";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<?php if(!isset($_COOKIE['user'])) { ?>
//Do Something
<?php } ?>
but Its not setting, I am using chrome and when I check my cookies, they are not there :(
From the setcookie documentation:
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE array. Cookie values may also exist in $_REQUEST.
You will not be able to immediately access cookies on the initial page load. Additionally, make sure that you are not outputting any HTML before setting the cookie (protocol restriction).
If you absolutely need to access the cookie immediately, you have a few options:
After setting the cookie, reload the page immediately with header
If this is not what you want to do, you can use JavaScript to set cookies, but you should note that some people disable JS in their browsers. I would not recommend this solution, personally.
$_COOKIE[] variable is set when the page loads, due to the stateless nature of the web.
Here's what the documentation says:
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE array. Cookie values may also exist in $_REQUEST.
But there are a number of word arounds to access it immediately after setting it.
you can manually set the value for $_COOKIE[] right when you set the cookie to access it or you could use an intermediate variable like so:
<?php
$cookie_name = "user";
$cookie_value = "James";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
$_COOKIE[$cookie_name] = $cookie_value;
?>
if(!isset($_COOKIE['user'])) will return true now.
Another less efficient solution world be to reload the page right after setting the cookie.
like:
$cookie_name = "user";
$cookie_value = "James";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
header("Location: your_script.php");
?>
When the page reloads, if(!isset($_COOKIE['user'])) will return true again.
Hope this helps! :)
As said in the comments, the cookie will not be visible within the same request that set it. You need to do a redirect in order to access the cookie, e.g.
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
header('Location: ' . $your_script_location_path);
exit;
Also, the code inside your check
if(!isset($_COOKIE['user'])) {
// Do something
}
will only get executed when the cookie is not set.
i am trying to insert multiple values in a cookie, but i could able to store only one value. hear is my code.
<?php
session_start();
$rand= "SED".rand(10000,99999);
?>
<!doctype>
<html lang="en">
<body>
<form action="result4.php" method="post">
<input type="hidden" name="productid" value="<?=$rand?>">
<button type="submit">submit</button>
</form>
</body>
</html>
and my result4.php
<?php
$cookie_name = "lastview";
$cookie_value = array($_POST['productid']);
$init = json_encode($cookie_value);
setcookie($cookie_name, $init, time() + (86400 * 30));
?>
<?php
echo count($_COOKIE["lastview"]);
echo '<pre>';
print_r($_COOKIE["lastview"]);
echo '</pre>';
?>
output
1
["SED73204"]
i am trying to get this
5
["SED73204"]
["SED73507"]
["SED23207"]
["SED73286"]
["SED23294"]
As mentioned, check if a value exists in the cookie already. If it does then extract that first, then add the new value.
$cookie_name = "lastview";
// Set the cookie value from previous (if exists) or else an empty array
$cookie_value = (isset($_COOKIE[$cookie_name])) ?
json_decode($_COOKIE[$cookie_name]) : array();
// Add the new value to the array if one exists
if (isset($_POST['productid']) && is_numeric($_POST['productid'])) {
$cookie_value[] = $_POST['productid'];
}
// Set the cookie
setcookie($cookie_name, json_encode($cookie_value), time() + (86400 * 30));
You may want to replace the call to is_numeric here with a preg_match to check for more specific product ID formats. For example:
if (preg_match('/^[\w]{3}[\d]{5}$/', $_POST['productid'])) { ... }
Also, you won't be able to see any values in the $_COOKIE array in the same execution cycle as setcookie(). You will need to wait for the browser to send the cookie back on the next request before you see the populated value in the $_COOKIE array.
You cant direclty store an array into a cookie,
One way to do would be to serialize the data :
setcookie('cookie', serialize($cookie_value), time()+3600);
Then unserialize data:
$data = unserialize($_COOKIE['cookie']);
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']
Im trying test the cookie that are set in my browser, earlier cookieid was given inside the url(mydomain.com?cookieid=1234). now im trying to set a cookie by calling the script which sets it. when i load the script known as proceed.php, i want that to go on and set the cookie as i have written. but it does not set the cookie as i intend
proceed.php
<?php
$cookieid = 1234;
include('bin/setcookie.php');
?>
setcookie.php
<?php
include_once dirname(__FILE__).'/../Lodread.php';
$cookieid = isset($_REQUEST["cookieid"]) ? floatval($_REQUEST["cookieid"]) : 0;
$project_id = isset($_REQUEST["projectid"]) ? intval($_REQUEST["projectid"]) : 0;
if (isset($_SERVER['HTTP_REFERER'])){
$urlParts=parse_url($_SERVER['HTTP_REFERER']);
if (isset($urlParts['query'])){
$vars = parse_str($urlParts['query']);
if (isset($vars['cookieid']) && floatval($vars['cookieid']) > 0 ){
$cookieid = floatval($vars['cookieid']);
}
}
}
if ($cookieid) {
if ( ! isset($_COOKIE["cid"])){
$cid = ($project_id?"$project_id:$cookieid":$cookieid);
setcookie("cid", $cid, time() + 60 * 60 * 24 * 365, "/", ".mydomain.com");
header('Location: '.Config_Reader::readProjectConfig('Cookie')->base_url.'/set2.php');
}
}
?>
This is sample, try like this.
How to Get the Contents of a Cookie:
Cookies set for a page can be retrieved from the variable $_COOKIE['cookie_name'] where 'cookie_name' is the name of the cookie you set earlier.
For example, if you wanted to display the value of the "userlogin" cookie, the following code should do the trick.
echo "Welcome back to the site" . $_COOKIE['userlogin'] ;
Note that you cannot set a cookie in PHP and hope to retrieve the cookie immediately in that same script session. Take the following non-working PHP code as an example:
/* WARNING: THIS WILL NOT WORK */
setcookie ( "userlogin", "anonymous", time()+60 );
echo "Value of userlogin: " . $_COOKIE['userlogin'] ;
Set Cookie without "mydomain.com".
use this:
setcookie("cid", $cid, time() + 60 * 60 * 24 * 365, "/");
now you check cookie set.
Try it without specifying the domain when using the setcookie function. Also, I would recommend passing $cid directly to your header function since the cookie value can't be retrieved within the same php script right away. Then finally you can see if the cookie is set for future use by using $_COOKIE['cookie_name'] in a separate php script to get the cookie's value.