Unsetting PHP session variable doesnt display error message - php

I am trying to display an error message when there is a username-password mismatch. I set a php session variable if username and password dont match. Then i header back to the same page, with an if conditioned php statement to display an error if the variable is set. But when i unset the variable after error display, there is no error displayed on the page.
I have seen similar problems mentioned in this forum. But i seem to be doing everything right as suggested in questions.. Please help me out...
This is part of my code flow...
<?php
ob_start();
session_start();
.
.
if ($result = $sth->fetch(PDO::FETCH_ASSOC)){
$_SESSION['admin_user'] = $result['id'];
header('Location: admin_user.php');
} else {
$_SESSION['user_found'] = 0;
header('Location: index.php');
}
.
.
//in html body
<?php
if (isset($_SESSION['user_found'])){
if($_SESSION['user_found'] == 0){
?>
<div>
<p class = "bg-danger text-danger">Username Password Mismatch</p>
</div>
<?php
unset($_SESSION['user_found']);
}
}
?>
Now, if unset is removed..it works fine. If it is there, there is no display of error message.

Try not reloading the same page.. remove the header redirect.
if ($result = $sth->fetch(PDO::FETCH_ASSOC)){
$_SESSION['admin_user'] = $result['id'];
header('Location: admin_user.php');
} else {
$_SESSION['user_found'] = 0;
//header('Location: index.php');
}

When I tried the your code, things seem to work fine. Something should be wrong with the code you've not mentioned here..
To troubleshoot the problem instead of
unset($_SESSION['user_found']);
try changing the value of the variable.. say
$_SESSION['user_found'] = -1;

Related

ERR_TOO_MANY_REDIRECTS in PHP

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();

My php script outputs a blank page

I have a php page that accepts and processes a form submission, the page displays normally when it is requested, however if the page is submitted and its form validation fails, the page suppose to be re-displayed with the form errors, but on page re-display, php displays a blank page when it reaches the error processing block. Here is the code that processes the validation errors:
<?php if(isset($errorLog) and is_array($errorLog)): ?>
<div class="alert alert-danger">
<?php $output = '';
if($errorLog['message'] == '') {
$output = "<ul class='error-list'>";
foreach($errorLog as $key => $value) {
if ($key != 'has_error_occured') {
$output .= "<li><strong>{html($key)}</strong>
<span>{html($value)} </span></li>";
}
}
$output .= "</ul>";
} else {
$msg = $errorLog['message'];
$output .= "<p>{html($msg)}</p>";
}
echo $output;
?>
</div>
<?php endif; ?>
and here is the code that processes the form submission
if(isset($_GET['transfer']) or
(isset($_POST['action']) and $_POST['action'] == TRANSFER)){
$transfer_type = $_GET['ttype'];
if(isset($_POST['action']) and
$_POST['action'] == TRANSFER){
//process money transfer.
$log = process_transfer();
if(isset($log) and is_array($log)){
if($log['has_error_occured']){
$_SESSION['error_log'] = $log;
//unset log
unset($log);
include_once $docRoot . '/users/temp/tranfer.html.php';
exit();
}else{
$_SESSION['transfer_msg'] = "Your international
transfer was processed successfully";
header('Location: ?summary');
}
}
//reload primary page.
header('Location: .');
}else{
include_once $docRoot . '/users/temp/tranfer.html.php';
exit();
}
}
Note:
I have tried passing the error array as a global variable as
you can see in the code snippet above.
I have also tried passing it in a session.
I also have tried using output buffering by appending the ob_start() at the beginning and ob_end_flush() at the end the form script.
I have also added error_reporting(-1); ini_set('display_errors', true); at the start of the form script so as to know if the page encounters any error during processing, all to no avail.
I am using PhpStorm with XAMPP v3.2.1 for development on windows 7.
Please, any help as to the cause of this nightmare will be appreciated. Thanks.
If you wanna use $_GET and $_POST then better use $_REQUEST, it allows to access both $_GET and $_POST
not TRANSFER but it should be "TRANSFER"
if errorlog is session data then it should be
if(isset($_SESSION['errorLog']) and is_array($_SESSION['errorLog'])):
i didn't find any thing created by name message
if($errorLog['message'] == '')
why u used it, i think it must be 'has_error_occured'
I discovered the problem through the output of php_error_log and through the various suggestions in the comments above, the problem problem was that I didn't check if the $erroLog['message'] was set before accessing it. But shouldn't php have outputted a warning instead of resorting to such indeterminate option of not fully executing the rest of the document?

php message using sessions

