I have a page where, after a user logs in, the session starts and there is a welcome message with the User's Name - like so:
<h2>Welcome, <?php echo $_SESSION["User"]; ?>, to the site!</h2>
Or something along those lines - haven't decided, yet.
But the problem is, is that it doesn't show up.
I have the code that authenticates the user and all that, and that portion works.
They authenticate and they have a session - it DOES exist (if not, the page would redirect them to the login or the error page depending on how many tries).
When they authenticate, the form posts to a "login.php" where all the other code happens, including this:
if (isset($_POST['submit']) && ($allowEntry == yes))
{
session_start();
session_register ("Logged_In");
session_register("User");
$_SESSION["Logged_In"] = 'true';
$_SESSION["User"] = $user;
if ($_SESSION["User"]=='SOMEUSER')
{
header( 'Location: /somepage.php' );
exit;
}
elseif ($_SESSION["User"]=='SOMEOTHERUSER')
{
header( 'Location: /someOtherPage.php' );
exit;
}
}
So, does anyone know how to make that text appear in the "" element above?
I'm not sure I completely understand the question, but I gather that you're setting the session in one script and trying to obtain a value from it in another? If so, it's most likely because you haven't called session_start() in the second. Note from the docs
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.
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.
Found a major problem on my website. I found tha if I login with user A. it sometimes kinda does log in but actually doesn't. Then I login with user B -> enter the site. I log out and then go manually back to url where login is needed and it somehow goes in with user A. It seems that I have two (maybe could have more) session_id cookies on different tabs or there is a ghost session_id that comes active I don't know. Pulling my hairs here.
Also found that, lets say I have a user dashboard and test page. With a little going back and forth with different credentials. I get this result:
Dashboard echoes user A's id, test echoes user B's id or not id at all. What the heck I am doing wrong with my sessions?
Login is done with AJAX. Login validation is the same on every page.
COMMON FUNCTIONS:
function validateUser($userid) {
session_regenerate_id();
$_SESSION['valid'] = 1;
$_SESSION['usersid'] = $userid;
}
function isLoggedIn() {
if (isset($_SESSION['valid']) && $_SESSION['valid'] == 1) {
return true;
} else {
return false;
}
}
function logout() {
$_SESSION = array();
session_unset();
session_destroy();
}
LOGIN/DB:
Login page:
session_start();
include 'include_files.php';
if(isLoggedIn()){
header('Location:loginrequiredpage.php');
die();
}
Login page sends username/password with AJAX to an controller php file that uses db functions as included file. It executes usercheckfunc() which checks user from db and then echoes succes or fail back to ajax.
from db functions - part of user check function
//if user found from db and password hash match
validateUser(**ID FROM DATABASE**);
Back in login page if ajax gets success message back, JS send user to login required url.
Here's where mystery sometimes occur The browser acts like if i just logged in somewhere, but the login page is loaded again. Sometimes I can manually go to login required page via address bar. Sometimes if I logout/idle too long etc. and login with different username/password I get in as a wrong user. Entered as user A, See user B's data OR echo different userids on pages or echo id only on other page.
LOGIN REQUIRED PAGE:
<?php
session_start();
require_once 'include_files.php';
if (!isLoggedIn()) {
logout();
header('Location:login.php');
die();
}
echo $_SESSION['usersid'];
Test page:
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once 'include_files.php';
if (!isLoggedIn()) {
logout();
header('Location:login.php');
die();
}
echo $_SESSION['usersid'];
Is there a "best" way to manage sessions? Help is much appreciated :)
Got rid of the problem by manually setting session cookie parameters everywhere before session_start is executed. Now the session cookie domain doesn't behave unexpectedly. Sorry, no idea why it did that mysterious changeing before.
This cookie parameters sets it to be valid on whole domain. I guess it's no good in situation where you need different sessions on the same domain (different applications etc.). But for me it was the healing patch I needed.
session_set_cookie_params(0, '/', '.example.com');
session_start();
I created a login page in php named as index.php. Now when the user logs in it redirects to mypage.php. The login works fine. But also mypage.php gets open when I type the url of mypage.php even without login. I want the user must logged in to see mypage.php and incase if he changes the url in browser then an error message should be triggered. What to do?
1.localhost/index.php
2.localhost/mypage.php
In index.php, once the user gets logged in successfully, set an session. like $_SESSION['login'] = true; before redirect. If invalid login, use $_SESSION['login'] = false; Don't forget to start the session on the top of the page. session_start();
In mypage.php, check if that session is set or not. If not set, throw error, else show the page.
session_start();
if(isset($_SESSION['login']) && $_SESSION['login'] == true) {
echo 'You are welcome';
} else {
echo 'redirecting to login page';
header('Location: index.php');
exit;
}
How are you storing the state of being 'logged in'?
You'll need to have your mypage.php check a variable that has been set by the index.php's successful login process.
Can you paste your code here and I can take a look
In order for a login to work correctly, your "secure" page (I use that term relatively because nothing is truly secure) needs to have some sort of validation conditional. In other words you need to have some way of determining if the user is logged in.
A simple way to do this in PHP is to set a session variable when you process the user's credentials. For example:
When the user successfully logs in set a session variable like so:
$_SESSION['isLoggedIn'] = true;
Then on the mypage.php check to see if the variable is set:
if(!isset($_SESSION['isLoggedIn']) || $_SESSION['isLoggedIn'] != true) {
header("Location: index.php");
exit;
}
Please also note, it is imperative if you are using sessions that you have session_start(); as the first line of all of your files. This allows $_SESSION variables that were set on a separate page to be able to be read on the current page.
Hope this helps.
I need to create a session on index page
if user already login in, it will header to member page.
if user destroy session, it will stay at index(login page)
what i did is
if(session_start){
header("location:member.php") or die();
}
if(isset($_POST['email']) && isset($_POST['password'])){
$email=strtolower($_POST['email']);
$password=md5($_POST['password']);
if($email && $password){
$connect=mysql_connect("localhost", "root", "");
$database=mysql_select_db("phplogin", $connect);
$SQL=mysql_query("SELECT * FROM users WHERE email='$email'");
$numrows=mysql_num_rows($SQL);
if($numrows!=0){
while($result=mysql_fetch_assoc($SQL)){
$db_email=$result['email'];
$db_password=$result['password'];
$db_firstname=$result['firstname'];
$db_lastname=$result['lastname'];
}
}
else{
die("Can't find the user");
}
if($email==$db_email && $password==$db_password){
session_start();
$_SESSION['firstname']=$db_firstname;
$_SESSION['lastname']=$db_lastname;
header("location:member.php");
}
else{
die("wrong username or password");
}
}
else{die("Please enter email or password");}
}
This works when user haven't destroy session, but when user destroy session
it didn't stay at index page
I need something like facebook, yet I don't know how facebook can share same the domain name on login page and user page.
so everytime i type facebook.com i will go to my user page, if i logout, it will become login page
You have used if(session_start). session_start() is a function. And it is used on each and every page. So it will redirect you everytime.
Another thing, you need to session_start() on the page you are storing the session and the page you are getting session values.
Instead of:
if(session_start){
header("location:member.php") or die();
}
Use:
session_start();
if(isset($_SESSION['firstname']) && isset($_SESSION['lastname'])){
header('location:member.php');
}
//and REMOVE session_start(); from where you have written.
How about on top of your page
if(!isset($_SESSION['firstname']) || !isset($_SESSION['lastname'])){
header("location:index.php") or die();
}
First of all; only checking if a session exists isn't enough if you want to check if your user is logged in (the session could exist all the same, even if the user isn't logged in). So you should write a is_logged_in() function (or something like that) first to properly check the logged in status.
The reason why your user is always redirected is because the function session_start() returns true if a session is started succesfully; if the session is destroyed, it just starts a new one. So basically it will return true pretty much always, if everything works correctly (like user has not turned cookies off etc.).
If you have written that function it's actually quite simple. Let's pretend you have two files: home.php and member.php. The first one is your homepage (with a "Hello visitor!" message and the login form), the second is the member page. If both files are 'standalone' scripts you can indeed header the user to the specific page (header('Location: home.php'); if user should login first, header('Location: member.php'); if user is already logged in).
But! If you want to 'cloak' the pages (pretty much like facebook does it), you can just include the files in your index.php. Do something like this:
if(is_logged_in()) {
require_once('member.php'); // present member profile page
} else {
require_once('home.php'); // present login page
}
In your index.php you can set a constant (see also the php manual about constants) to be sure the files can only be included from within index.php:
--- index.php:
define('VALID_INCLUDE', true);
// the rest of your code
--- home.php & member.php:
if(!defined('VALID_INCLUDE')) die('You should not request this page directly');
But please note that if you want to write applications like this, a framework could help you a lot; it covers a lot if this kind of problems and makes coding a lot faster (most frameworks come with a authentication modules of some sort, and allow you to use 'views' to present your user with the proper pages, like I have done above with the require_once solution).
Guys in my php project i want to check on Login page session's status..if its unset i want user to login.
ihave added this code to login page but it doesn't help as it loops.
if (strlen(session_id()) < 1) {
?>
<script>window.location.href="login.php";</script>
<?php
}
elseif(strlen(session_id()) > 1){
?>
<script>window.location.href="index.php";</script>
<?php
}
Now other thing I want is if session is already started and if user manually tries to go on login page from address bar he should be redirected back to that current page.
If he is not logged in he should be redirected back to login page if he tries to open directly any page.
Also a new doubt with this is
Guys i m using wamp server to run my PHP projects.I have used PHP sessions in my projects,Now when a user logins from one project the sessions get set and if on same pc if user open some other project which are not linked to each other he gets directly logged in without even doing it, if he logouts from one project he gets logout from all other project running on that pc.
Try this:
<?php
session_start();
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in'] == 1) {
//session is set
header('Location: /index.php');
} else if(!isset($_SESSION['logged_in']) || (isset($_SESION['logged_in']) && $_SESSION['logged_in'] == 0)){
//session is not set
header('Location: /login.php');
}
?>
In reply to above comments, yes you should create a session variable when the user is logged in. Edited code to reflect it.
you want to be checking for a particular session value, not the existence of a session ..
if ($_SESSION['logged_in']==1){
//
}else{
//
}
set $_SESSION['logged_in'] to 1 on log in and unset it (or set it to 0) on logout
Remember to include session_start(); on the top of every page to get the values of variable SET in the SESSION through $_SESSION['example'], otherwise You will not be able to the session Variable values ,
OR
A different Approach is to use session_start(); inside config.php file and include that file on the top of the code of every page where sessions are required otherwise U will not be able to get the value of SESSION variable..!!