PHP form validation: Where to plop the code

72 views Asked by At

I have the following form:

<!doctype html><html><head><link href="css/home.css" rel="stylesheet" type="text/css"></head><body><form>
        <?php
            if (isset($_REQUEST['email']))        
            {  
                $email = $_REQUEST['email'] ;
                $subject = "Email submission" ;
                $message = "Message body here" ;
                mail("[email protected]", $subject,
                     $message, "From:" . $email);
                     header('Location: /thanks.html');
            }     
        else
        {
            echo "<form method='post' action='index.php'> 
            Email: <br><input name='email' type='text'><br><br>   
            <input type='submit'>
            </form>";
        }
    ?>
    </form></body></html>

This works fine but recently submissions with blank email fields have started coming through. I've been trying to get the email field validated with 8 characters or more with this snippet before the form is allowed to be submitted:

if (strlen($input) < 8){ echo "Please enter a valid email";}

No matter where I put the code, the page returns a 500 internal error on load and nothing is displayed. I'm sure there's something elementary that I'm doing wrong and maybe I've been staring at the screen for too long but if someone can guide me as to how to get it functioning the way it should, that'd be great.

1

There are 1 answers

1
Alex On

Short answer: You're trying to access $input which is undefined due to your code mentioned in the question. try instead:

if (trim($_POST['mail']) == '') {return "Sorry, input mail is blank"; }

Strong solution:

Anyway even if you use such validations, you will still get spam mails or submission. You need to implant a captcha code and using a session token to ensure the human is posting forward your form, which maybe not a problem now, but dark cave in future.