PHP form verification - php

I'm new to PHP so please be gentle!
I'm trying to build a simple PHP form validation with an error message/confirm message. When I submit the form, it's supposed to check if fields are empty and display the corresponding message. But it keeps giving me an error and I have no idea why:
Parse error: syntax error, unexpected T_IF in process.php on line 6
Here's process.php code:
<form action="process.php" method="post">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
E-mail: <input type="text" name="email"><br>
<input type="hidden" name="submitted" value="1">
<input type="submit">
</form>
<?php
//If form was submitted
if ($_POST['submitted']==1) {
$errormsg = ""; //Initialize errors
if ($_POST[fname]){
$fname = $_POST[fname]; //If fname was entered
}
else{
$errormsg = "Please enter first name";
}
if ($_POST[lname]){
$lname = $_POST[lname]; //If lname was entered
}
else{
if ($errormsg){ //If there is already an error, add next error
$errormsg = $errormsg . ", last name";
}
else{
$errormsg = "Please enter last name";
}   
}
if ($_POST[email]){
$email = $_POST[email]; //If email was entered
}
else{
if ($errormsg){ //If there is already an error, add next error
$errormsg = $errormsg . " & email";
}else{
$errormsg = "Please enter email";
}
}
}
if ($errormsg){ //If any errors display them
echo "<div class=\"box red\">$errormsg</div>";
}
//If all fields present
if ($fname && $lname && $email){
//Do something
echo "<div class=\"box green\">Form completed!</div>";
}
?>

You forgot to add " on post array that is the reason for your error $_POST[lname] change to $_POST['lname']; . Pass string to your $_POST[];
if ($_POST["fname"]){
$fname = $_POST[fname]; //If fname was entered
}
else{
$errormsg = "Please enter first name";
}
if ($_POST["lname"]){
$lname = $_POST[lname]; //If lname was entered
}
else{
if ($errormsg){ //If there is already an error, add next error
$errormsg = $errormsg . ", last name";
}
else{
$errormsg = "Please enter last name";
}
}
if ($_POST["email"]){
$email = $_POST["email"]; //If email was entered
}

Some of your $_POST variables were missing single quotation marks, which is probably what caused the errors. However, generally speaking, there are other code suggestions which I've layed out.
I restructured your code to be more scalable and follow better practice with the following enhancements:
Form values will remember their previous value and not erased on each post.
Removed the 'submitted' field and replaced with if (!empty($_POST)) {} to make sure form was posted.
Moved error messages into an array. This is more maintainable and readable to my taste (imagine having 15+ fields to test for).
Added validate() function to run on your validation tests.
Removed variable assignments ($fname = $_POST['fname']) since they were not used except for the validation, which can access them directly.
Moved all tests inside the main if statement.
Hope this helps!
<form action="process.php" method="post">
First Name: <input type="text" name="fname" value="<?php echo isset($_POST['fname']) ? $_POST['fname'] : ''?>"><br>
Last Name: <input type="text" name="lname" value="<?php echo isset($_POST['lname']) ? $_POST['lname'] : ''?>"><br>
E-mail: <input type="text" name="email" value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''?>"><br>
<input type="submit">
</form>
<?php
//If form was submitted
if (!empty($_POST)) {
$errors = array();
if (empty($_POST['fname'])){
$errors[] = 'First name must be entered.';
}
if (empty($_POST['lname'])){
$errors[] = 'Last name must be entered.';
}
if (empty($_POST['email'])){
$errors[] = 'Email address must be entered.';
}
if ($errors){ //If any errors display them
$error_msg = implode('<br>',$errors);
echo "<div class=\"box red\">$error_msg</div>";
}
//If all fields present
elseif (validate()){
//Do something
echo "<div class=\"box green\">Form completed and validated!</div>";
}
}
function validate() {
/*you can run all your validation methods here, such as check for length, regexp email verification, etc.*/
$validated = false;
if ($_POST['fname'] && $_POST['lname'] && $_POST['email']) {
$validated = true;
}
return $validated;
}
?>

