I have a scenario like this:
UserJoe has session_id abc123 abc123 is stored in UserJoe's row in the users table in the DB.
UserJoe calls AdminBob and reports a problem.
AdminBob needs to experience UserJoe's problem first hand
So, I'd like to do something like:
01| $sessionId = getSessionId("UserJoe");
02| changeToExistingSession($sessionId);
03| if($_SESSION["name"] == "UserJoe") echo "successfully changed users";
Line 02 is where I'm kinda stuck... Any ideas?
(preferably not using session_save_path() anywhere :P)
EDIT: And it's just for the duration of the page execution. I'd like to keep AdminBob's session cookie intact.
If you store UserJoe's session ID in a database together with the report, then I think you can use session_id() to set AdminBob's session ID to UserJoe's session id.
<?php
if(!isset($_GET["id"]))
{
session_start();
$_SESSION["foobar"] = $_GET["bar"];
echo "Setting...";
var_dump($_SESSION);
var_dump($_COOKIE);
}
else
{
session_id($_GET["id"]);
var_dump($_GET["id"]);
var_dump($_COOKIE);
session_start();
var_dump($_SESSION);
}
?>
To test: Open this page in one browser and set bar to anything.
index.php?bar=blahblahblah
Open a new browser and visit the same page but do not set bar, get the value of PHPSESSID and set it as id's value
index.php?id=[value of PHPSESSID]
You should see the other browser's session in the newly opened browser
Related
I am working on a simple PHP web-application. And in that I want to get Id of user from the mysql database.
For that I have used session to store userID as soon as user in inserted in database:
session_start();
$_SESSION['customer_id']=mysqli_insert_id($con);
But it always says that undefined index customer_id on other pages.It is working fine on localhost but not on live server.
As per the documentation: mysqli_insert_id Returns the auto generated id used in the latest query. If you don't run an insert query before starting session, then mysqli_insert_id will not return what you're looking for.
Rather, try searching for the user with information obtained upon user login, like the user's email address or username.
E.g.
SELECT id FROM users WHERE users.username = userSuppliedEmail
It goes without saying that you should use prepared statements or some similar technology for this query.
It looks like something is preventing you from creating a session.
Before you do anything, where you declare session_start, do the following:
Instead of session_start() put:
$started = session_start();
echo "Session Started: " . ($started ? "YES" : "NO");
If PHP says the session is indeed started, make sure the session id is staying the same between requests. You can obtain the session id with:
echo session_id();
From request to request, the session id must be the same, unless it's expired, or deleted. If you get a session id on first page, but no session id on second page, then either session_start wasn't executed, or the session was not created.
Since you assured me session_start is executed, the next thing you need to do is verify that the session is indeed created, and written to a file on the server.
After you obtain the session id, (eg. 7815696ecbf1c96e6894b779456d330e) you should check your sessions folder for a file named 7815696ecbf1c96e6894b779456d330e (this is just an example, your file name will be different).
$sessionPath = ini_get('session.save_path'); // obtains the path to session
echo "Our session path is: $sessionPath <br/>";
$filesInSessionFolder = scandir($sessionPath); // obtain all files in session folder
if($filesInSessionFolder == false){
echo "Could not access session folder<br/>";
}else{
// display all files in the folder
print_r($filesInSessionFolder);
}
Now make sure that the session id exists in the list.
I got a problem, I will explain myself with a representative escenario:
I have two php scripts/pages:
Test1.php:
<?php
include_once('test2.php');
session_start();
$id = session_id();
echo "my session id: " .$id.'<br>';
setcookie("SSID", $id);
test();
?>
Test2.php:
<?php
function test() {
echo "session id on test2 <br>";
echo $_COOKIE["SSID"];
}
?>
This is a representative piece of code of my problem, what I am trying to do is to store my session id in a cookie and retrieve it in the second page to resume my session. I know that this is not necessary. In my test server I dont need to do this, but in the production one this is necessari. I can't change any configuration of the production server so I have to adapt the code to the server's configuration.
My main problem here is that the second script gets the session id stored in the cookie the last time. An example:
1st time executing test1.php I get:
my session id: dg2mjk8ros8ajrj3n6i8oa4gj1
session id on test2
vrulbnvvff23bpmm6qbbqbk960
2nd time executing test1.php:
my session id: cj17k0q08mhgpjn9gf0dt0n9i6
session id on test2
dg2mjk8ros8ajrj3n6i8oa4gj1
as you can see the cookie value retrieved in the test2.php function is the last used, not the current. I'm stuck.
I would appreciate any help, thanks.
Something is wrong with your code or most likely your server setup. You session_id shouldn't change, for some reason your web server is generating a new session every page load. This shouldn't happen it defeats the purpose of even having a session. Is there any other code running or is this it?
The reason your cookie is always the same as the previous value is because the $_COOKIE array is populated before your php code runs, it isn't changed if you create a new cookie in your code.
I tried this same code on my setup and I get the same session_id and same cookie value each time.
I would try to fix your server setup issue but if you can't you can force the session id to be consistent. Do this:
if(isset($_COOKIE['SSID']) {
session_start($_COOKIE['SSID']);
} else {
session_start();
}
Also if the cookie already exists you don't need to create a new one:
if(!isset($_COOKIE['SSID']) {
setcookie("SSID", $id);
}
I finally solved this using only session storage but not before changing some parameters in the production server, I dont know which one, sorry.
I really appreciate all your help.
Newbie question, but I'm wondering if I'm missing something elementary here.
If I register a session variable in a page - isn't this variable supposed to be accessible from another page on the same site?
First, I register a variable in the file session_var_register.php:
<?php
$_SESSION["myusername"] = 'user';
if (isset($_SESSION['myusername'])) {
echo 'Session var myusername is set to '.$_SESSION['myusername'];
}
?>
When I open this page, it writes:
Session var myusername is set to user
As expected.
Then I open another tab and another page, check_session_var.php:
<?php
if (isset($_SESSION['myusername'])) {
echo 'Session var myusername is set to '.$_SESSION['myusername'];
}
?>
This page is blank.
Isn't the point of a session variable that it should be accessible in the browser session, until the session is programatically destroyed or the browser closed?
I'm using IE 8 and Firefox 24, btw. Identical results.
You forgot
session_start()
On top, before using
$_SESSION
PS: Remember to call session_start() in every page you want to use $_SESSION.
The PHP docs state that you must call session_start() to start or resume a PHP session. This must be done before you try to access or use session variables. Read more here.
session_start();
Your session variables will be available on different pages of the same site but on top of each of these pages you must have at least:
session_start();
It works but not in all cases. You must also use the same session name (essentially a cookie name that stores id of your session) on all pages. Moreover cookies (which are essential (mostly) for sessions to work) may be made visible only in specific directory. So if for example you share the same host with other guys that use sessions too you do not want to see their variables and vice versa so you may want to have sth like that:
1) session_name( 'my_session_id' );
2) session_set_cookie_params( 0, '/my_dir', $_SERVER['HTTP_HOST'], false, true );
3) session_start();
You may also want to see your session variables on other servers and in such case custom session handlers may be useful. Take a day or two to implement yourself - great way to understand how sessions work hence I recommend.
Method
session_start();
Description
session_start() creates a session or resumes the current one based on a session identifier >passed via a GET or POST request, or passed via a cookie.
Usage in your case (and in the most of cases):
Put it before the $_SESSION usage.
Reference: session_start()
First Of all start session on that page
session_start();
your page like this way
<?php
session_start();
if (isset($_SESSION['myusername'])) {
echo 'Session var myusername is set to '.$_SESSION['myusername'];
}
?>
I installed a pre-built forum on my website and I want (in a diffrent page) to check if the forum's session is active.
Something like :
if (isset($_SESSION['forum'])) { echo "Session is active!"; }
Problem is - I don't know the sessions name...
Tried downloading some chrome add-ons for session managing but I can't get the name of the session.
Whats the right way of doing this?
Thanks ahead!
You can see the dump of $_SESSION variable
var_dump($_SESSION);
session_name() will give you the session name, that usually is defined in php.ini. By default it is always: PHPSESSID. This name is used as cookie name or as POST/GET variable name.
session_id() will give you the identifier for the current session. It will be the contents of the cookie or POST/GET variable.
Then you have $_SESSION that will contain all your session data. use print_r() to see what you have stored in it so far.
To know if session vars are set you can also just do if(isset($_SESSION)&&count($_SESSION))
try
print_r ($_SESSION);
taht way you'll see all sessions
<?php
session_start();
print_r($_SESSION);
?>
Use this to see which session variables are currently set.
You need to check that the session is currently active, and then that the forum key is defined
if ( ! ($sid = session_id()) {
session_start(); // open session if not yet opened
$sid = session_id(); // get sid as session ID
}
// $sid contains the session ID (in cookie)
if (isset($_SESSION['forum'])) {
// forum is defined
}
See also the answer from this page
I have this query in mysql in a php page:
mysql_query("INSERT INTO tz_todo SET text='".$text."',
position = ".$position.",
user_id=".$_SESSION['user_id'].",
view_stat=0");
I tried to echo the query and the result is this:
INSERT INTO tz_todo SET text='trial text', position = 21, user_id=, view_stat=0
it seems that it can't get the session value of user_id.
And $_SESSION['user_id'] is not working in social engine. How to correct this? I also made a localhost version in my xampp and everything is fine but when I converted it into social engine, session is not working.
In any page where you are using session objects, place this code at the beginning of the file:
if(!isset($_SESSION)){session_start();}
This way if the session is not already started, it starts it; otherwise it ignores the session start if the sesion is already started.
This is important because calling session_start() if session is started already can sometimes cause errors.
That's how I get my user id through session
session_start();
$userID = $viewer->getIdentity();
$_SESSION['user_id'] = $userID;
echo $_SESSION['user_id'];
Using session to store the user_id is totally wrong. To gain a user_id try
$viewer_id = Engine_Api::_()->user()->getViewer()->getIdentity(); (or $user->getIdentity if you have another user's object).
If you still need to use session for storing this data, use Zend-approach.
session_start();
$_SESSION["test"] = "hello world";
session_start();
echo $_SESSION["test"];
does above code work ? if not, check your session.save_path in the php.ini
NOTE: to retain this variable remember to call session_start() on each php script/page before calling for the variable from the session.
Yoy might be forget to start your session at the top of the page
<?php if(!isset($_SESSION)){ session_start(); } ?>
$_SESSION['user_id'] might not stored a value. check your login page (Basically after login session variables will set) or after register weather you assigned a value to that session variable..
setting a value to a session variable :
$_SESSION['user_id'] = "1234567";