PHP why is $_SESSION variable refusing to unset on browser close? - php

I am relatively new to php but I am encountering an error that is about to drive me INSANE.
I am working on creating a webpage that lets you browse files on the server.
However, for some reason, the $_SESSION variable keeps itself set, EVEN AFTER BROWSER RESTARTS...
Please, I am begging you, tell me why this happens before I go insane.
This is my code:
<html>
<?php
session_start();
if(!isset($_GET['location'])) {
header('Location: ?location=G:');
session_unset();
}
/* THIS IS WHERE THE BUG OCCURS. THIS VARIABLE SHOULD BE EMPTY ON BROWSER OPEN!!!! ?!?!?!?! I HAVE ADDED NOTHING TO SESSION YET*/
var_dump($_SESSION);
if(!isset($_SESSION['path'])) {
$_SESSION['path'] = array();
$_SESSION['path'][0] = $_GET['location'];
}
echo '<br><br><br><br><br><br>';
//* If user presses back and isn't in home folder, return to previous folder... *//
if(isset($_GET['back']) && $_GET['back'] == true && sizeof($_SESSION['path']) > 0) {
unset($_SESSION['path'][sizeof($_SESSION['path'])-1]);
$_GET['location'] = $_SESSION['path'][sizeof($_SESSION['path'])-1];
header ('Location: ?back=false');
} else {
//*However if user hasn't pressed back make sure that session is properly updated with location *//
if($_SESSION['path'][sizeof($_SESSION['path'])-1] != $_GET['location']) {
array_push($_SESSION['path'], $_GET['location']);
}
}
//*Now build the link from the session path array*//
$full_link = '';
for($i = 0; $i < sizeof($_SESSION['path']); $i++) {
$full_link .= $_SESSION['path'][$i];
$full_link .= '/';
}
//*Get all files from link path*//
$filesbrowsed = glob($full_link . '*');
?>
<head>
<meta charset "utf8">
<title>File Browser</title>
<link href="filebrowserstyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<header>
<ul class = "navigation">
<li>Home</li>
<li>Back</li>
<li></li>
<li></li>
</ul>
</header>
<div class = 'current_files'>
<?php
//* Now display all files in current path *//
for($i = 0; $i < sizeof($filesbrowsed); $i++) {
$filename = substr($filesbrowsed[$i], strlen($full_link), strlen($filesbrowsed[$i]) - strlen($full_link));
echo '<div>' . $filename . '</div>';
}
?>
</div>
</body>
</html>
Thank you all in advance!!!

You should unset session before redirecting user to another location.
<html>
<?php
session_start();
if(!isset($_GET['location'])) {
session_unset();
session_destroy();
header('Location: ?location=G:');
}
/* THIS IS WHERE THE BUG OCCURS. THIS VARIABLE SHOULD BE EMPTY ON BROWSER OPEN!!!! ?!?!?!?! I HAVE ADDED NOTHING TO SESSION YET*/
var_dump($_SESSION);

To delete all data in the session:
$_SESSION = [];

Related

Change a page for other users by what a admin selects in a form in PHP

