Trying to make a page redirect if not logged in. I'll try to show what I mean.
In the index.php:
<?php
// initialization of login system and generation code
$oSimpleLoginSystem = new SimpleLoginSystem();
echo $oSimpleLoginSystem->getLoginBox();
session_start();
$_SESSION["loggedin"] = False;
// class SimpleLoginSystem
class SimpleLoginSystem {
// variables
var $aExistedMembers; // Existed members array
// constructor
function SimpleLoginSystem() {
$this->aExistedMembers = array(
'test' => MD5('test'), //Sample: MD5('qwerty')
);
}
function getLoginBox() {
ob_start();
require_once('login_form.html');
$sLoginForm = ob_get_clean();
$sLogoutForm = 'logout';
if ((int)$_REQUEST['logout'] == 1) {
if (isset($_COOKIE['member_name']) && isset($_COOKIE['member_pass']))
$this->simple_logout();
}
if ($_REQUEST['username'] && $_REQUEST['password']) {
if ($this->check_login($_REQUEST['username'], MD5($_REQUEST['password'])))
{
$_SESSION["loggedin"] = True;
$this->simple_login($_REQUEST['username'], $_REQUEST['password']);
header( 'Location: /site.html' );
}
else {
return 'Username or Password is incorrect' . $sLoginForm;
}
} else {
if ($_COOKIE['member_name'] && $_COOKIE['member_pass']) {
if ($this->check_login($_COOKIE['member_name'], $_COOKIE['member_pass'])) {
header( 'Location: /site.html' );
}
}
return $sLoginForm;
}
}
In the site.php:
<?php
session_start();
if ($_SESSION["loggedin"] == 0)
{
header( 'Location: http://test-weeabear.c9users.io/' );
}
else
{
return "It worked!"
}
?>
Why is it when I open site.html, it redirects me back to index.html, even after logging in?
NOTE: Some things I changed, like links and names of files. For privacy.
You need session_start() at the start of your site.php
change the file extension from .html to .php
You are calling getLoginBox and then changing the loggedin back to false. You need to include an exit after the header redirect.
Like this:
header( 'Location: /site.php' );//changed to file extension as .php
exit;
Related
My logout.php file is like this. Is there any mistake in my code
logout.php
<?php
session_start();
session_destroy();
header('Location:index.php');
exit;
?>
Here is my index.php file. If I am set $_SESSION['s_activId'] then it is working properly but when I am trying to put condition if $_SESSION['s_activId'] is not set at that time I want to pass header on index page sometimes it works sometimes it does not work.
<?php
include('include/config.inc.php');
if(!isset($_SESSION['s_activId']))
{
$_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
header("Location:index.php");
}
else
{
$wrong = '';
if(isset($_POST['submit']))
{
$checkLogin = "SELECT userName,password,userType
FROM user
WHERE BINARY userName = '".$_POST['userName']."'
AND BINARY password = '".$_REQUEST['password']."'";
$checkLoginresult = mysql_query($checkLogin);
if($userLoginRow = mysql_fetch_array($checkLoginresult))
{
$_SESSION['s_activId'] = $userLoginRow['userName'];
$_SESSION['s_password'] = $userLoginRow['password'];
$_SESSION['hg_userType'] = $userLoginRow['userType'];
if(!$_SESSION['s_urlRedirectDir'])
{
header("Location:index.php");
}
else
{
header("Location:reminder.php");
}
}
else
{
$wrong = "UserId And Password Is Not Valid";
}
}
}
include("bottom.php");
$smarty->assign('wrong',$wrong);
$smarty->display("index.tpl");
?>
The problem arise in the condition below in index.php:
if(!isset($_SESSION['s_activId']))
{
$_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
header("Location:index.php");
}
When you logout, you are calling session_destroy() on logout.php and redirecting on index.php and the condition above gets true as s_activId is not set in session and again you are redirecting on index.php (without setting s_activId in session). The above condition will be true until the variable s_activId set in session and because of this you are getting ERR_TOO_MANY_REDIRECTS error.
The solution is, on index.php set the variable s_activId in session before calling the header method. Refer the code below:
if(!isset($_SESSION['s_activId']))
{
$_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
$_SESSION['s_activId'] = true;
header("Location:index.php");
}
Dont redirect index.php to index.php. you having redirects loop. Also
if you have code below that also can fire add die in if because after
redirect code below still executes. I didnt read your code, maybe
there isnt problems with this but after
header("Location: lalala"); always add die(); or exit();
I have the following code which works fine under several linux flavors I have tried (Ubuntu, Debian 8, CentOS 7), however when I use it on windows, the regeneration fails without an error. $duration is a value in the class represented as static $duration = 60 * SESSION_TIMEOUT; where SESSION_TIMEOUT is a constant defined in a config.inc.php file (user setting).
session_start();
self::csrf(false);
if(self::verify(false) === true) {
$_SESSION['expires'] = time() + self::$duration;
}
session_regenerate_id(true);
$id = session_id();
session_write_close();
session_id($id);
session_start();
If I echo $id after the line $id = session_id(); there is a value, however if I echo session_id() after the last session_start(), it is empty. (See session_regenerate_id if you think this method is 'Dodgy' )
I do not know why this regeneration code is failing :
session_regenerate_id(true);
$id = session_id();
// one of the lines below this are causing session_id() to be blank
session_write_close();
session_id($id);
session_start();
Please assist me in identifying what is causing the new session to be blank when it should contain the new session id.
session.save_path = 2;755;d:/server/www/127.0.0.1/sessions
Update: I was able to find this in the log, however the interesting part is the session file is created with data.
PHP Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (2;755;d:/server/www/127.0.0.1/sessions) in Unknown on line 0
As requested, a sample of $id before calling session_write_close() (and subsequent code), is 9vdom0ghuqkvsdcnkjacurc6rf2n4fn1s1gvfva44okd15jdpm30
Update:
After some more testing, I have traced the problem to be a bit more complex than stated above. The problem I initially had which I believed was a session regeneration issue, is more of a problem where session variables are not being stored. I believe this is still related to session regeneration somewhat on windows, however I still am unable to pinpoint a fix, as this code works beautifully on Linux.
Here is the class (minified):
class session {
static $duration = 60 * SESSION_TIMEOUT;
public static function start() {
session_start();
self::csrf(false);
if(self::verify(false) === true) {
$_SESSION['expires'] = time() + self::$duration;
}
session_regenerate_id(true);
$id = session_id();
session_write_close();
session_id($id);
session_start();
}
public static function csrf($new = false) {
if(!isset($_SESSION['csrf']) || $new === true) {
$_SESSION['csrf'] = sha1(openssl_random_pseudo_bytes(mt_rand(16,32)));
}
return $_SESSION['csrf'];
}
}
The code used to call it, is rather complex (when it comes to determining when to generate a new csrf token), but below is my attempt to extract a chunk from my overall project to demonstrate the usage. The login code behind should suffice I believe to view the logic:
if( session::verify() === true ) {
redirect();
} else {
$error = '';
$token = $_SESSION['csrf'];
if ( !empty($_POST) ) {
if ( isset($_POST['csrf']) ) {
// check CSRF token and if match ti token stored in session
$csrf = trim(filter_input(INPUT_POST, 'csrf', FILTER_SANITIZE_SPECIAL_CHARS, array('flags' => FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH)));
if($csrf != $_SESSION['csrf']) { session::destroy(); $error = 'CSRF Attack Detected'; }
if( isset($_POST['username']) && isset($_POST['password']) && empty($error) ) {
// login validation code
if($auth) {
// regenerate csrf token
$token = session::csrf(true);
session::create( $username );
// redirect back to application root
redirect();
}
$error = 'Invalid credentials';
} else {
if(empty($error)) { $error = 'Invalid credentials'; }
}
// user was not authenticated, regenerate csrf token to prevent form spam
$token = session::csrf(true);
} else {
// CSRF token did not match stored token in session
$error = 'CSRF Attack Detected';
}
}
}
The additional methods for my session class as used in the login code are as follows :
Update session data with user information.
public static function create($user) {
$_SESSION['nonce'] = sha1(microtime(true));
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
$_SESSION['agent'] = sha1($_SERVER['HTTP_USER_AGENT']);
$_SESSION['expires'] = time() + self::$duration;
$_SESSION['user'] = $user;
session_regenerate_id(true);
$id = session_id();
session_write_close();
session_id($id);
session_start();
}
Verify posted information matches server session
public static function verify($destroy = false) {
$valid = true;
try {
if( !isset($_SESSION['nonce']) ) { $valid = false; }
if( !isset($_SESSION['user']) ) { $valid = false; }
if( isset($_SESSION['ip']) ) { if($_SESSION['ip'] != $_SERVER['REMOTE_ADDR']) { $valid = false; } } else { $valid = false; }
if( isset($_SESSION['agent']) ) { if($_SESSION['agent'] != sha1($_SERVER['HTTP_USER_AGENT']) ) { $valid = false; } } else { $valid = false; }
if( isset($_SESSION['expires']) ) { if($_SESSION['expires'] <= time()) { $valid = false; } } else { $valid = false; }
} catch (Exception $e) {
$valid = false;
}
if($valid === false) {
if(isset($_SESSION['nonce'])) { unset($_SESSION['nonce']); }
if(isset($_SESSION['ip'])) { unset($_SESSION['ip']); }
if(isset($_SESSION['agent'])) { unset($_SESSION['agent']); }
if(isset($_SESSION['expires'])) { unset($_SESSION['expires']); }
if(isset($_SESSION['user'])) { unset($_SESSION['user']); }
if($destroy === true) {
session_unset();
session_destroy();
}
}
return $valid;
}
Update:
Narrowed this down by running a simple test :
// ensure sessions are writeable
if(!is_writable(session_save_path())) {
// try alternate session path
$_session_save_path = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'sessions';
if(!is_writable($_session_save_path)) {
echo "Can't write sessions"; exit;
} else {
session_save_path(
$_session_save_path
);
}
}
Which echo's the result 'Can't write sessions' meaning it failed all methods to try and write data.
What is interesting here, is that no matter what I do (even setting the root of the drive to 'Everyone' with 'Full' permissions, all subfolders and files seem to have a permanent semi-shaded 'Read Only' checkbox. Beyond this, file_put_contents("hello.txt", "hello"); exit(); works in the root folder of my local site, but not from any subfolder below 2 directories deep -- even after assigning (and checking) permissions. (e.g. d:\server\websites\127.0.0.1\htdocs\ works, but not d:\server\websites\127.0.0.1\htdocs\path1\path2\
Update:
Did some more troubleshooting, and the rabbit hole gets deeper. Ran a script to find what user PHP is running under to better assist in checking permissions:
echo 'Current script owner: ' . get_current_user();
which echo's 'Current script owner SYSTEM'
I followed up with this code :
$new = false;
session_start();
if(!isset($_SESSION['csrf']) || $new === true) {
$_SESSION['csrf'] = sha1(openssl_random_pseudo_bytes(mt_rand(16,32)));
}
session_regenerate_id(true);
$id = session_id();
session_write_close();
session_id($id);
session_start();
Which still failed. I did try something which finally worked, but I really don't feel comfortable with it as it involves not setting the security bits as documented in the php.ini file.
I changed :
session.save_path = "2;755;d:/server/www/127.0.0.1/sessions"
To
session.save_path = "d:/server/www/127.0.0.1/sessions"
And this works, however all the session files are now world accessible.
(Server is the same version of apache and php on all platforms configured with identical php.ini files, and server configuration files as close as possible)
I'm developing a user site in php. What I want to do, is allow people to use a ?return_to url variable to get back to the page they were on before they were asked to log in (for example, if they were on /me.php, then they will be redirected to login, and the url will be login.php?return_to=me.php.. I want to redirect to me.php after login.).
Currently, the way my system checks for login submission on the homepage is with the following:
if(isset($_POST['submitted']))
{
if($advena->Login())
{
$advena->RedirectToURL("/");
}
}
When I try to use
if (strpos($_SERVER['REQUEST_URI'], "?return_to") !== false){
$location .= "?return_to=" . urlencode($_GET["return_to"]);
if(isset($_POST['submitted']))
{
if($fgmembersite->Login())
{
$fgmembersite->RedirectToURL($location);
}
}
} else {
if(isset($_POST['submitted']))
{
if($fgmembersite->Login())
{
$fgmembersite->RedirectToURL("/");
}
}
}
It always redirects to "/" regardless of the presence of ?return_to. Here is the redirect php:
function RedirectToURL($url)
{
header("Location: $url");
exit;
}
Thank you in advance for any help anyone can provide :)
members.php - sample page
<?php
// set the return url value
$_SESSION['return_url'] = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
// redirect if not logged in
if (!not_logged_in()) {
header('Location: /login.php?return_to=' . rawurlencode($_SESSION['return_url']));
exit;
}
// checks if the user is logged in
function not_logged_in() {
return !isset($_SESSION['logged_in']);
}
?>
login.php - login page
<?php
if (isset($_POST['username'], $_POST['password'])) {
// do more...
// redirect
if (success()) {
// set a session for logged in user
$_SESSION['logged_in'] = sha1(time() . rand(0, 99999));
if (isset($_GET['return_to'], $_SESSION['return_url'])) {
$fgmembersite->RedirectToURL('/process.php?ret=' . urldecode($_GET['return_to']));
exit;
}
else {
$fgmembersite->RedirectToURL('/process.php');
exit;
}
}
}
?>
process.php - login processor
<?php
if (isset($_GET['return_to'], $_SESSION['return_url'])) {
# set: return url
$continue_url = rawurldecode($_GET['return_to']);
# do: redirect to the specified page
header("Location: {$continue_url}");
unset($_SESSION['return_url']);
# do: redirect with message
exit('Redirecting...');
}
else {
header('Location: /members.php');
}
?>
hye ,
My current Directory structure is like
Admin (index.php, country.php)
Classes(connection.php,login.php,country.php)
header.php
footer.php
index.php
includes(header.php,footer.php)
my problem is that on webserver when i am in /admin/country.php and add a country using form post method and action set to /classes/country.php my header statement "Header("Location: ../Admin/country.php")" is working ok but when i am on my index page in root directory and try to login with form action "classes/login.php" and on successful login i use header("Location: ../Admin/index.php") it never redirects but everything works fine my local server, i don't know whats the problem over here, Any help would be really appreciated,
I have searched this forum and others and tried to use the techniques they have told but nothing is working
my index page index.php
my Admin Section Admin/Country.php
my login.php script is below
<?php
ob_start();
include_once("classes/connection.php");
?>
<?php
class login
{
public static function validateLogin($userName,$password)
{
if(isset($userName) && isset($password))
{
$connection = dbconnection::getConnection();
$query = "Select * from tbllogin Where loginID ='" . $userName .
"' and password = '" . $password . "'";
$result = mysql_query($query);
$rowsAffected = mysql_affected_rows();
if($rowsAffected==0)
{
//header("Location: ../index.php/");
//exit();
return false;
}
else
{
while($row = mysql_fetch_array($result))
{
//working
$role = $row["role"];
if($role == "Admin")
{
//header('Location: ../Admin/index.php');
//exit();
return true;
}
else
{
//echo "hello";
//header("Location: ../index.php/");
//exit();
return false;
}
//return $result;
//header("Location: ../index.php");
}
}
}
else
{
//header("Location: ../index.php/");
return false;
}
}
}
?>
<?php
if(isset($_POST["btnSumbit"]))
{
$isValid = login::validateLogin($_POST["userID"],$_POST["password"]);
if(isset($isValid))
{
if($isValid ==true)
{
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'Admin/index.php';
header("Location: http://$host$uri/$extra");
exit();
}
}
}
ob_end_flush();
?>
Don't use header redirects with relative paths. You should redirect to the front end URL path or absolute paths.
It's possible that your "classes/login.php" is an included file into "index.php" -- so you're actually trying to step out of the web server directory - which is why it works locally but not on the server.
I've been fighting with the cookieless sessions solution. Of course cookieless sessions solution is amazing. I have a trouble in implementing it because I can't read the session information after redirecting to another page.
Here's my test code in testcode.php
<?php
ini_set('session.use_trans_sid', '1');
session_start();
if (isset($_GET['pagecode'])) {
session_id($_GET['pagecode']);
print_r($_SESSION); // **cannot read session information here**
exit();
}
if (isset($_SESSION['cookieconfirmed']) && $_SESSION['cookieconfirmed'] == 1) {
} else {
/** Checks if the user's browser is cookie-enabled **/
if (isset($_GET['redirected'])) { // if the page has gotten redirected
$_SESSION['cookieconfirmed'] = 1; // confirmed the cookie-disability
if (isset($_COOKIE['testcookie'])) {
header ('location: testcode.php');
} else {
header('location: testcode.php?pagecode=' . session_id());
}
} else {
setcookie('testcookie', 'OK'); //sets a test cookie.
header('location: testcode.php?redirected=1'); // redirects the page to check cookie-disability
}
exit(0);
}
?>
As you can see this code doesn't work. but if i redirect to another page by clicking a link it works well. Here's the code in testcode.php:
<?php
ini_set('session.use_trans_sid', '1');
session_start();
if (isset($_GET['pagecode'])) {
session_id($_GET['pagecode']);
print_r($_SESSION); // **able to read session information here**
exit();
}
if (isset($_SESSION['cookieconfirmed']) && $_SESSION['cookieconfirmed'] == 1) {
} else {
/** Checks if the user's browser is cookie-enabled **/
if (isset($_GET['redirected'])) { // if the page has gotten redirected
$_SESSION['cookieconfirmed'] = 1; // confirmed the cookie-disability
if (isset($_COOKIE['testcookie'])) {
header ('location: testcode.php');
} else {
echo 'Click here to continue';
}
} else {
setcookie('testcookie', 'OK'); //sets a test cookie.
header('location: testcode.php?redirected=1'); // redirects the page to check cookie-disability
}
exit(0);
}
?>
How can I get this to work without clicking a link?
ini_set('session.use_trans_sid', '1');
You have to have this on every single one of your PHP pages - you can't do it just within the session handling script. If it's not on when PHP generates a page, it won't insert the session ID into forms and urls on that page. As such, it'd be better if you put this into your php.ini, or at least httpd.conf/.htaccess (as a php_value) to make it a global option for all scripts.
PHP function for this is :
function append_sid($link) {
if(session_id() !== NULL && !isset($_COOKIE['PHPSESSID'])) {
if(strpos($link, "?") === FALSE) {
return $link . "?PHPSESSID=" . session_id();
} else {
return $link . "&PHPSESSID=" . session_id();
}
} else {
return $link;
}
}
Javascript Function for this is:
function append_sid(link) {
<?php if(session_id() !== NULL && !isset($_COOKIE['PHPSESSID'])) { ?>
var session_id = '<?php echo session_id ?>';
if(link.indexOf('?') == -1) {
return link + '?PHPSESSID=' + session_id;
} else {
return link + '&PHPSESSID=' + session_id;
}
<?php } else { ?>
return link;
<?php } ?>
}
A caveat – passing session id by URL requires the session.session.use_trans_sid tio be set to 1.
php_value session.use_trans_sid = 1 in the .htaccess file. You can also try the function:
ini_set('session.use_trans_sid', '1')