For the $_POST variables use syntax as $_POST['your variable name']
I corrected your code as below:
<form action="test.php" method="post">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
E-mail: <input type="text" name="email"><br>
<input type="hidden" name="submitted" value="1">
<input type="submit">
</form>
<?php
//If form was submitted
if ($_POST['submitted']==1) {
$errormsg = ""; //Initialize errors
if ($_POST['fname']){
$fname = $_POST['fname']; //If fname was entered
}
else{
$errormsg = "Please enter first name";
}
if ($_POST['lname']){
$lname = $_POST['lname']; //If lname was entered
}
else{
if ($errormsg){ //If there is already an error, add next error
$errormsg = $errormsg . ", last name";
}
else{
$errormsg = "Please enter last name";
}
}
if ($_POST['email']){
$email = $_POST['email']; //If email was entered
}
else{
if ($errormsg){ //If there is already an error, add next error
$errormsg = $errormsg . " & email";
}else{
$errormsg = "Please enter email";
}
}
}
if ($errormsg){ //If any errors display them
echo "<div class=\"box red\">$errormsg</div>";
}
//If all fields present
if ($fname && $lname && $email){
//Do something
echo "<div class=\"box green\">Form completed!</div>";
}
?>

As Ohgodwhy said,
You need to change every existence of $_POST[word] to $_POST['word']. Note the '.
And why are you using <input type="hidden" name="submitted" value="1">, this is not a good practice. Better use.
if($_SERVER['REQUEST_METHOD'] == "POST")

The issue here is a lack of register globals being enabled (which is a good thing in my eyes) and not using proper string encapsulation.
You need to change every existence of $_POST[word] to $_POST['word']. Note the '.

