can't pass a $variable in a header() - php

I'm trying to modify a login script from a File Manager I currently use on my website.
Currently, when the login attempt fails (wrong password, blank fields, etc..) an error message is stored in the $errors variable, and at the end of the script a function will include a file.php with $errors as a parameter, so the error message can be echo'd.
What I am unsuccessfully trying to do is replacing this include + parameter($errors) by a header() + $errors.
I have been around every thread dealing with this but so far I haven't found anything that works for me, I need some help : /
Here is the part of the login script that store the error message in $errors and include the file.php :
if(!isset($_SESSION['simple_auth']['username']) || isset($_GET["login"])) {
session_destroy();
session_start();
if(isset($_POST["submit"])) {
$user = gg::getUser($_POST['username']);
if (isset($user['permissions']) && !strstr($user['permissions'], 'r')
|| ($user['username'] == 'guest' && ggconf::get('allow_guests') == false)){
$errors = "Access Forbidden";
gg::writeLog('auth bad - not activated');
}
if (!isset($_POST['username']) || !isset($_POST['password']) || $_POST['username'] == '' || $_POST['password'] == ''){
$errors = "Enter username and password.";
gg::writeLog('auth bad - blank fields');
}
if (isset($user['akey']) && $user['akey'] != '' && strpos($user['akey'], 'otp-') === false){
$errors = "Please open your email and click on the link to proceed.";
gg::writeLog('auth bad - not activated');
}
if(!$errors && $user['username'] == $_POST['username'] && gg::checkPassword($_POST['password'], $user['password'])){
$this->loginUser($user);
}
if(!$errors){
$errors = "Wrong username or password.";
gg::writeLog('auth bad - wrong username or password');
sleep(1);
}
}
if (!isset($_GET["login"]) && ggconf::get('allow_guests') == true){
$user = gg::getUser('guest');
if($user){
$this->loginUser($user);
}
// reload
header('Location: '.ggconf::get('base_url'));
die;
}
gg::display("login.php", array('errors' => $errors));
exit;
}
As you see at the end of this code is the gg::display function that will include the file and its parameter, the function gg::display is the following :
/* DISPLAY VIEWS CONTROLLER */
public static function display($view, $params = null){
require_once ggconf::get('base_path').$view;
}
And last, here is the code inside the file.php that will display the error :
<?php if (isset($params['errors'])):?>
<div class=>
<?php echo $params['errors'];?>
</div>
<?php endif;?>
How can I get my variable $errors with a header() instead of the require_once currently used in the script ?
I found a lot threads dealing with this but nothing worked for me, also note that I'm not very experienced in php yet.
Anyways, I'm thankful for the help, and any suggestions are welcome.
-apatik

If you are redirecting to another page you should store the parameters via php session
session_start(); // this should be on top
$_SESSION['errors'] = $errors; // Add this after writing an error
And here is the view
<?php if (isset($_SESSION['errors'])):?>
<div class=>
<?php echo $_SESSION['errors'];?>
</div>
<?php endif;?>

Related

Session seems to disappear after header redirect

I have four pages so far:
index.php
login.php
setsessionconfig.php
account.php
The background:
When I click the login w/ facebook button from the index it takes me to login.php which if the user is already registered with the site it doesn't go through the facebook website it just continues. Login.php pulls the neccessary information for the session then header redirects to setsessionconfig.php which has the code below:
login.php has a 5 second delay for loading visual then redirects to ...
header( "refresh:5;url=".URLBASE."/setsessionconfig.php?uid=".$uid."&email=".$email );
setsessionconfig.php
$uid = isset($_GET['uid']) ? $_GET['uid'] : "";
$email = isset($_GET['email']) ? $_GET['email'] : "";
if( $uid != "" && $email != "") {
session_start();
$_SESSION[SESSION_UID] = $uid;
$_SESSION[SESSION_EMAIL] = $email;
$_SESSION[SESSION_IS_LOGGEDIN] = 1;
header("Location: account");
}
The Problem
When setsessionconfig.php redirects to account.php it checks to see if the users is logged in via the SESSION_UID global variable then displays the user information OR it displays the "you are not logged in" text. No matter what I do I think the header redirect to account.php is destroying session variables.
I even checked to see if the session was available with the following code in account.php.
function is_session_started()
{
if ( php_sapi_name() !== 'cli' ) {
if ( version_compare(phpversion(), '5.4.0', '>=') ) {
return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
} else {
return session_id() === '' ? FALSE : TRUE;
}
}
return FALSE;
}
if ( is_session_started() === FALSE )
echo "<script>console.log('FALSE');</script>";
else
echo "<script>console.log('TRUE - ".session_id()."');</script>";
Unfortunately that part actually returns the TRUE and the session ID... So I am sort of stuck because I have never had this issue with sessions before...
try using exit(); after the header
Since the function is_session_started, returned TRUE and also returned the session ID, obviously the session ID is passed properly.
I hope the account.php code looks something like this
<?php
session_start();
if (! empty($_SESSION['SESSION_UID']))
{
?>
your code here
<?php
}
else
{
echo 'You are not logged in.';
}
?>
Edit :
Try
$_SESSION['SESSION_UID'] = $uid;
$_SESSION['SESSION_EMAIL'] = $email;
$_SESSION['SESSION_IS_LOGGEDIN'] = 1;

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.

php custom error message shown incorrectly

