This is my php validtion code!
<?php //------------------------------------------------------------------------------>PHP VALIDATION
$user="";
$pass="";
$nameErr="";
$passErr="";
//$pattern='/^[a-zA-Z0-9#_ ]*$/';
if($_SERVER['REQUEST_METHOD']=='POST')
{
if(empty($_POST['uname']))
{
$nameErr='Enter Your Name!';
}
else
{
$user = test_input($_POST['uname']);
if(!preg_match('/^[a-zA-Z0-9#_]*$/',$user))
{
$nameErr=' Re-Enter Your Name! Format Inccorrect!( only alpha, numbers,#_ are allowed)';
}
}
if(empty($_POST['pas']))
{
$passErr='Enter Your Password!';
}
else
{
$user = test_input($_POST['pas']);
if(!preg_match('/^[a-zA-Z0-9#_]*$/',$pass))
{
$passErr='Invalid Format! Re-Enter Password!';
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
HTML:
<html>
<body>
<div id='shw'><?php echo $user;?></div>
<fieldset id='fld'>
<form method='post' name='f1' action='<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>'>
<table>
<tr>
<td>
User Name:<input type='text' id='uname' name='uname' class='uname' placeholder='USERNAME' autocomplete='off' autofocus maxlength='25'><span class='error'>*</span>
Password:<input type='password' id='pass' class='pass' name='pas' placeholder='PASSWORD' autocomplete='off'>
<input type='submit' name='submit' id='loggin' value='LOGIN' class='login' onclick='val()'>
</td>
</tr>
</table>
</form>
</fieldset>
<div class='errormsg' id='errmsg'><?php echo $nameErr;?></div>
</div>
</body>
</html>
iam having problm in validation i want to show user name after submit.
problem is that my username if else is running good but it skips the password part. iwant that it shud also validate pass field then only shows the username!
please help!
$user = test_input($_POST['pas']); should be $pass = test_input($_POST['pas']);
Your current code set $user in you first if..else block, it's not that PHP skips your second if...else block, it's just that no matter what this block will do, ûser is already set.
If you don't want to display $user if password is invalid, just set $user later in you code:
$nameErr = null;
$passErr = null;
if (empty($_POST['uname'])) {
$nameErr = 'Enter Your Name!';
} else {
$userTest = test_input($_POST['uname']);
if (!preg_match('/^[a-zA-Z0-9#_]*$/', $userTest)) {
$nameErr = ' Re-Enter Your Name! Format Inccorrect! (only alpha, numbers, #_ are allowed)';
} else {
$valid++;
}
}
if (empty($_POST['pas'])) {
$passErr = 'Enter Your Password!';
} else {
$pass = test_input($_POST['pas']);
if (!preg_match('/^[a-zA-Z0-9#_]*$/', $pass)) {
$passErr = 'Invalid Format! Re-Enter Password!';
} else {
$valid++;
}
}
if (is_null($nameErr) && is_null($passErr)) {
$user = $_POST['uname']
}
Here, I just check if $nameErr and $passErr are still null at the end of your tests. If both are null, then you can set $user, since no error has been detected.
Related
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"];
}
}
In the below code i have one check box i don't no how to validate checkbox.
I have a checkbox if it is uncheck it should give message please accept the agreement.
please help me friends
<?php
$firstname = $lname = "";
$firstnameErr = $lnameErr = "";
if ($_SERVER['REQUEST_METHOD']== "POST") {
$valid = true;
/*FirstName Validation starts here*/
if(empty($_POST["fname"])) {
$firstnameErr = "*firstname is Required";
$valid=false;
} else {
$firstname = test_input($_POST["fname"]);
}
/*LastName Validation starts here*/
if(empty($_POST["lname"])) {
$lnameErr = "*lastname is Required";
$valid=false;
} else {
$lname=test_input($_POST["lname"]);
}
if (isset($_POST['confirm'])) {
// do something
}
//if valid then redirect
if($valid){
echo 'success';
exit;
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="example.php">
firstname<input type="text" name="fname"/><?php echo $firstnameErr?><br /><br />
lastname<input type="text" name="lname"/><?php echo $lnameErr?><br /><br />
<input type="checkbox" name="agree" />
Agree the terms and condition
<input type="submit" value="Submit" />
</form>
please help me friends
please go through the below code.I think it will work fine.
<?php
$firstname=$lname="";
$firstnameErr=$lnameErr="";
if ($_SERVER['REQUEST_METHOD']== "POST") {
$valid = true;
/*FirstName Validation starts here*/
if(empty($_POST["fname"]))
{
$firstnameErr="*firstname is Required";
$valid=false;
}
else
{
$firstname=test_input($_POST["fname"]);
}
/*LastName Validation starts here*/
if(empty($_POST["lname"]))
{
$lnameErr="*lastname is Required";
$valid=false;
}
else
{
$lname=test_input($_POST["lname"]);
}
if(empty($_POST["agree"]))
{
$agreeErr="*check box is Required";
$valid=false;
}
else
{
$agree=test_input($_POST["agree"]);
}
if (isset($_POST['confirm'])) {
// do something
}
//if valid then redirect
if($valid){
echo 'success';
exit;
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="example.php">
firstname<input type="text" name="fname"/><?php echo $firstnameErr?><br /><br />
lastname<input type="text" name="lname"/><?php echo $lnameErr?><br /><br />
<input type="checkbox" name="agree" /><?php echo $agreeErr?>
Agree the terms and condition
<input type="submit" value="Submit" />
</form>
If you checkbox is checked, it will be passed to your PHP, otherwise it won't, so just use the isset() function:
if (!isset($_POST['agree'])) {
echo "Please accept the agreement";
}
here is the code
<body>
<?php
$name=$email=$pwd=$nameErr=$emailErr=$pwdErr=$flag="";
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
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";
$flag=0;
}
else
{
$flag=1;
}
}
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";
$flag=0;
}
else
{
$flag=2;
}
}
if(empty($_POST["pwd"]))
{$pwdErr="enter password";}
else
{
$pwd=test_input($_POST["pwd"]);
if(!preg_match("/^[a-zA-Z ]*$/",$pwd))
{
$pwdErr="Only characters and white spaces are allowed";
$flag=0;
}
else
{
$flag=3;
}
}
if($flag=1 && $flag=2 && $flag=3)
{
header("Location: login.php");
}
else
{
header("Location:form.php");
}
}
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
Name:<input type="text" name="name" value="<?php echo $name; ?>"/>
<span class="error"><?php echo $nameErr; ?></span><br />
Password:<input type="password" name="pwd" value="<?php echo $pwd; ?>" />
<span class="error"><?php echo $pwdErr; ?></span><br />
Email:<input type="text" name="email" value="<?php echo $email; ?>"/>
<span class="error"><?php echo $emailErr; ?></span><br />
<input type="submit" name="submit" value="submit" />
</form>
The problem is that I want the webpage to navigate to "login.php" after validations are completed. But it is getting navigated to the "login.php" page by clicking on button and the navigations are also not getting checked.
Can anyone help me to fix this? Thanks in advance.
There is a logical problem here if($flag=1 && $flag=2 && $flag=3) and secondly you should use == for comparison. And also how $flag has a value 1,2 and 3 simultaneously?
Adittionaly you should implement some session handling
http://www.w3schools.com/php/php_sessions.asp
http://www.php.net/manual/en/book.session.php
I am new to php. I have tried the following code to redirect the page when sign In button is clicked, but it is not happening. please help me editing the code. probably, there is an error in header() function. Have I used the header() function correctly?
<body>
<?php
$emailErr = $passwordErr = "";
$email = $password = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["email"])) {
$emailErr = "*Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["password"])) {
$passwordErr = "*Password is required";
} else {
$password = test_input($_POST["password"]);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
include("signInform.php");
if($_POST["sign"])
{
header('Location:signInform.php');
}
?>
<br/><br/><br/><br/><br/>
<h1>WELCOME</h1>
<h2>Please, Register Yourself!</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label>E-mail:</label><br />
<input type="text" name="email"/>
<span class="error"> <?php echo $emailErr;?></span>
<br />
<label>Password:</label><br />
<input type="password" name="password"/>
<span class="error"> <?php echo $passwordErr;?></span>
<br /><br />
<input type="submit" value="Register"/><br/>
<p>If already a user, Sign in! </p>
<input type="submit" value="Sign In" name="sign"/><br/>
</form>
</body>
Add #ob_start(); top of the page,
if (isset($_POST["sign"])) {
header('Location:signInform.php');
}
Just remove following line.
include("signInform.php");
and put header function like below.
header('location:signInform.php');
your issue is header already send.You can avoid this issue by using ob_start().Try like this:
<?php
ob_start();
$emailErr = $passwordErr = "";
$email = $password = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["email"]))
{
$emailErr = "*Email is required";}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
}
if (empty($_POST["password"]))
{$passwordErr = "*Password is required";}
else
{$password = test_input($_POST["password"]);}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
include("signInform.php");
if($_POST["sign"])
{
header('Location:signInform.php');
exit();
}
?>
<body>
<br/><br/><br/><br/><br/>
<h1>WELCOME</h1>
<h2>Please, Register Yourself!</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label>E-mail:</label><br />
<input type="text" name="email"/>
<span class="error"> <?php echo $emailErr;?></span>
<br />
<label>Password:</label><br />
<input type="password" name="password"/>
<span class="error"> <?php echo $passwordErr;?></span>
<br /><br />
<input type="submit" value="Register"/><br/>
<p>If already a user, Sign in! </p>
<input type="submit" value="Sign In" name="sign"/><br/>
</form>
</body>
use--- echo '<script> location.href="signInform.php";</script>';
instead of header('Location:signInform.php');
replace if($_POST["sign"])
{
header('Location:signInform.php');
}
to
if($_POST["sign"])
{
echo '<script> location.href="signInform.php";</script>';
}
and why did you include include("signInform.php"); this line that's why showing error already sent.
i am a newbie in this php. i am trying to make some validation for my form which will show the error msg if it exploits my validation rules.
my connection file.
<?php
$con = mysql_connect("localhost","root","") or die('could not connect the server: '. mysql_error());
mysql_select_db("interview",$con);
?>
my validate.php file
<?php
require_once('connect.php');
$realnameErr = $nickErr = $passwordErr = $emailErr = "";
$realname = $nick = $password = $email = "";
?>
my form
<form name='v2' id='login' method='post' action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<legend>Login</legend>
<label for='realname' >Real Name*:</label>
<input type='text' name='realname' id='realname' maxlength="50" value="<?php echo $realname;?>" /></br>
<span class="error"><?php echo $realnameErr;?></span>
<br>
<label for='nick' >Nick*:</label>
<input type='text' name='nick' id='nick' maxlength="50" value="<?php echo $nick;?>" /></br>
<span class="error"><?php echo $nickErr;?></span>
<br>
<label for='password' >Password*:</label>
<input type='password' name='password' id='password' maxlength="50" /></br>
<span class="error"><?php echo $passwordErr;?></span>
<br>
<label for='email' >Email*:</label>
<input type='text' name='email' id='email' maxlength="50" value="<?php echo $email;?>"/></br>
</fieldset>
<input type='submit' name='submit' value='submit' />
</form>
validation begins here
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST['submit'])) {
if (empty($_POST["realname"]))
{
$realnameErr = "Name is required";
}
else
{
$realname=test_input($_POST["realname"]);
if(!preg_match("/^[a-zA-z ]*$/",$realname))
{
$realnameErr = "only letters and white space allowed";
}}
if(empty($_POST["nick"]))
{
$nickErr = "Nick is required";
}
else {
$nick=($_POST["nick"]);
}
if(empty($_POST["password"]))
{
$passwordErr = "password is required";
}
else {
$password=($_POST["password"]);
}
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";
}}
checking then inserting
if((!$realnameErr) && (!$nickErr) && (!$passwordErr) && (!$emailErr)) {
$query="INSERT INTO `main`"."(realname,nick,password,email)". "VALUES". "('$realname','$nick',SHA('$password'),'$email')";
$res=mysql_query($query);
echo '<p>Your account has been Successfully created,You are now ready to login. </p>';
}
}}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
You need to have your working Script before you display your form. Because at the moment, the time you output <span class="error"><?php echo $nickErr;?></span> the variable $nickErr is still empty and therefore does not display anything.
Try this:
// Init
$errors = array();
// Validate Post Data
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['submit'])) {
if (empty($_POST["realname"])) {
$errors[] = "Name is required";
} else {
$realname = test_input($_POST["realname"]);
if (!preg_match("/^[a-zA-z ]*$/", $realname)) {
$errors[] = "only letters and white space allowed";
}
}
if (empty($_POST["nick"])) {
$errors[] = "Nick is required";
} else {
$nick = ($_POST["nick"]);
}
if (empty($_POST["password"])) {
$errors[] = "password is required";
} else {
$password = ($_POST["password"]);
}
if (empty($_POST["email"])) {
$errors[] = "email is required";
} else {
$email = test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$errors[] = "Invalid email format";
}
}
}
}
// If there is any error
if (sizeof($errors))
{
// display it
echo '<div>Following error(s) occured:<br /><br />'. implode('<br />', $errors) .'</div>';
}
else
{
// proceed with db insert here
}