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?
Related
So I am creating an application (new -ish to sessions) and have been trying to create a simple error handling statement using sessions.
To simplify things, let me describe the basics.
User enters query on page 1
User presses submit
Page 2 is loaded to check the value of the query
If the query is set, it is run and the result is displayed on page 3
If it is empty however, an error is caught, set and the user is redirected back to page 1
What I care about is the last step as I cannot get it to work for some reason.
Here is the code pertaining to the error:
Page 1s relevant code:
<?php
session_start();
$ERROR = $_SESSION['error'];
if($ERROR) {
echo $ERROR;
}
?>
And on page 2:
<?
session_start();
---------------- And as we go down the file a bit ----------------
if(trim($getQuery == "")){
$ERROR = "no search criteria entered";
$_SESSION['error'] = $ERROR;
if(!isset($_SESSION['error'])) {
die("the session error was not set for some reason");
}
$url = "localhost:8000/mysite"; //index.php is page 1 in this case so I just redirect to the parent directory as index is loaded by default obviously in that case
header("Location:" . $url);
}
?>
$getQuery is the value captured in the query box on page 1 and sent via the post method to page 2 as you may assume naturally.
But when I enter nothing in the query box and then send the query, the page refreshes (as it should when page 2 realises that the query is empty and header location reloads the page) but no error is shown, which it should considering I check on page 2 that it is set.
Any ideas?
Cheers,
-- SD
You have a typo in if(trim($getQuery == "")) { ... } it should be if(trim($getQuery) == "") { ... }, since you only want to trim the $getQuery variable, and not the whole condition. If you change this, then it will work.
Here's a minimum working example
<?php // 1.php
session_start();
$ERROR = $_SESSION['error'];
if($ERROR) {
echo $ERROR;
}
?>
<?php // 2.php
$getQuery = ""; // This is empty so it will redirect to 1 and show error message
session_start();
if(trim($getQuery) == ""){
$ERROR = "no search criteria entered";
$_SESSION['error'] = $ERROR;
if(!isset($_SESSION['error'])) {
die("the session error was not set for some reason");
}
$url = "1.php"; //index.php is page 1 in this case so I just redirect to the parent directory as index is loaded by default obviously in that case
header("Location:" . $url);
}
?>
Sometimes the browser redirect (your header("Location")) can be quicker than the server.
Just before the redirect you should put
session_write_close()
Just to make sure the session is written for next time.
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;
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']="";
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
}
I have added some server side validation to a dropdown box on one of my pages and when I did the page wouldn't work anymore. The code I added is as follows:
$show_form = true;
if (isset($_POST['submit'])) {
//All of the server side validations
$validator = new FormValidator();
$validator->addValidation("hospital_name","dontselect=000","No facility was chosen");
if ($validator->ValidateForm()) {
// All the variables from the submission form
$userid = $_SESSION['user_id'];
$hosp = $_POST['hospital_name'];
header('Location: ../site_hospital' . $hosp . '/hospital_submitform.php?usr=' . $userid . '&&hosp=' . $hosp);
exit;
$show_form = false;
} else {
echo "<B style='color:red;'>The following errors occurred:</B>";
$error_hash = $validator->GetErrors();
foreach ($error_hash as $inpname => $inp_err) {
echo "<p style='color:red;'>$inp_err</p>\n";
}
}}
if (true == $show_form) {
Through pure chance I added ob_start(); as part of my debugging to the beginning of the page and suddenly my code worked properly but I have no idea why and I was hoping the community could throw out an educated guess as to why. When the code stopped working it would not execute my header command above, the page would simply refresh and not change location, when I added ob_start(); to the top of the page the page redirected as planned. So the overall question is why would the page not direct using the header command without ob_start? I'm sure alot more detail and code is necessary for a definitive answer but I'm hoping someone has run into this before or has an educated guess that may lead me to my own answers. Thanks for any insight.
it's because you were writing to the output stream and preventing the header from working properly. once you started buffering other outputs, you removed the obstacle to the header's operation.