Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a PHP session variable through linux command prompt?

Tags:

linux

php

How to set a PHP session variable through linux command prompt?

Clarification

So, as you know we can set session variables in PHP using $_SESSION global variable when coding. I would like to know if there is a way to set this variable through php command prompt?

For example, in the code, if I can set $_SESSION['temp'] = "whatever"

Is there a way to set the same variable through command prompt PHP?

like image 218
Sev Avatar asked Jan 02 '11 00:01

Sev


2 Answers

PHP's default session handler stores the session data in serialize() format in a file, which means it's basically plain-text. You could certainly manipulate that file from the command line, using any of the standard unix text manipulation tools (perl, sed, awk, even echo/cat in a shell script, etc...), as long as you don't introduce a syntax error into the serialized data.

But at that point, unless you find a function/library/module that does unserialize() and most likely serialize() as well, you might as well just PHP itself to do the manipulation. It'd be a pretty rare system that doesn't have the CLI version of PHP installed alongside the webserver version.

$dat = file_get_contents('/path/to/session/file');
$session = unserialize($dat);
$session['temp'] = 'whatever';
$dat = serialize($session);
file_put_contents('/path/to/session/file', $dat);
like image 56
Marc B Avatar answered Oct 04 '22 17:10

Marc B


I've handled debugging code which uses $_SESSION variables by setting the relevant variables in a separate file (i.e. session_vars.php), then doing the following:

cat session_vars.php main.php | php

This will prepend the PHP from session_vars.php to main.php without making any changes to main.php, allowing you to keep your code clean.

like image 42
Spencer Judd Avatar answered Oct 04 '22 17:10

Spencer Judd