In web development, handling a HTML form is perhaps the most frequently process.
A HTML form consists of HTML input elements like text fields, text areas, checkboxes, radio buttons, etc. that get some data from the user and then submit it to the web server and process them.
An HTML form use the <form> tag
<form action="script.php" method="post"> </form>
The method specifies how the web browser sends the form data. You can use POST or GET.
The action specifies where the data is submitted to.
| GET | POST |
|---|---|
| sending small amounts of data via URL | send large amounts of data |
get data from $_GET Or _REQUEST array |
get data from $_POST Or _REQUEST array |
| Request can be saved in the browser history | Request cannot be saved in the browser history |
| Don't use for sensitive data | Used for sensitive data |
contact.php (or contact.html)
<html>
<head>
<title>PHP Contact Form Demo</title>
</head>
<body>
<h2>PHP Contact Form Demo</h2>
<form method="POST" action="action.php">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
Message:<textarea rows="7" cols="25" name="message"></textarea>
</div>
<input type="submit" name="submit">
</form>
</body>
</html>
When the user submit the form, data will be sent to action.php through POST method.
In PHP, datas sent by POST are saved in the superglobal variable $_POST.
For example, we can read the name field value from the $_POST array as follows:
$_POST['name']
action.php
<?php
echo "name:".$_POST['name'];
echo "email:".$_POST['email'];
?>
action.php with html code
<!DOCTYPE html>
<html>
<head>
<title>Welcome <?php echo $_POST['name']; ?></title>
</head>
<body>
<p>Hello <?php echo $_POST['name'] ?>,</p>
<p><?php echo $_POST['email'] ?> is your email.</p>
</body>
</html>
We should always verify the data that users submit to the server in order to prevent malicious users who are trying to hack the site.
To ensure the correctness of the data, a proper validation should be done.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// process code
} else {
die('Invalid Request');
}
We can use function trim() to strip whitespace from the beginning and end of a string.
<?php $str = " Lautturi "; // Outputs: Lautturi echo trim($str);
name field in the form should not be empty and remove any illegal characters from it:<?php
if(!empty($_POST['name'])){
$name = filter_var($_POST['name'],FILTER_SANITIZE_STRING);
}
We use empty() function to validate the Required field.
$email = filter_var($_POST['email'],FILTER_SANITIZE_STRING);
if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
// invalid email
}
Assume malicious users enter <script>alert('xss')</script> in the input field, if only echo $_GET['name']; in php,then we will see an alert.
So, we have to convert all applicable characters to HTML entities.
PHP provide a function htmlentities() or htmlspecialchars() to do this.
<?php
$str = "<script>alert('xss')</script>";
// Outputs: <script>alert('xss')</script>
echo htmlentities($str);
action.php
<?php
define('MAIL_TO','admin@lautturi.org');
$errors = array();
$name = '';
$email = '';
$subject = '';
$message = '';
function preprocessing($str){
return trim($str);
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {
// validate name
if($_POST['name'] != ''){
$name = preprocessing($_POST['name']);
$name = filter_var($name,FILTER_SANITIZE_STRING);
if($name == ''){
$errors[] = 'Name is not valid';
}
}else{
$errors[] = 'Name is required';
}
// validate email
if($_POST['email'] != ''){
$email = preprocessing($_POST['email']);
$email = filter_var($email,FILTER_SANITIZE_STRING);
if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
$errors[] = 'Email is not valid';
}
}else{
$errors[] = 'Email is required';
}
// validate message
if($_POST['message'] != ''){
$message = preprocessing($_POST['message']);
$message = filter_var($message,FILTER_SANITIZE_STRING);
if($message == ''){
$errors[] = 'Message is not valid';
}
}else{
$errors[] = 'Message is required';
}
if(count($errors)){
echo "The following error(s) occurred:";
echo "<ul>";
foreach ($errors as $error) {
echo "<li>$error</li>";
}
echo "</ul>";
}
else{
$mail_msg = '';
$mail_msg .= 'From: ' . $name . "\n";
$mail_msg .= 'Email: ' . $email . "\n";;
$mail_msg .= 'Message: ' . $message . "\n";
$subject = "test mail";
// send email to the MAIL_TO email address
if(!@mail(MAIL_TO, $subject, $mail_msg)){
echo 'Error sending email';
}
else{
echo "Thank you! your message has been sent.";
echo "<br>
Name: ".htmlentities($name)." <br>
Email: ".htmlentities($email)." <br>
Message: ".htmlentities($message)." <br>
";
exit(); // terminates the script
}
}
}
If the form action is not specified or no value, the browser submit the form to the same page.
<html>
<head>
<title>PHP Contact Form Demo</title>
</head>
<body>
<h2>PHP Contact Form Demo</h2>
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST') : ?>
<?php
// same as the code in action.php
?>
<?php else : ?>
<form method="POST" action="">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
Message:<textarea rows="7" cols="25" name="message"></textarea>
</div>
<input type="submit" name="submit">
</form>
<?php endif; ?>
</body>
</html>