PHP Form Validation

Trew

New Member
I'm trying to create my first php script for a contact form and it is always showing the $errors variable even when i first load the page. How can i make it so the $errors variable is only populated and displayed, after a user tried to submit the form without filling in the required fields?\[code\]<form method="post" action="<?php $_SERVER['PHP_SELF']; ?>"> <?php if(!is_null($errors)) { echo "<h3>$errors</h3>"; } ?> <label for="Name">Name</label><em>(Required)</em> <input type="text" name="Name"/> <label for="Email">Email</label><em>(Required)</em> <input type="text" name="Email"/> <label for="Website">Website</label> <input type="text" name="Website"/> <label for="Message">Message</label><em>(Required)</em> <textarea name="Message"></textarea> <button id="submit" type="submit" value="http://stackoverflow.com/questions/3615167/submit"name="submit">Submit</button> <input type="hidden" name="Submit" /></form>\[/code\]and my script to handle the form\[code\]$errors = null;if(isset($_POST['submit'])) { if(!empty($_POST['Name']) && !empty($_POST['Email']) && !empty($_POST['Message'])) { $name = $_POST['Name']; $email = $_POST['Email']; $website = $_POST['Website']; $message = $_POST['Message']; //strip any html tags and slashes off of the fields $nameClean = strip_tags($name); $emailClean = strip_tags($email); $websiteClean = strip_tags($website); $messageClean = strip_tags($message); $messageCleanAndStripped = stripslashes($messageClean); }} else { $errors = "Please fill in the required fields";}\[/code\]
 
Back
Top