Unable to redirect using header(Location:) - php

I am unable to redirect from the login page of my site to the dashboard. When I try to login by giving the correct username and password it again shows me the login page, but when I access the dashboard of my site by url I can access it which proves that session has started.
Below is my code:
<?php
error_reporting(0);
session_start();
include_once '../db.php';
if(isset($_REQUEST['admsubmit']))
{
$result=executeQuery("select * from adminlogin where admname='".htmlspecialchars($_REQUEST['name'],ENT_QUOTES)."' and admpassword='".md5(htmlspecialchars($_REQUEST['password'],ENT_QUOTES))."'");
// $result=mysql_query("select * from adminlogin where admname='".htmlspecialchars($_REQUEST['name'])."' and admpassword='".md5(htmlspecialchars($_REQUEST['password']))."'");
if(mysql_num_rows($result)>0)
{
$r=mysql_fetch_array($result);
if(strcmp($r['admpassword'],md5(htmlspecialchars($_REQUEST['password'],ENT_QUOTES)))==0)
{
$_SESSION['admname']=htmlspecialchars_decode($r['admname'],ENT_QUOTES);
unset($_GLOBALS['message']);
header('Location: admwelcome.php');
}else
{
$_GLOBALS['message']="Check Your user name and Password.";
}
}
else
{
$_GLOBALS['message']="Check Your user name and Password.";
}
closedb();
}
?>

