Removing $_SESSION['layout']['action'] globally from all users! - php

Ok, I am storing a session variable like so to load up users layouts faster if it's set instead of calling the database. But since the layout can be changed via the Administrator, I'd like to be able to globally remove all sessions where $_SESSION['layout']['action'] is set for all users.
$_SESSION['layout']['action'] = array(a ton of indexes and mulit-dimensional arrays);
Now, I know it's being stored into my database sessions table, there's a column for session_id, last_update, and data. So, question I have is how to remove that session array key ['action'] from all users.
Using
$_SESSION = array();
session_destroy();
Does not work.
Basically, session_start() is being loaded on every page load, so I just want to remove all ['action'] keys from ['layout'].
Is this possible to do?
Thanks

Ok, I am storing a session variable
like so to load up users layouts
wrong
I'd like to be able to globally remove
all sessions where
wrong
it's being stored into my database
OMG "t instead of calling the database"!
Is this possible to do? Thanks
Leave sessions alone and don't use it for the global settings.

If you don't want to hit the database each time to load configuration data, you can cache it in a generated .inc file. Remember, PHP is just text - you can use a PHP script to generate another PHP script:
$fh = fopen('sitevars.inc'); // skipping error handling, since this is an example.
fwrite($fh, '<' . '?php' . "\n"); // split the <? tags in case an unbalanced ' somewhere hoses things
fwrite($fh, '$lifetheuniverse = 42;' . "\n"); // single quotes to the $ doesn't have to be escaped.
fwrite($fh, "\$layoutaction = 'slap forehead with palm';\n");
fclose($fh);
and then you just include_once('sitevars.inc'); and boom, it's a "global" variable. No messing with sessions.
That being said, if your sessions are being stored in the database, most likely they're in serialized format. To do a proper job of stripping a particular "global" session var from each, you'd have to load each record, de-serialize, delete the variable, re-serialize, and re-save into the DB. And hope you don't trash someone's session who happens to be active at the time you're doing these updates.

Related

Saving PHP Session variables to local variables

Im having a big problem, i am generating content with my php script. I pass some text-input to my generating script. This script is putting all text-inputto the $_SESSION variable.
For example :
$_SESSION[text1] = $text1;
$_SESSION[text2] = $text2;
and so on...
In the generated page i take those $_SESSION variables and put them to local variables.
For example :
$text1 = $_SESSION['text1']
$text2 = $_SESSION['text2']
and so on...
But after i destroy the session (Cause of login/logout system) all the content on the generated site is gone. Only the HTML tags are still there. So that means for me, all session variables get empty after destroying the session.
My question now is how do i save those session variables without loosing them after a session_destroy();?
Ps: Im using a MySQL-Database but im not so talented with it.
Session var are destroyed after session_destroy, it is how it works. You can save what you want in mysql DB, in a file (json format), mongodb, in memcached, in redis ...
You can also use cookies for simple and non secure var.
A very simple thing is to save it in a file :
file_puts_content('filename.json',json_encode($_SESSION));
and to get it back
$_SESSION=json_decode(file_gets_content('filename.json'),true);
But it's much better to do it with a database.
A solution could be to store them in the MySQL Database.
Use PDO connector to insert rows in your tables : [Doc Here]
And Insert like this :
INSERT INTO my_table(`var1`,`var2`,`var3`) VALUES($val1,$val2,$val3);
What is the context of the application ?

PHP store a single variable on the server?

I want to store a single integer like so:
<?php
$_SERVER['amount'] = 54;
echo($_SERVER['amount']);
?>
And be able to modify it, as well as be accessed from every new php session. However whenever the session ends the server variable disappears. How can i store a single variable on the server without a database? A .txt file seems kinda unnecessary for 2 characters stored.
Your storage options are a file, a hardcoded variable in the PHP code, a database table, a cookie or a session variable, as I understand it. Probably the most elegant solution if you already are using a database is to add a new table with your permanent data variables.
Another solution, if you are looking for a quick and dirty solution, is to add a global php variable with a magic number, which is really what you are trying to do with your server variable, eg global $_AMOUNT = 54; // The amount is always 54 for all users. That doesn't really meet your requirement of being able to modify it each time the page is accessed, though.
$_SERVER is a superglobal, which is read from a file each time PHP is initiated on every pageload. You are not writing to the file that the variable is read from, and so it resets each time the script executes.
Just make a database table, in my opinion. Make one row for the table, amount. I am willing to bet the table will grow over time as you add more global variables.
You could use file_put_contents and create a kind of cache file then use file_get_contents to retrieve the data..
file_get_contents AND
file_put_contents
something like
$data = array(
'something' => 'this',
'somethingelse' => 'again',
);
$settings = json_encode($data);
file_put_content( 'settings.txt', $settings);
//then
$texstSettings = file_get_contents('settings.txt' );
$settings = json_decode(texstSettings);