I am try to develop flash message using sessions in php
suppose on successfully delete query I am setting
$_SESSION["msg"]="record deleted successfully";
header("location:index.php");
and I have the following script on all pages which checks if msg variable is available it echo its value as below
if(isset($_SESSION["msg"]) && !empty($_SESSION["msg"]))
{
$msg=$_SESSION["msg"];
echo "<div class='msgbox'>".$msg."</div>";
unset($_SESSION['msg']); //I have issue with this line.
}
if I comment
unset($_SESSION['msg']);
message is being displayed, but with this line message is not being displayed
what am I doing wrong, or any alternative.
You are saying that you have that script on every page. So my guess is that after you make header("location:index.php"); your code continues to run - your message is displayed and unset (you don't see it because of redirect to index.php). When you are redirected to index.php your message is already unset.
Try adding exit; after header("location:index.php");.
Edit: I will add two examples with one working and one not. To test you need access test page with following link - /index.php?delete=1
In this example you will never see message. Why? Because header function does not stop code execution. After you set your session variable and set your redirect your code continues to execute. That means your message is printed and variable unset too. When code finishes only than redirect is made. Page loads and nothing is printed because session variable was unset before redirect.
<?php
session_start();
// ... some code
if ($_GET['delete']==1) {
$_SESSION["msg"] = "record deleted successfully";
header("location: index.php");
}
// ... some code
if (isset($_SESSION["msg"]) && !empty($_SESSION["msg"])) {
$msg = $_SESSION["msg"];
echo "<div class='msgbox'>" . $msg . "</div>";
unset($_SESSION['msg']);
}
// ... some code
?>
But this code probably will work as you want. Note that I have added exit after header line.
You set your message, tell that you want redirect and tell to stop script execution. After redirect your message is printed and unset as you want.
<?php
session_start();
// ... some code
if ($_GET['delete']==1) {
$_SESSION["msg"] = "record deleted successfully";
header("location: index.php");
exit;
}
// ... some code
if (isset($_SESSION["msg"]) && !empty($_SESSION["msg"])) {
$msg = $_SESSION["msg"];
echo "<div class='msgbox'>" . $msg . "</div>";
unset($_SESSION['msg']);
}
// ... some code
?>
You clearly said that you have that code (message printing) on all pages. If your code is similar to my example than adding exit should fix your problem.
Another problem might be that you are doing more than one redirect.
You can simply set your session empty or null instead of unset it. Just do:
$_SESSION['msg']=NULL;
Or
$_SESSION['msg']="";

PHP:my session_variables shows when the page refresh

I know this is very simple thing but i am not aware of this. I have php code on same page for a signup form which have some session variables to be shown when any condition matches with the code.
The code structure is like this:
<?php
session_start();
if(isset($_POST['signup'])
{
if(condition)
{
$_SESSION['err1']="string";
}
else
{
$_SESSION['err2']="string";
}
}
?>
//HTML form
<?php if(isset($_SESSION['err1']) {?>
<li><?php echo $_SESSION['err1'];}?></li>
<?php if(isset($_SESSION['err2']) {?>
<li><?php echo $_SESSION['err2'];}?></li>
//rest of the form
I have more block of if-else in my code. Initially, when an condition is matched, the session message is shown. But as soon as the page refresh an another session message is shown along with previous session message.
Is this correct way of coding with forms? Because i want to show error messages inside the html form.
That's maybe because you do not empty your session variable.
Between 2 HTTP request, the session is kept on the server (juste reloading at each request).
So, if you are putting a message on $_SESSION['error1'] for the first call, it will show it. Then, on the second load, if you are putting a message on $_SESSION['error2'], you will also have the message of error1 because the session keep your data.
After showing the form, you should empty all your session messages
Simply unset your session variable after you echo.
<li><?php echo $_SESSION['err1'];} unset($_SESSION['err1']); ?></li>
This is really a bad example that use session to echo errors.
what i do many times at the starting of my php.
$errors = array(); // make a empty array errors before the conditional statements
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['Submit'])) {
//handle your POST variable
if(condition1){
$errors[] = "some error";
}
if(condition2) {
$errors[] = "some another error";
}
//more conditions
if (!empty($errors)) {
//process your form data if there is no errro
} else {
//display back your form along with Errors
if(isset($errors) && !empty($errors)) {
foreach($errors as $error) {
echo "<p class = 'error'>" . $error . "</p>";
}
}
<form action = "" method = "POST">
//your form elements
</form>
}
}
in first line of the php page, u can write
you can try any of the three lines between if condition
if(isset($_SESSION))
{
unset($_SESSION);
unregister($_SESSION['variable-name']) // try this also
session_destroy(); //try this also
}

Good error flagging | PHP

For everyone that was thinking of the error_reporting() function, then it isn't, what I need is whenever a MySQL query has been done, and the statement has like
if($result)
{
echo "Yes, it was fine... bla bla";
}
else
{
echo "Obviously, the echo'ing will show in a white page with the text ONLY...";
}
Whenever statements have been true or false, I want the error to be appeared when redirected with the header() function and echo the error reporting in a div somewhere on the page.
Basically something like this:
$error = '';
This part appears inside the div tags
<div><?php echo $error; ?></div>
So the error part will be echoed when redirected with the header()
if($result)
{
$error = "Yes, it was fine... bla bla";
header("Location: url");
}
else
{
$error = "Something wrong happened...";
header("Location: url");
}
But that just doesn't work :(
You can use $_SESSION superglobal.
Sample code:
/* in mysql result checking */
$_SESSION["error"] = "Something wrong happened...";
/* in div tags */
if(!empty($_SESSION["error"])) {
echo $_SESSION["error"];
$_SESSION["error"] = "";
}
I also think that you need to call session_start() in the start of your script, if that wasn't done before.
Best regards,
T.
That won't work because error is not declared in url. You're just discarding (unsetting) the error variable when you send the location header.
You should make your own error codes, for example:
0001 = ok
0002 = DB_error
...
and send them trough GET variables, catch'em in url and parse them.
header('Location: url?error='.urlencode($error));

Categories