How to set comma separated values in cookies - php

when i try to set cookie in the following way the values show me in the browser for the cookies are like this
cookie name -> recent and value 1%2c2
where 1 and 2 are my get parameters and %2c i dont know what is this i wants , in place of %2c
if(!empty($_GET['c']))
{
$c = $_GET['c'];
if(isset($_COOKIE['recent']))
{
$c=$_COOKIE['recent'].','.$c;
setcookie('recent',$c);
}
else
{
if(setcookie('recent',$c))
{
echo "yes";
}
else
{
echo "no";
}
}
}
echo $_COOKIE['recent'];

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.
http://php.net/manual/en/function.setcookie.php
http://www.php.net/manual/ru/function.urlencode.php

Related

setcookie(); does not set cookies

I have following problem, I am trying to set cookies without any success. setcookie(); function returns true so it looks like it setting cookie however when I am trying to access it on the same or following page I get error 'Undefined Index....'
<?
session_start();
ob_start();
echo setcookie("order",$_SESSION['cart'],time()+3600,'/',NULL);
//added to see if Cookie is set
echo "<br/>";
var_dump($_COOKIE);
exit();
if($_GET['paypal'] == 1){
header("Location: /paypal-express-checkout/process.php");
}else{
header("Location: /insert_order.php");
}
ob_end_flush();
exit();
?>
next page follows like this
<?php
session_start();
include_once("../includes/inc_config.php");
include_once("../order.php");
include_once("config.php");
include_once("paypal.class.php");
#region POST
if(!isset($_GET['token'])) //Post Data received from product list page.
{
//Mainly we need 4 variables from an item, Item Name, Item Price, Item Number and Item Quantity.
if(!isset($_COOKIE['order'])){
exit();
}
$paypal_data = '';
$ItemTotalPrice = 0;
$order = unserialize($_COOKIE['order']);
print_r($order);
exit;
You are setting the domain value to NULL. Try leaving the NULL away:
echo setcookie("order",$_SESSION['cart'],time()+3600,'/');
OR set it to your domain:
echo setcookie("order",$_SESSION['cart'],time()+3600,'/',".yourdomain.com");
I would var_dump or print_r the $_COOKIE variable before I make a decision that it's not getting passed through. Holding that thought once you setcookie something gets registered into the $_COOKIE variable for sure.
I agree with the statements above since you only can access $_COOKIE on the next refresh but there is another way to do it to make your form or page more interactive.
I would register the cookie and use a php page refresh (display a working... div while thats happening) then come back to the page and try to do what you originally tried doing. Very basic but pretty much straight forward.

strange result when trying to increment a n php cookie

can someone please how what hell this
cookie stops at 2 ?
<?php
if (isset($_COOKIE["count"]))
{
$cookie = ++$_COOKIE['count'];
}
else {
echo "Welcome guest!<br>";
setcookie("count", 1, time()+3600);
}
ECHO $cookie;
?>
thank you all
$cookie = ++$_COOKIE['count']; is only called once. If $_COOKIE[count] has a numerical value, $cookie will store that value plus 1.
Also, the following is not strictly correct:
echo "Welcome guest!<br>";
setcookie("count", 1, time()+3600);
You cannot call an echo before a header. I recommend you change it to this:
setcookie("count", 1, time()+3600);
echo "Welcome guest!<br>";
You cannot change cookie value by incrementing $_COOKIE[xxx], you have to use setcookie() function for that. This will work:
<?php
$cookie = isset($_COOKIE["count"]) ? $_COOKIE["count"] : 0;
setcookie('count', $cookie + 1, time()+3600);
ECHO $cookie;
You cannot update a cookie that way. However you can overwrite it.
See setcookie for more info.
If you set a cookie, it won't retrieved until the next request and so the data won't be present in $_COOKIE.
So setting a cookie and accessing it cannot be in same instance. You need to redirect or refresh after setting it.
Simply use setcookie() to increment.
to increment you place the ++ after the string, not before it.

Remove querystring value on page refresh

I am redirecting to a different page with Querystring, say
header('location:abc.php?var=1');
I am able to display a message on the redirected page with the help of querystring value by using the following code, say
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
echo 'Done';
}
}
But my problem is that the message keeps on displaying even on refreshing the page. Thus I want that the message should get removed on page refresh i.e. the value or the querystring should not exist in the url on refresh.
Thanks in advance.
You cannot "remove a query parameter on refresh". "Refresh" means the browser requests the same URL again, there's no specific event that is triggered on a refresh that would let you distinguish it from a regular page request.
Therefore, the only option to get rid of the query parameter is to redirect to a different URL after the message has been displayed. Say, using Javascript you redirect to a different page after 10 seconds or so. This significantly changes the user experience though and doesn't really solve the problem.
Option two is to save the message in a server-side session and display it once. E.g., something like:
if (isset($_SESSION['message'])) {
echo $_SESSION['message'];
unset($_SESSION['message']);
}
This can cause confusion with parallel requests though, but is mostly negligible.
Option three would be a combination of both: you save the message in the session with some unique token, then pass that token in the URL, then display the message once. E.g.:
if (isset($_GET['message'], $_SESSION['messages'][$_GET['message']])) {
echo $_SESSION['messages'][$_GET['message']];
unset($_SESSION['messages'][$_GET['message']]);
}
Better use a session instead
Assign the value to a session var
$_SESSION['whatever'] = 1;
On the next page, use it and later unset it
if(isset($_SESSION['whatever']) && $_SESSION['whatever'] == 1) {
//Do whatever you want to do here
unset($_SESSION['whatever']); //And at the end you can unset the var
}
This will be a safer alternative as it will save you from sanitizing the get value and also the value will be hidden from the users
There's an elegant JavaScript solution. If the browser supports history.replaceState (http://caniuse.com/#feat=history) you can simply call window.history.replaceState(Object, Title, URL) and replace the current entry in the browser history with a clean URL. The querystring will no longer be used on either refresh or back/previous buttons.
When the message prompt ask for a non exsisting session. If false, show the message, if true, do nothing. session_start(); is only needed, if there is no one startet before.
session_start();
if ($_GET['var']==1 && !isset($_SESSION['message_shown']))
{
$_SESSION['message_shown'] = 1;
echo 'Done';
}
Try this way [Using Sessions]
<?php
//abc.php
session_start();
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
if(isset($_SESSION['views']))
{
//$_SESSION['views']=1;
}
else
{
echo 'Done';
$_SESSION['views']=1;
}
}
}
?>
Think the question mean something like this?
$uri_req = trim($_SERVER['REQUEST_URI']);
if(!empty($_SERVER['REQUEST_URI'])){
$new_uri_req = str_replace('?avar=1', '?', $uri_req);
$new_uri_req = str_replace('&avar=1', '', $new_uri_req);
$pos = strpos($new_uri_req, '?&');
if ($pos !== false) {
$new_uri_req = str_replace('?&', '?', $new_uri_req);
}
}
if( strrchr($new_uri_req, "?") == '?' ){
$new_uri_req = substr($new_uri_req, 0, -1);
}
echo $new_uri_req; exit;
You can use then the url to redirect without vars. You can also do the same in js.
str_replace() can pass array of values to be replaced. First two calls to str_replace() can be unified, and filled with as many vars you like that needs to be removed. Also note that with preg_replace() you can use regexp that can so manage any passed var which value may change. Cheers!

