So I have created a PHP validation script. On test I filled and submitted the forms but so far $error returns undefined index and no data is set into the database. Can anyone take a look and give a second opinion on why its not functioning as intended? To my eye it all looks OK.
Otherwise my script runs OK (Insert into DB) it's just something about my validation script breaks it.
<?php
if (isset($_POST['Submit'])) {
if ($_POST['name'] != "") {
$_POST['name'] = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
if ($_POST['name'] == "") {
$errors .= 'Please enter a valid name.<br/><br/>';
}
} else {
$errors .= 'Please enter a name.<br/>';
}
if (isset($_POST['Submit'])) {
if ($_POST['address'] != "") {
$_POST['address'] = filter_var($_POST['address'], FILTER_SANITIZE_STRING);
if ($_POST['address'] == "") {
$errors .= 'Please enter a valid address<br/><br/>';
}
} else {
$errors .= 'Please enter a address.<br/>';
}
if (isset($_POST['postcode'])) {
if ($_POST['postcode'] != "") {
$_POST['postcode'] = filter_var($_POST['postcode'], FILTER_SANITIZE_STRING);
if ($_POST['postcode'] == "") {
$errors .= 'Please enter a valid name.<br/><br/>';
}
} else {
$errors .= 'Please enter a name.<br/>';
}
if (!$errors) {
$name = $_POST['name'];
$address = $_POST['address'];
$postcode = $_POST['postcode'];
$photo = $_POST['photo'];
$db1 = new dbmember();
$db1->openDB();
$numofrows = $db1->insert_member('', $name, $address, $postcode, $photo);
echo "Success. Number of rows affected:
<strong>{$numofrows}<strong>";
$sql="SELECT * from member";
$result=$db1->getResult($sql);
echo "<table class='table table-hover'>";
echo "<tr><th>Member ID</th><th>Name</th><th>Address</th><th>Postcode</th><th>Photo</th></tr>";
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>{$row['mid']}</td><td>{$row['name']}</td>";
echo "<td>{$row['address']}";
echo "<td>{$row['postcode']}";
echo"<td><img height='80' width='120' src='{$row['photo'] }' /></td>";
echo "</tr>";
}
echo "</table>";
$db1->closeDB();
}
}
}
}
echo "Records updated!<br/><br/>";
} else {
echo '<div style="color: red">' . $errors . '<br/></div>';
}
?>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post" name="myform" class = "well" id="myform" onsubmit="return validateForm( );">
Please fill in the fields to add a new member
<p></p>
<input type="text" class="span3" placeholder="Enter member name"name="name" id="name" /><br />
<input type="text" class="span3"placeholder="Enter an address"name="address" id="address" /><br />
<input type="text" class="span3"placeholder="Enter a postcode"name="postcode" id="postcode" /><br />
<input type="text"class="span3" placeholder="Enter a picture (optional)"name="photo" /><br />
<p>
<button class="btn btn-primary" type="submit" value="Save" >Submit </button>
</p>
</form>
Your button doesn't have a name="Submit" attribute. Your php code can't find the $_POST['Submit'] because it doesn't exist.
Consequently, the if (isset($_POST['Submit'])) { condition will return false meaning the validation is never performed and the $error variable never set to a value.
Related
Have this code i want to check if record exist in $pas before processing result
then try to verify $pas by form input
I have tried this:
$pas = "1234";
$text = "12345678910111213141516";
if(empty($pas)) {
echo $text;
}
else
{
if (isset($_POST["subscribe"]))
{
$phone = $_POST["phone"];
if ($phone == $pas)
{
echo $text;
}
else
{
if ($phone != "$pass")
{
echo erro;
}
}
}
}
if(!isset($_POST["phone"]) || $_POST["phone"] != $pas)
{
echo '<form action="#" method="POST">
Your Phone Number <br />
<input type="text" name="phone" value="080"/>
<input type="submit" name="subscribe" value="SEND PAYMENT"/>
</form>';
}
But I get result even when 'pas' is not there what am I doing Wrong?
<?php
$pas = "1234";
$text = "12345678910111213141516";
if(empty($pas)) {
echo $text;
}
else
{
if (isset($_POST["subscribe"]))
{
$phone = $_POST["phone"];
if ($phone == $pas)
{
echo $text;
}
else
{
if ($phone != "$pass")
{
echo erro;
}
}
}
if(!isset($_POST["phone"]) || $_POST["phone"] != $pas)
{
echo '<form action="#" method="POST">
Your Phone Number <br />
<input type="text" name="phone" value="080"/>
<input type="submit" name="subscribe" value="SEND PAYMENT"/>
</form>';
}
}
Your else bracket was closing sooner than you wanted so your echo would be executed anyway as it was outside of your if/else
I created the fields that has validation process like required fields, numbers only and valid email.
it displays the errors simultaneously after submit but upon changing only one of the fields, it accepts and does not revalidate the other.
example
name = Error : required field
telephone = Error : numbers only
email = Error : not a valid email
after i corrected only the email , it accepts and proceed on submitting without rechecking the others.
please see my code . thanks in advance
<?php
include("conn/db.php");
function renderForm($name ='', $tel = '', $email ='', $error='', $error2='', $error3='')
{
?>
<html >
<head> <title>Form</title></head>
<body>
<?php
if ($error != '') {
echo $error
}
if ($error2 != '') {
echo $error2;
}
if ($error3 != '') {
echo $error3;
}
?>
<form action="" method="post">
Name : <input type = "text" class = "form-control" name = "name_text" value="<?php echo $name; ?>"> <br/>
Tel :<input type = "text" class = "form-control" name = "tel_text" value="<?php echo $tel; ?>"> <br/>
Email :<input type ="text" class = "form-control " name = "email_text" value="<?php echo $email; ?>" > <br/>
<input name= "submit" type="submit" value="Update" class = "btn btn-primary" >
</form>
</body>
</html>
<?php
}
if (isset($_POST['submit'])){
$name = $_POST['name_text'];
$tel = $_POST['tel_text'];
$email = $_POST['email_text'];
if ($name== '' ){
$error = 'ERR: required field';
}
if(!is_numeric($telephone)){
$error2 = 'ERR: numbers only';
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error3 = 'ERR: Email not valid';
}
else
{
***WILL PROCESS THE SQL QUERY ***
header("Location: main.php");
}
renderForm($name, $tel , $email ,$error, $error2, $error3);
}
else{
renderForm();
}
$con->close();
?>
<?php
include("conn/db.php");
function renderForm($name ='', $tel = '', $email ='', $error='', $error2='', $error3='')
{
?>
<html >
<head> <title>Form</title></head>
<body>
<?php
if ($error != '') {
echo $error
}
if ($error2 != '') {
echo $error2;
}
if ($error3 != '') {
echo $error3;
}
?>
<form action="" method="post">
Name : <input type = "text" class = "form-control" name = "name_text" value="<?php echo $name; ?>"> <br/>
Tel :<input type = "text" class = "form-control" name = "tel_text" value="<?php echo $tel; ?>"> <br/>
Email :<input type ="text" class = "form-control " name = "email_text" value="<?php echo $email; ?>" > <br/>
<input name= "submit" type="submit" value="Update" class = "btn btn-primary" >
</form>
</body>
</html>
<?php
}
if (isset($_POST['submit'])){
$name = $_POST['name_text'];
$tel = $_POST['tel_text'];
$email = $_POST['email_text'];
$is_valid = true;
if ($name== '' ){
$error = 'ERR: required field';
$is_valid = false;
}
if(!is_numeric($telephone)){
$error2 = 'ERR: numbers only';
$is_valid = false;
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error3 = 'ERR: Email not valid';
$is_valid = false;
}
if($is_valid) {
***WILL PROCESS THE SQL QUERY ***
header("Location: main.php");
}
renderForm($name, $tel , $email ,$error, $error2, $error3);
}
else{
renderForm();
}
$con->close();
?>
Its just a small mistake:
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error3 = 'ERR: Email not valid';
} else {
***WILL PROCESS THE SQL QUERY ***
header("Location: main.php");
}
You only checked the email and if it is corecct it was proceding. It did not include the other 2 checks for name and number.
I added a small variable to check if all 3 are correct.
I have been racking my brain to understand why there are slashes ("/") in every one of by textboxes on my page when I run this php script. Everything on the page works fine. I have tried everything but they're just there. Here my whole code below. Thanks for any help!
function validateInput($data, $fieldName){
global $error;
if (empty($data)){
echo "\"$fieldName\" is a required field.<br />\n";
++$error;
$retval = "";
} else if (!preg_match('/[^A-Za-z]/', $data) == 0){
echo "\"$fieldName\" can only contain letters.<br />\n";
++$error;
$retval = "";
} else {
$retval = trim($stripslashes($data));
}
return ($retval);
}
function validateAddress($data, $fieldName){
global $error;
if (empty($data)){
echo "\"$fieldName\" is a required field.<br />\n";
++$error;
$retval = "";
} else if (!preg_match('/[^0-9A-Za-z]/', $data)){
echo "\"$fieldName\" can only contain letters or numbers.<br />\n";
++$error;
$retval = "";
} else {
$retval = trim(stripslashes($data));
}
return ($retval);
}
function validateNumber($data, $fieldName){
global $error;
if (empty($data)){
echo "\"$fieldName\" is a required field.<br />\n";
++$error;
$retval = "";
} else if (!is_numeric($data)){
echo "\"$fieldName\" must contain only numbers.<br />";
++$error;
$retval = "";
} else if (strlen($data) != 10){
echo "\"$fieldName\" must be 10 numbers long.<br />";
++$error;
$retval = "";
} else {
$retval = trim(stripslashes($data));
}
return ($retval);
}
function validateEmail($data, $fieldName){
global $error;
if (empty($data)){
echo "\"$fieldName\" is a required field.<br />\n";
++$error;
$retval = "";
} else {
$retval = trim(stripslashes($input));
$pattern = "/^[\w-]+(\.[\w-]+)*#" .
"[\w-]+(\.[\w-]+)*" .
"(\.[a-z]{2,})$/i";
if (preg_match($pattern, $retval) == 0){
echo "\"$fieldName\" is not a valid email address.<br />\n";
++$error;
}
}
return($retval);
}
function displayForm($name, $email, $address, $phone){
include("header.html");
?>
<div class="center">
<form name="contact_us" action="contact_us.php" method="post">
<p>Your Name: <input type="text" name="name" value=<?php echo $name; ?> /></p>
<p>Your Email: <input type="text" name="email" value=<?php echo $email; ?> /></p>
<p>Your Address: <input type="text" name="address" value=<?php echo $address; ?> /></p>
<p>Your Phone Number: <input type="text" name="phone" value=<?php echo $phone;?> /></p>
<p><input type="submit" name="Submit" value="Send" />
<input type="reset" value="Clear"/>
</form>
</div>
<?php
include("footer.html");
}
$showForm = TRUE;
$error = 0;
$name = "";
$email = "";
$address = "";
$phone = "";
if (isset($_POST['Submit'])){
$name = validateInput($_POST['name'], "Name");
$email = validateEmail($_POST['email'], "Email");
$address = validateAddress($_POST['address'], "Address");
$phone = validateNumber($_POST['phone'], "Phone");
if ($error == 0)
$showForm = FALSE;
else
$showForm = TRUE;
}
if ($showForm == TRUE){
if ($error > 0)
echo "<p>Please re-enter the form information below.<br/>\n";
displayForm($name, $email, $address, $phone);
} else {
echo "Your contact information has been recorded. Thank you!";
}
?>
You have to quote your value attributes in these lines:
<input type="text" name="name" value=<?php echo $name; ?> />
If $name is empty, which is true by default, your code reduces to
<input type="text" name="name" value=/ >
So your input boxes are filled with a / by default. To fix this error (and avoid other possible errors), quote your $name:
<input type="text" name="name" value="<?php echo htmlspecialchars($name); ?>" />
Notice that I also called htmlspecialchars to prevent XSS.
PHP runs addslashes() on all GET, POST, and COOKIE data by default.
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
}
Link to website: http://www.leonardpfautsch.com/contact.php
How do I make my contact form validated only using PHP? I want to be able to have error messages directly under the text field that has an error. For each text field, I do not want multiple errors to show up at once. If you submit the form with nothing in the fields, you see that under name and email two errors show up for each. I want the errors to show up only once due to some type of specifications. Right now I think I am on the right track. However, the code below does not have the email being sent. I am very new to PHP. If anybody could help me, I would really appreciate it.
<?php
if (($_SERVER['REQUEST_METHOD'] == 'POST') && (!empty($_POST['action']))){
$errors = array($name_error_1, $name_error_2, $email_error_1, $email_error_2, $subject_error, $message_error);
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
if ($name === '') {
$name_error_1 = '<div style="color:red;"> Name is a required field! </div>';
}
if ($email === '') {
$email_error_1 = '<div style="color:red;"> Email is a required field! </div>';
}
if ($subject === '') {
$subject_error = '<div style="color:red;"> Subject is a required field! </div>';
}
if ($message === '') {
$message_error = '<div style="color:red;"> Message is a required field! </div>';
}
if (isset($email) && (filter_var($email, FILTER_VALIDATE_EMAIL) === false)){
$email_error_2 = '<div style="color:red;"> The email address must be real! </div>';
}
if (ctype_alpha($name) === false) {
$name_error_2 = '<div style="color:red;"> Your name must only contain letters! </div>';
}
/*Main way that mail works*/
if (empty($errors) === true) {
/*Where_mail_goes_to, Subject, Body_text, Who_email_is_from*/
mail('email_address', $subject, "From " . $name . "\r\r" . $message, 'From: ' . $email);
/*Shows up in the URL if the message has been sent*/
header('Location: contact.php?sent');
exit();
}
} //end of main if
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>" >
<span class="label">Name</span><br/>
<?php if (isset($name_error_1)) { echo $name_error_1; } ?>
<?php if (isset($name_error_2)) { echo $name_error_2; } ?>
<input type="text" class="textfield" name="name" size="50" maxlength="50" <?php if (isset($_POST['name']) === true) { echo 'value="', strip_tags($_POST['name']), '"'; } ?> > <br/>
<span class="label">Email</span><br/>
<?php if (isset($email_error_1)) { echo $email_error_1; } ?>
<?php if (isset($email_error_2)) { echo $email_error_2; } ?>
<input type="text" class="textfield" name="email" size="50" maxlength="50" <?php if (isset($_POST['email']) === true) { echo 'value="', strip_tags($_POST['email']), '"'; } ?> > <br/>
<span class="label">Subject</span><br/>
<?php if (isset($subject_error)) { echo $subject_error; } ?>
<input type="text" class="textfield" name="subject" size="50" maxlength="50" <?php if (isset($_POST['subject']) === true) { echo 'value="', strip_tags($_POST['subject']), '"'; } ?> > <br/>
<span class="label">Message</span><br/>
<?php if (isset($message_error)) { echo $message_error; } ?>
<textarea rows="5" cols="50" name="message" id="textarea" maxlength="500"><?php if (isset($_POST['message']) === true){ echo $_POST['message'];}?></textarea><br/>
<input type="submit" value="Send" id="submit" name="action">
</form>
You could create an array of errors for each field and display just the first error added to it.
<?php
$email_errors = array();
if ($email == '')
{
$email_errors[] = 'First error';
}
if (more_email_checks($email) == false)
{
$email_errors[] = 'Second error';
}
?>
...
<span class="label">Email</span><br />
<?php echo array_shift($email_errors); ?>
To know whether to send e-mails or not, you could do something like this:
$errors_found = 0;
if (check_email($email) == false)
{
$email_error = 'Error message';
$errors_found++;
}
...
if ($errors_found == 0)
{
mail(...);
}
You can do it by using the elseif check
<span class="label">Email</span><br/>
<?php if (isset($email_error_1))
{
echo $email_error_1;
}
elseif(isset($email_error_2)) {
echo $email_error_2;
} ?>
Also move this line after the last validation check
if (ctype_alpha($name) === false) {
$name_error_2 = '<div style="color:red;"> Your name must only contain letters! </div>';
}
$errors = array($name_error_1, $name_error_2, $email_error_1, $email_error_2, $subject_error, $message_error);
you can by this code for name
<?
$message = "<div style = 'color :red ' /> ;
if (isset(name == '' ) {
echo $message
}
?>
this is name php vaildation but yo can create js
Change your email validation to:
<span class="label">Email</span><br/>
<?php if (isset($email_error_1))
{
echo $email_error_1;
}else if(isset($email_error_2)) {
echo $email_error_2;
} ?>
same if else can be applied to all the fields with multiple validation conditions.
and then move your error array just above the email condition check:
<?php
$errors = array($name_error_1, $name_error_2, $email_error_1, $email_error_2, $subject_error, $message_error);
//and change your mail function as:
$to = 'email_address';
$headers = $headers .= 'From: $name <$email>';
mail($to, $subject, $message, $headers);
?>
Also perform a check on the control, if you have filled the form completely then it should come to the mail function, I mean just check the if condition, in case you have some issue with the condition, try to put an echo inside if statement(which is responsible for sending email), and if that echo statement executes then mail should work.
:)