Cookie array with strings returns false - php

I'm trying to add the current page's URL to a cookie called '$visitedPages'. For reference, the Wordpress function 'get_permalink()' returns the URL.
In the below, the var_dump returns 'false'. Whereas if I replace 'get_permalink()' on line 2 with 'get_the_ID()', which returns the integer page IDs, this all works just fine.
I tried stripping special characters from the url, but it still returns 'false', so I suspect this problem is something to do with decoding strings from the cookie.
// define the new value to add to the cookie
$currentPage = get_the_permalink(get_the_ID());
// if the cookie exists, read it and unserialize it. If not, create a blank array
if(isset($_COOKIE['visitedPages'])) {
$visitedPagesSerialised = $_COOKIE['visitedPages'];
$visitedPages = unserialize($visitedPagesSerialised)
var_dump($visitedPages);
} else {
$visitedPages = array();
}
// add the current page id to the array and serialize
$visitedPages[] = $currentPage;
$newCookieSerialized = serialize($visitedPages);
// save the cookie for 30 days
setcookie('visitedPages', $newCookieSerialized, time() + (86400 * 30), "/");
?>

Try getting the ID, and adding it in to the permalink function. I'm assuming when you say you used get_the_ID() it means you are replacing permalink function with get ID function. Try using them in tandem.
$page_ID = get_the_ID();
$currentPage = get_the_permalink($page_ID);

I needed to remove escaped quotes from the cookie with stripslashes() before the json_decode. Why json_decode doesn't do this itself, I have no idea.
Here is the working code. Note: it is better to use exactly the same code but with json_encode() and json_decode() instead of serialize() and unserialize() so I've changed that too, but the principle is the same.
// define the new value to add to the cookie
$currentPage = get_the_permalink(get_the_ID());
// if the cookie exists, read it and unserialize it. If not, create a blank array
if(isset($_COOKIE['visitedPages'])) {
$visitedPagesSerialised = stripslashes($_COOKIE['visitedPages']);
$visitedPages = json_decode($visitedPagesSerialised)
var_dump($visitedPages);
} else {
$visitedPages = array();
}
// add the current page id to the array and serialize
$visitedPages[] = $currentPage;
$newCookieSerialized = json_encode($visitedPages);
// save the cookie for 30 days
setcookie('visitedPages', $newCookieSerialized, time() + (86400 * 30), "/");

Related

Retrieve last item in Session::

I was wondering how i could retrieve the last instance in the Session named smartBacklinks.
Here is the code
if(Session::has('smartBacklinks'))
{
// if(Request::header('referer') === LAST ITEM IN SESSION[smartBacklinks] ARRAY)
Session::push('smartBacklinks', Request::header('referer'));
}
else
{
Session::put('smartBacklinks', [Request::header('referer')]);
}
Also how do i retrieve this from a blade template ?
You can retrieve 'smartBacklinks' from the session based on the key like so:
$value = Session::get('smartBacklinks');
Also, you may want to note that you'd use Session::push() for pushing into an array session value and use Session::put() to simply store an item in session.
Retrieving the value from blade:
I guess you could pass the variable just retrieved to the view from the controller like so:
return View::make('foo.bar', array('smartBacklinks' => $value));
then use it in blade like so:
Go back
Hope that helps.
I edited my code alot and it is now functioning. I still need to add a few tweaks to make it behave 100% as i need it
The code looks like this right now:
if(Session::has('smartBacklinks')){
// Get the last item in Session array
$slice = array_slice(Session::get('smartBacklinks'), -1, 1);
// Check if Request::header('referer') is equal to the $slide[0]
if(Request::header('referer') != $slice[0]){
// Check if Request::header('referer') is empty
if(Request::header('referer') != '') Session::push('smartBacklinks', Request::header('referer'));
}
// If session[smartBacklinks] is not set. - Set
}else {
Session::put('smartBacklinks', [Request::header('referer')]);
$slice = array_slice(Session::get('smartBacklinks'), -1, 1);
}
Session::save();
Then of course the last instance of the session array is
$slice[0]
The last thing i need to add is:
when "back button" is clicked, it should remove the last instance of the session array, and it should not push URL into the session
I need to make sure that the session is loaded correctly so i dont have to refresh the webpage to get the correct "back URL"
Thanks for the answer!

Yii - Manipulating a sesssion variable

