How do I remember a url in php to serve it to a user after authentication. The idea is the user will request the url but while unauthenticated. In this case, I forward him to the login page, but what's the best practice to save that url so I can serve it to him once authenticated. I thought about saving it in session variables, but not sure about the implementation. Are there best practices for this?
Put it in a hidden field in the form or save it to a session variable.
Example
login.php?l=account.php (where l is the page to go after login).
<form action="action/login.php" method="post">
<input type="hidden" value="<?php echo $_GET['l'] ? $_GET['l'] : 'index.php'; ?>" name="redirect" />
...
</form>
action/login.php
<?php
... do some checking here...
if($loggedin){
redirect($_POST['redirect']);
// redirect() a wrapper function for header("Location: $url");
}else{
redirect('login.php?l='.$_POST['redirect']);
// go back to login page
}
?>
When the user goes to ProtectedPage.php without being authenticated, this should automatically redirect them to LoginView.php (with the previous page's URL attached). They can then proceed to login and the LoginAction.php page will redirect them back to the ProtectedPage.php
ProtectedPage.php
<?php
if (!$authenticated) {
header("Location: /LoginView.php?r=ProtectedPage.php");
}
?>
LoginView.php
<form action="LoginAction.php" method="post">
<input type="hidden" id="r" value="<?php echo $_GET['r'] ?>" />
...
</form>
LoginAction.php
<?php
... Authenticate the user ...
if (!empty($_POST['r'])) { header("Location: {$_POST['r']}"); }
else { header("Location: /"); }
?>
Related
Suppose, I have two pages login.php and index.php. In index.php I have two buttons Login and register.After clicking the buttons ,the user is directed to login.php.
If I want to implement a login functionality using PHP, something related to facebook such that the if a user has logged in before, then it bypasses the index page once the username and password are set and directly lands into the login page. Is $_SESSION a proper way of doing it.
For example:
<?php
session_start();
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Ayu</title>
</head>
<body>
<?php if (isset($_SESSION["user"])) { ?>
<h1>Hi <?php echo $_SESSION["user"]; ?></h1>
Logout
<?php } else { ?>
<h1>Login</h1>
<?php echo (isset($_GET["error"])) ? '<p>You idiot!</p>' : ""; ?>
<form action="new-user.php" method="post">
<div>
<label>
<strong>Username</strong>
<input type="text" name="username" />
</label>
</div>
<div>
<label>
<strong>Password</strong>
<input type="password" name="password" />
</label>
</div>
<input type="submit" value="Log In" />
</form>
<?php } ?>
</body>
</html>
In the login functionality, I am setting the $_SESSION values
<?php
session_start();
if (count($_POST))
if ($_POST["username"] == "ayu" && $_POST["password"] == "shee") {
$_SESSION["user"] = "Ayushi";
header("Location: ./");
} else {
unset($_SESSION["user"]);
header("Location: ./?error");
}
?>
Yes using and creating ($_SESSION) session is the correct way to check logged in users.
$_SESSION is a 'superglobal', or automatic global, variable. This
simply means that it is available in all scopes throughout a script.
There is no need to do global $variable; to access it within functions
or methods.
Check for session on very top of a page, if found redirect to index else to login page.
if(!isset($_SESSION['login_user'])){
header("location:login.php");
}
Refer this simple login example using my sql in php Here
EDIT
As requested by OP - if you want to hide a particular section in index.php page based on session value or say if a user is logged in or not that can be done like:
<?php
if(isset($_SESSION['login_user'])){
?>
<form>
<input type="submit" name="whatever" />
<!-- Other Fields -->
</form>
<?php
}
?>
Html Form in the above code will only be shown if a user is logged in else it will be hidden.
Yes, Session is best way to implement the same. You can use the below php code to solve your problem
<?php
session_start();
if (!empty($_POST))
if ($_POST["username"] == "ayu" && $_POST["password"] == "shee") {
$_SESSION["user"] = "Ayushi";
header("Location: ./");
} else {
if($_SESSION["user"]!=''){
unset($_SESSION["user"]);
}
header("Location: ./?error");
}else{
/* Write code for form */
}
?>
We call it html1 for simplicity.
When a user goes to html1, there's a login2.php login page to enable access to client.php which is the hidden page.
It then goes to checklogin.php...if the password and user name matches...it then goes to the hidden client.php page...if not..it goes back to homepage.
The user has to login to be able to view the contents of hidden client.php page.
However the user can access client.php by typing in ..../client.php on the address bar...therefore bypassing the auth page and rendering it useless. I can just type servername/client.php...and it still shows me the contents of client.php...but I want client.php...to be private!
How do I prevent this from happening?
thanks.
first login page...
<html>
<head>
<title>Login Form</title>
</head>
<body>
<h2>Login Form</h2>
<table>
<form method="post" action="checklogin2.php">
<div id="name">User Id: <input type="text" name="****"></div>
<div id="password">Password: <input type="password" name="*******"></div>
<div class="button"><input type="submit" value="Login"></div>
</form>
</table>
</body>
</html>
then it goes to....
checklogin2.php
<?php
$*** = $_POST['****'];
$***** = $_POST['***'];
if($uid == '****' and $***** == '*****')
{
session_start();
$_SESSION['sid']=session_id();
header("location:securepage.php");
}
else
{
header("location:index.html");
}
?>
Then it goes to...
securepage.php
<?php
session_start();
if($_SESSION['sid']==session_id())
{
header("location:client.php");
echo "<a href='logout.php'>Logout</a>";
}
else
{
header("location:login.php");
}
?>
In the beginning of your every page you have to check if user is authorized.
On checklogin.php if user entered correct login and password, just set something like
$_SESSION['authorized'] = TRUE;
...and on other pages just check if user is authorized:
if (isset($_SESSION['authorized']) && $_SESSION['authorized'] === TRUE) {
// Alright, let's show all the hidden functionality!
echo "Psst! Hey! Wanna buy some weed?";
} else {
// User is not authorized!
header('Location: login.php');
exit();
}
Note that you don't have to mess with cookies, session IDs etc. - just add session_start() before everything and freely use $_SESSION var.
This is the main pro of sessions (and $_SESSION variable in particular): you can remember some data among different pages on same website.
All pages has to check if the user is authed. I would recommend using objects, and always inherit a class that checks this for you. It's not fun to have the same code everywhere, doing the same thing.
if($_SERVER["PHP_SELF"] == '/yourpagefolder/yourpage.php' && !isset($_SESSION['login_user'])){
header('location: login.php');
}
I've searched but can't seem to figure this one out. I have a config.php which searches for an active session and if found passes the user through, if not it fowards to the login.php page. The config.php also grabs the orginal URL and posts to login.php so we can redirect them to the page they were going to originally.
From there it should be pretty simple, authenticate and then use the redirect variable to forward browser to original page. But it's not working like that. It forwards me back to the login.php and says "Object Moved". Its redirects if I put header("location: /index.php"); but not if I use the variable in the login.php like below.
Any help would be appreciated!
PHP (config.php):
<?php
session_start();
// put somewhere in a config file
define('SESSION_EXPIRE',3600); // in seconds
// check passage of time, force log-out session expire time
if(isset($_SESSION['last_activity']) && (time() - strtotime($_SESSION['last_activity']) > SESSION_EXPIRE)) {
// destroy session
session_unset();
session_destroy();
}
// if user is logged in and unexpired, update activity
if(isset($_SESSION['user'])) {
// user is logged in
$_SESSION['last_activity'] = date('Y-m-d H:i:s');
}
// if user doesn't have session forward them to login page and post requested URL
if (!(isset($_SESSION['user']) && $_SESSION['user'] != '')) {
header ("Location: ../login.php?location=" . urlencode($_SERVER['REQUEST_URI']));
}
?>
PHP (login.php):
<?php
include("authenticate.php");
// check to see if user is logging out
if(isset($_GET['out'])) {
// destroy session
session_unset();
$_SESSION = array();
unset($_SESSION['user'],$_SESSION['access']);
session_destroy();
}
// get orginal URL from config.php
$url = $_GET['location'];
// check to see if login form has been submitted
if(isset($_POST['userLogin'])){
// run information through authenticator
if(authenticate($_POST['userLogin'],$_POST['userPassword']))
{
// authentication passed
header("location:".$url);
die();
} else {
// authentication failed
$error = 1;
}
}
// output logout success
if (isset($_GET['out'])) echo "Logout successful";
?>
HTML:
<div class="panel-body">
<form action="login.php" method="post">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Username" name="userLogin" type="Username" autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="userPassword" type="password" value="">
</div>
<!-- Change this to a button or input when using this as a form -->
<input class="btn btn-lg btn-success btn-block" type="submit" name="submit" value="Login" />
</fieldset>
</form>
</div>
I am not sure if I understand your exact problem but if you are trying to redirect to $location and it is not going to the proper page or throwing an error then you may need to urldecode it before passing the variable.
in your config you encode the URI:
// if user doesn't have session forward them to login page and post requested URL
if (!(isset($_SESSION['user']) && $_SESSION['user'] != '')) {
header ("Location: ../login.php?location=" . urlencode($_SERVER['REQUEST_URI']));
}
So in your Login decode it:
$url = urldecode($_GET['location']);
As mGamerz said make sure that your header has a capitol L and a space after the colon
header("Location: ".$url);
You need to remove login.php from here: action="login.php" You're losing the $url variable because it's not being included in the GET after the page posts back to itself.
I'm developing a simple member management system with php, and I've met a problem:
The user logs in and it is redirected to a main page and the user ID is saved in the session; there are some links to other pages in the main page, after the user clicks and is trying to go back to main by pressing browser "Back" button, sometimes the user ID in the session is lost.
I've checked the session save path, a new session file is created when I click "Back" button, so I assume the session_start() creates a new session for it; but I still don't know why, it's a random case...
Is there any way to solve it?
main.php:
<?php session_start(); ?>
<?php
$echo_string = '
<body>
a
b
</body>';
if (!empty($_SESSION['user']))
echo $echo_string;
else
header("Location: login.php");
?>
login.php:
<?php
session_start();
if (isset($_POST['userLogin'])) {
$_SESSION['user'] = $_POST['userLogin'];
// check userLogin in db
...
}
header("Location: main.php");
?>
<form novalidate="" method="post" action="login.php">
<label class="hidden-label" for="Username">Username</label>
<input id="Username" name="userLogin" type="text" placeholder="Username" value="" spellcheck="false" class="">
<label class="hidden-label" for="Passwd">Password</label>
<input id="Passwd" name="userPassword" type="password" placeholder="Password" class="">
<input id="signIn" name="signIn" class="rc-button rc-button-submit" type="submit" value="Log in">
</form>
a.php:
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>...</head>
<?php
$echo_string = '...'; // a html format string
if (!empty($_SESSION['user']))
echo $echo_string;
else
header("Location: login.php");
?>
</html>
b.php is almost same as a.php
Thanks.
BR,
Sean
session_start()-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."
so you see, that when a session exists it doesnt create a new, that means when you set something like $_SESSION['logged_in'] = true; you should check before if $_SESSION is already filled with your infos
I am doing a project in school, I need to know a simple way to stop poeple from entering the site without a session. I have alot of pages I don't believe I spent the time pasting code on every page. Also I have menu bar that is included in every page thanks to php, so i was wondering wat type of code would I have to put in the menu to block user without a session. The rest of the content code is on the pages that I want to hide. I believe that you can login by typing out the url and allow users to see hidden pages that are for logged in users.
Please do not use a plain cookie. Sessions are the way to go. Or if can't use sessions and must use a cookie, sign the cookies first to be able to verify that your application was really the one to set it.
<?php
session_start();
if (!isset($_SESSION['authenticated'])) {
header('Location: login.php');
exit;
}
... whatever logged in users should see ..
If you don't want to use session, then use cookie.
<?php
/*Just add this piece of PHP code to top of any page you
don't want not-logged in users to see */
if (!isset($_COOKIE['logged']))
header("Location: login.php"); //It redirects the user to your login page
?>
<html>
<body>
...
</body>
</html>
Login page could be like this:
<?php
if (isset($_COOKIE['logged']))
header("home.php");
if ($_POST['submit']) {
//get username and password
$uname = $_POST['uname'];
$pass = $_POST['password'];
if ($uname=="correct" && $pass=="correct"){ //EDIT
setcookie('logged','1');
header("Location: home.php"); //Redirect to home page
}
else echo "Wrong combinaton!";
}
?>
<html>
<body>
<form action="login.php" method="post">
<label>Username</label><input type="text" name="uname" /><br />
<label>Password</label><input type="password" name="pass" /><br />
<input type="submit" name="submit" value="Login" />
</form>
</body>
</html>