Is it possible to read the cookie / session value when executing a PHP5 script through the command line?

I need to read some values ​​from a cookie or session when I execute my php script using the command line. How can i do this?

How to access cookie or session value from windows command line?

+4
source share
3 answers

Cookies are sent from the user's web browser. When you execute php script from the command line, the browser cannot send or receive cookies. It is not possible to access or save cookies, and nothing is sent to the script, except for the parameters that you pass on the command line.

As they say, there is a way to read a session that a user has already accessed with a browser if you know his PHPSESSID cookie.

Let's say someone accessed your script with a web browser and their PHPSESSID is a1b2c3d4, and you want to execute the script with their session. Run the following command at a command prompt.

php -r '$_COOKIE["PHPSESSID"] = "a1b2c3d4"; session_start(); require("path_to_php_script.php");' 

Where path_to_php_script.php is the path to the php script you want to execute. And in fact, you do not need to start a session if the php file you want to execute starts the session itself. So you can try this command:

 php -r '$_COOKIE["PHPSESSID"] = "a1b2c3d4"; require("path_to_php_script.php");' 

OK, now let me say that you don’t want to access someone else's session, but you just want to execute the script as if you already had a session. Just run the previous command, but enter any session you want. And your session will remain intact between script calls if you use the same PHPSESSID every time you call the script.

+9
source

There are no cookies in the CLI, so ... yes.

You can pass the session name as an argument or environment variable, and then use session_name() to set it to your script.

+2
source

You should try the following:

 exec('php -r \'$_COOKIE["'.session_name().'"]="'.$_COOKIE[session_name()].'";include("file_path.php");\''); 

Then on the script do the following:

 session_start(); @session_decode(@file_get_contents(session_save_path().'/sess_'.$_COOKIE[session_name()])); 

And now you have your session ready to use!

Remember that the session_save_path() function will get the default path set in the .ini files.

You can always use a custom path to load a session.

0
source

All Articles