I tried to validate a form by making another page that's specifically for validating the user input. After done validating, it will take the user to another page to display the result. Main issue is I keep getting Undefined array key on specific attributes/ codes.
pbt1.php
<html>
<?php
session_start();
if(isset($_SESSION['pbt1']))
{
$nameError = $_SESSION['pbt1']['nameError'];
$numberError = $_SESSION['pbt1']['numberError'];
$addressError = $_SESSION['pbt1']['addressError'];
$cityError = $_SESSION['pbt1']['cityError'];
}
?>
<style>
.registrationform
{
padding: 20px;
margin: auto;
margin-top: 20px;
line-height: 30px;
width: 600px;
border: solid 3px red;
}
Label
{
width:200px;
display:inline-block;
}
</style>
<div class= "registrationform">
<h1>ONLINE MARATHON REGISTRATION</h1>
<br><br>
<form name = "pbt1" method = "post" action = "validation.php">
<Label>Name<span style="color: red;">*</span>: </Label>
<input type = "text" name = "name">
<span id = "warning" style="color: red;" > <?php echo isset($nameError) ?$nameError :'';?></span>
<br><br>
<Label>Gender <span style="color: red;">*</span>:</Label>
<input type = "radio" name = "gender" value = "Female">Female
<input type = "radio" name = "gender" value = "Male">Male
<span id = "warning" style="color: red;"><?php echo isset($genderError) ? $genderError :'';?></span>
<br><br>
<Label>Date Of Birth <span style="color: red;">*</span>:</Label>
<input type = "date" name = "date">
<span id = "warning" style="color: red;"><?php echo isset($dateError) ? $dateError:'';?></span>
<br><br>
<Label>Contact Number <span style="color: red;">*</span>:</Label>
<input type = "text" name = "phonenumber">
<span id = "warning" style="color: red;"><?php echo isset($numberError) ? $numberError:'';?></span>
<br><br>
<Label>Address <span style="color: red;">*</span>:</Label>
<input type = "text" name = "address" >
<span id = "warning" style="color: red;"><?php echo isset($addressError) ? $addressError :'';?></span>
<br><br>
<Label>City <span style="color: red;">*</span>:</Label>
<input type = "text" name = "city" >
<span id = "warning" style="color: red;"><?php echo isset($cityError) ? $cityError:'';?></span>
<br><br>
<Label>Zip Code <span style="color: red;">*</span>:</Label>
<input type = "text" name = "zipcode" >
<span id = "warning" style="color: red;"><?php echo isset($zipcodeError) ? $zipcodeError:'';?></span>
<br><br>
<div style="text-align:center;">
<input type = "submit" value = "Submit" name="Submit">
</div>
</form>
</div>
<br><br>
</html>
pbt2.php
<?php
session_start();
?>
<html>
<style>
table
{
text-align:center;
}
</style>
<div style="background-color:cyan;">
<h1 align = 'center'> YOUR INFORMATION AS THE TABLE BELOW </h1>
<table width = '400' border = '1' align = 'center'>
<tr>
<td>Name</td>
<td><?php echo $_SESSION['Userdata']['name'];?></td>
</tr>
<tr>
<td>Phone Number</td>
<td><?php echo $_SESSION['Userdata']['phonenumber'];?></td>
</tr>
<tr>
<td>Address</td>
<td><?php echo $_SESSION['Userdata']['address'];?></td>
</tr>
<tr>
<td>City</td>
<td><?php echo $_SESSION['Userdata']['city'];?></td>
</tr>
<tr>
<td>Zip Code</td>
<td><?php echo $_SESSION['Userdata']['zipcode'];?></td>
</tr>
<tr>
<td>Gender</td>
<td><?php echo $_SESSION['Userdata']['gender'];?></td>
</tr>
<tr>
<td>Date</td>
<td><?php echo $_SESSION['Userdata']['date'];?></td>
</tr>
</table>
</div>
</html>
validation.php
<?php
session_start();
if(isset($_POST['Submit']))
{
$name = $_POST['name'];
if(isset($name) && empty($name))
{
$_SESSION['pbt1']['nameError']="Name must be required!";
header('location: pbt1.php');
exit;
}
else
{
if(!preg_match("/^[a-zA-Z ]*$/",$name))
{
$_SESSION['pbt1']['nameError'] = "Only letters and white space allowed";
header('location: pbt1.php');
exit;
}
}
$phonenumber = $_POST['phonenumber'];
if(isset($phonenumber) && empty($phonenumber))
{
$_SESSION['pbt1']['numberError'] = "Error, insert phone number";
header('location: pbt1.php');
exit;
}
else
{
if(!preg_match('/^([0-9]*)$/', $phonenumber))
{
$_SESSION['pbt1']['numberError'] = "Numbers only";
header('location: pbt1.php');
exit;
}
}
$address = $_POST['address'];
if(isset($address) && empty($address))
{
$_SESSION['pbt1']['addressError'] = "Enter your address";
header('location: pbt1.php');
exit;
}
$city = $_POST['city'];
if(isset($city) && empty($city))
{
$_SESSION['pbt1']['cityError']="Name must be required!";
header('location: pbt1.php');
exit;
}
else
{
if(!preg_match("/^[a-zA-Z ]*$/",$city))
{
$_SESSION['pbt1']['cityError'] = "Only letters and white space allowed";
header('location: pbt1.php');
exit;
}
}
$zipcode = $_POST['zipcode'];
if(isset($zipcode) && empty($zipcode))
{
$_SESSION['pbt1']['zipcode'] = "Error, insert phone number";
header('location: pbt1.php');
exit;
}
else
{
if(!preg_match('/^([0-9]*)$/', $zipcode))
{
$_SESSION['pbt1']['zipcode'] = "Numbers only";
header('location: pbt1.php');
exit;
}
}
$gender = $_POST['gender'];
if(isset($gender) && empty($gender))
{
$_SESSION['pbt1']['genderError'] = "Error, please select a gender";
header('location: pbt1.php');
exit;
}
$date = $_POST['date'];
$_SESSION['Userdata'] = ['name'=>$name , 'phonenumber'=>$phonenumber,'address'=>$address,'city'=>$city,
'zipcode'=>$zipcode,'gender'=>$gender,'date'=>$date ];
header("location:pbt2.php");
exit;
}
?>
Errors I got so far are :
Warning: Undefined array key "dateError" pbt1.php on line 11
Warning: Undefined array key "addressError" pbt1.php on line 12
Warning: Undefined array key "cityError" pbt1.php on line 13
It's so weird that $nameError and numberError work just fine while the rest aren't.
Related
I'm new to PHP and the validation. I have been asked by my lecturer to make a form with session and validation.I have 3 php pages such as pbt1.php , pbt2.php and validation.php After all validated, it will go to display page. However, it seems like it only stopped at validation page [validation.php]. I need someone to check if my codes are correct or wrong too.
pbt1.php
session_start();
?>
<html>
<?php
if(isset($_SESSION['pbt1']))
{
$nameError = $_SESSION['pbt1']['nameError'];
$numberError = $_SESSION['pbt1']['numberError'];
$cityError = $_SESSION['pbt1']['cityError'];
$addressError = $_SESSION['pbt1']['addressError'];
$zipcodeError = $_SESSION['pbt1']['zipcodeError'];
$dateError = $_SESSION['pbt1']['dateError'];
}
?>
<style>
.registrationform
{
padding: 20px;
margin: auto;
margin-top: 20px;
line-height: 30px;
width: 600px;
border: solid 3px red;
}
Label
{
width:200px;
display:inline-block;
}
</style>
<div class= "registrationform">
<h1>ONLINE MARATHON REGISTRATION</h1>
<br><br>
<form name = "pbt1" method = "post" action = "validation.php">
<Label>Name<span style="color: red;">*</span>: </Label>
<input type = "text" name = "name">
<span id = "warning" style="color: red;" > <?php echo isset($nameError)?$nameError :'';?></span>
<br><br>
<Label>Gender <span style="color: red;">*</span>:</Label>
<input type = "radio" name = "gender" value = "Female" required>Female
<input type = "radio" name = "gender" value = "Male" required>Male
<br><br>
<Label>Date Of Birth <span style="color: red;">*</span>:</Label>
<input type = "date" name = "date">
<span id = "warning" style="color: red;"><?php echo isset($dateError)?$dateError:'';?></span>
<br><br>
<Label>Contact Number <span style="color: red;">*</span>:</Label>
<input type = "text" name = "phonenumber">
<span id = "warning" style="color: red;"><?php echo isset($numberError)?$numberError:'';?></span>
<br><br>
<Label>Address <span style="color: red;">*</span>:</Label>
<input type = "text" name = "address" >
<span id = "warning" style="color: red;"><?php echo isset($addressError)?$addressError :'';?></span>
<br><br>
<Label>City <span style="color: red;">*</span>:</Label>
<input type = "text" name = "city" >
<span id = "warning" style="color: red;"><?php echo isset($cityError)?$cityError:'';?></span>
<br><br>
<Label>Zip Code <span style="color: red;">*</span>:</Label>
<input type = "text" name = "zipcode" >
<span id = "warning" style="color: red;"><?php echo isset($zipcodeError)?$zipcodeError:'';?></span>
<br><br>
<div style="text-align:center;">
<input type = "submit" value = "Submit" name="Submit">
</div>
</form>
</div>
<br><br>
</html>
pbt2.php
<?php
session_start();
?>
<html>
<style>
table
{
text-align:center;
}
</style>
<div style="background-color:cyan;">
<h1 align = 'center'> YOUR INFORMATION AS THE TABLE BELOW </h1>
<table width = '400' border = '1' align = 'center'>
<tr>
<td>Name</td>
<td><?php echo $_SESSION['Userdata']['name'];?></td>
</tr>
<tr>
<td>Phone Number</td>
<td><?php echo $_SESSION['Userdata']['phonenumber'];?></td>
</tr>
<tr>
<td>Address</td>
<td><?php echo $_SESSION['Userdata']['address'];?></td>
</tr>
<tr>
<td>City</td>
<td><?php echo $_SESSION['Userdata']['city'];?></td>
</tr>
<tr>
<td>Zip Code</td>
<td><?php echo $_SESSION['Userdata']['zipcode'];?></td>
</tr>
<tr>
<td>Gender</td>
<td><?php echo $_SESSION['Userdata']['gender'];?></td>
</tr>
<tr>
<td>Date</td>
<td><?php echo $_SESSION['Userdata']['date'];?></td>
</tr>
</table>
</div>
</html>
validation.php
<?php
session_start();
if(isset($_POST['Submit']))
{
$name = $_POST['name'];
if(isset($name) && empty($name))
{
$_SESSION['pbt1']['nameError']="Name must be required!";
header('location:pbt1.php');
}
else
{
if(!preg_match("/^[a-zA-Z ]*$/",$name))
{
$_SESSION['pbt1']['nameError'] = "Only letters and white space allowed";
header('location:pbt1.php');
}
}
$phonenumber = $_POST['phonenumber'];
if(isset($phonenumber) && empty($phonenumber))
{
$_SESSION['pbt1']['numberError'] = "Error, insert phone number";
header('location:pbt1.php');
}
else
{
if(!preg_match('/^([0-9]*)$/', $phonenumber))
{
$_SESSION['pbt1']['numberError'] = "Numbers only";
header('location:pbt1.php');
}
}
$address = $_POST['address'];
if(isset($address) && empty($address))
{
$_SESSION['pbt1']['addressError'] = "Error, enter your address";
header('location:pbt1.php');
}
$city = $_POST['city'];
if(isset($city) && empty($city))
{
$_SESSION['pbt1']['cityError'] = "Error, enter your city";
header('location:pbt1.php');
}
$zipcode = $_POST['zipcode'];
if(isset($zipcode) && empty($zipcode))
{
$_SESSION['pbt1']['zipcodeError'] = "Error, enter your zipcode";
header('location:pbt1.php');
}
else
{
if(!preg_match('/^([0-9]*)$/', $zipcode))
{
$_SESSION['pbt1']['zipcodeError'] = "Numbers only";
header('location:pbt1.php');
}
}
$gender = $_POST['gender'];
$date = $_POST['date'];
if(isset($date) && empty($date))
{
$_SESSION['pbt1']['dateError'] = "Error, select the date";
header('location:pbt1.php');
}
$_SESSION['Userdata'] = ['name'=>$name ,'phonenumber'=>$phonenumber,'address'=>$address,'city'=>$city,
'zipcode'=>$zipcode,'gender'=>$gender,'date'=>$date ];
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if($_SESSION['pbt1']['nameError'] == "" && $_SESSION['pbt1']['numberError'] == "" && $_SESSION['pbt1']['addressError']== "" && $_SESSION['pbt1']['cityError']=="" && $_SESSION['pbt1']['zipcodeError']=="" && $_SESSION['pbt1']['dateError']=="")
{
header("location:pbt2.php");
exit; }
?>
Depending on the PHP version (>= 7.0) you are using, you could change
<?php echo isset($nameError)?$nameError :'';?>
to
<?php echo $nameError ?? ''; ?>
As for HTML, you might want to change
<form name = "pbt1" method = "post" action = "validation.php">
to
<form name="pbt1" method="post" action="validation.php">
That doesn't change the outcome, but easier to read.
What's next...
$name = $_POST['name'];
if(isset($name) && empty($name))
{
could be changed into
if (array_key_exists('name', $_POST) && trim($_POST['name']) === '') {
Looks like more code, but the intention of the if becomes more clear.
As far as this one goes
if(isset($_SESSION['pbt1']))
{
$nameError = $_SESSION['pbt1']['nameError'];
$numberError = $_SESSION['pbt1']['numberError'];
$cityError = $_SESSION['pbt1']['cityError'];
$addressError = $_SESSION['pbt1']['addressError'];
$zipcodeError = $_SESSION['pbt1']['zipcodeError'];
$dateError = $_SESSION['pbt1']['dateError'];
}
...don't trust your session. I would change it to
if (array_key_exists('pbt1', $_SESSION)) {
$nameError = $_SESSION['pbt1']['nameError'] ?? '';
$numberError = $_SESSION['pbt1']['numberError'] ?? '';
$cityError = $_SESSION['pbt1']['cityError'] ?? '';
$addressError = $_SESSION['pbt1']['addressError'] ?? '';
$zipcodeError = $_SESSION['pbt1']['zipcodeError'] ?? '';
$dateError = $_SESSION['pbt1']['dateError'] ?? '';
}
This one
$_SESSION['Userdata'] = ['name'=>$name ,'phonenumber'=>$phonenumber,'address'=>$address,'city'=>$city,
'zipcode'=>$zipcode,'gender'=>$gender,'date'=>$date ];
I would change to
$_SESSION['Userdata'] = [
'name' => $_POST['name'] ?? '',
'phonenumber' => $_POST['phonenumber'] ?? '',
'address'. => $_POST['address'] ?? '',
'city'. => $_POST['city'] ?? '',
'zipcode' => $_POST['zipcode'] ?? '',
'gender'. => $_POST['gender'] ?? '',
'date'. => $_POST['date'] ?? '',
];
Since validation.php is pure PHP, get rid of
?>
at the end of the file.
What else...
At the beginning of validation.php, make sure you clear out $_SESSION['pbt1'] aka.
unset($_SESSION['pbt1']);
Instead of doing header('location:pbt1.php'); after every issue, remove header('location:pbt1.php'); from every individual if block and put it at the end, as in
if(isset($date) && empty($date)) {
$_SESSION['pbt1']['dateError'] = "Error, select the date";
// header('location:pbt1.php');
}
if (array_key_exists('pbt1', $_SESSION)) {
header('location:pbt1.php');
exit;
}
$_SESSION['Userdata'] = ...
that way you don't have to fix every error by itself and you show them all at once.
I have moved over the validation to the bikeInfo.php file. Not much changes have been made to the code, but not sure why the validation is not being processed... appreciate the help!
<?php
$nameErr = $phoneErr = $emailErr = $sErr = $errorMsg = "";
$name = $phone = $email = $serial = $type = $formSubmit = $description = "";
?>
<head>
<title>Register your bikes!</title>
</head>
<style>
body {
margin-left: auto;
margin-right: auto;
text-align: center;
padding: 8px;
}
div.sellerInfo {
position: relative;
top: 50px;
}
.error {
position: absolute;
color: red;
}
</style>
<html>
<body>
<form method="post" action="bikeInfo.php">
<b style="font-size: 20px;">Bike Information</b>
</br></br>
<div class="sellerInfo">
Name:
<input type="text" name="sName" value="<?php echo $name;?>"/>
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Phone:
<input type="text" name="sNum" value="<?php echo $phone;?>"/>
<span class="error">* <?php echo $phoneErr;?></span>
<br><br>
Email:
<input type="text" name="sEmail" value="<?php echo $email;?>"/>
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Serial:
<input type="text" placeholder="yy-nnn-cc" name="serial" value="<?php echo $serial;?>"/>
<span class="error">* <?php echo $sErr;?></span>
<br><br>
Type:
<input type="text" name="type" value="<?php echo $type;?>"/>
<span class="error">* <?php echo $errorMsg;?></span>
<br><br>
Description:
<textarea name="description" rows="5" cols="50" value="<?php echo $description;?>"></textarea>
<br><br>
<input type="submit" name="formSubmit" value="Submit"/>
</div><br><br><br>
</form>
</body>
</html>
This is my bikeInfo.php file which does validation and displaying of the submitted values. Not sure am i suppose to separate them...
<?php
//set to empty strings
$name = $phone = $email = $serial = $type = $formSubmit = $description = "";
$nameErr = $phoneErr = $emailErr = $sErr = $errorMsg = "";
if (isset($_POST["formSubmit"]))
{
if (empty($_POST["sName"]))
{
$nameErr = "Name is required";
} else {
$name = test_input($_POST['sName']);
}
//validate phone number
if (empty($_POST["sNum"]))
{
$phoneErr = "Phone number is required";
} else {
$phone = test_input($_POST['sNum']);
if (!is_numeric($phone)) //check for letters
{
$phoneErr = "No letters allowed";
}
}
//validate email
if (empty($_POST["sEmail"]))
{
$emailErr = "Email is required";
} else {
$email = test_input($_POST['sEmail']);
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailErr = "Invalid email format";
}
}
//validate serial
if (empty($_POST["serial"]))
{
$sErr = "Serial number is required";
} else {
$serial = test_input($_POST['serial']);
//determing the pattern of the serial no. yy-nnnn-cc
if (!preg_match("/[0-9][0-9]\-\d{3}\-[a-z]{2}/", $serial))
{
$sErr = "Format is yy-nnn-cc";
}
}
//validate type
if (empty($_POST["type"]))
{
$errorMsg = "Type is required";
} else {
$type = test_input($_POST["type"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<html>
<style>
.body {
text-align: center;
padding: 20px;
}
</style>
<body>
<h1 style="text-align:center; padding: 20px">Bike listings</h1>
<?php
$listings = $name . "<br>" . $phone . "<br>" . $email . "<br>" . $serial . "<br>" . $type . "<br>" . $description;
echo "<div style='text-align:center; padding: 50px'>$listings</div>";
?>
</body>
</html>
I had a little play about refactoring the code so that you could use a single page to perform both the validation and display. Perhaps it may be of use.
<?php
error_reporting( E_ALL );
$errors=array();
$nameErr = $phoneErr = $emailErr = $sErr = $errorMsg = '';
$sName = $sNum = $sEmail = $serial = $type = $description = '';
if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
$_POST['sName'],
$_POST['sNum'],
$_POST['sEmail'],
$_POST['serial'],
$_POST['type']
)){
# modified to accept uppercase chars at end and limited to 2 integers at atart
$pttn='/[0-9]{2}\-\d{3}\-[a-zA-Z]{2}/';
# config to filter POST vars
$args=array(
'sName' => FILTER_SANITIZE_STRING,
'sNum' => FILTER_SANITIZE_STRING,
'sEmail' => FILTER_SANITIZE_EMAIL,
'serial' => FILTER_SANITIZE_STRING,
'type' => FILTER_SANITIZE_STRING,
'description' => FILTER_SANITIZE_STRING
);
# test for unaccounted POST fields - possibly malicious
foreach( $_POST as $field => $value ){
if( !in_array( $field, array_keys( $args ) ) ){
$errors[]=sprintf('Unknown field %s',$field);
}
}
if( empty( $errors ) ){
# rebuild the POST array with only filtered values
$_POST=filter_input_array( INPUT_POST, $args );
# extract known values from POST array into variables
extract( $_POST );
#error messages
$nameErr=empty( $sName ) ? 'Name is required' : '';
$phoneErr=empty( $sNum ) ? 'Phone number is required' : '';
$emailErr=empty( $sEmail ) ? 'Email is required' : '';
$sErr=empty( $serial ) ? 'Serial number is required' : '';
$errorMsg=empty( $type ) ? 'Type is required' : '';
# Validate particular variables
$sEmail=filter_var( $sEmail, FILTER_VALIDATE_EMAIL );
# to filter the phone number might remove leading zero and thus appear invalid
# possibly reassign error message variables
if( !preg_match( $pttn, $serial ) )$sErr='Invalid Serial. The format is: yy-nnn-cc';
if( !$sEmail )$emailErr='Invalid email format';
if( !$sNum )$phoneErr='Invalid phone number. No letters allowed!';
# save to database, email somewhere, write text etc etc
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Register your bikes!</title>
<style>
body {
margin:auto;
text-align:center;
padding:8px;
}
div.sellerInfo {
top:50px;
}
.error {
position:absolute;
color:red;
}
section{
margin:2rem auto;
width:300px;
padding:1rem;
display:block;
border:1px solid black;
}
section *{
text-align:left;
}
</style>
</head>
<body>
<form method='post'>
<b>Bike Information</b>
<div class='sellerInfo'>
<div>
Name:
<input type='text' name='sName' value='<?php echo $sName;?>' />
<span class='error'>* <?php echo $nameErr;?></span>
</div>
<div>
Phone:
<input type='text' name='sNum' value='<?php echo $sNum;?>' />
<span class='error'>* <?php echo $phoneErr;?></span>
</div>
<div>
Email:
<input type='text' name='sEmail' value='<?php echo $sEmail;?>' />
<span class='error'>* <?php echo $emailErr;?></span>
</div>
<div>
Serial:
<input type='text' placeholder='yy-nnn-cc' name='serial' value='<?php echo $serial;?>' />
<span class='error'>* <?php echo $sErr;?></span>
</div>
<div>
Type:
<input type='text' name='type' value='<?php echo $type;?>' />
<span class='error'>* <?php echo $errorMsg;?></span>
</div>
<div>
Description:
<textarea name='description' rows='5' cols='50' value='<?php echo $description;?>'></textarea>
</div>
<input type='submit' />
</div>
</form>
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
$sName,
$sNum,
$sEmail,
$serial,
$type,
$description
)){
if( empty( $errors ) ){
printf('
<section>
<h1 style="text-align:center; padding: 20px">Bike listings</h1>
<ul>
<li>%s</li>
<li>%s</li>
<li>%s</li>
<li>%s</li>
<li>%s</li>
<li>%s</li>
</ul>
</section>',
$sName,
$sNum,
$sEmail,
$serial,
$type,
$description
);
}else{
foreach( $errors as $error )printf('<div class="error">%s</div>',$error);
}
}
?>
</body>
</html>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {
color:red;
}
.button {
background-color: #4CAF50;
border: none;
color: white;
padding: 10px 25px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
.div1 {
background-color: #f2f2f2;
margin-top: -19px;
margin-bottom: -25px;
margin-left: -19px;
}
.copy {
border-radius: 4px;
padding: 6px 20px;
border-style: ridge;
}
.copy1{
border-radius: 4px;
padding: 6px 28px;
border-style: ridge;
}
.copy2{
border-radius: 4px;
padding: 4px 2px;
}
</style>
</head>
<body>
<?php
session_start();
if (isset($_SESSION['id'])){
header('location:welcome.php');
}
?>
<?php
// define variables and set to empty values
include_once 'connect.php';
$nameErr = $emailErr = $usernameErr = $passwordErr = $DateOfBirthErr = $departmentErr = $ageErr = $fileToUploadErr = $fileToUploadErrr = $fileToUploadErrrr = $fileToUploadErrrrr = $fileToUploadErrrrrr = "" ;
$name = $email = $username = $password = $DateOfBirth = $department = $age = $fileToUpload = $filename = $file = "";
if (isset($_POST['submit'])) {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["username"])) {
$usernameErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$username)) {
$usernameErr = "Only letters";
}
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password = test_input($_POST["password"]);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// check weather password is alphanumeric
if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{6,}$/', $password))
{
$passwordErr = "Password must be alphanumeric and atleast 6 characters long!";
}
}
if (empty($_POST["Date_of_birth"])) {
$DateOfBirthErr = "Date Of Birth is required";
} else {
$DateOfBirth = test_input($_POST["Date_of_birth"]);
}
if (empty($_POST["department"])) {
$departmentErr = "Department is required";
} else {
$department = test_input($_POST["department"]);
}
if (empty($_POST["age"])) {
$ageErr = "Age is required";
} else {
$age = test_input($_POST["age"]);
}
//UPLOAD FILE
$uploaddir = 'upload/';
$uploadfile = $uploaddir . basename($_FILES['fileToUpload']['name']);
$imageFileType = pathinfo($uploadfile,PATHINFO_EXTENSION);
if($_FILES['fileToUpload']['name'] != '')
{
// Check the image is actaully image or not
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check == false)
{
$fileToUploadErrrrr = "File is not an image.";
}
// Check if file already exists
if (file_exists($uploadfile)) {
$fileToUploadErrrrrr = "Sorry, file already exists.";
}
if($imageFileType != "jpg" && $imageFileType != "png" )
{
$fileToUploadErr = "Sorry, only JPG,PNG files are allowed.";
}
elseif($_FILES['fileToUpload']['size'] > 500000)
{
$fileToUploadErrrr = "Sorry, your file is too large.";
}
else
{
/* if($filename != '')
{
$target = "upload/".$filename;
unlink($target);
}*/
$uploaded = move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile);
if ($uploaded) {
$file = $_FILES['fileToUpload']['name'];
}
else{
$file = $filename;
}
}
}
elseif($_FILES['fileToUpload']['name'] = " ")
{
$fileToUploadErrr = "Please Select an image!";
}
else {
$file = $filename;
}
if($nameErr == "" && $emailErr == "" && $usernameErr == "" && $passwordErr == "" && $fileToUploadErr == "" && $fileToUploadErrr == "" && $fileToUploadErrrr == "" && $fileToUploadErrrrr == "" && $fileToUploadErrrrrr == "" )
{
$check="SELECT * FROM users WHERE username = '$_POST[username]'";
$rs = mysqli_query($mysqli,$check);
$da = mysqli_fetch_array($rs, MYSQLI_NUM);
if($da[0] > 0) {
echo "Username Already in Exists<br/>";
}
else
{
$sql = "INSERT INTO users(`userid`,`username`, `password`, `email` , `name` , `Date_of_birth` , `department` ,`age` , `filename` )
VALUES ('','".$username."', '".$hashed_password."', '".$email."' , '".$name."' , '".$DateOfBirth."' , '".$department."' , '".$age."' , '".$file."')";
if (mysqli_query($mysqli, $sql)) {
echo "Registered successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
mysqli_close($mysqli);
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div style="padding-left: 250px" class="div1">
<h2 style="color:#009999">Registration Form :</h2>
<p><span class="error">All fields are required </span></p>
<form action="" method="post" enctype="multipart/form-data">
<span style="color:#0099ff">Name: </span>
<input type="text" name="name" class= "copy" style="margin-left: 52px" value ="<?php
if (isset($name))
echo $name;
?>">
<span class="error"> <?php echo $nameErr;?></span>
<br><br>
<span style="color:#0099ff"> E-mail: </span>
<input type="text" name="email" class= "copy" style="margin-left: 48px" value ="<?php
if (isset($email))
echo $email;
?>">
<span class="error"><?php echo $emailErr;?></span>
<br><br>
<span style="color:#0099ff"> Username: </span>
<input type="text" name="username" class= "copy" style="margin-left:26px" value ="<?php
if (isset($username))
echo $username;
?>">
<span class="error"> <?php echo $usernameErr;?></span>
<br><br>
<span style="color:#0099ff"> Password: </span>
<input type="password" name="password" class= "copy" style="margin-left:30px">
<span class="error"> <?php echo $passwordErr;?></span>
<br><br>
<span style="color:#0099ff"> Date Of Birth : </span>
<input type="date" class= "copy1" name="Date_of_birth" value ="<?php
if (isset($DateOfBirth))
echo $DateOfBirth;
?>">
<span class="error"> <?php echo $DateOfBirthErr;?></span>
<br><br>
<span style="color:#0099ff"> Age : </span>
<input type="number" name="age" class= "copy" style="margin-left:62px" value ="<?php
if (isset($age))
echo $age;
?>">
<span class="error"> <?php echo $ageErr;?></span>
<br><br>
<span style="color:#0099ff"> Department : </span>
<select name="department" class= "copy2" style="margin-left:14px" value ="<?php
if (isset($department))
echo $department;
?>">
<option value="EE">Electrical & Electronics</option>
<option value="EC">Electronics & Communication</option>
<option value="ME">Mechanical</option>
<option value="CS">Computer Science</option>
<option value="CV">Civil</option>
<option value="IS">Information Science</option>
</select>
<span class="error"> <?php echo $departmentErr;?></span>
<br><br>
<span style="color:#0099ff"> Select image : </span>
<input type="file" name="fileToUpload">
<?php if($filename !=''){ ?> <img src="<?php echo "upload/" .$filename ?>" style="width:180px;height:100px;padding:10px;"/> <?php } ?>
<span class="error"><br> <?php echo $fileToUploadErr; ?></span>
<span class="error"><br> <?php echo $fileToUploadErrr; ?></span>
<span class="error"><br> <?php echo $fileToUploadErrrr; ?></span>
<span class="error"><br> <?php echo $fileToUploadErrrrr; ?></span>
<span class="error"><br> <?php echo $fileToUploadErrrrrr; ?></span>
<input type="submit" class="button" name="submit" value="Register">
<p style="color:black">Already Registered? Login.</p>
</form>
</div>
</body>
</html>
Hi, guys I have only one small issue please help me, I have a registration form with the various input,
my problem is if I give blank space to the name input field and then if I give submit then it should
show any error that no space are allowed
i.e., their should be only letters except that it should not accept any numbers special characters and other thing please.
Can any one help me in this please ?
This line if (!preg_match("/^[a-zA-Z ]*$/",$name)) { must be like this:
if (!preg_match("/^[a-zA-Z]*$/",$name)) {
Explanation:
Your regex has a space at the end. Removing it will solve your problem.
I know the tag form has an attribute called action and I know how action works, this is how I used it
<form method="post" action = "registerd.php">
</form>
The registerd.php page also exists as well.
Now I am doing some validation in the tag form using php validation, but why does it jump to the registerd.php page without validating the values at first?
is there any other solutions to this rather than using the header at the end of php code like :
header("location : registerd.php")
here is the whole code I'm writing
Thank you very much in advance
<div id = "content">
<?php
$fnameErr = "";
$lnameErr = "";
$idErr = "";
$placeErr = "";
$dateErr = "";
$emailErr = "";
$pswErr = "";
$file;
$content = "";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(isset($_POST['register'])){
if(isset($_POST['firstname'])){
if(!empty($_POST['firstname'])){
if(strlen($_POST['firstname'])>1){
if(preg_match("/[a-zA-Z]+/", $_POST['firstname'])==1){
$firstname = test_input($_POST['firstname']);
$content .= "firstname:";
$content .= $firstname;
$content .= " ";
}
else{
$fnameErr = "your first name should only include letters";
}
}
else{
$fnameErr = "your first name must be at least 2 characters";
}
}
else{
$fnameErr = "enter your first name";
}
}
else{
$fnameErr = "enter your first name";
}
if(isset($_POST['lastname'])){
if(!empty($_POST['lastname'])){
if(strlen($_POST['lastname'])>3){
if(preg_match("/[a-zA-Z]+/", $_POST['lastname'])==1){
$lastname = test_input($_POST['lastname']);
$content .= "lastname:";
$content .= $lastname;
$content .= " ";
}
else{
$lnameErr = "your last name should only include letters";
}
}
else{
$lnameErr = "your last name must be at least 2 characters";
}
}
else{
$lnameErr = "enter your last name";
}
}
else{
$lnameErr = "enter your last name";
}
if(isset($_POST['idnum'])){
if(!empty($_POST['idnum'])){
if(strlen($_POST['idnum'])==10){
if(preg_match("/[0-9]{10}/", $_POST['idnum'])==1){
$idnum = test_input($_POST['idnum']);
$content .= "ID_No.:";
$content .= $idnum;
$content .= " ";
}
else{
$idErr = "your ID number should only include digits";
}
}
else{
$idErr = "your ID number must be 10 digits";
}
}
else{
$idErr = "enter your ID number";
}
}
else{
$idErr = "enter your ID number";
}
if(isset($_POST['placeOfBirth'])){
if(!empty($_POST['placeOfBirth'])){
if(strlen($_POST['placeOfBirth'])>2){
if(preg_match("/[a-zA-Z]+/", $_POST['placeOfBirth'])==1){
$placeOfBirth = test_input($_POST['placeOfBirth']);
$content .= "placeOfBirth:";
$content .= $placeOfBirth;
$content .= " ";
}
else{
$placeErr = "your place of birth should only include digits";
}
}
else{
$placeErr = "your place of birth must be at least 3 letters";
}
}
}
if(isset($_POST['date'])){
if(!empty($_POST['date'])){
$date = test_input($_POST['date']);
$content .= "date:";
$content .= $date;
$content .= " ";
}
else{
$dateErr = "enter your date of birth";
}
}
else{
$dateErr = "enter your date of birth";
}
if(isset($_POST['email'])){
if(!empty($_POST['email'])){
$email = test_input($_POST['email']);
$content .= "email:";
$content .= $email;
$content .= " ";
}
else{
$emailErr = "enter your email";
}
}
else{
$emailErr = "enter your email";
}
if(isset($_POST['password'])){
if(!empty($_POST['password'])){
if(preg_match("/(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$/", $_POST['password'])==1){
$password = test_input($_POST['password']);
$content .= "password:";
$content .= $password;
$content .= " ";
}
else{
$pswErr = "your password should have numbers, uppercase<br/> & lowercase letters";
}
}
else{
$pswErr = "enter your password";
}
}
else{
$pswErr = "enter your password";
}
if(file_exists($email.".txt")){
echo(
"<script>
alert('this email already exists!');
</script>"
);
$firstname = $lastname = $idnum = $date = $placeOfBirth = $password = "";
}
else{
$file = fopen($email.".txt","a+") or die("Unable to open file!");
fwrite($file, $content);
fclose($file);
header("location: registered.php");
}
}
?>
<fieldset id = "fieldset">
<legend><h1 class = "reg" >Register Form</h1></legend>
<form method="post" action="#" enctype = "multipart/form-data">
<table class = "table">
<tr>
<td class = "labels">
<p class = "star">*</p> First Name
</td>
<td><input class = "inclass" type="text" required="required" placeholder="Please enter your first name" id = "firstname" name="firstname" onclick = "colorBorder(this.id)"/></td>
</tr>
<td class = "err">
<span>
<?php
echo $fnameErr;
?>
</span>
</td>
<tr>
<td class = "labels"><p class = "star">*</p> Last Name</td>
<td><input class = "inclass" type="text" required="required" placeholder="Please enter your last name" name="lastname" id = "lastname" onclick = "colorBorder(this.id)"/></td>
</tr>
<td class = "err">
<span>
<?php
echo $lnameErr;
?>
</span>
</td>
<tr>
<td class = "labels">Gender</td>
<td>
<input class = "inclass" type="radio" name="gender" value="0" /><p class = "radio" >Male</p>
<input class = "inclass" type="radio" name="gender" value="1" /><p class = "radio" >Female</p>
</td>
</tr>
<tr>
<td class = "labels"><p class = "star">*</p> ID Number</td>
<td><input class = "inclass" type="text" id="idnum" required="required" placeholder="Please enter your ID number" name="idnum" onclick = "colorBorder(this.id)"/></td>
</tr>
<td class = "err">
<span>
<?php
echo $idErr;
?>
</span>
</td>
<tr>
<td class = "labels">Place of Birth</td>
<td><input class = "inclass" type="text" placeholder="Please enter your place of birth" name="placeOfBirth" id = "place" onclick = "colorBorder(this.id)"/></td>
</tr>
<td class = "err">
<span>
<?php
echo $placeErr;
?>
</span>
</td>
<tr>
<td class = "labels"><p class = "star">*</p> Date Of Birth</td>
<td><input class = "inclass" type="date" id = "date" name="date"/></td>
</tr>
<td class = "err">
<span>
<?php
echo $dateErr;
?>
</span>
</td>
<tr>
<td class = "labels"><p class = "star">*</p> Email</td>
<td><input class = "inclass" type="email" required="required" placeholder="Please enter your email" name="email" id = "email" onclick = "colorBorder(this.id)"/></td>
</tr>
<td class = "err">
<span>
<?php
echo $emailErr;
?>
</span>
</td>
<tr>
<td class = "labels"><p class = "star">*</p> Passwords</td>
<td><input class = "inclass" type="password" required="required" placeholder="Please enter your password" name="password" id = "password" onclick = "colorBorder(this.id)"/></td>
</tr>
<td class = "err">
<span>
<?php
echo $pswErr;
?>
</span>
</td>
<tr>
<td><input type="submit" name="register" value="register" class="save"/></td>
<td><input type="reset" name = "reset" id = "reset"/></td>
</tr>
</table>
</form>
</fieldset>
</div>
write down your php validation code on register.php and if value are not validate than redirect to ur form page using header function.
header("location : form.php")
I believe the solution to your problem is to separate your code, the HTML in one file ("form.php"), the PHP validation in another file ("validate.php") :
"form.php" will collect the data, the "action" of the form will execute "validate.php".
"validate.php" will validate the data, if no error found it will "header" to "registered.php", if error found it will store the message in $_SESSION and "header" back to "form.php", where the message will be displayed.
Example :
form.php
<?php
session_start(); // NECESSARY TO USE $_SESSION.
?>
<html>
<body>
<form action="validate.php" method="post">
Enter 0 or 1 : <input type="text" name="num"/>
<br/>
<input type="submit" value="Submit"/>
</form>
<?php
// CHECK IF THERE IS ERROR MESSAGE FROM VALIDATION.
if ( isset( $_SESSION[ "err_msg" ] ) )
{ echo $_SESSION[ "err_msg" ];
unset( $_SESSION[ "err_msg" ] ); // VERY IMPORTANT : DESTROY ERROR MESSAGE.
}
?>
</body>
</html>
validate.php
<?php
session_start(); // NECESSARY TO USE $_SESSION.
if ( isset( $_POST[ "num" ] ) ) // IF CALLED FROM "FORM.PHP"
{ $num = $_POST[ "num" ];
if ( ( $num == "0" ) || ( $num == "1" ) ) // VALIDATE NUMBER.
header( "Location: registered.php" ); // NO ERROR.
else { $_SESSION[ "err_msg" ] = "Number must be 0 or 1."; // MESSAGE.
header( "Location: form.php" ); // ERROR.
}
}
else header( "Location: form.php" ); // WASN'T CALLED FROM "FORM.PHP".
?>
Create two files with the given names and copy-paste previous codes, then run "form.php".
You will have to paste all your huge validation in "validate.php". Your validation has many messages, I recommend you to insert one "header" after each message and add "exit" immediately after (because "header" does not stop the execution of the script).
The approach adopted below bypasses the superfluous use of isset. This also means that the checking for all $_POST['data'] Variables where consolidated unto one section of the Code, right after checking if the Submit Button-Value was set. The Function function test_input($data) {...} was completely removed since the Section mentioned above also does exactly the same thing... Multiline String-Concatenation was condensed to one single Line for brevity... There seemed also to be some extraneous if(){...}else{...} clauses all over the place. Those were ignored since they might serve some purpose to the Original Poster (though unlikely). Finally, to ensure that the form is posted back to the Current, Executing Script (considering that the processing of the Form Data is in the same Script); we would leave the action Attribute of the Form EMPTY: meaning that the Form would automatically post back to itself - the current Script.
<?php
// AT THE VERY TOP OF THE SCRIPT - PREFERABLY NOT WITHIN A DIV OR ANY CONTAINER, START YOUR PHP CODES...
$fnameErr = "";
$lnameErr = "";
$idErr = "";
$placeErr = "";
$dateErr = "";
$emailErr = "";
$pswErr = "";
$content = "";
$file;
if(isset($_POST['register'])){
// GATHER A FILTERED VERSION OF THE POST VARIABLES:
$firstName = isset($_POST['firstname']) ? htmlspecialchars(stripslashes(trim($_POST['firstname']))) : null;
$lastName = isset($_POST['lastname']) ? htmlspecialchars(stripslashes(trim($_POST['lastname']))) : null;
$idNum = isset($_POST['idnum']) ? htmlspecialchars(stripslashes(trim($_POST['idnum']))) : null;
$placeOfBirth = isset($_POST['placeOfBirth']) ? htmlspecialchars(stripslashes(trim($_POST['placeOfBirth']))) : null;
$date = isset($_POST['date']) ? htmlspecialchars(stripslashes(trim($_POST['date']))) : null;
$email = isset($_POST['email']) ? htmlspecialchars(stripslashes(trim($_POST['email']))) : null;
$password = isset($_POST['password']) ? htmlspecialchars(stripslashes(trim($_POST['password']))) : null;
if($firstName){
if(!empty($firstName)){
if(strlen($firstName)>1){
if(preg_match("/[a-zA-Z]+/", $firstName)==1){
$content .= "firstname:" . $firstName . " ";
}
else{
$fnameErr = "Your first name should only include letters";
}
}
else{
$fnameErr = "Your first name must be at least 2 characters";
}
}
else{
$fnameErr = "Enter your first name";
}
}else{
$fnameErr = "Enter your first name";
}
if(isset($lastName)){
if(!empty($lastName)){
if(strlen($lastName)>3){
if(preg_match("/[a-zA-Z]+/", $_POST['lastname'])==1){
$content .= "lastname:" . $lastName . " ";
}
else{
$lnameErr = "Your last name should only include letters";
}
}
else{
$lnameErr = "Your last name must be at least 2 characters";
}
}
else{
$lnameErr = "Enter your last name";
}
}else{
$lnameErr = "Enter your last name";
}
if(isset($idNum)){
if(!empty($idNum)){
if(strlen($idNum) == 10){
if(preg_match("/[0-9]{10}/", $_POST['idnum'])==1){
$content .= "ID_No.:" . $idNum . " ";
}
else{
$idErr = "Your ID number should only include digits";
}
}
else{
$idErr = "Your ID number must be 10 digits";
}
}
else{
$idErr = "Enter your ID number";
}
}else{
$idErr = "Enter your ID number";
}
if(isset($placeOfBirth)){
if(!empty($placeOfBirth)){
if(strlen($placeOfBirth)>2){
if(preg_match("/[a-zA-Z]+/", $placeOfBirth)==1){
$content .= "placeOfBirth:" . $placeOfBirth . " ";
}
else{
$placeErr = "Your place of birth should only include digits";
}
}else{
$placeErr = "Your place of birth must be at least 3 letters";
}
}
}
if(isset($date)){
if(!empty($date)){
$content .= "date:" . $date . " ";
}else{
$dateErr = "Enter your date of birth";
}
}else{
$dateErr = "Enter your date of birth";
}
if(isset($email)){
if(!empty($email)){
$content .= "email:" . $email . " ";
}else{
$emailErr = "Enter your email";
}
}else{
$emailErr = "Enter your email";
}
if(isset($password)){
if(!empty($password)){
if(preg_match("/(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$/", $password)==1){
$content .= "password:" . $password . " ";
}else{
$pswErr = "Your password should have numbers, uppercase<br/> & lowercase letters";
}
}else{
$pswErr = "Enter your password";
}
}else{
$pswErr = "Enter your password";
}
if(file_exists($email.".txt")){
echo "<script type='text/javascript'>alert('this email already exists!');</script>";
$firstname = $lastname = $idnum = $date = $placeOfBirth = $password = "";
}
else{
$file = fopen($email.".txt","a+") or die("Unable to open file!");
fwrite($file, $content);
fclose($file);
header("location: registered.php");
}
}
?>
<div id = "content">
<fieldset id = "fieldset">
<legend><h1 class = "reg" >Register Form</h1></legend>
<!-- SINCE YOUR VALIDATION IS IN THE CURRENT SCRIPT, LEAVING THE action ATTRIBUTE EMPTY IMPLIES THAT THE FORM WILL POST BACK TO ITSELF [THE CURRENT SCRIPT]. -->
<form method="POST" action="" enctype = "multipart/form-data">
<table class = "table">
<tr>
<td class = "labels">
<p class = "star">*</p> First Name
</td>
<td>
<input class = "inclass" type="text" required="required" placeholder="Please enter your first name" id = "firstname" name="firstname" onclick = "colorBorder(this.id)"/>
</td>
<td class = "err">
<span><?php echo $fnameErr; ?></span>
</td>
</tr>
<tr>
<td class = "labels"><p class = "star">*</p> Last Name</td>
<td>
<input class = "inclass" type="text" required="required" placeholder="Please enter your last name" name="lastname" id = "lastname" onclick = "colorBorder(this.id)"/>
</td>
<td class = "err">
<span><?php echo $lnameErr; ?></span>
</td>
</tr>
<tr>
<td class = "labels">Gender</td>
<td>
<input class = "inclass" type="radio" name="gender" value="0" /><p class = "radio" >Male</p>
<input class = "inclass" type="radio" name="gender" value="1" /><p class = "radio" >Female</p>
</td>
</tr>
<tr>
<td class = "labels"><p class = "star">*</p> ID Number</td>
<td>
<input class = "inclass" type="text" id="idnum" required="required" placeholder="Please enter your ID number" name="idnum" onclick = "colorBorder(this.id)"/>
</td>
<td class = "err">
<span><?php echo $idErr; ?></span>
</td>
</tr>
<tr>
<td class = "labels">Place of Birth</td>
<td>
<input class = "inclass" type="text" placeholder="Please enter your place of birth" name="placeOfBirth" id = "place" onclick = "colorBorder(this.id)"/>
</td>
<td class = "err">
<span><?php echo $placeErr; ?></span>
</td>
</tr>
<tr>
<td class = "labels"><p class = "star">*</p> Date Of Birth</td>
<td>
<input class = "inclass" type="date" id = "date" name="date"/>
</td>
<td class = "err">
<span><?php echo $dateErr; ?></span>
</td>
</tr>
<tr>
<td class = "labels"><p class = "star">*</p> Email</td>
<td>
<input class = "inclass" type="email" required="required" placeholder="Please enter your email" name="email" id = "email" onclick = "colorBorder(this.id)"/>
</td>
<td class = "err">
<span><?php echo $emailErr; ?></span>
</td>
</tr>
<tr>
<td class = "labels"><p class = "star">*</p> Passwords</td>
<td>
<input class = "inclass" type="password" required="required" placeholder="Please enter your password" name="password" id = "password" onclick = "colorBorder(this.id)"/>
</td>
<td class = "err">
<span><?php echo $pswErr; ?></span>
</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="register" value="register" class="save"/></td>
<td><input type="reset" name = "reset" id = "reset"/></td>
</tr>
</table>
</form>
</fieldset>
</div>
I am trying to send a form that it has taken me about 3 days to manage to build! I am really struggling with php but learning. Anyway, I have done what I think is correct but my form is not getting to me? I hope this is an easy fix! Code is as follows and I really appreciate any help:
<?php
// define variables and set to empty values
$addDateErr = $nameErr = $emailErr = $subjectErr = $messageErr = $questionErr = "";
$addDate = $name = $email = $subject = $message = $WebSearch = $SocialMedia = $WordOfMouth = $Other ="";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//Date
if (empty($_POST["addDate"]))
{$comment = "";}
else
{$comment = test_input($_POST["addDate"]);}
//Name
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = "Only letters and white space allowed";
}
}
//Email
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{
$email = test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
}
//Subject
if (empty($_POST["subject"]))
{$comment = "";}
else
{$comment = test_input($_POST["subject"]);}
//Message
if (empty($_POST["message"]))
{$messageErr = "A message is required";}
else
{$comment = test_input($_POST["message"]);}
//Question
if (isset($_POST['question']))
{
$menuVar = $_POST['question'];
} else {
$menuVar = "----------";}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" id="form" action="send.php">
<p><span class="error">* required field.</span></p><br />
<!--<form method="post" id="form" action="<php echo htmlspecialchars($_SERVER["PHP_SELF"]);>">-->
<!--Date--><div class="contact-font">
Date Photography needed (if necessary)<br />
<input type="text" name="addDate" id="datepicker" size="25" value="<?php if(isset($_POST['addDate'])) {echo $_POST['addDate']; } ?>">
</div>
<!--Name--><div class="contact-font" style=" margin-top: 20px;">
<span class="asterix">* </span>Name:<br />
<input type="text" name="name" class="border" size="25" value="<?php if(isset($_POST['name'])) {echo $_POST['name']; } ?>">
<span class="error"><?php echo $nameErr;?></span>
</div>
<!--Email--><div class="contact-font" style=" margin-top: 20px;">
<span class="asterix">* </span>Email: (please double check enty)<br />
<input type="text" name="email" class="border" size="25" value="<?php if(isset($_POST['email'])) {echo $_POST['email']; } ?>"><span class="error">
<?php echo $emailErr;?></span>
</div>
<!--Subject--><div class="contact-font" style=" margin-top: 20px;">
Subject:<br />
<input type="text" name="subject" class="border" size="25" value="<?php if(isset($_POST['subject'])) {echo $_POST['subject']; } ?>">
</div>
<!--Message--><div class="contact-font" style=" margin-top: 20px;">
<span class="asterix">* </span>Message:<br />
<textarea cols="40" rows="10" name="message" class="border"><?php if(isset($_POST['message'])) {echo $_POST['message']; } ?></textarea>
<span class="error"><?php echo $messageErr;?></span>
</div><br />
<select name="question">
<option <?php if($menuVar=="----------") echo 'selected="selected"'; ?> value="----------">----------</option>
<option <?php if($menuVar=="WebSearch") echo 'selected="selected"'; ?> value="WebSearch">Web Search</option>
<option <?php if($menuVar=="SocialMedia") echo 'selected="selected"'; ?> value="SocialMedia">Social Media</option>
<option <?php if($menuVar=="Wordofmouth") echo 'selected="selected"'; ?> value="Wordofmouth">Word of mouth</option>
<option <?php if($menuVar=="Other") echo 'selected="selected"'; ?> value="Other">Other</option>
</select>
<div>
<input type="submit" value="Send" id="submit">
</div>
</form>
<script>
$(document).ready(function() {
$("#datepicker").datepicker({minDate: 129, maxDate: "+5Y", changeMonth: true,changeYear: true, showButtonPanel: true, dateFormat: 'dd MM yy'});
});
$('#form').on('submit', function(){
return $('#email').val() == $('#emailConfirmation').val();
});
</script>
<style type="text/css">
.asterix{color: #bc2021;font-size: 20px;}
.contact-font, #info-req, #opening-text{font-family: 'Raleway', sans-serif; font-weight: 100; color: #000;}
.border:focus{border: 2px solid #bc2021;}
#datepicker:focus{border: 2px solid #bc2021;}
.error {color: #FF0000;}
#marketing{border: 1px solid black; width: 150px; height: 22px;}
#submit{width: 100px; height: 25px; font-size: 15px;}
#submit:active{background-color: #bc2021;}
</style>
Below is the send.php file contents:
<?php
$addDate = $_POST['addDate'];
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$question = $_POST['question'];
$to = "some#email.com";
$subject = "Help!";
$body = "Please do not reply!";
mail($to,$subject,$body);
echo "Message Sent!<a href='index.html'>Home</a>";
?>