I'm trying to do a simple thing in PHP and saving the currently visited page to a cookie by saving the value of $_SERVER['REQUEST_URI']
.
However, the cookie value always include a float number such as path/to/file.php?0.449978803506048
. If the URI includes parameters these are stripped and replaced by the float number.
Visiting the page path/to/file.php?param=value
:
<?php
$this_page = $_SERVER['REQUEST_URI'];
echo $this_page; // returns: path/to/file.php?param=value
setcookie("last_page", $this_page, time()+3600);
echo $_COOKIE['last_page']; // returns: path/to/file.php?0.449978803506048
?>
The number changes for each page reload which leads me to belive it has something to do with a timestamp. Is there a PHP setting or something that I need to be aware of? The result is the same in different browsers and I've also tried to encode the value in base 64 before saving the cookie but the result is still the same.
I'm usually not programming much PHP so it might be a very simple solution to this, but I cannot find it!
Running on a Apache 2.2.20 with PHP Version 5.3.6 on Ubuntu Server 11.10 (GNU/Linux 3.0.0-16-server x86_64).
Well, I think you misunderstand the setcookie effect, infact it don't change the current value of $_COOKIE variable, so a correct version of your code can be this following:
<?php
if(isset($_COOKIE['last_page'] )){
echo "cookie: ". $_COOKIE['last_page'] .'</br>'; // echo the current val of cookie
}
$this_page = $_SERVER['REQUEST_URI'];
echo "this val". $this_page ."</br>"; // returns: path/to/file.php?param=value
//setcookie("last_page", $this_page, time()+3600,'/');
setcookie("last_page", $this_page, time()+3600);
?>
The fractional number come from ajax/javascript call (I'm sure at 99.99%), you can see it in access_log, if you see always the fractional value, you will found a set of couples in the log:
127.0.0.1 - - [18/Jun/2012:11:06:04 +0200] "GET /index.php?0.1234567784534 HTTP/1.1" "-"
127.0.0.1 - - [18/Jun/2012:11:06:04 +0200] "GET /index.php?param=val HTTP/1.1" "-"
EDIT
Best solution(?) to detect if a request is ajax or not:
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';){
// this is an ajax request
} else {
// set cookie
}