php validation removes the data from html input - php

I'm having some problem with html input validation using PHP. The validation itself is working. I have two inputs: name and office.
If I enter a value on Name input but i didn't put value to the office input and click the submit button, the validation on office input works but it CLEAR/null the data i entered on name input
What am I doing wrong here?
This is my PHP validation:
if (isset($_POST['submit'])){
$signatory_name = $_POST['sig_name'];
$signtory_position = $_POST['sig_position'];
if (!$_POST['sig_name']) {
$errname='<div class="alert alert-danger">Sorry there was an error: Please Enter Your Name</div>';
}
if (!$_POST['sig_office']) {
$erroffice='<div class="alert alert-danger">Sorry there was an error: Please Enter Your office</div>';
}
}
this is my html code
<form action="signatory.php" method="Post" role="form">
<input class="form-control " id="signatoryname" name="sig_name" placeholder="Name:" >
<input class="form-control " id="signatoryoffice" name="sig_office" placeholder="Office:">
</form>

It's not really clear what you are doing or trying to do but here is my attempt:
First: You should know that if (!$_POST['sig_name']) { means if the value assigned is FALSE you may want to reconsider this and use empty() instead.
After validating the inputs you need to repopulate the form with the submitted values - here is an example:
<?php
$errname = "";
$erroffice= "";
if (!empty($_POST)) { // Only if there are POST values attached.
$signatory_name = $_POST['sig_name'];
$signtory_position = $_POST['sig_position'];
if (empty($_POST['sig_name'])) {
$errname='<div class="alert alert-danger">Sorry there was an error: Please Enter youre Name</div>';
}
if (empty($_POST['sig_office'])) {
$erroffice='<div class="alert alert-danger">Sorry there was an error: Please Enter youre office</div>';
}
if (empty($errname) && empty($erroffice)) {
//Do whatever you need with the validated inputs...
} else {
//Expose the alerts:
echo $errname.$erroffice;
}
}
?>
<form method="POST" role="form">
<input class="form-control" id="signatoryname" name="sig_name" value="<?php echo (isset($_POST['sig_name']))?$_POST['sig_name']:""; ?>" placeholder="Name:" />
<input class="form-control" id="signatoryoffice" name="sig_office" value="<?php echo (isset($_POST['sig_office']))?$_POST['sig_office']:""; ?>" placeholder="Office:" />
<!-- rest of your form and buttons -->
</form>

You need to re-populate your form as Scuzzy said.
Most browsers might do you for you, but you can't rely on it.
<form action="signatory.php" method="Post" role="form">
<input class="form-control " id="signatoryname" name="sig_name" placeholder="Name:" value="<?php echo !empty($_POST['sig_name']) ? $_POST['sig_name'] : ''; ?>">
<input class="form-control " id="signatoryoffice" name="sig_office" placeholder="Office:" value="<?php echo !empty($_POST['sig_office']) ? $_POST['sig_office'] : ''; ?>">
</form>

Related

bootsrap php contact form value shows error <br /><b>Notice</b>: Undefined variable: myThema in <b>C:\x\testForm.php</b> on line <b>105</b><br />

I am using bootstrap and I want to create a contact Form. I have create a File with the name testForm.php and there I have written my php and my html code(should I make a different files? one for php and one for html?). My file starts with the php code to and after the html code. As soon as I put an <?php echo.... in the html area, everywhere, appears all the time in the site Undefined index: .for example
Now I m trying only with one parameter :thema to see if it works and how it works and if I put something to value comes the result like the picture above.
My php code:
<?php
if (isset($_POST["submit"])) {
$thema = $_POST['thema'];
// Check if thema has been entered
if (!$_POST['thema']) {
$errThema = 'Please enter your thema';
}
}
?>
and my html code:
<!-- MAIN SEITE -->
<h4><p class="text-primary"><u>Neuanforderungsformular</u></p></h4>
<!-- START FORM -->
<form method="post" role="form" action="testForm.php">
<!-- Thema Feld -->
<div class="form-group">
<label for="usr">Thema / Title:</label>
<input type="text" id="thema" name="thema" class="form-control input-lg" value="<?php echo htmlspecialchars($_POST['thema']); ?>">
</div>
<!-- Email Adresse Feld-->
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<div class="input-group col-sm-5">
<input type="text" class="form-control input-lg" placeholder="Ihre Email Addresse" aria-describedby="basic-addon2">
<span class="input-group-addon" id="basic-addon2">#teswt.de</span>
</div>
how can I fix the provbem so my contact form will works?
use like this
$thema = isset($_POST['thema']) ? $_POST['thema'] : '';
instead of
$thema = $_POST['thema'];
update.1
try it
<?php $thema = !empty($thema) ? $thema : ''; ?>
<input type="text" id="thema" name="thema" class="form-control input-lg" value="<?php echo htmlspecialchars($thema); ?>">
instead of
<input type="text" id="thema" name="thema" class="form-control input-lg" value="<?php echo htmlspecialchars($_POST['thema']); ?>">
You are accessing to $_POST['thema']) also when an entry for thema is not present in $_POST
<div class="form-group">
<label for="usr">Thema / Title:</label>
<input type="text" id="thema" name="thema" class="form-control input-lg"
value="<?php echo htmlspecialchars($_POST['thema']); ?>">
</div>
then you should use a proper setting for a var eg $myThema
if (isset($_POST["submit"])) {
if (isset($_POST['thema'])){
$myThema = $_POST['thema'];
} else {
$errThema = 'Please enter your thema';
$myThema = '';
}
}
.
<div class="form-group">
<label for="usr">Thema / Title:</label>
<input type="text" id="thema" name="thema" class="form-control input-lg"
value="<?php echo htmlspecialchars($myThema); ?>">
</div>
Try this:
<?php
if (isset($_POST["submit"])) {
if (isset($_POST['thema'])){
$thema = $_POST['thema'];
} else {
$thema = 'Please enter your thema';
}
}
?>
You should check first if $thema has been set. What you did is you are using $_POST['thema'] without checking, thus the error appearing in the text field
I would use something like that:
function GetPostOrDefault($key, $default = '')
{
if (array_key_exists($key, $_POST))
{
return $_POST[$key];
}
return $default;
}
And then
<input value="<?= GetPostOrDefault('thema') ?>">
or
<input value="<?= GetPostOrDefault('thema', 'Neues Thema') ?>">
You get this error because the index is not defined, if you have made no post.
That means $_POST['thema'] is only available if you have submitted a form that contains a field with the name thema. On your initial page load, you do a GET request. The form is not submitted.
Simply move your default $thema value outside of the check for $_POST['submit']. Your current code only sets it when the form has been submitted.
$thema = '';
$errThema = '';
if (isset($_POST["submit"])) {
// Check if thema has been entered
if (!$_POST['thema']) {
$errThema = 'Please enter your thema';
} else {
$thema = $_POST['thema'];
}
}
Of course, you should then display $thema instead of $_POST['thema'] in your form.

