I'm looking for a review of my code for better design (to make sure it's more readable and legible).
<?php
// define variables and set to empty values
$nameErr = $phoneErr = $streetErr = $cityErr = $stateErr = $zipErr = "";
$name = $phone = $street = $city = $state = $zip = "";
// start script if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
}
else {$name = test_input($_POST["name"]);
// check if name only contains letters and whitespaces
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["phone"])) {
$phoneErr = "Phone # is required";
}
else {$email = test_input($_POST["phone"]);
// check if phone only contains numbers and dashes in correct format
if (!preg_match("/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/",$phone)) {
$phoneErr = "Please resubmit Phone # in the following format: 555- 555-5555";
}
}
if (empty($_POST["street"])) {
$streetErr = "Address is required";
}
else {$street = test_input($_POST["street"]);
// check if address syntax is valid
if (!preg_match("/^[0-9a-zA-Z. ]+$/",$street)) {
$streetErr = "Address appears to be invalid.";
}
}
if (empty($_POST["city"])) {
$cityErr = "City is required";
}
else {$city = test_input($_POST["city"]);
// check if city syntax is valid
if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
$cityErr = "City appears to be invalid." ;
}
}
if (empty($_POST["state"])) {
$stateErr = "State is required";
}
else {$state = test_input($_POST["state"]);
// check if state is valid uppercase abbv. and two letters
if (!preg_match("/^(A[LKSZRAP]|C[AOT]|D[EC]|F[LM]|G[AU]|HI|I[ADL N]
|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]
|T[NX]|UT|V[AIT]|W[AIVY])$/",$state)) {
$stateErr = "State appears to be invalid. (Hint...Use Upper-case!)" ;
}
}
if (empty($_POST["zip"])) {
$zipErr = "Zip Code field is required";
}
else {$zip = test_input($_POST["zip"]);
// check if zip only contains numbers and dashes in correct format
if (!preg_match("/^[0-9]{5}-[0-9]{4}$/",$phone)) {
$phoneErr = "Please resubmit Zip Code in the following format: 55555-5555";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
test_input
function does ? – matheussilvapb May 22 '14 at 1:49htmlspecialchars()
– matheussilvapb May 22 '14 at 2:03