I'm developing a website, where in most of pages user need to log in to view pages of website. What is the best way to check if user is logged in or not, and if not redirect it to log-in page.
currently I'm using following code to do that.
if(!isset($_SESSION["username"])) //I set the session when user log in and destroy when user logout
header("location: login.php");
There are lot of pages and I put this code in every page. It also works well.
I want to know is there any other batter way to do this? Or what I'm doing is good way? and I don't need to change anything.
Simple Solution is create a file named as session.php
include your session checking code into that. Like,
if(!isset($_SESSION['YOUR_VAR'])) {
header('Location: login.php');
}
include this file into all your pages, with include OR require
I prefer require function. example in your home.php file at the beginning of page write,
<?php
session_start(); //don't forget to do this
require('session.php');
?>
NOTE : In future if you enhance your session checking code you just
have to change one file.
I usually just set a session like this once the user logs in:
$_SESSION['loggedIn'] = TRUE;
Then just check if TRUE or FALSE when needed.
ex:
if($_SESSION['loggedIn']){
//Something here
} else{
//Don't do it
}
It is depend on you architecture. If you are using any framework, like symfony you don't need to handle these for each and every page. I guess you are using pure PHP without any framework support. So you need to check whether the user is authenticated for each and every request by your own. I suggest you to without placing code segment related to logout in every page, just place it in a global function and call it in your every page. So that, if you want any simple change in that code segment, you can achieve it only changing that global function
Related
I'm slowly learning PHP ;-) I'm having difficulties understanding how separate PHP-files work together.
I make AJAX calls to different php files that all need to be connected to the backend (Parse). Such as:
sign_up.php
login.php
verify_email.php
get_something_out_of_the_database.php
What is the standard way to stay logged in over the different php files? (or what is the google search term for it..?)
Update:
Thanks for all your answers about 'sessions'. I doesn't work very well yet, so i made a new question.
Thanks!
Remzo
You should use PHP sessions. These are a way to store information on visitor browser between multiple pages...
To start a session, you first need to add session_start(); in every PHP file you intend to use it. Usually it's added in a header.php
Then, you can use sessions already.
To store a result:
$_SESSION['some_data'] = $var;
To retrieve a result in another page, for example:
echo $_SESSION['some_data']; // will echo $var
More info can be found here:
http://www.w3schools.com/php/php_sessions.asp
You can do this for example by storing the login-data in a session-variable and checking it at the start of every new page.
Example:
You check if login-data is valid. Then
session_start();
$_SESSION["login"] = $loginname;
At the start of another page:
session_start();
if(!isset($_SESSION["login"]) || $_SESSION["login"] != "check_somehow")
{
header("Location: logout.php");
exit;
}
For logging out you can use
session_start();
session_destroy();
On the start of your user logged in, you can do something like
session_start();
$_SESSION['USER'] = <some user info>;
In your other pages you can see if
if(isset($_SESSION['USER'])){
// do something
}
at last on logout
session_destroy();
will kill the session
I'm fairly new to PHP an was wondering how I have to make the user login before they can go to any other page on the website.
For example on www.cyka.us/p/index.php it will redirect them to www.cyka.us/p/login.php
Have you ever used sessions in php? You can use sessions as a marker if a certain user is logged in or not. It can be implemented like this:
$isLogIn = $session('login');
if($isLogIn){
//go to other webpages
}
Search sessions for further information :)
You simply test for it:
if (!user_is_logged_in()) {
http_response_code(403);
include("p/login.php");
exit;
}
… the specifics of the user_is_logged_in function will depend on how you've implemented your login system.
You can do this with sessions concept in php. For every page you need check whether the user is logged in or not and redirect to (login)desired page.
I have a simple script where a user logs in. I am trying to use sessions, so that a user remains logged in on whatever page he browses through the website.
I have these scripts:
index.php - http://pastebin.com/yqLtqPRC
login.php - http://pastebin.com/KcQWjfw1
dbConfig.php - http://pastebin.com/GKyfaJJV
upload.php - http://pastebin.com/iMrz3WB8
functions.php - http://pastebin.com/x44KrmxK
If the user logs in or is logged in, 'You are now logged in, $user' is supposed to be shown, but the default 'You are not logged in.' displays throughout the pages.
No error messages are shown whenever I change page or try to log in.
Latest version of the code can be found here: http://www.mediafire.com/?7n6qo3p4gpkaao4
Can anyone help please?
thanks.
Put the session_start() on the top of the page in each file where you need sessions just after<?php and you should be fine. You need to call this function before any actual html is echo'd on the page.
Read the php session documentation here
Further looking into your code, if you want to limit the user to see other pages only if he's logged in then make a new file called logincheck.php with contents below and include it on the top of each file by require_once("logincheck.php");. In this case don't put the session_start() code again as mentioned above.
<?php
session_start();
if(isset($_SESSION["username"])){
$welcomeMsg = "<p align='right'>Welcome, </p>" .$_SESSION["username"];
}else{
if(basename($_SERVER["PHP_SELF"])=="index.php")
$welcomeMsg = "You are not logged in";
else
header("Location:index.php");//will redirect the user to index page if he has not logged in
}
?>
Now u can use $welcomeMsg and echo it anywhere on page where u want to display the error msg.
Hope that helps answer your query.
form action="?op=login" method="POST" action="login.php"
why are using action twice in form?
action="login.php" is only required.
I didn't see exactly where your problem was, too much code to read, but by looking through 2 files (the first 2) I noticed some stuff that could become a problem:
A Session_id is supposed to identify a user. if you simply put in a boolean (true) I could easily break in your user reserved part of the site by just modifying my HTTP header.
second thing is that you put a redirect on the login.php before you echo something.... guess you wont see anything.... the redirect happens before the echo.
The third thing is that you should definetly hash the passwords you get and store. It is so sad when people get access to databases and have without any work all passwords of all people.
And a last advice: try to put the Session_Start as the first statement in every file... could be that.
I stopped at this point:
redirect('../TASK2PHP/upload.php');
what's that function and what does it do?
Maybe you meant to use http_redirect or header or HttpResponse::redirect ...
Here you go. There were a ton of errors.
http://www.2shared.com/file/A2V_Ztw8/login.html
That should at least get you started. It is also commented along the way. I did not use the functions.php file there was nothing important in there. Also when you use this change your dbConfig file accordingly.
I have edited index.php, login.php and setup working flow of sessions. Follow the code structure for setting up sessions in others file accordingly.
Download following login-form rar file;
https://www.box.com/s/1ie9ilp9jgluvokf6say
you code structure of login methods seems confusing and its always a good idea to echo everything before you redirect otherwise httpresponse complains about it. Moreover my advise is you first turn on error reporting its always a good idea to do development with error reporting enabled. You can do this inside your login.php just place at the beginning of the file.
error_reporting(E_ALL); or set E_ALL to 1
ini_set('display_errors','On');
TL,DR. But here is an article that teaches the general design pattern for this sort of thing. All web sites that use PHP client authentication follow this design.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_2391-PHP-login-logout-and-easy-access-control.html
You can copy and paste the code snippets from the article. If you have any questions about what the code is doing, please post a comment here and I'll try to help explain. ~Ray
Hope this may help :
you can debug if session is empty or not.
session_id() returns the string identifying the current session. If a session hasn't been initialized, it will return an empty string.
if(session_id() == '')
{
// session has NOT been started
session_start();
}
else
{
// session has been started
}
and
check session in php if empty
Make it on index.php file and include your pages if user logged in. and check inside each and every page you including. if user not set then redirect to login page.
example :
index.php
if(isset($_SESSION['UserId'])){
//make simple function to get the username from user ID
$dUserName = getUserName($_SESSION['UserId']);
echo "wellcome".$dUserName;
echo "<href='logout.php'>Logout</a>";
}
else{
echo "<href='login.php'>Logout</a>";
}
if(isset($_GET['page'])){
$includePage = "includes/".$_GET['page'].".php";
}
else{
$includePage = "includes/login.php";
}
if(isset($includePage)){
include($includePage);
}
sample page loading from index
sample.php
if(isset($_SESSION['user']) && $_SESSION['user'] != ''){
//show your page
}
else{
//redirect to login page
echo '<SCRIPT language="JavaScript">window.location="index.php?page=login";</SCRIPT>';
}
I have fixed the files...
The main problem is in login.php in the loginUser function.
Change this line:
$sql = "SELECT * FROM users WHERE Username = '$username' AND Password = '$password'";
To this:
$sql = "SELECT * FROM users WHERE Username = '".$username."' AND Password = '".$password."'";
The problem with the first line is that it is looking for the text '$username' (and '$password' and not the variable $username and $password
As you can see the solution is to close the string before and after the variables reference'
P.S. You would gain tremendously from using a framework such as CodeIgniter to build your site, besides for saving you a lot of time fixing errors like this, it is also much more secure.
Let me know if you need me to upload the fixed files.
I have a web app I am developing for a school project, I am having issues with the logout page. When a user clicks logout it will send them to a logout.php which just looks like this:
<?php include ("includes/check_authorization.php");
// Unset the session and destroy it
session_unset();
session_destroy();
// Redirect to the home page
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=index.php">';
exit;
?>
It is very simple, but it will unset, then destroy the session, and redirect to the index, which is the login page. However when this is run the index immedietley redirects to a user homepage. The check_authorization page included at the top will redirect someone to login if the username and id are not set and matching in the $_SESSION, so this means that it is setting these for me? I am really confused as to how this is happening. I am using CAS for authentication.
EDIT: the check_authorization.php also initializes the session as well as checking those key values
For like this situation I did as follows, this is working for me all the browsers,
#session_unset();
$old_sessid = #session_id();
#session_regenerate_id();
$new_sessid = session_id();
#session_id($old_sessid);
#session_destroy();
Rather than just unsetting the data, try assigning a dummy value to the session, like:
$_SESSION['authKey'] = '!!INVALID!!';
session_unset();
session_destroy();
Even if the session 'revives', the authentication can't possibly succeed anymore because of the "fake" data.
There are some possibilities :
The most simple possibility : did you include the
session_start();
on top the file? before you include a file? I've been there before, and it pissed me off.
The second possibility : try to put
session_regenerate_id();
on the very top of your file (before you declare session_start();). Because in some Server Hosting, their configuration still using "LINUX" style that i can't explain to you here. But, the point is they always using "cache" when you redirect. In other words, you always redirect into your "cached" page when you rediret to another page. See.. it's hard to explain for you here. But just try the session_regenerate_id(); code, maybe it would work.
I never use the "echo" things in doing redirect things. Try :
header("location:index.php");
i don't know if this working or not. I just simply giving you my analysis based of my assumptions.
Hope these helpful. :)
I have a website running in PHP and I have a page (say confirm.php)
And I only want to allow the users who land to confirm.php comes from a page that I specified (e.g. say register.php), may I know is it possible to achieve this?
Regards,
Andy.
You can not rely on the HTTP REFERER because users can manipulate it and browsers can refuse to send it.
The only "secure" way would be to set a session variable on register.php and check if that variable is set on confirm.php. Something like this:
register.php:
session_start();
$_SESSION['valid_user'] = true;
confirm.php:
session_start();
if(!isset($_SESSION['valid_user'])) {
die("You did not come from the page i specified!");
}
However, this will not take into account if the latest page was register.php, BUT that the user have been on register.php.
Because HTTP is stateless, you need to keep track of this at the server level. If you don't have a authenticated user for which you can track all pageviews, this is going to be very hard to implement. How secure do you really need it to be?
Because HTTP is a stateless protocol, you will need to store the state information server-side.
One method is to store a key into the PHP Session Store, then pass it during redirection, then check it again.
register.php
<?php
session_start();
// some other code
$_SESSION['stateKey'] = sha1(time() . mt_rand()); // save a randomly created key
header('Location: confirm.php?key=' . $_SESSION['stateKey']);
?>
confirm.php
<?php
session_start();
if($_SESSION['stateKey'] == $_GET['key']){
// pass, do things here
}
?>
use the: $_SERVER['HTTP_REFERER'], and redirect it using header or some custom function...
Look at $_SERVER['HTTP_REFERREF'] array in you script to detect from wich page this script was invoked
use
$_SERVER['HTTP_REFERER']
more info: here