Php Form Validation (don't Know How To Split It In Two Different Pages)
I am working on a contact form in PHP. My knowledge of PHP is pretty much non-existent. I've tried for a while to get a HTML form to submit to PHP form to have its text fields val
Solution 1:
Here is a basic form send example. This can all be on one page. PHP at the top, before all the html loads to browser, <form>
html down anywhere in the <body>
of the html page:
EDIT: I have updated the code to include your PHP Emailer.
<?phpclassEmailEngine{
publicstaticfunctionSend($settings = false)
{
$email = (!empty($settings['email']))? $settings['email']:false;
$first_name = (!empty($settings['first-name']))? $settings['first-name']:false;
$last_name = (!empty($settings['last-name']))? $settings['last-name']:false;
$message = (!empty($settings['message']))? $settings['message']:false;
$alt_message = (!empty($settings['alt_message']))? $settings['alt_message']:'To view the message, please use an HTML compatible email viewer!';
require(__DIR__.'/PHPMailerAutoload.php');
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP$mail->Host = 'host_specified'; // Specify main and backup SMTP servers$mail->SMTPAuth = true; // Enable SMTP authentication$mail->Username = 'email_specified'; // SMTP username$mail->Password = 'password_specified'; // SMTP password$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted$mail->Port = 587;
$mail->addReplyTo( $email, $first_name );
$mail->addAddress( $email, $first_name );
$mail->addAddress( 'email_specified', 'Staff' );
$mail->From = 'email_specified';
$mail->FromName = 'Staff';
$mail->isHTML(true); // Set email format to HTML$mail->Subject = 'Hotel Room Request';
$mail->Body = $message;
$mail->AltBody = $alt_message;
return$mail->send();
}
}
// Just make an error reporting function to return errorsfunctionerror_report($val = false)
{
$array["first-name"] = "First name is required";
$array["last-name"] = "Last name is required";
$array["email"] = "Email is required";
$array["message"] = "A message is required";
return (isset($array[$val]))? $array[$val] :false;
}
// Sanitize. I add false so no error is thrown if not setfunctionsanitize_vals($data = false)
{
if(empty($data))
returnfalse;
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return$data;
}
// If a value is posted (any will do from your form) process the rest of the $_POSTif(isset($_POST["first-name"])) {
// Just loop through the $_POST instead of doing all the manual if/else...foreach($_POSTas$key => $value) {
// This specifically processes your email addressif(($key == 'email')) {
// If not valid email, send to errorsif(!filter_var($value,FILTER_VALIDATE_EMAIL))
$errors[$key] = error_report('email');
else$payload[$key] = $value;
}
// This processes the restelse {
$value = sanitize_vals($value);
// Checks for emptyif(empty($value))
$errors[$key] = error_report($key);
else$payload[$key] = $value;
}
}
// If all is good and no errors set, send the emailif(!isset($errors)) {
// SEND MAIL HERE.$page = (EmailEngine::Send($payload))? "Result" : "Error";
header("Location: url/contact{$page}.html");
exit;
}
}
?><formclass="ui form"method="post"action="<?phpecho htmlspecialchars($_SERVER["PHP_SELF"]);?>"><divclass="field"><label>First Name</label><inputname="first-name"id="first-name"placeholder="First Name"type="text"value="<?phpif(!empty($_POST['first-name'])) echo htmlspecialchars($_POST['first-name'],ENT_QUOTES);?>" /><spanclass="error">* <?phpif(!empty($errors['first-name'])) echo$errors['first-name'];?></span></div><divclass="field"><label>Last Name</label><inputname="last-name"id="last-name"placeholder="Last Name"type="text"value="<?phpif(!empty($_POST['last-name'])) echo htmlspecialchars($_POST['last-name'],ENT_QUOTES);?>" /><spanclass="error">* <?phpif(!empty($errors['last-name'])) echo$errors['last-name'];?></span></div><divclass="field"><label>Email</label><inputname="email"id="email"placeholder="Email"type="email"value="<?phpif(!empty($_POST['email'])) echo preg_replace('/[^0-9a-zA-Z\@\.\_\-]/',"",$_POST['email']);?>" /><spanclass="error">* <?phpif(!empty($errors['email'])) echo$errors['email'];?></span></div><divclass="field"><label>Message</label><textarearows="2"placeholder="Please type in your message"name="message"id="message"><?phpif(!empty($_POST['message'])) echo htmlspecialchars($_POST['message'],ENT_QUOTES);?></textarea><spanclass="error">* <?phpif(!empty($errors['message'])) echo$errors['message'];?></span></div><buttonclass="ui button"type="submit">Submit</button></form>
Solution 2:
<?php
session_start(); //allows use of session variablesif ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!isset($_POST["first-name"])) {
$firstNameErr = "First name is required";
} else {
$first_name = test_input($_POST["first-name"]);
}
if (!isset($_POST["last-name"])) {
$lastNameErr = "Last name is required";
} else {
$last_name = test_input($_POST["last-name"]);
}
if (!isset($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (!isset($_POST["message"])) {
$messageErr = "Message is required";
} else {
$message = test_input($_POST["message"]);
}
if(isset($first_name) && isset($last_name) && isset($email) && isset($message))
{
$_SESSION['first_name'] = $first_name;
$_SESSION['last_name'] = $last_name;
$_SESSION['email'] = $email;
$_SESSION['message'] = $message;
header("Location: php_mailer_form.php");
}
}
functiontest_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return$data;
}
?><formclass="ui form"method="post"action="<?phpecho htmlspecialchars($_SERVER["PHP_SELF"]);?>"><divclass="field"><label>First Name</label><inputname="first-name"id="first-name"placeholder="First Name"type="text"><?phpif(isset($firstNameErr)) print ('<span class="error">* ' . $firstNameErr . '</span>'); ?></div><divclass="field"><label>Last Name</label><inputname="last-name"id="last-name"placeholder="Last Name"type="text"><?phpif(isset($lastNameErr)) print ('<span class="error">* ' . $lastNameErr . '</span>'); ?></div><divclass="field"><label>Email</label><inputname="email"id="email"placeholder="Email"type="email"><?phpif(isset($emailErr)) print ('<span class="error">* ' . $emailErr . '</span>'); ?></div><divclass="field"><label>Message</label><textarearows="2"placeholder="Please type in your message"name="message"id="message"></textarea><?phpif(isset($messageErr)) print ('<span class="error">* ' . $messageErr . '</span>'); ?></div><buttonclass="ui button"type="submit">Submit</button></form>
Now in your other page, to access the variables, simply call "session_start();" at the top of the page as we did here, then use call "$_SESSION['message']" to get the value of message. Does this answer your question? Also note, I edited the html so that the error message div only prints if the error variable was set.
Post a Comment for "Php Form Validation (don't Know How To Split It In Two Different Pages)"