How Check current PHP session set or unset - php

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..!!

Related

PHP- How can I restrict access to a page?

I have multiple pages that needs to be protected depending on the user privilege. I have a php to check the current session variable upon page load.
page being tested; the php code is placed above the !DOCTYPE. this code is suppose to check for unlogged in customers. if not logged in or no session variable set redirect to error page otherwise do nothing and load page normally
<?php
if (!isset($_SESSION["username"])){
header("location: error.php");
}
?>
my session variables are only set after logging in, after logging in the user is redirected to the page referred to above:
if (mysqli_num_rows($results6) < 1) { //$results6 is a query to check if the user exits in the users database
$logInMsg = "invalid log in";
} else {
session_start();
$_SESSION["username"] = $uName; //$uName is a user input user name
header("location: pageabove.php");
}
the problem is that even after logging in I still get redirected to the error page
That would be because you haven't started the session yet. You need to specify a session start on each page that you intend to use sessions in (Read more about session_start()):
<?php
session_start(); // start session
// do check
if (!isset($_SESSION["username"])) {
header("location: error.php");
exit; // prevent further execution, should there be more code that follows
}
This is for everything. On your login page and all. Anywhere you want to harness the sessions, you need to start it, otherwise it's "lost in the wind".

Prevent direct access to a webpage by typing the URL

So I'm hosting my website (let's call is abc.com) on goDaddy.
I have a login page (abc.com/login.html).
Which takes me to a second page called booking (abc.com/booking.html) once the login credentials are verified.
So I don't want people to be able to just type abc.com/booking.html and access it. I want them to go to abc.com/login.html and then go to abc.com/booking.html
So I came across 2 ways to fix this -
Include a validating php script in booking.html and changing the extension from html to phtml. -> This didn't work for me
Include a .htacess file. -> I'm not really sure how to do that
so your login screen should already have session code implemented into it that has a variable that specifies if the user is logged in or not. If you don't have that implemented yet, the code would look similar to:
<?php session_start();//at the very top of the page
?>
//... your own code
//if the user successfully logs in then:
$_SESSION['authenticated']=true;
Then on the booking.php page (it should be php to allow php scripts which is super important for validating if a user is logged in), you would then check if the user did log in. If he did, the rest of the page loads, if he didn't, you would redirect them to login.php:
at the very top of booking.php:
<?php session_start();
if (!isset($_SESSION['authenticated']))
{
//if the value was not set, you redirect the user to your login page
header('Location https://www.example.com/login.php');
exit;
}
else
{
//if the user did login, then you load the page normally
}
Use $_SESSION or
Pass a variable from login.php to booking.php. And then authenticate every user based on the variable passed using the $_POST method.
eg.
if (!isset($_POST['auth'])) {
// redirect user back to login page
} else {
// successful login
}
You can do it like
rename extensions of all pages where you want this authentification
e.g.
login.html >> login.php
booking.html >> booking.php
booking-suceess.html >> booking-success.php
create one script namely auth.php with following code
<?php
session_start();
if(!isset($_SESSION['username'])){
header("location:login.php");
}
?>
In login.php add session
$_SESSION['username'] = $_POST['username'];
Now you can add auth.php in any php page where you want login compulsory as follow :
include ('auth.php');

Login Page in PHP

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.

PHP Session (Login page and userpage)

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).

Check whether user is logged in or not

I am doing a web-application using PHP for job searching.
I have one query; when user is not logged in and wants to apply for the job given by clicking 'apply' button, he redirects to the login page. If the user is logged in when clicking, he should get directly to the application page. I'm not sure how to implement this.
I'm confused because I'm new to PHP.
Your question is very vague - maybe start with Authentication in PHP
Well, when the user clicks on 'apply' in your application the user is redirected to the login page if he is not logged in(which you can check if user session exists or not), remember when you redirect the page send the url of the current page in parameters to your login page so that when the user logs in he can be redirected back to the previous page and click on apply for that particular job.....
This is how the logic works, if you want the php, mysql explanation it would take some time for you to understand as you yourself conceded you are new to php..
You could store a value in the Session called "Login" and set this when the user logs in. This can also be used to re-direct the user if they haven't been logged in:
<?php
// check that the session variable does exist
// check that the user 'LoggedIn' has been set to 1 (true)
if (!isset($_SESSION['LoggedIn']) && $_SESSION['LoggedIn'] != 1)
{
// redirect to login page for user to authenticate themselves.
// pass page location (with parameters if necessary) to redirect
// the user on successful login.
header("Location: Login.php?redir=ApplyForJob.php?JobID=12345");
}
else
{
// user is logged in
// redirect the user directly to the apply for job page.
header("Location: ApplyForJob.php?JobID=12345");
}
?>
Can you, when the user logs in, assigns a $_Session variable to that user? i.e., after authentication, you set the $_SESSION['user'] variable.
$_SESSION['user']='admin';
So if you want to check whether the user is already log in after that, just use this:
if(isset($_SESSION['user']))
{
// user is login, direct to the job page
}
else
{
// no login, go to the login page
}
On each page set a cookie or session to which page they were just on:
$expire=time()+60*60*24*30;
setcookie("wherewasi","",time() - 1000);
setcookie("wherewasi",$_SERVER['REQUEST_URI'], $expire);
Then after login redirect them:
$loc = ($_COOKIE['wherewasi'])?$_COOKIE['wherewasi']:'index.php';
header("location: ".$loc);
exit();
There are two things that you need to worry about... checking that they've logged in, and then once they've logged in, directing them to the correct page.
This is all about 'saving state' across page requests. To do this you need can use cookies or more usefully sessions (which may be done via cookies or handled by the PHP engine for you automatically).
Sessions are probably a good way to go. To use sessions, every page needs to start with a
<?php session_start(); ?>
at the very least, before any html code that writes to the browser.
Once that's done you can use your the session variable to store
<?php $_SESSION['user']='joe_blow'; ?>
(and check)
<?php
if(isset($_SESSION['user']) && $_SESSION['user']!='' {
// do something
}
?>
whether the user is logged in, and which page they need to be redirected to after login.
<?php header("location: ".$_SESSION['redirect_location']));
But in order to write the any more useful code I think people would need to know what authentication method you were using... (How are you doing your login? Are you storing ID's in a database? Are you using an off-the-shelf package?)

Categories