I have php application in that, when user login to application then session started. In session i have stored user type and id. Using user type restrict the access of user pages like add.php, display.php, edit.php etc.
My problem is that the when user login to application that user type and id will be stored in session but when any user change in url like add.php. this page will be accessed by other user.
I want to do when user changes url then say some error message.
<?php
session_start();
if(!isset($_SESSION['username']) || !isset($_SESSION['login_type']) )
{
header("Location:logout.php");
exit;
}
?>
DO NOT just use isset. That will only check whether the variable exists or not and it wont check what value that variable contains
So, you can include something like this in the function
if(!isset($_SESSION['username']) && $_SESSION['login_type'] != 'Admin') )
{
header("Location:logout.php"); //Do not allow him to access.
exit;
}
First of all, when you will be creating a session create session variables that will be having logintype like user,admin,superadmin
And then create a general function to check the session. like
checkSession();
Put this function in a file which you will include it
This function should be able to verify whether the user is authorized or not at the top, before even the file is processed and displayed.
Related
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');
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..!!
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?)
How can I prevent a user from accessing a page when they are not logged in? I want him to be redirected to the login page. I know it has something to do with sessions.
It works like this:
Start a session: session_start()
If Session["user"] == null, redirect to the login page, else continue.
In the login page, ask the user for password using a form
Post this form to the login page
Check against your authentication service (e.g. a table in mysql) if the user is authorized
If yes, Session["user"] = $userName, redirect the user to the page. If no, prompt for password again
Of course, this is all very, very simple. In your session, you could keep a complex user object, or anything. Good luck coding.
As Svetlozar Angelov pointed out the following code would work well:
if (!isset($_SESSION['nID']))
header("Location: login.php");
However.. this would not actually secure the page against users who really wanted access. You need to make some adjustments:
if (!isset($_SESSION['nID']))
{
header("Location: login.php");
die();
}
This prevents bots and savy users who know how to ignore browser headers from getting into the page and causing problems. It also allows the page to stop executing the rest of the page and to save resources.
Its also noteworthy that $_SESSION['nID'] can be swapped out for any other variable you are using to store usernames or id's.
When he logs - store a session variable. Then in the beginning of every page
session_start();
if (!isset($_SESSION['nID']))
header("Location: login.php");
If the login is ok
session_start();
$_SESSION['nID'] = 1; //example
Follow these steps:
Create a login.php page accessible to everybody where a user enters her username and password in a form. This form must be submitted to login.php itself. (action='login.php'). Also include a hidden variable in your form which tracks if the form has been submitted.
If the hidden variable is set, check if the username ($_POST['user']) exists in your DB, and that the password matches the username. If it does, store the username in a $_SESSION variable like this:
$_SESSION['username'] = $_POST['user'];
If it does not, reload login.php like this:
echo 'header("login.php")'; //You should not have echoed anything before this
Now include login.php in every user page you create. Suppose you were writing an email application, create an inbox.php like this
include ("login.php")
Now, login.php will check if the session variable 'user' is set and allow access to authorised users only.