i'm working on a php assignment for log in function using .txt file instead of db, but i'm facing with some sort of problem here. supposedly the "invalid email or password" to be shown after a non exist details key in, but when the page load, the msg showed by default, below is my code
<?php
$lines= file("customers.txt");
$matchFound=false;
$errmsg = 'Invalid email or password';
for($i=0;$i<count($lines);$i++)
{
if ($i!=0)
{
$line=trim($lines[$i]);
$cells=explode("\t",$line);
$_SESSION['email'] = isset($_POST['email'])? $_POST['email'] : null;
$_SESSION['password'] = isset($_POST['password']) ? $_POST['password'] : null;
if ($_SESSION['email']==$cells[2] && $_SESSION['password']==$cells[3])
{
$matchFound=true;
break;
}
}
}
if ($matchFound == true)
{
header('Location: login2.php');
}
else
{
echo $errmsg;
}
?>
This is because you're not checking if the user submitted the form input correctly. The value of $matchFound is FALSE by default, and the error message will always be displayed when the script is ran.
Specify a name attribute for your form submit button, and then add an if block to make sure the form was correctly submitted:
if (isset( $_POST['submitButton'] )) {
# code...
}
That way, the code inside the if block won't be run if the user input wasn't received and you could avoid the error being displayed every time you load the page.
Also, you're missing the session_start() statement at the top of your script. This is required if you want the sessions to work properly.
Try:
if ($matchFound == true)
{
header('Location: login2.php');
}
else if(isset($_POST['email']))
{
echo $errmsg;
}
Also you need session_start to use $_SESSION array

Page should show exist instead of blank page

I made login.php file by following video tutorial and I am trying to make so that the page will show exist instead of blank page. I know that user exists because I made user with my name on phpMyAdmin.
Her is the code
<?php
include 'core/init.php';
if (user_exists('Denis') === true) {
echo 'exists';
}
die();
if(empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) === true || empty($password) === true) {
$errors[] = 'You need to enter a username and password';
} else if (user_exists($username) === false) {
$errors[] = 'We can\'t find that username. Have you registered?';
}
}
?>
Init.php
<?php
session_start();
error_reporting(0);
require 'database/connect.php';
require 'functions/general.php';
require 'functions/users.php';
$errors = array();
?>
you are calling the die() function at line 7
this function terminates the running script
Clearly user_exists('Denis') is returning false, since it's getting past the echo 'exists'; line and hitting the die() call.
Depending on how you are returning your boolean, you might try two "==" signs rather than three. It might not be able to type cast.
You can try:
if (user_exists('Denis')) {
echo 'exists';
}
As long as user_exists('Denis') evaluates to true (i.e. is not empty or 0), you will "exists" will be echoed.
If that doesn't work, try to figure out why user_exists() is getting a falsy value. There may be something wrong with the logic to check if a user exists.

php redirection not working

Ive got this register script that puts the information into a mysql database. now it all works fine and when someone does something wrong its says the error (e.g. "Username not defined")
but when it goes wrong it does not look very good because it just displays the message on an empty page, so i thought i would make it redirect to the form page and display the message there.
here is the working script
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$password = $_POST['password'];
$username = $_POST['username'];
$errors = array();
if(!$username) {
$errors[] = "Username is not defined";
}
if(!$password) {
$errors[] = "Password is not defined";
}
and it continues.
now i just thought i could do this
$errors = array();
if(!$username) {
$errors[] = header( 'Location: http://localhost/muiltabledistractions/#!/page_register_error-Username-is-not-defined' ) ;
}
if(!$password) {
$errors[] = "Password is not defined";
}
but no, all it does is ignore it.
could someone please help me
please feel free to ask for more of the script if you need it
many thanks connor
You cannot wrap a header in a array like that.
You just call the function, then it redirects.
header( 'Location: http://localhost/muiltabledistractions/#!/page_register_error-Username-is-not-defined' ) ;
it does not look very good because it just displays the message on an empty page,
What's the problem?
Why not to show the form again? with fields already filled.
This is going to be a user-friendly interface.
Just include your form in the same page with fields populated.
That's more common way than your redirects to blank form.
This is called POST/Redirect/GET pattern and here goes a short example of it:
the code
<?
if ($_SERVER['REQUEST_METHOD']=='POST') {
$err = array();
//performing all validations and raising corresponding errors
if (empty($_POST['name']) $err[] = "Username field is required";
if (empty($_POST['text']) $err[] = "Comments field is required";
if (!$err) {
// if no errors - saving data
// and then redirect:
header("Location: ".$_SERVER['PHP_SELF']);
exit;
} else {
// all field values should be escaped according to HTML standard
foreach ($_POST as $key => $val) {
$form[$key] = htmlspecialchars($val);
}
} else {
$form['name'] = $form['comments'] = '';
}
include 'form.tpl.php';
?>
the template
<? if ($err): ?>
<? foreach($err as $e): ?>
<div class="err"><?=$e?></div>
<? endforeach ?>
<? endif ?>
<form>
<input type="text" name="name" value="<?=$form['name']?>">
<textarea name="comments"><?=$form['comments']?></textarea>
<input type="submit">
</form>
You are placing the return value of the header function in an array, then continuing with your page execution.
If you don't care about anything that would normally happen below that redirection, which I believe is what you're implying, you should just set the header and then immediately exit. Do not try to place the return value of the header function into the errors array like that, as there's no point.
if(!$username) {
header('Location: http://localhost/muiltabledistractions/#!/page_register_error-Username-is-not-defined');
exit;
}
I don't if this is the problem, but it's important to include the status code in header too. Like:
header("Location: /foo.php",TRUE,302);
307 for Temporary Redirect, 302 for permanently moved. Chrome, a while ago, didn't accepted headers redirect without status code (i don't know nowadays).
try this after filling your error array:
if (count($errors) > 0)
{
header( 'Location: http://localhost/muiltabledistractions/#!/page_register_error-Username-is-not-defined' );
exit;
}
Keep in mind there should be no html output before this part!

Categories