I am Using thing type of simple validation. Here is my javascript code:
var ck_name = /^[A-Za-z0-9 ]{3,50}$/;
var ck_email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;
var ck_mob = /^[0-9 ]{8,11}$/;
function validate(form){
var name = form.name.value;
var email = form.email.value;
var mob = form.mob.value;
var errors = [];
if (!ck_name.test(name))
{
errors[errors.length] = "Your valid Name .";
}
if (!ck_email.test(email))
{
errors[errors.length] = "Your must enter a valid email address.";
}
if (!ck_mob.test(mob))
{
errors[errors.length] = "Your valid Mobile Number.";
}
if (errors.length > 0)
{
reportErrors(errors);
return false;
}
return true;
}
function reportErrors(errors)
{
var msg = "Please Enter Valide Data...\n";
for (var i = 0; i<errors.length; i++)
{
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}

Related

PHP Variable not storing value after submit

I have a simple PHP page, and am attempting to validate form input.
Upon hitting submit with invalid data, the inputted value is not being returned in my echo statement
I want to echo the input as the value so that the user can understand what they typed wrong. Below is my code;
Neither the echo of "TEST" . $contactEmail nor the input value are displaying $contactEmail
<?php
// define variables and set to empty values
$contactFirstNameErr = $contactEmailErr = $retailerIDErr = "";
$contactFirstName = $contactEmail = $retailerID = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input fields
if (empty($_POST["contactFirstName"])) {
$contactFirstNameErr = "<br>*First Name is required";
} else {
$contactFirstName = test_input($_POST["contactFirstName"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$contactFirstName)) {
$contactFirstNameErr = "<br>*Only letters and white space allowed";
}
}
//Email Field
if (empty($_POST["contactEmail"])) {
$contactEmailErr = "<br>*Email is required";
} else {
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$contactEmailErr = "<br>*Invalid email format";
} else {
$contactEmail = test_input($_POST["contactEmail"]);
}
}
//Option Field
if (empty($_POST["retailerID"])) {
$retailerIDErr = "<br>*Retailer is required";
} else {
$retailerID = test_input($_POST["retailerID"]);
}
}
?>
<!--Begin HTML Form-->
<div class="Form_container">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Contact First Name<span class="required">*</span><span class="formError"><?php echo $contactFirstNameErr;?></span><br> <!--<p class='spacerLine'></p>-->
<input type="text" class="largeInput" name="contactFirstName" value="<?php echo $contactFirstName;?>">
<br><br>
Contact E-mail<span class="required">*</span><span class="formError"> <?php echo $contactEmailErr;?></span><br>
<input type="text" class="largeInput" name="contactEmail" value="<?php echo $contactEmail;?>">
<br><br>
<?php echo "TEST" . $contactEmail;?>
<br><br>
Retailer<span class="required">*</span><span class="formError"><?php echo $retailerIDErr;?></span><br>
<input type="text" class="largeInput" name="retailerID" value="<?php echo $retailerID;?>">
<br><br>
<input type="submit" class="button" name="submit" value="Add Contact">
</form>
</div>
Any thoughts? I'm new to PHP but have been following the W3 tutorial pretty tightly. Could it be my classes throwing things off? Or did I just mess up a variable name?
Thanks for all help
I want to echo the input as the value so that the user can understand what they typed wrong.
Neither the echo of "TEST" . $contactEmail nor the input value are displaying $contactEmail
First of all, echo $_POST values instead of $contactFirstName, $contactEmail etc. because these values are available only after it crosses all the validation steps.
Second, there's no function named test_input() in your code, or may be it is defined somewhere else.
And finally, look at this statement here:
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { ..
There's no variable named $email in your code. It should be:
if (!filter_var($_POST["contactEmail"], FILTER_VALIDATE_EMAIL)) { ..
So your code should be like this:
<?php
function test_input($string){
// your code
}
$contactFirstNameErr = $contactEmailErr = $retailerIDErr = "";
$contactFirstName = $contactEmail = $retailerID = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input fields
if (empty($_POST["contactFirstName"])) {
$contactFirstNameErr = "<br>*First Name is required";
} else {
$contactFirstName = test_input($_POST["contactFirstName"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$contactFirstName)) {
$contactFirstNameErr = "<br>*Only letters and white space allowed";
}
}
//Email Field
if (empty($_POST["contactEmail"])) {
$contactEmailErr = "<br>*Email is required";
} else {
// check if e-mail address is well-formed
if (!filter_var($_POST["contactEmail"], FILTER_VALIDATE_EMAIL)) {
$contactEmailErr = "<br>*Invalid email format";
} else {
$contactEmail = test_input($_POST["contactEmail"]);
}
}
//Option Field
if (empty($_POST["retailerID"])) {
$retailerIDErr = "<br>*Retailer is required";
} else {
$retailerID = test_input($_POST["retailerID"]);
}
}
?>
<div class="Form_container">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Contact First Name<span class="required">*</span><span class="formError"><?php echo $contactFirstNameErr; ?></span><br>
<input type="text" class="largeInput" name="contactFirstName" value="<?php if(isset($_POST['contactFirstName'])){ echo $_POST['contactFirstName']; } ?>">
<br><br>
Contact E-mail<span class="required">*</span><span class="formError"> <?php echo $contactEmailErr;?></span><br>
<input type="text" class="largeInput" name="contactEmail" value="<?php if(isset($_POST['contactEmail'])){ echo $_POST['contactEmail']; } ?>">
<br><br>
<?php
echo "TEST ";
if(isset($_POST['contactEmail'])){ echo $_POST['contactEmail']; }
?>
<br><br>
Retailer<span class="required">*</span><span class="formError"><?php echo $retailerIDErr;?></span><br>
<input type="text" class="largeInput" name="retailerID" value="<?php if(isset($_POST['retailerID'])){ echo $_POST['retailerID']; } ?>">
<br><br>
<input type="submit" class="button" name="submit" value="Add Contact">
</form>
</div>
Here's the reference for isset() function:
isset()
Sidenote: Even though this answer will work you temporarily, but you should definitely look at how to strictly validate form inputs using regex.
The below line validates the value of the variable $email, but i can't see anywhere in your code where does that variable get set a value, that can be the first step in fixing the issue.
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
You are not defining test_input() function and $email is not defined in this line:
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
This code works for me so far:
$contactFirstNameErr = $contactEmailErr = $retailerIDErr = "";
$contactFirstName = $contactEmail = $retailerID = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input fields
if (empty($_POST["contactFirstName"])) {
$contactFirstNameErr = "<br>*First Name is required";
} else {
$contactFirstName = $_POST["contactFirstName"];
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$contactFirstName)) {
$contactFirstNameErr = "<br>*Only letters and white space allowed";
}
}
//Email Field
if (empty($_POST["contactEmail"])) {
$contactEmailErr = "<br>*Email is required";
} else {
// check if e-mail address is well-formed
if (empty($_POST["contactEmail"])) {
$contactEmailErr = "<br>*Invalid email format";
} else {
$contactEmail = $_POST["contactEmail"];
}
}
//Option Field
if (empty($_POST["retailerID"])) {
$retailerIDErr = "<br>*Retailer is required";
} else {
$retailerID = $_POST["retailerID"];
}
}