I am stuck with a bit of a problem.
I have to build an application that shows everyone that visits the webserver a message wich sais if there is maintenance or a failure on the server.
Wich of the 2 messages gets shown to the user depends on what the admin sets it to. This is done by clicking one of two buttons on the admin page.
I got it working to the point where if I click one of the two buttons on the admin page it redirects me to the index page and shows the right text.
My problem is that the choice I made is a one time thing and will not be saved.
Meaning that if anyone else visits the site he/she gets to see an empty index page.
I am not allowed to use a database to store the choice i made, so I will have to store the variable somewhere else.
But I have no idea how to save a variable without a database.
My code goes something like this:
Index.php:
if(!session_id()) session_start();
$filename = $_SESSION['filename'];
$page = $_POST['sb'];
// // echo $page;
//
if($page == 'Maintenance')
{
require './pages/index.html';
}
elseif($page == 'Failure')
{
require './pages/fail.html';
}
Admin.php:
if(!session_id()) session_start();
//include("global.php");
$_SESSION['filename'] = $page;
require './functions.php';
$page = $_POST['sb'];
change();
Functions.php:
if(!session_id()) session_start();
$filename = "test";
if(!isset($_SESSION['filename'])) {
$_SESSION['filename'] = $filename;
}
echo '<div class="switch">' .
'<form method="POST" action="../index.php">' .
'<input class="button" type="submit" name="sb" value="Maintenance">' .
'<input class="button" type="submit" name="sb" value="Failure">' .
'</form>' .
'</div>';
}
I would recommend using a txt file as a place to store your data and retrieve it in the index file to display the correct page.
Posting "sb" to txt file on server:
<?php
if($_POST['sb'] != ""){
$file = fopen('sbstore.txt', 'w');
fwrite($file, $_POST['sb']);
fclose($file);
}
?>
Retrieving data from txt file on server:
<?php
if (filesize('sbstore.txt') != 0){
$txt_file = file_get_contents('sbstore.txt');
$sb = $txt_file;
} else {
$sb = "Default";
}
?>

Php redirect after successful login

I'm having an issue with a simple verification file, it doesn't redirect to index page after successful login.
Basically the login.php file has the html form for login, the form calls auth.php file which already has the login data and decides if your login and password is correct or not. Now it should redirect to index.php after successful login but it doesn't , instead it just cleans up the form in the login.php file and you keep trying , BUT if you refresh the page ( after successful login ) you get auto redirected to index page.
Fixed! changed the code to something even simpler than that.
if($logindata[$_POST["username"]]==$_POST["password"])
This bit doesn't look correct; maybe you were looking for:
if($logindata[$_POST["password"]]==$_POST["password"])
Sometimes headers does not work well for some reasons, instead try to use a simple html redirect like this:
<?php
$usernames = array("user1", "user2");
$passwords = array("pass1", "pass2");
$page = "index.php";
for($i=0;$i<count($usernames);$i++){
$logindata[$usernames[$i]]=$passwords[$i];
}
$found = 0;
for($i=0;$i<count($usernames);$i++) {
if ($usernames[$i] == $_POST["username"]) {
$found = 1;
}
}
if ($found == 0) {
$redirect_url = "./login.php?login_error=1"
}
if($logindata[$_POST["username"]]==$_POST["password"]) {
session_start();
$_SESSION["username"]=$_POST["username"];
$redirect_url = "./index.php"
}
else {
$redirect_url = "./login.php?login_error=2"
}
echo "<center><br><br><br><p>You will be redirected in about 2 seconds. If not, click this link: <a href='$redirect_url'>Back</a></p></center>";
?>
<html>
<head>
<meta http-equiv="refresh" content="2;url='<?php echo "$redirect_url"; ?>'/>
<title>Redirecting...</title>
</head>
</html>
<?php
exit;
?>
I presumed the redirect location is in the same folder of the php file. Adjust the var $redirect_url path of they aren't.

URL Redirecting issue does not redirect on server

