Post Self Form Validation and Submission in PHP - php

So I built and tested this form using an online IDE for a class. The validation and post_self submission was working great, now it appears that it doesn't work and I'm not really sure as to what I did wrong. Essentially, on submit the form self posts and echos out the information from the form beneath the form. It worked wonderfully before, but I have clearly made some form of error. The self_post action for the form wasn't working at all and I think I fixed that, but the
<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01//EN'
'http://www.w3.org/TR/1999/REC-html401-19991224/strict.dtd'>
<html>
<head>
<title>Registration Form</title>
<meta charset = "utf-8" />
</head>
<body>
<?php
$nameErr = $phoneErr = $addressErr = $cityErr = $stateErr = $zipErr = "";
$name = $phone = $address = $city = $zip = $state = "";
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 whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
$name = "";
}
}
if (empty($_POST["phone"])) {
$phoneErr = "Phone number is required";
}
else {
$phone = test_input($_POST["phone"]);
}
if (empty($_POST["address"])) {
$addressErr = "Street address is required";
}
else {
$address = test_input($_POST["address"]);
}
if (empty($_POST["city"])) {
$cityErr = "City is required";
}
else {
$city = test_input($_POST["city"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
$cityErr = "Only letters and white space allowed";
$city = "";
}
}
if (empty($_POST["state"])) {
$stateErr = "State is required";
}
else {
$state = test_input($_POST["state"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$state)) {
$stateErr = "Only letters and white space allowed";
$state = "";
}
}
if (empty($_POST["zip"])) {
$zipErr = "Zip code is required";
}
else {
$zip = test_input($_POST["zip"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method = "post" action = ""<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"">
<div id = "table" style = "margin: 200px 0px 0px 0px;">
<h2 align = "center">Please register to enjoy our services</h2>
<table align = "center" border = "1">
<tr>
<td> Name: </td>
<td> <input type = "text" name = "name" size = "30" value = ""<?php echo $name;?>""/><span class="error">* <?php echo $nameErr;?></span></td>
</tr>
<tr>
<td> Street Address: </td>
<td> <input type = "text" name = "address" size = "30" value=""<?php echo $address;?>"" /><span class="error">* <?php echo $addressErr;?></span></td>
</tr>
<tr>
<td> City: </td>
<td> <input type = "text" name = "city" size = "30" value=""<?php echo $city;?>""/><span class="error">* <?php echo $cityErr;?></span></td>
</tr>
<tr>
<td> State: </td>
<td> <input type = "text" name = "state" size = "30" value=""<?php echo $state;?>""/><span class="error">* <?php echo $stateErr;?></span></td>
</tr>
<tr>
<td> Zip Code: </td>
<td> <input type = "text" name = "zip" size = "30" value=""<?php echo $zip;?>""/><span class="error">* <?php echo $zipErr;?></span></td>
</tr>
<tr>
<td> Phone: </td>
<td> <input type = "text" name = "phone" size = "30" value=""<?php echo $phone;?>""/><span class="error">* <?php echo $phoneErr;?></span></td>
</tr>
</table>
</div>
<br />
<div id = "button" align = "center">
<input type = "Submit" name = "register" value = "Register"/>
<input type = "Reset" name = "clear" value = "Clear Form"/>
</div>
</form>
<div id = "results" align = "center">
<?php
echo "<h2>Registration Information:</h2>";
echo $name;
echo "<br>";
echo $address;
echo "<br>";
echo $city;
echo "<br>";
echo $state;
echo "<br>";
echo $zip;
echo "<br />";
echo $phone;
?>
</div>
</body>
</html>

Check out http://www.php.net/manual/en/reserved.variables.server.php. It says "The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here." Something changed in the config of your server, and $_SERVER["REQUEST_METHOD"] is not populated anymore. An alternative way to see if the method was a post (assuming some query parameters were posted) is if(count($_POST)>0) {...}

Related

PHP Validation. It won't go to display page

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.

how can I get the action attribute in form tag to work correctly?

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>

PHP ignoring if statements

I am having a very weird problem here, my if else statements just get ignored after I submit the form and all values entered or not entered goes through to the database.
Firstly, I pre populate all fields with info submitted during registration then users can edit and change their info - this works fine but I decided to add it as I don't know whether it might have a hand in this mystery error.
Here's my code to retrieve details, the variables holding retrieved values are echoed in their respective fields in the form.
<?php
include("connect.php");
$results = $conn->query("SELECT username, first_name,last_name, email,phone,address FROM users WHERE email='$user_logged'");
while ($row = $results->fetch_assoc()) {
$u_name = $row['username'];
$f_name = $row['first_name'];
$l_name = $row['last_name'];
$email = $row['email'];
$phone = $row['phone'];
$address = $row['address'];
}
$results->free();
$conn->close();
?>
It's not checking for empty fields. Functions test_input and preg_match do not work alsko. The form just submits and database gets updated.
I have spent 2 days going through to look for where the error might be but I can't detect it.
<?php
$user_logged = $_SESSION['logged_in'];
if (isset($_POST['btnUpdate'])) {
include("connect.php");
$phoneErr = $f_nameErr = $l_nameErr = "";
$user_email = $first_name = $last_name = $phone_upadate = $address_updated = "";
if (empty($_POST["fname"])) {
$f_nameErr = "First Name is required";
} else {
$first_name = test_input($_POST["fname"]);
if (!preg_match("/^[a-zA-Z ]*$/", $first_name)) {
$f_nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["lname"])) {
$l_nameErr = "Last Name is required";
} else {
$last_name = test_input($_POST["lname"]);
if (!preg_match("/^[a-zA-Z ]*$/", $last_name)) {
$l_nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["phone"])) {
$phoneErr = "Phone No is required";
} else {
$phone_upadate = test_input($_POST['phone']);
if (!preg_match("/^[0-9]{0,18}$/", $phone_upadate)) {
$phoneErr = "Only numbers and white space allowed";
}
}
$user_email = $_POST['email'];
$address_updated = $_POST['txtaddress'];
$results = $conn->query("UPDATE users SET
first_name='$first_name',last_name='$last_name',
email='$user_email',phone='$phone_upadate',
address='$address_updated'
WHERE email='$user_logged'");
if ($results) {
header("Location: edit-info.php");
} else {
print 'Error : (' . $conn->errno . ') ' . $conn->error;
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Here is my html code
<form action="edit-info.php" method="POST">
<?php $username_error="can't be changed"; ?>
<p>Username</p>
<p><input type="text" name="username" id="txtuser" value="<?php echo $u_name; ?>" readonly></input><span id="error"><?php echo $username_error?></span></p>
<p>First Name</p>
<p><input type="text" name="fname" id="txtuser" value="<?php echo $f_name; ?>"></input><span id="error"><?php echo $f_nameErr;?></span></p>
<p>Last Name</p>
<p><input type="text" name="lname" id="txtuser" value="<?php echo $l_name; ?>" ></input><span id="error"><?php echo $l_nameErr;?></span></p>
<p>Email</p>
<p> <input type="text" name="email" id="txtuser" value="<?php echo $email; ?>" readonly></input><span id="error"><?php echo $f_nameErr;?></span></p>
<p>Phone</p>
<p><input type="text" name="phone" id="txtuser" value="<?php echo $phone; ?> " ></input></p>
<span id="error"><?php echo $phoneErr;?></span>
<p>Address</p>
<p><textarea id="txtaddress" name="txtaddress" cols="40" rows="10" ><?php echo $address; ?></textarea></p>
<p><input type="submit" name="btnUpdate" value="UPDATE" /></p>
</form>
You need to check the values of $phoneErr, $f_nameErr, $l_nameErr before you proceed UPDATE like this
if(empty($phoneErr) && empty($f_nameErr) && empty($l_nameErr)){
$results = $conn->query("UPDATE users SET first_name='$first_name',last_name='$last_name', email='$user_email',phone='$phone_upadate',address='$address_updated' WHERE email='$user_logged'");
}
Because when you have any validation error in empty or preg_match you are updating these values. And without checking these $phoneErr, $f_nameErr, $l_nameErr variables you are proceeding to UPDATE
You could try replacing
"/^[a-zA-Z ]*$/"
with
"/^[a-zA-Z ]+$/"
Notice we are replacing the multiplication sign with a summation sign.

PHP How to submit form, if there are no errors. no javascript

I have separate email script; however, how would we run that code if there are no errors. I have a array with form errors $errors = array($nameErr, $emailErr, $phoneErr, $zipErr, $serviceErr); but they have different strings, if there are no strings or Null or '' inside the array, we would like to send email.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $phoneErr = $emailErr = $zipErr = $serviceErr = "";
$name = $phone = $email = $zip = $service = $comment = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "name required.";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "letters and spaces only.";
}
}
if (empty($_POST["email"])) {
$emailErr = "email 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["phone"])) {
$phoneErr = "phone required.";
} else {
//Check phone for numbers () or - only
$phone = test_input($_POST["phone"]);
if (!preg_match("/^[\+0-9\-\(\)\s]*$/", $phone)) {
$phoneErr = "format.";
}
}
if (empty($_POST["zip"])) {
$zipErr = "zip required.";
} else {
$zip = test_input($_POST["zip"]);
}
if (!preg_match("/^[\+0-9\-\(\)\s]*$/", $zip)){
$zipErr = "format.";
}
if ($_POST["service"] == NULL ) {
$serviceErr = "service required.";
}else {
$service = test_input($_POST["service"]);
}
$comment = test_input($_POST["comment"]);
//**********************************************************************
$errors = array($nameErr, $emailErr, $phoneErr, $zipErr, $serviceErr);
if (isset($_POST['Submit'])) {
//if no errors run send email CODE.
}
//***********************************************************************
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td> Name:
<br />
<input name="name" type="text" size="20" value="<?php echo $name;?>">
<span class="error">* <?php echo "<br />"; echo $nameErr;?></span>
</td>
</tr>
<tr>
<td> Phone:
<br />
<input name="phone" type="text" size="20" value="<?php echo $phone;?>">
<span class="error">* <?php echo "<br />"; echo $phoneErr;?></span>
</td>
</tr>
<tr>
<td> E-mail:
<br />
<input name="email" type="text" size="20" value="<?php echo $email;?>">
<span class="error">* <?php echo "<br />"; echo $emailErr;?></span>
</td>
</tr>
<tr>
<td> Zip:
<br />
<input name="zip" type="text" size="20" value="<?php echo $zip;?>">
<span class="error">* <?php echo "<br />"; echo $zipErr;?></span>
</td>
</tr>
<tr>
<td> Service:
<br />
<select name="service">
<option selected="selected" value="<?php echo $service;?>"><?php echo $service;?></option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<span class="error">* <?php echo "<br />"; echo $serviceErr;?></span>
</td>
</tr>
<tr>
<td> Message:
<br />
<textarea name="comment" rows="2" cols="20"><?php echo $comment;?></textarea></td>
</tr>
<tr>
<td>
<input type="submit" name="Submit" value="Send" />
</td>
</tr>
</table>
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $phone;
echo "<br>";
echo $zip;
echo "<br>";
echo $service;
echo "<br>";
echo "$comment";
?>
</body>
</html>
try with the below code:
$errors = array($nameErr, $emailErr, $phoneErr, $zipErr, $serviceErr);
if (isset($_POST['Submit'])) {
if(!array_filter($errors)){
// code here
}
else {
echo "Error";
}
}
Save your errors in an array, then check if the array is empty at the end. If so, no errors - submit email. Else, display errors:
//dont declare separate variables,use an array
//$nameErr = $phoneErr = $emailErr = $zipErr = $serviceErr = "";
$errors = [];
if (empty($_POST["name"])) {
$errors['nameErr'] = "name required.";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$errors['nameErr'] = "letters and spaces only.";
}
}
//other validation here, then
if(empty($errors){
//no errors, submit
your_submit_function();
}else{
//display errors
foreach($errors as $val){
echo $val . '<br/>';
}
}

PHP code not working (Not inserting data into database)

I am trying to process a form which will insert data into database, but it is inserting anything in database. I am trying this since couple of days...but got no solution....it is also not showing any error also..please guide....asap...
<?php
if(isset($_POST['submit'])){
$generic_drug_name = $_POST['generic_drug_name'];
$brand_drug_name = $_POST['brand_drug_name'];
$manufacturer_name = $_POST['manufacturer_name'];
$type = $_POST['type'];
$price = $_POST['price'];
}else{
$generic_drug_name = '';
$brand_drug_name = '';
$manufacturer_name = '';
$type = '';
$price = '';
}
$errors = '';
$errors['generic_drug_nameErr'] = '';
$errors['brand_drug_nameErr'] = '';
$errors['manufacturer_nameErr'] = '';
$errors['typeErr'] = '';
$errors['priceErr'] = '';
?>
<body>
<header>
<?php echo navigation(); ?>
</header>
<section>
<div id="envelope">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["generic_drug_name"])) {
$errors['generic_drug_nameErr'] = "Name is required";
}else{
$generic_drug_name = test_input($_POST["generic_drug_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$generic_drug_name)) {
$errors['generic_drug_nameErr'] = "Only letters and white space allowed";
}
}
if (empty($_POST["brand_drug_name"])) {
$errors['brand_drug_nameErr'] = "Name is required";
}else{
$brand_drug_name = test_input($_POST["brand_drug_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$brand_drug_name)) {
$errors['brand_drug_nameErr'] = "Only letters and white space allowed";
}
}
if (empty($_POST["manufacturer_name"])) {
$errors['manufacturer_nameErr'] = "Name is required";
}else{
$manufacturer_name = test_input($_POST["manufacturer_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$manufacturer_name)) {
$errors['manufacturer_nameErr'] = "Only letters and white space allowed";
}
}
if (empty($_POST["type"])) {
$errors['typeErr'] = "Type is required";
} else {
$type = test_input($_POST["type"]);
// check if e-mail address is well-formed
if (!preg_match("/^[a-zA-Z ]*$/",$type)) {
$errors['typeErr'] = "Only letters and white space allowed";
}
}
if (empty($_POST["price"])) {
$errors['priceErr'] = "";
} else {
$price = test_input($_POST["price"]);
// check if e-mail address is well-formed
if (!preg_match("/^[0-9\_]{1,4}/",$price)) {
$errors['priceErr'] = "Invalid price format";
}
}
}
?>
<center><h1>Add a new brand drug</h1></center><br>
<label>Generic Drug Name</label><span class="error">* </span><span class="text"><?php echo $errors['generic_drug_nameErr'];?></span>
<input type="text" name="generic_drug_name" placeholder="Enter Generic drug Names" value="<?php echo htmlspecialchars($generic_drug_name); ?>" width="100px;"/>
<label>Brand Drug Name</label><span class="error">* </span><span class="text"><?php echo $errors['brand_drug_nameErr'];?></span>
<input type="text" name="brand_drug_name" placeholder="Amlokind" autofocus="autofocus" value="<?php echo htmlspecialchars($brand_drug_name); ?>" width="100px;">
<label>Manufacturer</label><span class="error">* </span><span class="text"><?php echo $errors['manufacturer_nameErr'];?></span>
<input type="text" name="manufacturer_name" placeholder="Glaxo Smithkline Pharmaceuticals Pvt. Ltd." autofocus="autofocus" value="<?php echo htmlspecialchars($manufacturer_name); ?>">
<label>Type</label><span class="error">* </span><span class="text"><?php echo $errors['typeErr'];?></span>
<input type="text" name="type" placeholder="Tablet" autofocus="autofocus" value="<?php echo htmlspecialchars($type); ?>">
<label>Price</label><span class="error">* </span><span class="text"><?php echo $errors['priceErr'];?></span>
<input type="text" name="price" placeholder="10.45" autofocus="autofocus" value="<?php echo htmlspecialchars($price); ?>" >
<input type="submit" name = "submit" value="Add" id="submit"/>
</form>
</div>
<?php
if(isset($_POST['submit'])){
/*$generic_drug_name = $_POST['generic_drug_name'];
$brand_drug_name = $_POST['brand_drug_name'];
$manufacturer_name = $_POST['manufacturer_name'];
$type = $_POST['type'];
$price = $_POST['price'];*/
if(empty($errors)){
$safe_generic_drug_name = strtoupper($generic_drug_name);
$safe_brand_drug_name = strtoupper($brand_drug_name);
$safe_manufacturer_name = ucwords($manufacturer_name);
$safe_type = ucfirst($type);
$safe_price = $price;
$query = "INSERT INTO brand_generic.brand_drug (drug_id, brand_drug_name, manufacturer, type, price)
SELECT id, '{$safe_brand_drug_name}','{$safe_manufacturer_name}', '{$safe_type}', {$safe_price}
FROM brand_generic.generic_drug
WHERE generic_drug_name = '{$safe_generic_drug_name}';";
//INSERT INTO brand_generic.brand_drug (drug_id, brand_drug_name, manufacturer, type, price) VALUES ((SELECT id FROM brand_generic.generic_drug WHERE generic_drug_name = 'AMLODIPINE'), 'ZODIPINE', 'Zorex Pharma Pvt Ltd', 'Tablet', 10);
if(!$query){
die(mysqli_error());
}
$result = mysqli_query($connection, $query);
var_dump($result);
if($result){
$_SESSION["message"] = "Successfully subject created";
//redirect_to("manage_content.php");
echo $_SESSION["message"];
}else{
$_SESSION["message"] = "Sorry, subject couldn't be created";
//redirect_to("new_subject.php");
echo $_SESSION["message"];
}
}
}
?>
This code is also not showing any error....so that's why I can't tell you what's wrong here......but it's not working...that's all I can say right now....Thank You...:)
Hello everyone once again, thanks for your suggestion, but it didn't work for me....but when I put
if(!empty($errors)){
instead of
if(empty($errors)){
it works....it should not work, right?...because it will take any data and insert it into database..if not please guide me....Thank you to all...:)
You cant use set a session after starting printing to browser.
so move
if(isset($_POST['submit'])){
to the top of page, before the HTML.
It shows a debug error message like follows.
Fatal error: Call to undefined function navigation() in /var/www/poc.php on line 25
It mean the function navigation() is used but not created any where in the script. And fatal error won't let the script to further proceed. So it is a blocking point
At least include following line at top of PHP block will avoid the error
<?php
function navigation(){
return 1;
}
?>
Additionally if you want to see the error message on your server use following two lines on the top of the script.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
?>

Categories