button(submit) didn't work - but input(submit) work

I want to make Login page with PHP.
And want to use button but it didn't works.
and it looks like just refresh the page.
I tried button tag in the form.
How can I make this works??
<?php
include "login.php";
?>
<form method="post" id="sign">
<div class="mdl-textfield mdl-js-textfield">
<input class="mdl-textfield__input" type="email" name="user_mail" id="user_mail" value="<?php echo addslashes($_POST['user_mail'] ?? '') ?>">
<label class="mdl-textfield__label" for="user_mail">Email</label>
</div>
<div class="mdl-textfield mdl-js-textfield">
<input class="mdl-textfield__input" type="password" name="passcode" id="passcode" value="<?php echo addslashes($_POST['passcode'] ?? '') ?>">
<label class="mdl-textfield__label" for="passcode">Password</label>
</div>
</form>
//this <input> works
<input type="submit" name="signup" form="sign"/>
//I want to use this <button>
<button type="submit" name"signup" form "sign" formmethod="post"></button>
<?php
if ($error ?? '') {
echo addslashes($error);
}
login.php
if ($_POST['signup'] ?? '') {
$error = '';
if (!$_POST['user_mail']) $error .= "<br />Please enter email";
else if (!filter_var($_POST['user_mail'], FILTER_VALIDATE_EMAIL)) $error .= "<br />Please enter valid email";
if (!$_POST['passcode']) $error .= "<br />Please enter password";
else {
if (strlen($_POST['passcode']) < 8) $error .= "<br />Please enter a password more than eight";
if (!preg_match('`[A-Z]`', $_POST['passcode'])) $error .= "<br />please least one capital letter";
}
if ($error) $error = "there were errors:" . $error;
<button> means put a button on the page and execute whatever is in the onclick method. <submit> submits a form.
If you want a button to sumbit your form, use the onclick method of the button to do it. Why can't you use submit, though?
See here, they use a link <a onclick='...' but you can do the same for your button: How to submit a form with JavaScript by clicking a link?
As #Arun says below, you can use:
<button type='submit'> inside your form, too. There are lots of ways to do things, so my only advice on top of this is to be consistent. I use input out of habit, and that way I don't have a bunch of mixed conventions throughout my code.
If you want to submit a form on button click, add click event of button using jquery and submit a form like:
Html:
<button type="submit" name"signup" id="btn_submit" value="submit" >Submit</button>
Jquery:
$("#btn_submit").click(function() {
$("#sign").submit(); // submit a form
});
You need to make 2 changes:
Add action attribute
Move your button element inside the form. You can't expect any button on the page to submit your form. It must be inside the form, to which it is associated.
<form method="post" id="sign" action="form-destination.php">
<div class="mdl-textfield mdl-js-textfield">
<input class="mdl-textfield__input" type="email" name="user_mail" id="user_mail" value="<?php echo addslashes($_POST['user_mail'] ?? '') ?>">
<label class="mdl-textfield__label" for="user_mail">Email</label>
</div>
<div class="mdl-textfield mdl-js-textfield">
<input class="mdl-textfield__input" type="password" name="passcode" id="passcode" value="<?php echo addslashes($_POST['passcode'] ?? '') ?>">
<label class="mdl-textfield__label" for="passcode">Password</label>
</div>
<button type="submit" name"signup" form "sign" formmethod="post"></button>
</form>
<?php
if ($error ?? '') {
echo addslashes($error);
}
?>
I think you need to put a action on the form element:
<form method="post" id="sign" action="login.php">
i don't know PHP so i might be wrong.

Problems with contact form functionality in php

Before You read the code, I have tried separating each part into their own php files and just using requires to fetch the code, but using requires or having all the code in the same file I seem to be getting the same errors regardless. I think it may have something to do with the the version of PHP I'm using.
I seem to be getting an error with submit on line 3 of the BACKEND part. Being an undefined property.
The second is an undefined error on the USER FEEDBACK section.
I've used this template before and has worked successfully.
I'm running PHP 5.4.12 and Apache 2.4.4 using WAMP on my Windows 8.1 Pro PC.
Any help would be appreciated
/** BACKEND **/
<?php
if($_POST['submit'])
{
$fName=$_POST['fName'];
$topic=$_POST['topic'];
$email=$_POST['email'];
$message=$_POST['message'];
function verify_email($email)
{
if(!preg_match('/^[_A-z0-9-]+((\.|\+)[_A-z0-9-]+)*#[A-z0-9-]+(\.[A-z0-9-]+)*(\.[A-z]{2,4})$/',$email))
{
return false;
}
else
{
return $email;
}
}
function verify_email_dns($email)
{
list($name, $domain) = split('#',$email);
if(!checkdnsrr($domain,'MX'))
{
return false;
}
else
{
return $email;
}
}
if(verify_email($email))
{
if(verify_email_dns($email))
{
if ($fName=='')
{
header('location:./contact.php?error=missing');
}
elseif ($email=='')
{
header('location:./contact.php?error=missing');
}
elseif ($message=='')
{
header('location:./contact.php?error=missing');
}
else
{
foreach ($myvars as $var)
{
if (isset($_POST[$var]))
{
$var=$_POST[$var];
}
}
$subject = "Email Submission for review";
$add.="test.email#gmail.com";
$msg.="First Name: \t$fName\n";
$msg.="Email: \t$email\n";
$msg.="Topic: \t$topic\n";
$msg.="Message: \t$message\n";
$mailheaders="From: $email\n";
$mailheaders.="Reply-To: $email\n";
mail("$add", "$subject", $msg, $mailheaders);
header('location:./contact.php?error=none');
}//end else
}//end inner-if
else
{
header('location:./contact.php?error=mx');
}
}// end outter-if
else
{
header('location:./contact.php?error=format');
}
}// end starting if
/** VIEW for form **/
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="contactForm">
<label for="fName" class="first-name">Name:</label>
<input type="text" name="fName" value="" id="fName">
<br><br>
<label for="email" class="email-name">Email:</label>
<input type="text" name="email" value="" id="email">
<br><br>
<label for="topic" class="subject-name">Subject:</label>
<input type="text" name="topic" value="" id="topicsubject">
<br><br>
<label for="message" class="message-name">Message:</label>
<textarea name="message" rows="5" cols="60" id="message"></textarea>
<br><br>
<input type="submit" name="submit" id="submit-btn" class="submit-btn" value="Email Me">
</form>
/** USER FEEDBACK if error occurs **/
<?php
$error=$_GET['error'];
switch ($error)
{
case "mx":
echo "<br><span class='red'>Your email address you entered is invalid. Please try again.</span><br>";
break;
case "format":
echo "<br><span class='red'>Your email address is not in the correct format, it should look like name#domain.com. Please try again.</span><br>";
break;
case "missing":
echo "<br><span class='red'>You seem to be missing a required field, please try again.</span><br>";
break;
case "none":
echo "<br>Your email was sent. I will get back to you as soon as I can. Thank you for your interest.<br>";
break;
default:
echo "<br><br>";
}
?>
You are assuming that there are POST and GET variables when you are visiting the page. So its possible that $_POST['submit'] only exists when you actually submit the form otherwise you will get an error when first visiting that page.
try this condition instead:
if(isset($_POST['submit']) ) {
// now its safe to do something
}
You should never assume that any $_POST or $_GET variable is available when visiting the page.
Also off topic:
In your HTML you are using an 'action' attribute with the same url as the page you are visiting on this line here:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="contactForm">
Basically if you just leave out the action attribute all together it will have the same effect and its also semantic to do so. This is a better way of doing it and it has the same effect:
<form method="post" name="contactForm">
You can check this previous Stack Overflow question for a better explanation on that matter:
Is it a good practice to use an empty URL for a HTML form's action attribute? (action="")

PHP error display

I am new with php, but I have already made a registration script that works fine. But the problem is every time I press the submit button to check my error, I'm going to a new page.
My question is how I make that error comes on the same page?
The code I am useing for the html form.
I want the error display in the error div box that I made Any idea ?
<div id="RegistrationFormLayout">
<h1>Registration Page</h1>
<div id="ErrorMessage"></div>
<form action="script/registration.php" method="post">
<label for="Username">Username</label>
<input type="text" name="Regi_username">
<label for="FirstName">FirstName</label>
<input type="text" name="Regi_Firstname">
<label for="LastName">LastName</label>
<input type="text" name="Regi_Lastname">
<label for="EamilAddress">Regi_EmailAddres</label>
<input type="text" name="Regi_EmailAddres">
<label for="Password">Password</label>
<input type="password" name="Regi_password">
<button type="submit" value="Submit" class="Login_button">Login</button>
</form>
</div>
If I understand correctly, you want form validation errors there. This is a very common pattern, and the simple solution is to always set a form's action attribute to the same page that displays the form. This allows you to do the form processing before trying to display the form (if there are $_POST values). If the validation is successful, send a redirect header to the "next step" page (with header()).
The basic pattern looks like this (in very very simplified PHP)
<?php
if(count($_POST)) {
$errors = array();
$username = trim($_POST['Regi_username']);
if(empty($username)) {
$errors[] = 'username is required';
}
if(count($errors) == 0) {
header('Location: success.php');
die();
}
}
<ul class="errors">
<?php foreach($errors as $error) { ?>
<li><?php echo $error;?></li>
<?php } ?>
</ul>

Input values lost when form submitted with errors

My form is working fine with the validations being done by PHP.
I have three fields: Name, EMail and Message.
Form and PHP code is within the same pgae, same page is called for validations when user submits the form.
When a user submits the form, same page is called and it checks whether the form is submitted or not.
If the form is submitted it then does the validations for blank entries and throws error message below the fields to inform user that field is left blank. It also shows error icon next to field.
Till this, it is working fine.
However, the problem, is if the user has filled any field, for example name filed and left the other two fields(EMail and Message) blank, then on submittion, it throws error messages for blank fields which is ok, but for name field which was filled by user it empty the content and shows blank name field and does not show error(as earlier user had filled it).
My only concern is that when it relods the form after submission, it should also reload the earlier values in the respective fields which user input before submitting.
Below is the PHP validation code.
<?php
error_reporting(E_ALL & ~E_NOTICE);
if(isset($_POST['nameField_Name']) AND isset($_POST['nameField_EMail']) AND isset($_POST['nameField_Message']) AND isset($_POST['nameSubmit'])){
// Form Submited
if ($_POST['nameField_Name']) {
$phpVarNameField = mysql_escape_string($_POST['nameField_Name']);
} else {
$errormsgNameField = "Name field is required, Please enter your Name.";
}
if ($_POST['nameField_EMail']) {
$phpVarEMailField = mysql_escape_string($_POST['nameField_EMail']);
} else {
$errormsgEMailField = "E-Mail field is required, Please enter your E-Mail ID.";
}
if ($_POST['nameField_Message']) {
$phpVarMessageField = mysql_escape_string($_POST['nameField_Message']);
} else {
$errormsgMessageField = "Message field is required, Please enter your Message.";
}
}
?>
Below is the form code.
<form name="myform" action="contactus.php" method="post"">
<div id="r1">
<div id="r1c1">
<input type="text" name="nameField_Name" id="idField_Name" placeholder="Enter your name here"/>
</div>
<div id="r1c2">
<?php
if(isset($errormsgNameField)){ // Check if $msg is not empty
echo '<img src="error.png" width="45" height="45" style="margin: 5px 0px" alt="">';
}
?>
</div>
</div>
<div id="afterr1">
<?php
if(isset($errormsgNameField)){ // Check if $msg is not empty
echo '<div class="statusmsg" id="idErrorMsgNameField">'.$errormsgNameField.'</div>'; // Display our message and wrap it with a div with the class "statusmsg".
}
?>
</div>
<div id="r2">
<div id="r2c1">
<input name="nameField_EMail" type="text" id="idField_EMail" placeholder="Enter your E-Mail address here" />
</div>
<div id="r2c2">
<?php
if(isset($errormsgEMailField)){ // Check if $msg is not empty
echo '<img src="error.png" width="45" height="45" style="margin: 5px 0px" alt="">';
}
?>
</div>
</div>
<div id="afterr2">
<?php
if(isset($errormsgEMailField)){ // Check if $msg is not empty
echo '<div class="statusmsg" id="idErrorMsgEMailField">'.$errormsgEMailField.'</div>'; // Display our message and wrap it with a div with the class "statusmsg".
}
?>
</div>
<div id="r3">
<div id="r3c1">
<textarea name="nameField_Message" id="idField_Message" placeholder="Enter your message for us here"></textarea>
</div>
<div id="r3c2">
<?php
if(isset($errormsgMessageField)){ // Check if $msg is not empty
echo '<img src="error.png" width="45" height="45" style="margin: 115px 0px" alt="">';
}
?>
</div>
</div>
<div id="afterr3">
<?php
if(isset($errormsgMessageField)){ // Check if $msg is not empty
echo '<div class="statusmsg" id="idErrorMsgMessageField">'.$errormsgMessageField.'</div>'; // Display our message and wrap it with a div with the class "statusmsg".
}
?>
</div>
<div id="r4">
<div id="r4c">
<input type="Submit" name="nameSubmit" id="idButton_Submit" value="Submit" alt="Submit Button"/>
</div>
</div>
</form>
Any help will be great on this.
Thank You.
You will need to add a value attribute on your <input> elements:
<input type="text"
name="whatever"
value="<?php echo htmlspecialchars($_POST['whatever']); ?>"
>
It may be easier to read if PHP outputs the field:
<?php
printf('<input type="text" name="%s" value="%s">',
'whatever',
htmlspecialchars($_POST['whatever']));
?>
This can even be wrapped in a function so you don't need to retype it for every single form field.
Note the call to htmlspecialchars. It is needed so that < and > and quotes don't destroy your HTML document.
Try changing your tag like :
<input type="text"
name="nameField_Name"
id="idField_Name"
placeholder="Enter your name here"
value ="<?php
if (isset($phpVarNameField))
echo $phpVarNameField;
?>"
/>
.......
<input
name="nameField_EMail"
type="text"
id="idField_EMail"
placeholder="Enter your E-Mail address here"
value ="<?php if (isset($phpVarEMailField)) echo $phpVarEMailField; ?>"
/>
.......
<textarea name="nameField_Message" id="idField_Message" placeholder="Enter your message for us
here" value ="<?php if (isset($phpVarMessageField)) echo $phpVarMessageField; ?>" ></textarea>
Good Luck !
Well, You could do validation with jQuery validation plugin - easy and good. jQuery plugin
Or with PHP store POST data in array, check for errors and fields that are not empty set as value to input text.
if (isset($_POST)) {
$data = $_POST;
}
foreach ($data as $row) {
if ($row == "")
$error = true; // do what ever you want
}
and then in form
<input type="text" name="name" value="<?php ($data['name'] != "")? $data['name'] : '' ?>" />
something like this.

Categories