how can i post the variable value in another form without using submit

I am trying to echo $_POST['admin_name']; on next page but it's not working.
How can I do this?
if(($a_name==$adminname)&&($pass_word==$pass)) {
if($a_name=="goher") {
$_POST['admin_name']=$a_name;
echo "<script>window.location='home.php'</script>";
}
else {
$_POST['admin_name']=$a_name;
echo "<script>window.location='upload.php'</script>";
}
}
else {
echo "<script>window.location='signin.php?msg=Try Again'</script>";
}
Assigning something to $_POST does not make the data available on some other page (you don't even POST in your case).
I think what you want is $_SESSION - when using sessions the data you stored there will be available on subsequent page loads (assuming you always call session_start()).

Session-cookies: Weird Behaviour? Or Have I not understood something here?

Here is the piece of code:
session_name('somename');
session_start();
echo 'session name:'.session_name();
The above does print the session name as somename.
If I append the code below,
if(isset($_COOKIE['somename'])) {
echo "<br/><br/>"."Cookie somename not yet set";
}
else {
echo "<br/><br/>".var_dump($_COOKIE['somename']);
}
The output is always
Cookie somename not yet set.
Am I using the isset function wrong?
If I just append this:
echo "<br/><br/>".var_dump($_COOKIE['somename']);
Then, the output for the first time is:
session name:somename
Notice: Undefined index: somename in /path/to/file.php on line 12 NULL
If I refresh the page, then the output is
session name:somename
string(26) "367jr029jj17mdu5fgkfgiv0u6"
Isn't the cookie variable supposed to get set before the page content is loaded? or Have I not understood sessions/cookies?
Expanding on Jani Hartikainen's answer
isset() checks to see if $_COOKIE['somename'] is set.
First time through before cookies are set:
// $_COOKIE['somename'] is NOT set so skip to else
if(isset($_COOKIE['somename'])) {
echo "<br/><br/>"."Cookie somename not yet set";
}
else {
// $_COOKIE['somename'] is NOT set so you get an error.
echo "<br/><br/>".var_dump($_COOKIE['somename']);
}
Second time through after cookies are set:
// $_COOKIE['somename'] is set so show message
if(isset($_COOKIE['somename'])) {
echo "<br/><br/>"."Cookie somename not yet set";
}
else {
// $_COOKIE['somename'] is set so skip this part.
echo "<br/><br/>".var_dump($_COOKIE['somename']);
}
A more appropriate use of isset would be something like:
if(isset($_COOKIE['somename'])) {
echo "<br/><br/>".var_dump($_COOKIE['somename']);
}
else {
echo "<br/><br/>"."Cookie somename not yet set";
}
In the last example I use isset to determine if $_COOKIE['somename'] has been set. If so, then I dump it; otherwise, I show the message “Cookie somename not yet set”
Cookies aren't set into $_COOKIE until the browser actually sends them.
It works something like this:
Request 1:
Your script starts
$_COOKIE is empty
session_start()
Your script ends
-> cookies to browser
Request 2:
<- browser sends cookies in request
Your script starts
$_COOKIE contains your cookie
...

Categories