From my experience with PHP, the problem is you cannot redirect a user after the page buffer has been emptied. The problem is you must send the headers before anything else for them to be recognized. You script sends html data before sending the Location header that causes the user to redirect, that's why redirecting does not work.
To resolve this issue you must start the buffer at the first line of PHP code to prevent html data being sent, and empty it (if the buffer gets full, it will empty automatically) at the end of the file. You can also specify the buffer size in the config file.
To turn on output_buffering add the following line to your .htaccess file
php_flag output_buffering on
To start the buffer you use the ob_start() function (http://www.php.net/manual/ro/function.ob-start.php).
To empty the buffer in case it has not filled, you use the ob_end_flush() function (http://www.php.net/manual/ro/function.ob-end-flush.php).
Your code should be:
<?php
ob_start(); // start the page buffer so html data is not sent before the header
error_reporting(0);
session_start();
include_once '../db.php';
if(isset($_REQUEST['admsubmit']))
{
$result=executeQuery("select * from adminlogin where admname='".htmlspecialchars($_REQUEST['name'],ENT_QUOTES)."' and admpassword='".md5(htmlspecialchars($_REQUEST['password'],ENT_QUOTES))."'");
// $result=mysql_query("select * from adminlogin where admname='".htmlspecialchars($_REQUEST['name'])."' and admpassword='".md5(htmlspecialchars($_REQUEST['password']))."'");
if(mysql_num_rows($result)>0)
{
$r=mysql_fetch_array($result);
if(strcmp($r['admpassword'],md5(htmlspecialchars($_REQUEST['password'],ENT_QUOTES)))==0)
{
$_SESSION['admname']=htmlspecialchars_decode($r['admname'],ENT_QUOTES);
unset($_GLOBALS['message']);
header('Location: admwelcome.php');
}else
{
$_GLOBALS['message']="Check Your user name and Password.";
}
}
else
{
$_GLOBALS['message']="Check Your user name and Password.";
}
closedb();
}
ob_end_flush(); // empty the buffer and send the html code back to the browser
?>
I also use a redirect function so I can redirect more easily:
function redirect($to) {
header("Location: " . $to);
}
Now you can redirect like this (it seems far more easier to the eye):
redirect("admwelcome.php");
Please rate my answer as I am a new user and can't rate others just yet :-)

I had the same problem 2 minutes ago... Now is solved :)
Try using JavaScript. Remplace header location, in the php code
?>
<script type="text/javascript">
window.location ="http://www.sirobd.com/index.php";
</script>
<?php

try this code with meta. in content attribut, you can change the number, it's the time in second before the redirection
if(strcmp($r['admpassword'],md5(htmlspecialchars($_REQUEST['password'],ENT_QUOTES)))==0){
$_SESSION['admname']=htmlspecialchars_decode($r['admname'],ENT_QUOTES);
unset($_GLOBALS['message']);
echo '<meta http-equiv="Refresh" content="2;url=http://yourWebsite/admwelcome.php">';
}else{
$_GLOBALS['message']="Check Your user name and Password.";
}

Try adding:
session_write_close();
before the header call, and then add exit for good measure.
session_write_close();
header('Location: admwelcome.php');
exit;

Related

PHP How to completely destroy a session after leave the page

I want to make a simple PHP page where you can only access if you log in first. My code is something like this:
if (the user logged in correctly) {
session_start();
echo "THE HTML PAGE. (I did this in echo because I only want to show it for the logged in users.)";
} else {
header ("Location: index.html");
die();
session_destroy();
}
So my goal is that, when the user click onto the "Go back on page" button, the session gets destroyed, and only start a new after logged in. But now, if the user click onto the "Go back on page" button, than click onto the "Go forward on page" button. it says, Document Exired. It's cool, but if I refresh the page, I can access the page without login.
Here is a solution
// put on top of every page
session_start();
function is_logged_in(): bool
{
if (isset($_SESSION['email']) && isset($_SESSION['id']) && isset($_SESSION['is_logged_in'])) {
return true;
} else {
return false;
}
}
function is_auth()
{
if (!is_logged_in()) {
session_destroy(); // change happend here
header("Location: index.html");
die();
}
}
is_auth();
// add your code here
if(isset($_SESSION['email']) && isset($_SESSION['id']))
{
return true;
}
else
{
return false;
}
// and then call this function in header file to check.
header ("Location: index.html");
die();
session_destroy();
Regarding session destruction, you cannot do it that way. See below:
First you need to destroy the session.
Then you need to redirect the user.
Correct:
session_destroy();
header ("Location: index.html");
die();
sometimes unset function also works see unset and destroy are two seprate function,
unset is useful for unsetting the some values like email,id,name etc and destroy completely destroys session, so make sure destroying the session you again not need the session so try to use unset().

stop session from logging user out

I have some code that I added to try and prevent the user from auto logging out (session). - but it still logs the user after so long
What I want is for the user to be able to access multiple pages when logged in and not log them out if they go idle, hence why I put a large idle time - or in other words , stay logged in until they decide to click logout.
login-page
$result = mysqli_query($connection,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['username'] = $username;
$_SESSION['username']=time();
// Redirect user to index.php
header("Location: admin-index.php");
}else{
$_SESSION['incorrect'] = 'Incorrect email or password. Please try again.';
header ("Location: admin-login.php?=incorrectlogin");
}
}
logged in index page
<?php
session_start();
$idletime=6000000;
if (time()-$_SESSION['username']>$idletime){
session_destroy();
session_unset();
header ("Location: admin-login.php");
}else{
$_SESSION['username']=time();
}
//on session creation
$_SESSION['username']=time();
?>
<!DOCTYPE html>
<html lang="en" >
<head>
second php page
<?php
session_start();
if(!isset($_SESSION["username"])){
header("Location: admin-login.php");
exit(); }
?>
There are a few ways of handling this:
You could change the lifespan of the sessions on the servers itself or if you can't access the server settings, you could try overwriting it through code:
ini_set('session.gc_maxlifetime', 6000000);
session.gc_maxlifetime manual
If you are unable to change the lifespan of sessions on the server, you could use this small code 'trick', keep in minde that if the clients pc shuts down or goes into sleep mode, the sessions will also expire:
Basicly you create a php script containing:
session_start();
Second you just write some jquery with the following code:
$(document).ready(function() {
// keep alive
setTimeout(keepalive(),120000);
});
function keepalive() {
$.get( "url/to/ajax.php", function( data ) { setTimeout(callserver,12000); });
}
You can use a trick, http://php.net/manual/en/function.session-start.php#example-5997
Starting with Php version 7.0 was added an option to prevent session expire. A time of 86400 means 1 days. You can adjust as you want.
if (session_status() == PHP_SESSION_NONE) {
if (version_compare(PHP_VERSION, '7.0.0') >= 0) {
session_start(['cookie_lifetime' => 86400,]);
} else {
session_start();
}
}
You can put at the top of Php files or include a file with this code on your project.
Hope this help.

