PHP - Redisplay forms with valid values in fields and error messages where validation fails

10,989

Try using a separate variable for errors, and not output error messages to the input field.

You could use global variables for this, but I'm not fond of them.

login.php

<?php 
$firstname = '';
$password  = '';
$username  = '';
$emailadd  = '';
$response  = '';
include_once('loginprocess.php');
include_once('includes/header.php);
//Header stuff
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8");?>" method="post">
    <fieldset>
        <p>Please enter your username and password</p>
    <legend>Login</legend>
        <div>
        <label for="fullname">Full Name</label>
            <input type="text" name="fname" id="fullname" value="<?php echo $firstname ?>" />
        </div>
        <div>
         <label for="emailad">Email address</label>
         <input type="text" name="email" id="emailad" value="<?php echo $emailadd; ?>"/>
        </div>
        <div>
        <label for="username">Username (between 5-10 characters)</label>
        <input type="text" name="uname" id="username" value='<?php echo $username; ?>' />
        </div>
        <div>            
        <label for="password">Password (between 8-10 characters)</label>
        <input type="text" name="pw" id="password" value="<?php echo $password; ?>" />
        </div>
        <div>            
            <input type="submit" name="" value="Submit" />
        </div>
    </fieldset>
</form>
<?php
//Output the $reponse variable, if your validation functions run, then it
// will contain a string, if not, then it will be empty.
if($response != ''){
    print $response;         
}     
?>
//Footer stuff

loginprocess.php

//No need for header stuff, because it's loaded with login.php
if($_SERVER['REQUEST_METHOD'] == 'POST'){//Will only run if a post request was made.
    //Here we concatenate the return values of your validation functions.
    $response .= validate_fname();
    $response .= validate_email();
    $response .= validate_username();
    $response .= validate_pw();
}    
//...or footer stuff.

functions.php

function validate_fname() {
    //Note the use of global...
    global $firstname;
    if (!empty($_POST['fname']))    {
        $form_is_submitted = true;
        $trimmed = trim($_POST['fname']);
        if(strlen($trimmed)<=150  && preg_match('/\\s/', $trimmed)){
            $fname = htmlentities($_POST['fname']);
            //..and the setting of the global.
            $firstname = $fname;
            //Change all your 'echo' to 'return' in other functions.
            return"<p>You entered full name: $fname</p>";
        } else {
            return "<p>Full name must be no more than 150 characters and must contain one space.</p>";
        }
    }
}

I wouldn't suggest using includes for small things like forms, I find it tends to make a mess of things quite quickly. Keep all your 'display' code in one file, and use includes for functions (like you have) and split files only when the scope has changed. i.e your functions.php file deals with validation at the moment, but you might want to make a new include later that deals with the actual login or registration process.

Look at http://www.php.net/manual/en/language.operators.string.php to find out about concatenating.

Share:
10,989
naznaq
Author by

naznaq

Updated on August 29, 2022

Comments

  • naznaq
    naznaq over 1 year

    I have created a PHP form to take 4 text fields name, email, username and password and have set validation for these. I have my code currently validating correctly and displaying messages if the code validates or not. However, I would like for it to keep the correctly validated fields filled when submitted and those that failed validation to be empty with an error message detailing why.

    So far I have the following code, the main form.php:

        <?php
        $self = htmlentities($_SERVER['PHP_SELF']);
        ?>
        <form action="<?php echo $self; ?>" method="post">
            <fieldset>
            <p>You must fill in every field</p>
            <legend>Personal details</legend>
                <?php
                include 'personaldetails.php';
                include 'logindetails.php';
                ?>
                <div>            
                    <input type="submit" name="" value="Register" />
                </div>
            </fieldset>
        </form>
        <?php
        $firstname = validate_fname();
        $emailad = validate_email();
        $username = validate_username();
        $pword = validate_pw();
        ?>
    

    My functions.php code is as follows:

    <?php
    function validate_fname() {
        if (!empty($_POST['fname']))    {
            $form_is_submitted = true;
            $trimmed = trim($_POST['fname']);
            if  (strlen($trimmed)<=150  && preg_match('/\\s/', $trimmed))   {
                $fname = htmlentities($_POST['fname']);
                echo "<p>You entered full name: $fname</p>";
            }   else    {
                    echo "<p>Full name must be no more than 150 characters and must contain one space.</p>";
            }   }
            }
    
    function validate_email() {        
        if (!empty($_POST['email']))    {
            $form_is_submitted = true;
            $trimmed = trim($_POST['email']);
            if  (filter_var($trimmed, FILTER_VALIDATE_EMAIL))   {
                $clean['email'] = $_POST['email'];              
                $email = htmlentities($_POST['email']);
    
                echo "<p>You entered email: $email</p>";
            }   else    {
                    echo "<p>Incorrect email entered!</p>";
            }   }   
            }
    
    function validate_username() {
        if (!empty($_POST['uname']))        {
            $form_is_submitted = true;
            $trimmed = trim($_POST['uname']);
            if  (strlen($trimmed)>=5 && strlen($trimmed) <=10)  {
                $uname = htmlentities($_POST['uname']);
                echo "<p>You entered username: $uname</p>";
            }   else    {
                    echo "<p>Username must be of length 5-10 characters!</p>";
            }   }   
        }
    
    function validate_pw()  {
        if (!empty($_POST['pw']))   {
            $form_is_submitted = true;
            $trimmed = trim($_POST['pw']);
            if  (strlen($trimmed)>=8 && strlen($trimmed) <=10)  {           
                $pword = htmlentities($_POST['pw']);
                echo "<p>You entered password: $pword</p>";
            }   else    {
                    echo "<p>Password must be of length 8-10 characters!</p>";      
            }   }
        }
    ?>
    

    How can I ensure that when submit is pressed that it will retain valid inputs and empty invalid ones returning error messages.

    Preferably I would also like there to be an alternate else condition for initial if(!empty). I had this initially but found it would start the form with an error message.

    Lastly, how could I record the valid information into an external file to use for checking login details after signing up via this form?

    Any help is greatly appreciated.