Where is the Php source code for generating the unique session sequence?

I've not found any session handling with mod_lua.
So I guess I'll have to write my own session handler.
Note: that's great because Php lacks of handling timeouts by values, it only handles timeout for the whole session.
I'm just looking for the source code of Php where it generates the unique number of the session, to make it with mod_lua.
I've downloaded the whole Php code source but... I don't know where to look.
Why not just use r.log_id to get a unique number?
or something like:
local session_id = r:getcookie("lua_sessionid")
if not session_id then
session_id = r:sha1(r.log_id .. r.clock())
r:setcookie{
key = "lua_sessionid",
value = session_id
}
end
Alternately, see http://modlua.org/recipes/cookies for how to work with cookies and unique IDs.
The code for generating PHP session ids is in php_session_create_id, which is available for anyone to view at https://github.com/php/php-src/blob/0021095c40a2c2d3d95398c48ae83a06f1381f71/ext/session/session.c#L284

save php variables permanently without database

In the admin area of my site there is a form which is for the hostname, username and password for the mysql database that the site uses. Currently these values are hardcoded into a php class. But who can I link it so the form can edit the variables in the php class (and keep the results on the server, in other words the variables are hardcoded). I'd normally keep things like this in a database but obviously this can't be done.
Create a configuration file, and grant your web server write access to it. Then it's just a simple matter of writing a script which saves the DB config to this file. E.g.
$fh = fopen('config.php', 'w');
fwrite($fh, chr(60) . "?php\n");
fwrite($fh, sprintf("define('DB_HOST', '%s');\n", addslashes($_POST['DB_HOST'])));
fwrite($fh, sprintf("define('DB_USER', '%s');\n", addslashes($_POST['DB_USER'])));
fwrite($fh, sprintf("define('DB_PASS', '%s');\n", addslashes($_POST['DB_PASS'])));
fclose($fh);
Keep the values in a config file. And make sure it is not accessible from the web.
The easiest solution is to keep the values in a configuration array - the user enters the values, you generate an array from it, then file_put_contents("config.php", "<?php $config = " . var_export($config)). With this method whenever you need the config array, all you need to do is include config.php and it's there.
This is untested code, for example purposes only. Depending on your situation, you may need to solve race conditions, file_put_contents is not enought for that. The main point of the above code is: var_export returns valid php code, that you can eval (if you're evil enough) or echo to a file and include that later.

Saving variables (not sessions)

This may be a silly question, but how do I save variables that are not specific to a particular session. An simple example of why you might want to do this would be a visitor counter - a number that increases by one each time someone visits a web page (note - I'm not actually doing that, my application is different, but that is the functionality I need). The only ways I can think of doing this are either writing the variables to a file, or putting the variables into a database. Both seem a bit inelegant. Is there a better way to to this kind of thing?
If you need to save global state, you need to save global state. This is typically done in either a file or a database as you already noted.
It's not "inelegant" at all. If you need to save something (semi-)permanently, you put it in a database. That's what databases are for.
Have a look at the serialize() function in PHP http://uk3.php.net/serialize where you'll be able to write an array or such to a file and re-retrieve:
<?php
// Save contents
$var = array('pageCounter' => 1);
file_put_contents('counter.txt', serialize($var));
// Retrieve it
$var = unserialize(file_get_contents('counter.txt'));
?>
Otherwise save the value to a database.
Given that PHP is stateless and that each pageload is essentially re-running your page anew, if you're going to be saving variables that will increment over multiple pageloads (e.g., number of distinct users), you'll have to use some form of server-end storage - file-based, database, whatever - to save the variable.
You could try installing APC (Alternative PHP Cache) which has cool features for sharing data between all PHP scripts, you could try using shared memory too or like you said, use a file or database
I think I've found the answer - session_name('whatever') can be used to have a fixed name for a session, I can refer to that data as well as the session specific session.
If you want it to be permanent, database and files are really your only two choices.
If you only want to temporarily store these values in memory, if APC is installed, you can do this:
// Fetch counter value back from memory
$success = false;
$counter = apc_fetch('counter', &$success);
if ($success) {
// fetch succeeded
} else {
// fetch failed
$counter = 0;
}
// Increment the counter and store again
// Note that nothing stops another request/page from changing this value
// between the fetch and store calls.
$counter++;
apc_store('counter', $counter);
That was just an example.
For a counter, you're better off using apc_inc('counter') / apc_dec('counter').
Presumably other opcode caches have similar methods. If you're not running an opcode cache... really? You want PHP to recompile a page every time its requested?
Elegant, no database and no file ?
Store it in your server memory with shmop and hope your server does not reboot !

Categories