Alei
Alei

Reputation: 51

How to display error messages on redirect?

It's worth noting I'm new to php. I would like to have an answer in php as well (if possible).

Here's what I'm trying to achieve: I want to redirect the user if any errors I check for are found to a html/php form (that the user see's first where inputs are previously created) with custom error messages that come from a file separate to the html/php form.

Details: The User see's the HTML/PHP form first where they enter names in a csv format. After they click create, the names are processed in another file of just php where the names are checked for errors and other such things. If an error is found I want the User to be redirected to the HTML/PHP form where they can fix the errors and whatever corresponding error messages are displayed. Once they fix the names the User can click the 'create user' button and processed again (without errors hopefully) and upon completion, redirect user to a page where names and such things are displayed. The redirect happens after the headers are sent. From what I've read this isn't the best thing but, for now, it'll do for me.

Code For HTML/PHP form:

<!DOCTYPE HTML>
<HTML>
    <head>
        <title>PHP FORM</title>
    </head> 
    <body>
<form method="post" action="processForm.php">

    Name: <input type="text" name="names" required = "required"><br>
    <input type="submit" value="Create Users" onclick="formInputNames"><br>

    Activate: <input type="checkbox" name="activate">
</form>
<?php
// include 'processForm.php';
// errorCheck($fullname,$nameSplit,$formInputNames);
?>
    </body>
    </html>

I tried messing around with 'include' but it doesn't seem to do anything, however, I kept it here to help illustrate what I'm trying to achieve.

Code For Process:

$formInputNames = $_POST['names'];

$active = (isset($_POST['activate'])) ? $_POST['activate'] : false;
//checks if activate checkbox is being used
$email = '@grabby.com';
echo "<br>";
echo "<br>";

$fullnames = explode(", ", $_POST['names']);

if ($active == true) {
    $active = '1';
    //sets activate checkbox to '1' if it has been selected
}
/*----------------------Function to Insert User---------------------------*/
         A Function is here to place names and other fields in database.
/*-------------------------End Function to Insert User--------------------*/

/*-----------------------Function for Errors---------------------*/

function errorCheck($fullname,$nameSplit,$formInputNames){
    if ($formInputNames == empty($fullname)){
        echo 'Error: Name Missing Here: '.$fullname.'<br><br>';
        redirect('form.php');
    }
    elseif ($formInputNames == empty($nameSplit[0])) {
        echo 'Error: First Name Missing in: '.$fullname.'<br><br>';
        redirect('form.php');
    }
    elseif ($formInputNames == empty($nameSplit[1])) {
        echo 'Error: Last Name Missing in: '.$fullname.'<br><br>';
        redirect('form.php');
    }
    elseif (preg_match('/[^A-Za-z, ]/', $fullname)) {
        echo 'Error: Found Illegal Character in: '.$fullname.'<br><br>';
        redirect('form.php');
    }
}

/*-----------------------------End Function for Errors------------------------*/

/*--------------------------Function for Redirect-------------------------*/

function redirect($url){
    $string = '<script type="text/javascript">';
    $string .= 'window.location = "' .$url. '"';
    $string .= '</script>';

    echo $string;
}

/*-------------------------End Function for Redirect-----------------------*/

//  Connect to database
     I connect to the database here

foreach ($fullnames as $fullname) {
    $nameSplit = explode(" ", $fullname);

            //opens the database
I Open the database here

        errorCheck($fullname,$nameSplit,$formInputNames);

        $firstName = $nameSplit[0];//sets first part of name to first name
        $lastName = $nameSplit[1];//sets second part of name to last name
        $emailUser = $nameSplit[0].$email;//sets first part and adds email extension

        newUser($firstName,$lastName,$emailUser,$active,$conn);

        redirect('viewAll.php');
        //echo '<META HTTP-EQUIV="Refresh" Content="0; URL=viewAll.php">';
//if you try this code out, you can see my redirect to viewAll doesn't work when errors are found...I would appreciate help fixing this as well. My immediate fix is using the line under it but I don't like it.
}

All the research I've done hasn't gotten me far. I understand that sending the headers isn't good practice. I looked at ob_open (php function-I think it was called) and couldn't figure out how to properly use it. I couldn't find a question on here that satisfied the conditions I'm trying to meet either.

Any help is certainly appreciated.Thank You

EDIT: This is not a duplicate of 'Passing error messages in PHP'.
-------While the idea is similar, they are 'Passing error messages in PHP' before the headers are sent. Therefore it's not the same.

Upvotes: 2

Views: 6439

Answers (3)

Josh J
Josh J

Reputation: 6893

An HTTP Redirect causes a new HTTP request. Since php is stateless, it cannot natively support remembering a message to display to a specific user in another request. In order to get around this limitation, you would need to use a stateful storage mechanism (session or cookies), or pass the error message along to the next request via query string parameter. The usual way this is handled is by using session storage to save flash messages.

Here is a library that can make it a bit easier for you https://github.com/plasticbrain/PhpFlashMessages

Upvotes: 1

Parveen Shukhala
Parveen Shukhala

Reputation: 243

Set session of error and display on the page on which you are redirecting

Upvotes: 0

Geoff Atkins
Geoff Atkins

Reputation: 1703

Store the error in a session and echo it on the destination page.

Put session_start() at the top of the code of the form.php page. Like this:

<?php session_start(); ?>
<!DOCTYPE HTML>
<HTML>
    <head>

Then replace the echo error with:

$_SESSION['error'] = 'Error: Name Missing Here: '.$fullname.'<br><br>';
redirect('form.php');

Use this in your conditions instead of the echo. Then in the form.php page:

if (isset($_SESSION['error'])) {
  echo $_SESSION['error'];
  unset($_SESSION['error']);
}

The unset makes sure that the error is repeated.

Upvotes: 3

Related Questions