Redirect not working with header("Location: - 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.

Related

How to prevent user from bypassing php authentication

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');
}

Redirect user who already logged in PHP

I want to redirect logged in users to home page(member-index.php), I have used the following code to accomplish this, but this doesn't work.
<?php
function redirect() {
header('location:member-index.php');
}
?>
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
if(isset($_SESSION['SESS_FIRST_NAME'])){
redirect();
}
?>
<form id="loginForm" name="loginForm" method="post" action="login-exec.php">
<input name="email" type="text" class="textfield" id="login" placeholder="username" />
<input name="password" type="password" class="textfield" id="password" placeholder="password"/>
<input type="submit" name="Submit" value="LOGIN" />
</form>
</body>
</html>
session variables at (login-exec.php)
$qry="SELECT * FROM members WHERE email='$login' AND passwd='".md5($_POST['password'])."'";
$result=mysql_query($qry);
//Check whether the query was successful or not
if($result) {
if(mysql_num_rows($result) == 1) {
//Login Successful
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $member['member_id'];
$_SESSION['SESS_FIRST_NAME'] = $member['fullname'];
The other pages with sessions, works perfectly fine, I could get and print the logged in user on another page, But couldn't get session work in login-form page..
Any help would be appreciated!
I'm surprised error reporting error_reporting(E_ALL); ini_set('display_errors', 1); didn't throw you a warning about outputting before header.
I.e.:
Warning: session_start(): Cannot send session cache limiter - headers already sent...
Move your <?php session_start(); ?> at the top of your code.
<?php session_start(); ?>
<?php
function redirect() {
header('location:member-index.php');
exit;
}
?>
and add exit; after your header to avoid further execution.
Also make sure all your files do not contain a byte order mark (BOM) and that there is no output before header. A space, HTML, nothing, not even a cookie, or anything else that would account as output.
All files should be saved in your code editor, as UTF-8 WITHOUT BOM.
I added this code at top of my login form, and it worked!
<?php
//Start session
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
if(isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) {
header("location: member-index.php");
exit();
}
?>
Do this at the top of your file instead
<?php
session_start();
if(isset($_SESSION['SESS_FIRST_NAME'])){
header("location: member-index.php");
}
?>
<html>....the rest of your html
You can look at the php docs for header to see why you are having an issue. The paragraph that starts with 'Remember' specifically

Bug using PHP Sessions (Two Log On screens)

In the application I'm developing I'm having a bug where I direct my browser to my app's index.php, and is then properly redirected to login.php if there is no current session. My problem is that after I type in my correct details on login.php and click submit, I am linked to another login.php screen (instead of returning to index.php with an active session) and required to put in my details again. The first screen has the same CSS formatting as index.php, while the second screen doesn't.
After entering my details on the second screen and clicking login, the sessions seem to function normally. Also, many times I will be presented with one logon screen, ill login and the user's correct Home screen data will be displayed (which requires successful queries from the login data), but if I navigate away from index.php to another screen that requires an active session, it will present the unformatted login.php screen.
If I logout, navigate to a different non-restricted page, and attempt to log back in again within the same browser session, the logon functions correctly with only one screen.
Here are snippets from the relevant files:
index.php
<?php
include_once 'db_functions.php';
require_once 'access.php';
if (isset($_POST['action'])) {
if (userIsLoggedIn()) {
header('Location: http://www.myapp.com/index.php'); //prevents users from having to confirm form resubmission if they refresh the page
}
}
if (!userIsLoggedIn()) {
include 'login.php';
exit();
}
login.php:
login.php
<body>
<h1>Log In</h1>
<?php
if (isset($loginError)) {
echo $loginError;
}
?>
<form action="" method="post">
<div>
<label for="email">Email: <input type="text" name="email" id="email" /> </label>
</div>
<div>
<label for="password">Password: <input type="password" name="password" id="password" /></label>
</div>
<div>
<input type="hidden" name="action" value="login" />
<input type="submit" value="Log in" />
</div>
</form>
</body>
access.php:
<?php
function userIsLoggedIn() {
if (isset($_POST['action']) and $_POST['action'] == 'login') {
if (!isset($_POST['action']) or $_POST['email'] == '' or
!isset($_POST['password']) or $_POST['password'] == '') {
$GLOBALS['loginError'] = 'Please fill in both fields';
return FALSE;
}
$email = $_POST['email'];
$password = $_POST['password'];
if (databaseContainsAuthor($email, $password)) {
session_start(); //LINE 17
$_SESSION['loggedIn'] = TRUE;
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
return TRUE;
}
else {
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
$GLOBALS['loginError'] = 'The specified email address or password was incorrect.';
return FALSE;
}
}
if (isset($_POST['action']) and $_POST['action'] == 'logout') {
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
header('Location: ' . $_POST['goto']);
exit();
}
session_start();
if (isset($_SESSION['loggedIn'])) {
return databaseContainsAuthor($_SESSION['email'], $_SESSION['password']);
}
}
function databaseContainsAuthor($email, $password) {
include_once './db_functions.php';
$db = new DB_Functions();
$result = $db->accountExists($email, $password);
return $result;
}
?>
Any help would be greatly appreciated!
UPDATE:
Error logs are showing multiple occurances of this error:
PHP Notice: A session had already been started - ignoring session_start() in /home3/monitot5/public_html/app/access.php on line 17
Access.php line 17:
if (databaseContainsAuthor($email, $password)) {
session_start(); //LINE 17
$_SESSION['loggedIn'] = TRUE;
What you should do is to use
session_start();
at the beginning of access.php file and don't use this function any more.
You should also completely change login of your access.php file. The first thing you should always do in this file is checking if there's a valid session for this user. Now you check it at the end of file and probably earlier you clear it because you unset session if there are no $_POST data.
In addition you shouldn't also use password in your session. It's rather very insecure. You should simple store login for your system when user filled in form valid username/email and password and unset it if user has logged out.
Sorry, but I won't write the whole code for you. You should simple look at some examples of code in Google to check how to handle user login/logout in PHP.

missing session data after clicking browser back button

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

Remembering URL until authentication is complete

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: /"); }
?>

Categories