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']);
Related
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];
?>
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 have a session variable 'touser' which resets everytime I refresh the page but my session variable for the whole session "user" does not reset.
<?php
session_start(); require("source/header.php");
require("scripts/connection/signup/db.php");
?>
<?php
session_start();
$touser=$_POST["chats"];
$_SESSION["touser"]=$touser;
echo $_SESSION["touser"];
?>
The problem is on page refresh POST values are gone and since you assign them to $touser and it used for session so every page refresh Session value is reset.
Solution is :-
<?php
session_start();
if (isset($_POST['touser'])) { // check if POST have that index or not
$touser = $_POST["chats"]; // if yes then reassign it's value
$_SESSION["touser"] = $touser; // set reassigned value to session variable
}
echo $_SESSION["touser"];// print session value (here if POST have data then new value will show otherwise old one will show)
?>
Check, if $_POST['touser'] exists.
<?php
session_start();
if (isset($_POST['touser'])) {
$touser = $_POST["chats"];
$_SESSION["touser"] = $touser;
}
echo $_SESSION["touser"];
?>
You have to check whether $_POST["chats"] is set or not and then put value into session.
session_start();
if (isset($_POST["chats"])) {
$_SESSION["touser"]=$_POST["chats"];
}
echo $_SESSION["touser"];
I have a question about how I can access the value from a variable from one page on another one.
I have a registration script and the registration form is on my homepage. I want to dynamically create a random name for every input field (change the value of the name attribute). The current name attribute for the input is just firstName, but I want it to be like firstName_345635. The 345635 is a randomly generated number and will change everytime the page refreshes.
Here is my random number variable:
$firstNameInputName = 'firstName_' . rand(10000, 50000);
The output becomes: firstName_[randomNumer].
The problem is, the register.php has all the post variables to get the form data. What I have now is this:
$firstName = $_POST["firstName"]);
I need to get the value from the random number variables from the homepage and instead of giving the $firstname variable the name firstName, it should get the name that the random number generating variable has produced on the homepage.
How can I achieve this?
You should use a session (or cookies) var to save this dynamic name.
Approach 1. Session (or cookies)
page1.php
<?php
session_start();
$customCode = rand(5, 15);
$_SESSION['customCode'] = $customCode; ?>
<form action="page2.php" method="post">
<input type="text" name="firstName_<?php echo $customCode; ?>" />
</form>
page2.php
<?php
session_start();
$customCode = $_SESSION['customCode']; ?>
$firstName = $_POST['firstName_'.$customCode];
Approach 2. You can put a input hidden field in your form like:
<input type="hidden" name="customCode" value="345635" />
And get it in second page like:
$firstName = $_POST['firstName_'.$_POST['customCode']];
Approach 3. You can iterate over your $_POST array to get firstName like:
foreach($_POST in $key => $value) {
if(strpos($key, "firstName")) {
$firstName = $value;
}
}
The solution is sessions, session variables are superglobal variables which means you can use them in different files as long as its the same session, to use them you need to start the session at every page you'll use them in, also, starting the session has to be done before any output is shown.
Ex (registeration page):
<?php
session_start();
/**
** HTML AND FORM HERE WHATEVER ELSE YOU NEED TO DISPLAY
**/
$_SESSION['FirstName'] = $firstNameInputName;
?>
Ex (processing page):
<?php
session_start();
echo $_POST[$_SESSION['FirstName']]; // Output: Whatever was entered inside the field
?>
I am implementing a php page counter that will keep track of each time the user visits this page until the browser is closed. I am checking to see if the cookie is set, if it is. Then I am increment it and reset its value. But the problem I am having is that the counter is always at two, why is this?
<html>
<head>
<title>Count Page Access</title>
</head>
<body>
<?php
if (!isset($_COOKIE['count']))
{
?>
Welcome! This is the first time you have viewed this page.
<?php
$cookie = 1;
setcookie("count", $cookie);
}
else
{
$cookie = $_COOKIE['count']++;
setcookie("count", $cookie);
?>
You have viewed this page <?= $_COOKIE['count'] ?> times.
<?php }// end else ?>
</body>
</html>
Edit: Thanks everyone, I did the pre increment thing and got it to work
This is happening because of the ++ being used as a post-increment instead of a pre-increment. Essentially what is happening is you're saying, "set $cookie to the value of $_COOKIE['count'], and then increment $_COOKIE['count']. This means that each time you set it you're only actually making $cookie equal 1, and even though $_COOKIE['count'] is showing it as 2, the actual cookie you send will only equal 1. If you do $cookie = ++$_COOKIE['count']; you should get the correct result.
This line is the problem:
$cookie = $_COOKIE['count']++;
It doesn't increment the way you expect; the variable $cookie is set to the value of $_COOKIE, and then $_COOKIE is incremented. It's the postincrement operator.
Use the preincrement operator instead, which increments and then returns:
$cookie = ++$_COOKIE['count'];
the _COOKIE array is populated ONCE when the script first starts up (before any code is actually executed), and then is NOT touched again by PHP. Even if you do a setcookie() call to change one of the cookies, that change will NOT take effect until the next page load.
As well, the ++ operator is working in "post-increment" mode. Doing
$cookie = $_COOKIE['count']++;
boils down to this:
$cookie = $_COOKIE['count'];
$_COOKIE['count'] = $_COOKIE['count'] + 1;
What you want is the PRE-increment version:
$cookie = ++$_COOKIE['count'];
which increments the cookie value and THEN assigns it to the cookie var.
You only need to do this
setcookie('count', isset($_COOKIE['count']) ? $_COOKIE['count']++ : 1);
Like so:
<?php
setcookie('count', isset($_COOKIE['count']) ? $_COOKIE['count']++ : 1);
$visitCount = $_COOKIE['count'];
?>
<html>
<head>
<title>Count Page Access</title>
</head>
<body>
<?if ($visitCount == 1): ?>
Welcome! This is the first time you have viewed this page.
<?else:?>
You have viewed this page <?= $_COOKIE['count'] ?> times.
<?endif;?>
</body>
</html>