How to catch and validate the input date type?

I am trying to create a PHP validation form. I have two problems here:
Validate the email input
Validate the date input
For some reason it doesn't catch these two. Here's my form.php
<div class="form_reg">
<h2>Registration Form</h2>
<form action="registration_process.php" method="post">
<p><label for="email">Email:</label>
<input type="email" name="email" value=""/></p>
<p><label for="first_name">First Name:</label>
<input type="text" name="first_name" value=""/></p>
<p><label for="last_name">Last Name:</label>
<input type="text" name="last_name" value=""/></p>
<p><label for="password">Password:</label>
<input type="password" name="password" value=""/></p>
<p><label for="confirm_password">Confirm Password:</label>
<input type="password" name="confirm_password" value=""/></p>
<p><label for="date">Birth Date:</label>
<input type="date" name="date" value=""/></p>
<input type="submit"/>
</form>
Here's my validate.php:
session_start();
$errors = array();
//empty array to collect errors
if(empty($_POST['email']) AND !filter_var($email, FILTER_VALIDATE_EMAIL) === false)
{
$errors[] = "email cannot be blank";
}
if(empty($_POST['first_name']))
{
$errors[] = "First Name cannot be blank";
}
if(empty($_POST['last_name']))
{
$errors[] = "Last Name cannot be blank";
}
if(empty($_POST['password']))
{
$errors[] = "Password cannot be blank";
}
if(empty($_POST['confirm_password']) AND $_POST['password'] == $_POST['confirm_password'])
{
$errors[] = "Please enter matching password";
}
if(empty($_POST['confirm_password']) AND $_POST['password'] == $_POST['confirm_password'])
{
$errors[] = "Please enter matching password";
}
if(isset($_POST['date']) && strtotime($_POST['date']))
{
$errors[] = "Birth Date cannot be blank";
}
if(!empty($errors))
{
//if there are errors, assign the session variable!
$_SESSION['errors'] = $errors;
//redirect your user back using header('location: ')
header('Location: registration_page.php');
}
else
{
$email = $_POST['email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$password = $_POST['password'];
$birth_date = $_POST['date'];
//redirect your user to the next part of the site!
}
?>
Any idea?
Might be you should try like this also. First, check either email is blank or not. If not blank, check either it is in correct format:
if(empty($_POST['email']))
{
$errors[] = "email cannot be blank";
}else if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$errors[] = "invalid email";
}
and this also:
if(!isset($_POST['date']){
$errors[] = "date is blank";
}else if(!strtotime($_POST['date'])){
$errors[] = "invalid date";
}
Firstly your code for email is saying if the email is NOT empty then ignore the email format checking. This I do not think is what you wanted. Additionally you have a double negative using !filter_var and then === false.
I believe you wanted something like: (I separated them onto different lines so you can see the flow better)
if( empty($_POST['email']) OR
( filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false ) ) {
$errors[] = "email is blank or incorrectly formatted";
}
Secondly your Date is doing a similar thing, I believe you want something like below again:
if( isset($_POST['date']) OR
!strtotime($_POST['date'])) {
$errors[] = "Birth Date must be a valid date";
}
NOTE: strtotime will return -1 not false on version previous to PHP 5.1.0, you are most likely on a version higher then that thou.
EDIT: Notice I change the $email to $_POST['email'] as you never set $email anywhere in the code you showed.
Your logic is just a smidge off.
For the email, try:
if(empty($_POST['email']))
{
// if no email was entered
$errors[] = "email cannot be blank";
}
else if (filter_var($email, FILTER_VALIDATE_EMAIL) === false)
{
// email was entered, but was invalid
$errors[] = "please enter a valid email";
}
You want to trigger this if block if $_POST['email'] is blank, or if it isn't a valid email address. Since you're checking the output of the filter_var() function, you want to check whether it is equal to false.
For the date, try:
if(!isset($_POST['date']))
{
// if no date was entered
$errors[] = "Birth Date cannot be blank";
}
else if (strtotime($_POST['date']) === false)
{
// date was entered, but was invalid
$errors[] = "please enter a valid date";
}
Since you want to trigger the date error if a) the date is left blank, or b) it's not a valid date, this if block should run only if $_POST['date'] is not set, or if strtotime() returns false.