I've fully functional website works fine on my site on my localhost wamp server but i upload the same file into the server on 1&1 the redirect does not work. the code is below
<?php require_once('../model/class.user.php'); ?>
<?php require_once('../model/class.person.php'); ?>
<?php require_once('../model/class.session.php'); ?>
<?php require_once('../model/class.loginrecord.php'); ?>
<?php require_once('../controller/general_functions.php'); ?>
<?php require_once('../controller/utility_functions.php'); ?>
<!DOCTYPE html>
<html lang="en">
<head>
if(isset($_POST['checkUser'])){
$usrnme = htmlspecialchars($_POST['un']);
$paswrd = htmlspecialchars($_POST['pwd']);
if(!empty($usrnme) && !empty($paswrd)){
//verify user credentials
$foundUser = User::verify(array($usrnme, $paswrd));
if($foundUser){ //if user found in DB
//$errors[] = "Username : found<br />";
$UID = $foundUser->id;
$userRole = $foundUser->role;
$userPersonID = $foundUser->person_id;//user_person_id has stored the reference to person's table
$ip = getenv('HTTP_CLIENT_IP')?:
getenv('HTTP_X_FORWARDED_FOR')?:
getenv('HTTP_X_FORWARDED')?:
getenv('HTTP_FORWARDED_FOR')?:
getenv('HTTP_FORWARDED')?:
getenv('REMOTE_ADDR')?: "UNKNOWN";
LoginRecord::save(array(null, $foundUser->id, getCurrentDateTime(), $ip));
$findPerson = Person::findByID($userPersonID);//find the user based on the
$userFN = Person::fullName($findPerson);//find the full name of the person
$session->setValues(md5('loginStatus'), encrypt('true'));
$session->setValues(md5('userID'), encrypt($UID));
$session->setValues(md5('userFullName'), encrypt($userFN));
if($userRole == ROLE_ADCMIN)
{
$session->setValues(md5('role'), encrypt(ROLE_ADCMIN));
redirectTO('admin/dashboard.php');
}
elseif ($userRole == ROLE_AGENT)
{
$session->setValues(md5('role'), encrypt(ROLE_AGENT));
redirectTO('agent/index.php');
}
elseif ($userRole == ROLE_OTHER)
{
redirectTO('superuser/index.php');
}
} else {
$errors[] = "Sorry Username/Password not valid <br />";
}//end if($foundUser)
} else {
$errors[] = "Text fields are empty.";
}
}
the function that redirect the page is below:
function redirectTO($url = null){
if($url != null){
header("Location:{$url}");
exit();
}
}
I've everything i could but it just does not work show blank page... can you please help me get out of this mess... do you have any idea?
Regards
use <?php ob_start(); ?> at the very start of the page and use <?php ob_end_flush(); ?> at the very end of the page.
It looks as though you are trying to redirect AFTER you have already outputted data. Headers must be sent before any output is sent to the browser.
Your HTML here:
<!DOCTYPE html>
<html lang="en">
<head>
is being outputted before your redirectTo function is called.
Also, you are missing an opening PHP tag after your HTML.
May be use only $url .. don't set $url=null
function redirectTO($url){
if($url != null){
header("Location:{$url}");
exit();
}
}
let me know if it works ..

Redirect page when user is verified

i have this code to verify if users have Administrator account to backoffice of my website, but if user don't have it don't redirect user to ..index.php. He stay in this page but no content is shown.
Code of verification
<?php
$Usuario = isset($_SESSION["Usuario"]) ? $_SESSION["Usuario"]: '';
$Rank = isset($_SESSION['Rank']) ? $_SESSION['Rank'] : '';
if ($Usuario != '' && $Rank == 'Administrador'){
}
else
{
echo "<script>alert(\"Area Restrita\");</scrpit>";
header("Location: ../index.php");
}
?>
In this page, (header) i call this file to verify session.
<?php
session_start();
require_once "../config.php";
require "verificar.php";
?>
<div id="header">
<img src="img/logo.png">
</div>
header("Location: ../index.php"); is not going to stop the rest of the code from running - if you just want to redirect him you should die(); or exit; right after you send the Location header
The alert part before the Location header is also unnecessary because the browser will redirect the user before he'll be able to see the alert. and also it is forbidden to call header function after you sent something to the output (for example, like you did with echo)
Another thing that you should consider - is the security issues that raised from validating user solely by looking at values in the $_SESSION - this means - that if someone is logged - you are not able to log him out until the session expires
The better way is to keep some token in the $_SESSION and save the status of the user in the database - that way, you can change his status directly from the DB without relying on the session/changing code
Your index file:
<?php
session_start();
require_once "../config.php";
require "verificar.php";
?>
<div id="header">
<img src="img/logo.png">
</div>
Your verification file:
<?php
$Usuario = isset($_SESSION["Usuario"]) ? $_SESSION["Usuario"]: '';
$Rank = isset($_SESSION['Rank']) ? $_SESSION['Rank'] : '';
if ($Usuario != '' && $Rank == 'Administrador'){
// do some action for administrator
}
else
{
header("Location: ../index.php");
exit();
//echo "<script>alert(\"Area Restrita\");</scrpit>"; <-- you don't need this here
}
?>
Note, that I commented echo. You mustn't output anything before header. If you will output something (and you do in your example) you will get headers already sent error.
Your main mistake is you output something first and after that tried to redirect.
Anyway, I think better to use a bit another approach.
Form and form handler:
<?
$username = $_POST['username'];
$password = $_POST['password'];
// here is some query which will check if this user with this password exists and get the role of the user
// if exists $userExists = true; else $userExists = false;
if($userExists) {
$_SESSION['userLoggedIn'] = true;
if($role == 'administrator') {
$_SESSION['isAdministrator'] = true;
}
else
{
$_SESSION['isAdministrator'] = false;
}
header('Location: index.php');
exit(); // <-- don't forget this
}
else
{
// handler for bad user/password
}
?>
<form action='' method='post'>
<input type='text' name='username' />
<input type='password' name='password' />
</form>
Now, pages which are restricted will start from this code:
<?
$isAdministrator = $_SESSION['isAdministrator'];
if(!$isAdministrator) {
ban_ban_ban();
die('bye bye');
}
// content for administrator
?>
NOTE: This is just example, don't forget to add some check everywhere!!!!!11
But, as you wish :) Hope, this will help you.

