Form Validation in php

When you allow users to input data, you typically need to validate that data before using it or storing it for later use. There are several strategies available for validating data. The first is JavaScript on the client side. However, since the user can choose to turn JavaScript off, or may even be using a browser that doesn’t support it, this cannot be the only validation you do

A more secure choice is to use PHP to do the validation

Form validation (data_validation.php)

$name = $_POST['name'];
$mediaType = $_POST['media_type'];
$filename = $_POST['filename'];
$caption = $_POST['caption'];
$status = $_POST['status'];
$tried = ($_POST['tried'] == 'yes');
if ($tried) {
 $validated = (!empty($name) && !empty($mediaType) && !empty($filename));
 if (!$validated) { ?>
 <p>The name, media type, and filename are required fields. Please fill
 them out to continue.</p>
 <?php }
if ($tried && $validated) {
 echo "<p>The item has been created.</p>";
// was this type of media selected? print "selected" if so
function mediaSelected($type)
 global $mediaType;
 if ($mediaType == $type) {
 echo "selected"; }
} ?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
 Name: <input type="text" name="name" value="<?= $name; ?>" /><br />
 Status: <input type="checkbox" name="status" value="active"
 <?php if ($status == "active") { echo "checked"; } ?> /> Active<br />
 Media: <select name="media_type">
 <option value="">Choose one</option>
 <option value="picture" <?php mediaSelected("picture"); ?> />Picture</option>
 <option value="audio" <?php mediaSelected("audio"); ?> />Audio</option>
 <option value="movie" <?php mediaSelected("movie"); ?> />Movie</option>
 </select><br />
 File: <input type="text" name="filename" value="<?= $filename; ?>" /><br />
 Caption: <textarea name="caption"><?= $caption; ?></textarea><br />
 <input type="hidden" name="tried" value="yes" />
 <input type="submit" value="<?php echo $tried ? "Continue" : "Create"; ?>" />

In this case, the validation is simply a check that a value was supplied. We set $valida ted to be true only if $name, $type, and $filename are all nonempty. Other possible validations include checking that an email address is valid or checking that the supplied filename is local and exists

For example, to validate an age field to ensure that it contains a nonnegative integer, use this code:

$age = $_POST[‘age’];
$validAge = strspn($age, “1234567890”) == strlen($age);

The call to strspn() finds the number of digits at the start of the string. In a nonnegative integer, the whole string should be composed of digits, so it’s a valid age if the entire string is made of digits. We could also have done this check with a regular expression:

$validAge = preg_match(‘/^\d+$/’, $age);

Leave a Comment