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.
<?php
class EmailEngine
{
public static function Send($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 errors
function error_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 set
function sanitize_vals($data = false)
{
if(empty($data))
return false;
$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 $_POST
if(isset($_POST["first-name"])) {
// Just loop through the $_POST instead of doing all the manual if/else...
foreach($_POST as $key => $value) {
// This specifically processes your email address
if(($key == 'email')) {
// If not valid email, send to errors
if(!filter_var($value,FILTER_VALIDATE_EMAIL))
$errors[$key] = error_report('email');
else
$payload[$key] = $value;
}
// This processes the rest
else {
$value = sanitize_vals($value);
// Checks for empty
if(empty($value))
$errors[$key] = error_report($key);
else
$payload[$key] = $value;
}
}
// If all is good and no errors set, send the email
if(!isset($errors)) {
// SEND MAIL HERE.
$page = (EmailEngine::Send($payload))? "Result" : "Error";
header("Location: url/contact{$page}.html");
exit;
}
}
?>
<form class="ui form" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="field">
<label>First Name</label>
<input name="first-name" id="first-name" placeholder="First Name" type="text" value="<?php if(!empty($_POST['first-name'])) echo htmlspecialchars($_POST['first-name'],ENT_QUOTES);?>" />
<span class="error">* <?php if(!empty($errors['first-name'])) echo $errors['first-name'];?></span> </div>
<div class="field">
<label>Last Name</label>
<input name="last-name" id="last-name" placeholder="Last Name" type="text" value="<?php if(!empty($_POST['last-name'])) echo htmlspecialchars($_POST['last-name'],ENT_QUOTES);?>" />
<span class="error">* <?php if(!empty($errors['last-name'])) echo $errors['last-name'];?></span> </div>
<div class="field">
<label>Email</label>
<input name="email" id="email" placeholder="Email" type="email" value="<?php if(!empty($_POST['email'])) echo preg_replace('/[^0-9a-zA-Z\@\.\_\-]/',"",$_POST['email']);?>" />
<span class="error">* <?php if(!empty($errors['email'])) echo $errors['email'];?></span> </div>
<div class="field">
<label>Message</label>
<textarea rows="2" placeholder="Please type in your message" name="message" id="message"><?php if(!empty($_POST['message'])) echo htmlspecialchars($_POST['message'],ENT_QUOTES);?></textarea>
<span class="error">* <?php if(!empty($errors['message'])) echo $errors['message'];?></span> </div>
<button class="ui button" type="submit">Submit</button>
</form>
Solution 2:
<?php
session_start(); //allows use of session variables
if ($_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");
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form class="ui form" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="field">
<label>First Name</label>
<input name="first-name" id="first-name" placeholder="First Name" type="text">
<?php if(isset($firstNameErr)) print ('<span class="error">* ' . $firstNameErr . '</span>'); ?>
</div>
<div class="field">
<label>Last Name</label>
<input name="last-name" id="last-name" placeholder="Last Name" type="text">
<?php if(isset($lastNameErr)) print ('<span class="error">* ' . $lastNameErr . '</span>'); ?>
</div>
<div class="field">
<label>Email</label>
<input name="email" id="email" placeholder="Email" type="email">
<?php if(isset($emailErr)) print ('<span class="error">* ' . $emailErr . '</span>'); ?>
</div>
<div class="field">
<label>Message</label>
<textarea rows="2" placeholder="Please type in your message" name="message" id="message"></textarea>
<?php if(isset($messageErr)) print ('<span class="error">* ' . $messageErr . '</span>'); ?>
</div>
<button class="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)"