I need to read some values from cookie or session when I am executing my php script using command prompt. How can I do that?
How to access cookie or session value from Windows command prompt?
I need to read some values from cookie or session when I am executing my php script using command prompt. How can I do that?
How to access cookie or session value from Windows command prompt?
Cookies are sent from the user's web browser. When you execute a php script from the command line, there is no browser to send or receive cookies. There is no way to access or save cookies and nothing is sent to the script except the parameters you pass on the command line.
That being said, there is a way to read a session that someone with a browser has already accessed if you know their PHPSESSID cookie.
Let's say someone has accessed your script with a web browser and their PHPSESSID is a1b2c3d4, and you want to execute the script with their session. Execute the following at the command line.
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 actually, you shouldn't have to start the session if the php file you want to execute starts the session itself. So, you may want to actually try this command:
php -r '$_COOKIE["PHPSESSID"] = "a1b2c3d4"; require("path_to_php_script.php");'
OK, now let's say you don't want to access someone's session, but you just want to execute the script as if you already had a session. Just execute the previous command, but put in any sessionid you want. And your session will remain intact between calls to the script as long as you use the same PHPSESSID every time you call the script.
There are no cookies in the CLI, so... yeah.
You can pass the desired session name as an argument or environment variable and then use session_name()
to set it in your script.
You should try this:
exec('php -r \'$_COOKIE["'.session_name().'"]="'.$_COOKIE[session_name()].'";include("file_path.php");\'');
Then on your script, do this:
session_start();
@session_decode(@file_get_contents(session_save_path().'/sess_'.$_COOKIE[session_name()]));
And now you have your session ready to be used!
Remember that the function session_save_path()
will get the "default" path, set in .ini files.
You can always use a custom path to load the session.
$_SESSION
content back to disk when the script finishes. Aktually all he needs is set the session ID, then call session_start()
. At least under Xampp (Windows), I got this working smoothly. However, all my attempts under Linux failed. I didn't put enough time in to know why. Another thing to keep in mind is that the browser user with that session might be waiting while the session is locked by CLI. –
Threw © 2022 - 2024 — McMap. All rights reserved.