PHP login script in a separated file

I have been developing the following php script (+ sqlite database) to create a login for my web.
Up to now I had used just one PHP file, but now I want to use different files for login and protected contents, I mean, I used to have all my web in one file php (contents and password script were together) but now I want to detach it in different php files (one for the login, login.php, and other phps protected: index.php, calendar.php...)
I used this code to password-protect php content:
<?php require_once "Login.php"; ?>
but it doesn't seem to work: it displays the form to login next to the content I wanted to protect.
This is the php script I'm using as login.php:
<?php
$db = new PDO('sqlite:data.db');
session_start();
if (isset($_GET['logout'])) {
unset($_SESSION['pass']);
header('location: index.php');
exit();
}
if (isset($_SESSION['timeout'])) {
if ($_SESSION['timeout'] + 4 < time()) {
session_destroy();
}
}
if (!empty($_POST['pass'])) {
$result = $db->query("SELECT user,password FROM users");
foreach ($result as $row) {
if (password_verify($_POST['pass'], $row['password'])) {
echo "Welcome! You're logged in " . $row['user'] . "! <a href='index.php?logout=true'>logout</a>";
$_SESSION['pass'] = $_POST['pass'];
$_SESSION['timeout'] = time();
}
}
}
if (empty($_SESSION['pass'])) {
echo '<form method="POST" action=""><input type="password" name="pass"><form>';
}
?>
MY QUESTION IS: How can I use my php script to protect different files?Is there any way to embed a logout link too?
One way is to store a token in session variables when a user logs in. Confirm the token is there on each page, if it isn't redirect the user to the login page. For example assert_login.php:
<?php
session_start();
if('' == $_SESSION['token']) {
header("Location: login.php");
exit();
}
?>
Then, in the PHP at the top of each of your pages:
<?php
require('assert_login.php');
?>
You can also clear the session variable on logout, logout.php for example:
<?php
require('assert_login.php'); // has session_start() already
$_SESSION['token'] = ''; // empty the token
unset($_SESSION['token']); // belt and suspenders
header("Location: login.php");
exit();
?>
I was also going through same issue & the way I solved it:
PSEUDO CODE:
PHP SESSION START
if(isset(GET(logout){
SetLogout();
die()}
$redirect=false
if not session[auth] exists
if SERVER REQUEST METHOD IS POST
$redirect=true;
if POST(username) && POST(pass) exists
Sanitize both of them & assign to $user& $pass
if user == "John" && $pass == "secret"
Go To SetLogin();
else{
Go To SetLogout();
echo "Wrong Username or Password"
drawlogin();
die();}
} //user pass comparing ends
} //Server method is NOT POST, so maybe it is GET.
//Do nothing, let the control pass to next lines.
}//SESSION(auth) does not exists, so ask user to login
else {
drawlogin();
}
//Post-Redirect-Get
if ($redirect)
redirect header to this same page, with 301
die()
// Secret Content here.
function SetLogin($user){
$SESSION(auth) = TRUE;}
function SetLogout($user){
if SESSION(auth) exists
unset($SESSION(auth))
redirect back with 301, without query string //shake ?logout
}
function drawlogin(){
echo all the HTML for Login Form
What it does is, it checks various things/variables, and if all passes, the control passes to Secret Content.
Save it as pw.php, & include it on top of any file you want to protect. Logout can be triggered by Logout
Note that this is just a pseudo code, typed on a tablet. I will try to update it with actual version. It is not checked for errors. Use all standard PHP Security precautions..

PHP Session not carrying over to protected pages

I've been having a really rough time trying to implement a logon system for my web application.
I have the basic logic working as far as my index.php goes - if users try to navigate there and are not logged in it redirects them to the logon screen. Once they've provided correct credentials they are directed properly back to the protected index.php page.
This logic in code is seen here:
(index.php)
<?php
session_start();
include_once 'db_functions.php';
require_once 'access.php';
if (!userIsLoggedIn()) {
include 'login.php';
exit();
}
The problem occurs when a user attempts to navigate to another protected page. My logic was for protected pages to check whether the user was logged in, and if not send them back to the index which would in turn send them to a logon screen.
(protectedpage.php)
<?php
session_start();
require_once 'access.php';
echo "Logged in: " + $_SESSION['loggedIn'];
echo "User: " + $_SESSION['email'];
echo "Password: " + $_SESSION['password'];
// receive data from HTML readcalllog request
$rName=$_POST["registration"]; //irrelevant post data
$rowId=$_POST["rowid"]; //irrelevant post data
if ($_SESSION['loggedIn'] == FALSE) {
header('Location: http://www.myapp.com/index.php'); //if not logged in, return to index.php, which in turn redirects to a logon page.
exit();
}
As you can see I included test echo statements to print out the details of the current session. When I would navigate to the page (turning off the redirect feature) to check the error messages it would print "000", without the "Logged in: " or "User: " text in front of it.
I performed a test and printed out the details successfully on the index.php page, so for some reason the session is being lost as I navigate from index.php to another protected page.
Any help would be greatly appreciated!
EDIT:
Here is a portion of the userIsLoggedIn() in access.php function which sets the session variables:
function userIsLoggedIn()
{
if (databaseContainsAuthor($_POST['email'], $password))
{
session_start();
$_SESSION['loggedIn'] = TRUE;
$_SESSION['email'] = $_POST['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;
}
}
}
EDIT 2:
If I login to the index page, go to the protected page(which sends me to a logon screen) and login again, the sessions function properly and all protected pages are accessible.
I just need to figure out what's preventing the initial logon from creating a proper session that carries over.
First of all, you do not need to include session_start(); more then once in a page. Just insert it at the beginning of each file.
If I were you, I would use this statement to see if the user is logged in or not in the protected pages:
if ( !isset($_SESSION['email'] && !isset($_SESSION['password'] ) ) {
header('Location: http://www.myapp.com/index.php'); //if not logged in, return to index.php, which in turn redirects to a logon page.
exit();
} else {
echo "Logged in";
}
Also, I would recommend you using both $_SESSION and $_COOKIES to create a stronger log in system.

use php to display log in and log out link according to active session

This is the code i have at the moment but will not work, displays log out button when logged in only on one page then logs user out automatically ?
<?php
if(!session_is_registered(myusername))
{
echo '<b>Log In</b>';
}
else
{
echo '<b>Log Out</b>';
}
?>
You had forgotten to do session_start() out of many things, and please make sure to share that, on every one of your pages, where you want to enable session protection.
<?php
session_start();
if(!isset($_SESSION['username']) && empty($_SESSION['username']))
{
echo '<b>Log In</b>';
}
else
{
echo '<b>Log Out</b>';
}
?>
session_is_registered is deprecated. Try using $_SESSION instead
if ($_SESSION["isLoggedIn"]) {
// Log out HTML goes here
} else {
// Log in HTML goes here
}
You'll need to include session_start() at the top of all of your files and you can set $_SESSION["isLoggedIn"] just like any other variable: $_SESSION["isLoggedIn"] = TRUE

Categories