Clear form fields after a successful submit

well im working on a small html form.
<form class="contact" action="" method="POST">
<label>Name : </label><input type="text" name="name" value="<? echo $name; ?>"/>
<p class="middle"><label>Comment : </label><textarea name="message"></textarea><? echo $message; ?></p>
<label class="captcha"><img src="captcha.php" style="line-height: 30px;"></label><input type="text" name="code"/>
<input type="submit" class="csubmit" value="Now !" name="get"/>
</form>
and this is the php code:
<?php
if (isset($_POST['get'])) {
$error = "";
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$error .= "no name. <br />";
}
if (!empty($_POST['message'])) {
$message = $_POST['message'];
} else {
$error .= "no message <br />";
}
if(($_POST['code']) == $_SESSION['code']) {
$code = $_POST['code'];
} else {
$error .= "wrong captcha <br />";
}
if (!empty($error)) {
echo '<p class="error">Error :<br/>' . $error . '</p>';
} elseif (!empty($success)) {
echo $success;
}
if (empty($error)) {
$message = mysql_real_escape_string($message);
$name = mysql_real_escape_string($name);
$id = mysql_real_escape_string($_GET['id']);
$date = date("Y-m-d H:i:s");
mysql_query("INSERT INTO comments(id, name, comment, time,approved)VALUES('$id', '$name', '$message', '$date', '0')");
echo "thank you";
}
}
?>
As you can see i user $message and $name to keep informations after a submit with wrong captcha code, but the problem is that i want to clear those fields after a submit with correct informations. Can you please tell me how can i clear form fields after a succesfull submit ?
You can use .reset() on your form.
$("#form")[0].reset();
You could follow that with Javascript too
document.getElementById('form').reset();
Or, if successful, redirect the user back to your contact page:
header("Location: contact.php"); // redirect back to your contact form
exit;
EDIT
<input type="submit" class="csubmit" value="Now !" name="get" onClick="clearform();" />
function clearform()
{
document.getElementById("name").value=""; //don't forget to set the textbox ID
document.getElementById("message").value=""; //don't forget to set the textbox ID
document.getElementById("code").value=""; //don't forget to set the textbox ID
}
Also use:
required="required"
so people will be required to fill out the input fields :)
Which by the way is the prefered method. If you keep the user in a page that was reached through a POST method, if he refreshes the page the form will be submitted again.

Undefined variable in php registration from

