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.
Related
I'm kinda lost here.
So here is what i'm trying to do.
I have a session, that's called "test", i have set the session to be an array every time that $_POST['process'] isset.
The $_POST['process'] is containing a integer, that's fetched from a DB Table.
Here's my code:
if(isset($_POST['process']))
{
$_SESSION['test'] = array();
$array_merge = array_push($_SESSION['test'], $_POST['process']);
}
It work's at first time, here's the result:
[test] => Array
(
[0] => 21311
)
I was expecting, that it would create a new key, and assign it to the other value that get's fetched from $_POST['process'] - but instead it just overwrites the 0 key.
What am i doing wrong here?
Kind regards
In your code you're writing $_SESSION['test'] = array(); which is resetting the value of $_SESSION['test'] to an empty array. Therefore it has removed your previous value and have put in your new one.
To fix this check if $_SESSION['test'] is already set, if it's not do $_SESSION['test'] = array();, otherwise just insert new values.
Full example:
if(isset($_POST['process'])) {
if(!isset($_SESSION['test'])) {
$_SESSION['test'] = array();
}
$array_merge = array_push($_SESSION['test'], $_POST['process']);
}
Honestly, this is one precise case where using array_push() is a disadvantage versus its alternative square bracket syntax.
array_push() requires you to declare the empty array in advance; [] will not AND it is functionless AND it is more brief to code.
Furthermore, I am nearly 100% sure that you don't actually want to know the new element count after pushing. The PHP Manual says:
Returns the new number of elements in the array.
...so, if you do want to know the new count, then perhaps rename your variable from $array_merge to $array_size or $array_count or $array_length.
I know I wouldn't want to write an extra condition just to declare an empty variable then use a function to add a new element, especially when it can be done in one line
if(isset($_POST['process'])) {
$_SESSION['test'][] = $_POST['process']; // all done
}
This will work the first time and every time as desired.
User gives a input for label and for key too with the other parameters(Key and Label are just example)
I want to add Key to label only once means only at first execution (first button press - but after that on every button click it should not add; php file loads on every button)after that it should be avoided to add (prepend) (key_valuelabel_value)
So my existing code adds key to label but this fails when if user gives label which has value similar to key.
For example:- key='123' and label='123 test' then my condition fails.
So anyone suggest me on this how can I handle this case ?
This is php, everytime it reloads so counter also failed.
I don't asking why do you need that. Hope this code can helps:
function isKeyInLabel($key, $label) {
$keys = explode(' ', $label);
// remove last element (it's a label)
array_pop($keys);
return in_array($key, $keys);
}
usage example:
// this condition will returns true
if (isKeyInLabel('456', '123 456 789 test')) {
// already exists
}
notice: of course you can't use keys or labels with spaces
UPD:
You'll need another variable, for example:
// of course you need a place where you can save this array
// as possible place you can use session or cookies, or
// whatever you want, here is session usage example
session_start();
// this hash will have keys that already executed
$execKeys = isset($_SESSION['execKeys'])?$_SESSION['execKeys']:array();
// assuming that $execKeys[$label] is an array
if (isset($execKeys[$label]) && in_array($key, $execKeys[$label])) {
// code already executed
} else {
$execKeys[$label] = isset($execKeys[$label])?$execKeys[$label]:array();
$execKeys[$label][] = $key;
// and if you still need it
$label = $key.' '.$label;
}
$_SESSION['execKeys'] = $execKeys;
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!
I am looking for a way to delete only certain amounts of SESSION data that is stored whilst preserving the session data associated with the user being logged on.
At the moment I am doing this by individual unset statements to the SESSION variables I want to delete.
However I was hoping there may be a more clever way to just delete a whole section of the SESSION array whilst preserving specific variables
e.g.
$_SESSION['username'];
$_SESSION['user_id'];
$_SESSION['ttl'];
The use case for this process would be:
User Logs In --> User performs task --> Once task is complete delete session data associated with task --> User is still logged in!
I had considered perhaps using a table in my Database monitoring logins, what are your opinions on that?
Thanks for your time!
There is no way to delete "whole section of the SESSION array whilst preserving specific variables".Instead of that you can use two dimensional array for a task and delete that array.
$_SESSION["task1"]["username"] = "name"
$_SESSION["task1"]["pass"] = "pass"
$_SESSION["task2"]["name"] = "name";
when task1 complete delete like
unset($_SESSION["task1"]);
now $_SESSION["task2"] still exist.
Well you could store all this volatile data inside another key:
$_SESSION['volatile'] = array(
'one' => 'value'
);
If you dnt want to do that you could use array comparison functions like:
// specify what keys to keep
$_SESSION = array_intersect_key($_SESSION, array('keepme1', 'keepme2', 'etc'));
//specify what keys to remove
$_SESSION = array_diff_key($_SESSION, array('deleteme1', 'deleteme2', 'etc'));
As far as the DB you could do that but its not necessary to accomplish your objective, and unless there are moving parts you didnt list in your original question id say you probably dont need to do anything that complex right now.
Structure your session data in a hierarchy:
$_SESSION['loggedIn'] = TRUE;
// Temporary session data
$_SESSION['temporary'] = array(
'temp_var1' => 'foo',
'temp_var2' => 'bar',
// ...
'temp_var99' => 'baz'
);
echo $_SESSION['temporary']['temp_var2']; // bar
// Remove all temporary session data
unset($_SESSION['temporary']);
echo $_SESSION['loggedIn'] ? 'yes' : 'no'; // yes
I will have to disagree with #sathishkumar, the following method destroys partially session variables.
public static function destroyPartial($keys)
{
if (session_status() === \PHP_SESSION_NONE) {
session_start();
}
if (!is_array($keys)) {
$keys = [$keys];
}
foreach ($_SESSION as $k => $v) {
if (in_array($k, $keys, true)) {
unset($_SESSION[$k]);
}
}
$recoveringSession = $_SESSION;
session_destroy();
session_start();
$_SESSION = $recoveringSession;
}
In the php docs for the session_destroy function, we can read this:
session_destroy() destroys all of the data associated with the current
session. It does not unset any of the global variables associated with
the session, or unset the session cookie. To use the session variables
again, session_start() has to be called.
So, the "trick" is to call session_start AFTER session_destroy.
Hope this helps.
I have about 15-20 permission settings that are loaded when a user logs in. These are each stored as a session with a value of 1 or 0.
I'm wondering, would it be better to have one session like $_SESSION['permissions'] with a value of: dothis:0,dothat:1,doanother:1, etc. (one large string) which I can explode and seperate later on with PHP, or would it be best to have all these as separate sessions with just a value of 1 or 0?
Rather than a string to parse, store them as an array in $_SESSION. This makes it much easier to modify individual permissions without having to do piles of string operations.
session_start();
$_SESSION['permissions'] = array();
$_SESSION['permissions']['dothis'] = TRUE;
$_SESSION['permissions']['dothat'] = FALSE;
$_SESSION['permissions']['doanother'] = TRUE;
Addendum
You might have figured this out already, but I thought I would add that it is easiest to interact with these via a few tiny functions. These will save a lot of typing (and typing errors), and make sure the values all end up as booleans.
function grant($permission) {
$_SESSION['permissions'][$permission] = TRUE;
}
function revoke($permission) {
$_SESSION['permissions'][$permission] = FALSE;
}
// Test if the user is allowed to do $permission
// FALSE if the permission isn't set
function user_can($permission) {
return isset($_SESSION['permissions'][$permission]) ? $_SESSION['permissions'][$permission] : FALSE;
}
The you can just call them as:
grant('dothis');
revoke('dothat');
if (user_can('doanother')) {
// congratulations you're allowed
}
I'd have an associative array that held all the permissions...
$_SESSION['permissions'] = array(
...
);