I am a still a newbie when it comes to using YII, but I been working with session variables for the past few days, and I can't seem to grasp to the concept behind my error. Any advice will be appreciated.
My add function works perfectly so far, for my current purpose of keeping track of the last 3 variables added to my session variable nutrition.
public function addSessionFavourite($pageId)
{
$page = Page::model()->findByPk($pageId);
$categoryName = $page->getCategoryNames();
if($categoryName[0] == 'Nutrition')
{
if(!isset(Yii::app()->session['nutrition']))
{
Yii::app()->session['nutrition'] = array();
}
$nutrition = Yii::app()->session['nutrition'];
array_unshift($nutrition, $pageId);
array_splice($nutrition, 3);
Yii::app()->session['nutrition'] = $nutrition;
}
My remove function doesn't seem to work at all, no matter what I try to do with it. The reason why I am transfering the session array to a temp array was to try to get around the "If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called." But it was a total failure.
public function removeSessionFavourite($pageId)
{
$page = Page::model()->findByPk($pageId);
$categoryName = $page->getCategoryNames();
if($categoryName[0] == 'Nutrition')
{
if(!isset(Yii::app()->session['nutrition']))
{
return true;
}
$nutritionArray = Yii::app()->session['nutrition'];
unset($nutritionArray[$pageId]);
Yii::app()->session['nutrition'] = $nutritionArray;
}
Any advice or push toward to the correct direction will be appreciated.
I personally I have never used Yii::app()->session I normally use the Yii user and I have never had any issues with it:
Yii::app()->user->setState('test', array('a'=>1,'b'=>2));
print_r(Yii::app()->user->getState('test')); //see whole array
$test = Yii::app()->user->getState('test');
unset($test['b']);
Yii::app()->user->setState('test',$test);
print_r(Yii::app()->user->getState('test')); //only 'a'=>1 remains
Yii::app()->user->setState('test', null);
print_r(Yii::app()->user->getState('test')); //now a null value
As I put in a comment above there seems to be issues with multidimensional arrays with the session variable: https://code.google.com/p/yii/issues/detail?id=1681

Changes to $_SESSION without page reload

I have two $_SESSION variables declared as array in index.php, say:
$_SESSION['a'] = array(1,2,3);
$_SESSION['b'] = array(4,5,6);
I make a AJAX call from index.php to result.php, where values of session variables are changed
to, say:
$_SESSION['a'] = array(2,3,1,4);
$_SESSION['b'] = array(5,6);
What I do is, I remove the first element from both the arrays and append it back to first array, $_SESSION['a'].
On successful AJAX call, I want to print the first elements of both the variables in index.php. Is it possible?
Yes, on a successful ajax call, you can do that.
This is pretty straight forward.
In your results.php you simply returned the new data with a bit of JSON.
result.php:
//set the session vars to whatever here....
//now, return them. In the example, I shall assign your session vars to temp vars.
$sessA=$_SESSION['a'];
$sessb=$_SESSION['b'];
echo json_encode(array('a'=>$sessA,'b'=>$sessb));
And now in your AJAX (assuming you're using jQuery):
$.getJSON('results.php', function(data){
alert(data.a);
alert(data.b);
});
And there you have it.
EDIT:
In your index.php, you say you set the session vars to the original value. But in your comments, you say you want to use the new vars in index.php. This won't be possible if you are setting them to the original value in index.php on every request. What you should do is check if they're already set first, and then do what needs to be done. Like this:
instead of:
$_SESSION['a'] = array(1,2,3);
$_SESSION['b'] = array(4,5,6);
Do this:
if ( isset($_SESSION['a']) === false && isset($_SESSION['b']) === false )
{
# - The vars are not already set...so it's okay to set them to its original value.
$_SESSION['a'] = array(1,2,3);
$_SESSION['b'] = array(4,5,6);
}

Session not been set

public function action_adicionar_item()
{
$lista_item_pedido = array();
$x = 0;
if(Session::has('lista_item_pedido'))
{
foreach(Session::get('lista_item_pedido') as $item)
{
$lista_item_pedido[$x] = $item;
$x++;
}
}
$lista_item_pedido[$x] = Input::all();
Session::put('lista_item_pedido', $lista_item_pedido);
}
The first time I ran this method, the session is not created so the if is ignored and it sets the array value and should define the session with name a value but it doesn't.
The second time I call it, the session is created but with no values, what is weird.
Any ideas why on my first run the session is created with the empty array?
Input::all() is returning the correct values.
I have checked the file storage/sessions/ the file is created and the value is set correctly:
s:17:"lista_item_pedido";a:1:{i:0;a:7:{s:2:"id";s:3:"162";s:10:"referencia";s:12:"112233445566";s:9:"descricao";s:6:"Sapato";s:5:"grade";s:14:"Grade 41 ao 46";s:8:"grade_id";s:1:"4";s:5:"valor";s:5:"50.00";s:10:"fornecedor";s:2:"30";}}}s:13:"last_activity";i:1340395110;}
This is created the first time I run the method, so it is created but I can't access it, only when I add two values and in this case, the first is ignored.
Try using $_SESSION instead...

Adding an key to a existing (or not) array

I got this code:
if( empty ($cache[$id]) ) {
$arr[$id] = #TIMENOW;
setcookie('id', cArr($arr, 'set'), -1, #PATH);
} else {
$cache[$id] = #TIMENOW;
setcookie('id', cArr($cache, 'set'), -1, #PATH);
}
And it is adding only one key, to the cookie, if I'll go to the another thread , it'll reset the array, and won't add more keys. I mean, if the user goes to the thread with id 1 then if( empty ($cache[1]) ) is adding 1, instead it'll update existing value, AND if user will go now to the thread with ID 5, it will do the same, and if( empty ($cache[5]) ) is empty , then it'll add the key with ID 5 to the array so I'll have both keys now: 1 and 5.
Hope you got it. If you don't , feel free to ask for whatever you wan't, I'll reply for all of your quesitons.
It would be helpful to know what you're doing in cArr(). But without it, this will add to your cookie for each new thread a user visits.
//get previous values
$id = $_GET['thread_id'];
$cache = array_key_exists('id', $_COOKIE) ? unserialize($_COOKIE['id']) : array();
//add to $cache
$cache[$id] = TIMENOW;
setcookie('id', serialize(cArr($cache, 'set')), -1, PATH);
WARNING: But keep in mind, that with just setting a cookie, your webserver can be exploited. So better not use searialize and unserialize to store simple static values inside your cookie.

Categories