Continuing from my previous post "PHP and MYSQL database connection and table creation only once", I created the registration form with the PHP code and server side validation. I’m getting some errors as stated below.
i.e. all errors are occurring at the place where i try to print the errors in their respected html class “”. I've made the html "span class" text bold for easy recognition. If their is anything extra solutions for better performance of the form please let me know...
List of errors:
Notice: Undefined variable: error_name in C:\wamp\www\18+\register.php
Notice: Undefined variable: error_username in C:\wamp\www\18+\register.php
Notice: Undefined variable: error_password in C:\wamp\www\18+\register.php
Notice: Undefined variable: error_password2 in C:\wamp\www\18+\register.php
Notice: Undefined variable: error_email in C:\wamp\www\18+\register.php
Register.php
<?php
include ‘database.php';
session_start();
if (isset($_POST['submit'])) {
$error = " "; //Declare a null variable to store error messages
//validation for fullname
if (empty($_POST['fullname'])) {
$error_name = 'Enter Fullname...';
} else {
$fullname = mysql_real_escape_string(trim($_POST['fullname']));
}
//validation for username
if (empty($_POST['username'])){
$error_username = 'Enter Username...';
} else {
$username = mysql_real_escape_string(trim($_POST['username']));
}
//validation for password
if(empty($_POST['password'])){
$error_password = 'Please Enter Your Password...';
} else {
if (empty($_POST['password2'])) {
$error_password2 = 'Re-enter Your Password...';
} else {
if(($_POST['password'])!=($_POST['password2'])){
$error_password2 = 'Passwords Do not match...';
} else {
$confirm = mysql_real_escape_string(md5($_POST['password2']));
}
}
}
//validation for e-mail
if (empty($_POST['email'])) {
$error_email = 'Please Enter your Email ';
} else {
if (preg_match("//custom preg match characters", $_POST['e-mail'])) {
//regular expression for email validation
$email = mysql_real_escape_string($_POST['email']);
} else {
$error_email = 'Your E-mail Address is invalid ';
}
}
if (empty($error)) //send to Database if there's no error '
{
$query= "DB INSERT QUERY";
$result = mysqli_query($dbc, $query);
if (!$result) {
echo 'Failed to Register Your Account...!';
} else {
echo 'Account Registered Successfully...!';
}
}
mysqli_close($sql);//Close the DB Connection
}
?>
Index.php
<form action="register.php" method="post" id="user_registration">
<p id="head">Create Account</p>
<input type="text" id="fullname" name="fullname"/>
**<span class="error" id="fullname"><?php echo $error_name; ?></span>**
<input type="text" id="username" name="username"/>
<span id="availability_status"></span>
**<span class="error" id="username"><?php echo $error_username; ?></span>**
<input type="password" id="password" name="password"/>
**<span class="error" id="password"><?php echo $error_password; ?></span>**
<input type="password" id="password2" name="password2"/>
**<span class="error" id="divCheckPasswordMatch"><?php echo $error_password2;?></span>**
<input type="email" id="email" name="email"/>
**<span class="error" id="email"><?php echo $error_email; ?></span>**
<p class="submit">
<button type="submit"id="submit" name="submit" value="Register”>Register</button>
</p>
</form>
First of all You need to fix the quote at include ‘database.php'; to include 'database.php'; never use curly quote due to this all your code is being blocked.
Next You need to initialize all variable to null or simply ""
OR
You can check if the variable exist or not using isset() like if you want to print value of an variable $val then use this if(isset($val)) echo $val;
UPDATE
You can easily use an array to store errors:
simply use like
$error['name']='Enter Fullname...';
And to check if name error occurs use
if(isset($error['name'])){
//Its an error print error
}
you may need to define these variable on top of the page before using them in code something like this.
$error_name = '';
$error_username = '';
$error_password = '';
$error_password2 = '';
$error_email = '';
Put an else to your if (isset($_POST['submit']))
else { /* What if the user didn't click submit? Else is the answer */
$error_name="";
$error_username="";
$error_password="";
$error_password2="";
$error_email="";
}
The problem is, you are setting the messages only if certain conditions are true. Thus, these variables are not found if those conditions aren't true. To resolve this, use isset() when displaying the errors, e.g.
<?php echo isset($error_name)?$error_name:'' ; ?>
This means check if $error_name is set, if yes display it or display nothing.
Another thing (logically) is that your code is not actually checking for the errors. The $error remains an empty string and you are checking if it is empty which will always be true. You need to either store the errors as arrays or check if all the variables are empty.
Additional:
Can u tell me how to store the errors as arrays..plz
Try this:
<?php
include 'database.php';
session_start();
if (isset($_POST['submit'])) {
$error = array(); //<-- Declare array here
//validation for fullname
if (empty($_POST['fullname'])) {
$error['fullname'] = 'Enter Fullname...'; //<-- adding error into array
} else {
$fullname = mysql_real_escape_string(trim($_POST['fullname']));
}
//validation for username
if (empty($_POST['username'])){
$error['username'] = 'Enter Username...'; //<-- here too and so on..
} else {
$username = mysql_real_escape_string(trim($_POST['username']));
}
//validation for password
if(empty($_POST['password'])){
$error['password'] = 'Please Enter Your Password...';
} else {
if (empty($_POST['password2'])) {
$error['password2'] = 'Re-enter Your Password...';
} else {
if(($_POST['password'])!=($_POST['password2'])){
$error['password2'] = 'Passwords Do not match...';
} else {
$confirm = mysql_real_escape_string(md5($_POST['password2']));
}
}
}
//validation for e-mail
if (empty($_POST['email'])) {
$error['email'] = 'Please Enter your Email ';
} else {
if (preg_match("//custom preg match characters", $_POST['e-mail'])) {
//regular expression for email validation
$email = mysql_real_escape_string($_POST['email']);
} else {
$error['email'] = 'Your E-mail Address is invalid ';
}
}
if (!empty($error)) //send to Database if there's no error '
{
$query= "DB INSERT QUERY";
$result = mysqli_query($dbc, $query);
if (!$result) {
echo 'Failed to Register Your Account...!';
} else {
echo 'Account Registered Successfully...!';
}
}
}
?>
Change your HTML to:
<form action="register.php" method="post" id="user_registration">
<p id="head">Create Account</p>
<input type="text" id="fullname" name="fullname"/>
<!-- checking if error message is set -->
**<span class="error" id="fullname"><?php echo isset($error['fullname'])?$error['fullname']:''; ?></span>**
<input type="text" id="username" name="username"/>
<span id="availability_status"></span>
**<span class="error" id="username"><?php echo isset($error['username'])?$error['username']:''; ?></span>**
<input type="password" id="password" name="password"/>
**<span class="error" id="password"><?php echo isset($error['password'])?$error['password']:''; ?></span>**
<input type="password" id="password2" name="password2"/>
**<span class="error" id="divCheckPasswordMatch"><?php echo isset($error['password2'])?$error['password2']:''; ?></span>**
<input type="email" id="email" name="email"/>
**<span class="error" id="email"><?php echo isset($error['email'])?$error['email']:''; ?></span>**
<p class="submit">
<button type="submit"id="submit" name="submit" value="Register">Register</button>
</p>
</form>
Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Using Sessions To Remember User on PHP Form