html/php no cache but keep cookies

I have a simple login page but i am having trouble displaying the logged in page. When the form is submitted, the same login page is displayed. I will have to click refresh or F5 before i can see the logged in page. I tried the no-cache (meta tag) but my problem is that the cookies are also gone (i couldn't store state).
By the way, my login uses redirect. The form submit calls a different page doing the validation and then redirects back to the same page but supposedly with different content (login form should not be there anymore).
I believe this is basic but unfortunately couldn't find an answer elsewhere.
Thanks.
Update:
Here are some codes:
Login page has ExtJs Form with submit:
login.getForm().getEl().dom.action='bridge.php/login';
login.getForm().getEl().dom.submit();
bridge.php is a rest client to another server:
snippet:
<?php
//echo $HTTP_SERVER_VARS['PATH_INFO'];
require_once "RESTclient.php";
require_once "http_request.php";
$rest = new RESTclient();
$http_req = new httpRequest();
//$headers = $http_req->headers();
$headers = apache_request_headers();
foreach($headers as $key => $value) {
if($key != "Cookie" && $key != "Content-Type"){
unset($headers[$key]);
}
}
//$headers["Content-Type"] = "";
$inputs = array_merge($_GET, $_POST);
//$inputs = array_merge($inputs, $_);
$url = "http://another_server/rest_service_here";
$path = $HTTP_SERVER_VARS['PATH_INFO'];
$server = $url.$path;
$rest->createRequest("$server",$http_req->method(),$inputs);
$rest->addHeaders($headers);
$rest->setBody($http_req->body());
$rest->sendRequest();
// get the headers now
$responseheaders = $rest->getResponseHeaders();
$responsecookies = $rest->getResponseCookies();
if ($responseheaders != null) {
foreach ($responseheaders as $key => $value) {
header($key.': '.$value);
}
}
if ($responsecookies != null) {
foreach ($responsecookies as $key => $value) {
$name = $value['name'];
$val = $value['value'];
setcookie($name, $val);
}
}
if($path=='/login') {
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Logging in</title>
<meta HTTP-EQUIV="REFRESH" content="0; url=/new_index.php">
</HEAD>
<BODY>
Redirecting to homepage...
</BODY>
</HTML>
<?php
} else {
$output = $rest->getResponse();
//$output = $output." ".$http_req->method();
// start doing something about the output.
//echo $http_req->body();
//echo $http_req->raw();
echo $output;
//var_dump($headers);
}
?>
As long as you're doing the following...
Always set/delete the login cookie before you output anything
Always re-direct after you've set the cookie. Ideally this should be to a page with a different URL (even if it's only a different query string), but failing that one that isn't cached should work fine.
As soon as you re-direct (via a header('Location: ...'); call) end script processing via exit.
..then all should be well. That said, as #Jon says post some code and we can take a look.

Categories