After trawling through other posts, I could not find the answer.
The problem is that when i create a custom session name, I am not able to access session variables on any other pages. How can I get this working with custom session variable?
Scenario A
Login page
after successful login, the following is called
function initiatenewsession($app, $userid){
$session_name = getuniquesessionid($app,$userid); // Set a custom session name
session_name($session_name);
session_start();
session_regenerate_id(true);
$_SESSION["loggeduserid"] = $user_id;
echo("1a)SESSION NAME[".session_name()."]");
echo("1b)logged user[".$_SESSION["loggeduserid"]."]");
}
Echo result
1a) SESSION NAME[myappsessionid6520150528184534]
1b) logged user[65]
Registration page (User clicks a link after logging in)
session_start();
echo("2a)SESSION NAME[".session_name()."]");
echo("2b)logged user[".$_SESSION["loggeduserid"]."]");
2a)SESSION NAME[PHPSESSID]
2b)logged user[]
Scenario B
Login page
after successful login, the following is called
function initiatenewsession($app, $userid){
session_start();
session_regenerate_id(true);
$_SESSION["loggeduserid"] = $user_id;
echo("1a)SESSION NAME[".session_name()."]");
echo("1b)logged user[".$_SESSION["loggeduserid"]."]");
}
Echo result
1a) SESSION NAME[PHPSESSID]
1b) logged user[65]
Registration page (User clicks a link after logging in)
session_start();
echo("2a)SESSION NAME[".session_name()."]");
echo("2b)logged user[".$_SESSION["loggeduserid"]."]");
2a)SESSION NAME[PHPSESSID]
2b)logged user[65]
As per my comment, when you do session_start(), php will check if you set a session name via session_name(), otherwise it'll use its default.
Session startup is basically like this, in php-ish pseudocode:
if (custom_session_name_was_set()) {
$session_name = get_custom_session_name();
} else {
$session_name = ini_get('session.name');
}
if (isset($_COOKIE[$session_name])) {
$id = $_COOKIE[$session_name];
} else {
$id = generate_new_random_id();
setcookie($session_name, $id);
}
$session_data = file_get_contents('/path/to/session/files/' . $id);
$_SESSION = unserialize($session_data);
For your first bit of code, you set a custom name, so that's the name that's used for the session cookie.
In your other code, you do NOT set a custom name, so php uses its default: PHPSESSID. Now you've got two sessions floating around, each with their own unique names, and their own different IDs, and their own separate data in $_SESSION.
If you're going to be using custom session names, you have do session_name($customName) EVERYWHERE you have session_start().
If using a custom session name you must call session_name().
You must call session_start() before headers_sent().
On servers with multiple PHP version support check phpversion() to ensure that the server did not decide to run the wrong version (and hence the wrong session_save_path()).
Related
I want to access $_SESSION['roleid'] in master.php. master.php is included in every page. I'm only able to access $_SESSION['roleid'] in dashboard.php after user login. How to access $_SESSION['roleid'] in every page.
<?php
session_start();
if($_SESSION['login']==1) {
$_SESSION['loggedIn'] = true;
$role_id1 = $_GET['role_id'];
// store here in session
$name=$_GET['name'];
$_SESSION['roleid'] = $role_id1;
// $role_id=$_SESSION['roleid'];
$a=$_SESSION['roleid'];
// echo $a;die;
if(isset($_SESSION["roleid"])){
header("location:api/dashboard.php?role_id=$a?name=$name");
}
} else {
header("location:index.php");
echo "login unsuccessful.";
}
?>
To be able to access the session variables you need to call session_start(); on top of every page that will use the session variable. After the start call has been made you can use session variables like this echo $_SESSION["my_var"]; and this to set the content $_SESSION["my_var"] = "Var content";, if you are unsure what the session actually belongs it is possible to check the content of the session by doing var_dump($_SESSION);. This will show all the data the session contains since it is passed as an array.
Please do remember that a session is not recursive through subdomains because of the cookie that is being used to track which session belongs to who. A session is also dependent on that headers are not sent yet since it needs to interact with the cookies.
To delay sending of headers do this:
1. Call ob_start(); at the completely top of the scripts that needs to set multiple headers
2. Do the things you need to do like set headers and so on
3. Call ob_end_flush(); to send the headers.
Here is the offical PHP docs on this:
https://www.php.net/manual/en/function.ob-start.php
https://www.php.net/manual/en/function.ob-end-flush.php
you should check $_SESSION['roleid']:
* if having $_SESSION['roleid'], you will get it. On that code, you store $_GET['role_id'] to $_SESSION['roleid'] but $_GET['role_id'] have no in all page, it's only in dashboard.
I think that. You should try.
I am storing data into database,with customer id.The insertion will be done only if the customer is logged in.if the user moves to any other page and comes back to same page the customer id disappears .so i need to include customer id in every page and how do i do it.the login page must be in last part.
Once the authentication (ex. login with a mail & password) finishes and successful, you can store the user id in the session Global Variable like this: $_SESSION['user'] = $id
And as long as the session is alive, you can retrieve this id from this Super Variable on any page: $user_id = $_SESSION['user']
Make sure to use session_start() before using the session global variable. Like:
<?php
// index.php
session_start();
echo $_SESSION['user'];
If you're not using front controller pattern then you have to use this function on every page before using $_SESSION.
You must start the session using session_start() in every page at the top. refer from below link.
https://www.w3schools.com/php/php_sessions.asp
I've created a login which sets a session variable to the users id which I get from my database. After the user clicks login after entering their details I redirect them to the home page which uses the session variable to get the users id for display purposes. The problem I am having is with the session variable. This is what my code looks like (simplified):
$_SESSION['user_id'] = $User_id;
header('Location: http://localhost/Projects/Login/home.php');
exit();
This is the snippet of code which sets my session variable, I have tested an it works. The next snippet of code is the function which is called from the home page (home.php). It is used to check if the user is logged in or not
function logged_in(){
return isset($_SESSION['user_id']);
}
I then use this if statement to perform different displays based on whether the user is logged in or not, again it has been simplified.
if( logged_in() === true ){
$session_user_id = $_SESSION['user'];
print "logged in";
}
else{
print "not logged in";
}
The problem seems to be with the if statement as it unsets the session variable to an empty array. If I print out the session variable I get Array(). I have started a session on each of the pages.
There seem to be two issues here.
First is the array keys; you're using user in one case and user_id in the other.
The second is speculative; you said it results in an empty array (I assume you have var_dump($_SESSION) or similar to confirm this?). If so it suggests you haven't started the session. You need to call session_start(); to get access to the session data.
Each time your script runs it needs to get access to the sessions stored on the server, this is why you run session_start(). The long version is that it obtains a lock on the local file which stores the session data (leading to whats known as session locking). As a result you may (for longer running scripts and/or performance) wish to call session_write_close() when you're finished with the $_SESSION superglobal.
So I got an ini.php file which I included on top of every file. It includes my database connection + session_start().
When the login of the user is succesful then I set a session which equals $_SESSION['login'] = true.
Now I can do stuff like this:
if (!isset($_SESSION['login'])) {
include 'php/includes/login_form.php';
}
else {
include 'php/includes/welcome.php';
}
What if I wanted this specific login to be specific to the user? Do I have to link the session somehow with the username on login?
A session is always unique to one visitor. session_start generates a random session id, which it puts in a cookie, which only your current visitor will receive. On the next request, that cookie with the unique session id is picked up on by session_start and the session is resumed.
However, this by itself won't tell you which of your user accounts specifically the session belongs to. You'll have to record that information yourself. E.g.:
if (/* login successful */) {
session_start();
$_SESSION['user_id'] = $loggedInUserId;
}
i have this code:
$username = $_POST["username"];
$password = $_POST["password"];
if(mysql_num_rows($result80)>0)
{
$row80 = mysql_fetch_assoc($result80);
$_SESSION["loginmng"] = 1;
$_SESSION["username"] = $username;
$_SESSION["password"] = $password;
$fname = $row80["fname"];
$lname = $row80["lname"];
$userid = $row80["id"];
}
and every thing is ok because i tryed to echo the session and its work in the same page (index.php)
now i have this check:
if(($_SESSION["loginmng"]!=1)||(!isset($_SESSION["username"]))||(!isset($_SESSION["password"])))
{
header("Location: index.php");
}
when i put this into new folder:
newfolder/index.php
the check is not working right,when i have logged in , and the session is set....when i am tring to echo $_SESSION["loginmng"] and the other sessions,,its values is empty like no session setted and the header is got run ...and go to index...i have put session_start(); in the first php line too
i tryed too:
if($_SESSION["loginmng"]!=1)
{
header("Location: ../index.php");
}
and the same thing...like no session set, what may be the problem
A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.
PHP Session Variables
When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.
A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.
Starting a PHP Session
Before you can store user information in your PHP session, you must first start up the session.
Note: The session_start() function must appear BEFORE the <html> tag.
Maybe you forgot to add session_start(); on top of the file.
To make session start on each page you need to start the session on each page.
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.