Intro: I'm trying to learn PHP on $_SESSION. What I was trying to do is call the value assigned through sessions that when you close your tab will keep the value assigned and echoes it on the browser when you open a tab in the browser.
Issue: There's something wrong with my code where for some reason I couldn't echo the value entered in on a form.
The form looks like this:
Name:_____________
Email:_____________ Remember me? __ SUBMIT
I made it so that $_SESSION['name'] = "John" and $_SESSION['email'] = "someemail#email.com" only when user click on "remember me".
If you close a "tab" on the browser but not the browser itself should echo...
John
someemail#email.com
Here's your download link (some link here)...
But of course if you close the browser, session is lost. Cookies can be used but I'm working on sessions to learn more.
Below's code runs but for some reason I couldn't echo values from $_SESSION variables.
<?php
//Start session
session_start();
// session
if (isset($_POST['remember'])) {
$customer_name = $_SESSION['name'];
if (!($customer_name)) {
$customer_name = $_POST['name'];
}
$customer_email = $_SESSION['email'];
if (!($customer_email)) {
$customer_email = $_POST['email'];
}
}
//If form submit validate
if (isset($_POST['Submit'])) {
// Santize fields here but FILTER_VALIDATE_STRING isn't necessary as there is no absolute way
//to validate names absolutely
// Also shows error message if there's error
if ($_POST['name'] != "") {
$_POST['name'] = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
if ($_POST['name'] == "") {
$errors .= 'Please enter a valid first name.<br/><br/>';
}
} else {
$errors .= 'Please enter your first name.<br/>';
}
// Sanitize and validate email
// Error message shows if any
if ($_POST['email'] != "") {
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors .= "$email is NOT a valid email address.<br/><br/>";
}
} else {
$errors .= 'Please enter your email address.<br/>';
}
// If no errors, submitted form is emailed
if (!$errors) {
echo "I did something!<br /><br />"; // might add some message
//downloadLink();
echo "<br /><br />";
}
} else {
echo '<div id="error">' . $errors . '<br /></div>';
}
?>
<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Name:
<?php
if (isset($_SESSION['name'])) {
echo $_SESSION['name']."<br />";
}
else {
?>
<input type="text" name="name" value="<?php echo $_POST['name']; ?>" size="25" /><br />
<?php } ?>
Email:
<?php
if (isset($_SESSION['email'])) {
echo $_SESSION['email']."<br /><br />";
// echo link.. downloadLink();
}
else {
?>
<input type="text" name="email" value="<?php echo $_POST['email']; ?>" size="25"/>
<input type="checkbox" name="remember" /> Remember me
<input type="submit" name="Submit" />
<?php } ?>
</form>
</div>
Put this at the beginning under session_start();
if (!isset($_SESSION['name'])) {
echo "Your session is not good";
} else { echo "Session is set";
}
then replace $customer_name = $_SESSION['name']; with $_SESSION['name']=$_POST['remember']; and you will start getting results.

Categories