PHP Sticky Forms - php

I've been doing a project for php, about sticky keys. It's quite straight forward. However I'm getting a few errors... I'm using CodeLobster.
Can anyone help me find my error on this ?
I've been looking for 2hrs now, I tried the debug, but I don't really know how to use it here.
Thank you so much. Any helps will be appreciated
This is what I am getting:
Output should be this:
<html><head><title>Empty Fields</title>
<body><div align="center">
<h2>Validating Input</h2>
<?php
$errors = array();
if(isset($_POST['submit'])){
validate_input();
if(count($errors) != 0){
display_form();
}
else{
echo "<b>OK! Go ahead and Process the form!</b><br/>";
}
}
else{
display_form();
}
function validate_input(){
global $errors;
if($_POST['name'] == ""){
$errors['name'] = "<font color='red'>***Your name?***</font>";
}
if($_POST['phone'] == ""){
$errors['phone'] = "<font color='red'>***Your phone?</font>";
}
}
function display_form(){
global $errors;
?>
<b>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
What is your name?<br/>
<input type="text" name="name" value="<?php echo $_POST['name']; ?>" /><br/>
<?php echo $errors['name']; ?><br/>
What is your phone number?<br/>
<input type="text" name="phone" value="<?php echo $_POST['phone']; ?>" /><br/>
<?php echo $errors['phone']; ?><br/>
<input type="reset" />
<input type="submit" name="submit" /><br/>
</form></b>
<?php
}
?>
</div>
</body>
</html>

Can you please check once this code:-
<html><head><title>Empty Fields</title>
<body><div align="center">
<h2>Validating Input</h2>
<?php
$errors = array();
if(isset($_POST['submit'])){
validate_input();
if(count($errors) != 0){
display_form();
}
else{
echo "<b>OK! Go ahead and Process the form!</b><br/>";
}
}
else{
display_form();
}
function validate_input(){
global $errors;
if($_POST['name'] == ""){
$errors['name'] = "Your name?";
}
if($_POST['phone'] == ""){
$errors['phone'] = "Your phone?";
}
}
function display_form(){
global $errors;
?>
<b>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
What is your name?<br/>
<input type="text" name="name" value="<?php if(isset($_POST['name'])){echo $_POST['name'];} ?>" /><br/>
<?php if(isset($errors['name'])){echo $errors['name'];} ?><br/>
What is your phone number?<br/>
<input type="text" name="phone" value="<?php if(isset($_POST['name'])){$_POST['phone'];} ?>" /><br/>
<?php if(isset($errors['phone'])){echo $errors['phone'];} ?><br/>
<input type="reset" />
<input type="submit" name="submit" /><br/>
</form></b>
<?php
}
?>
</div>
</body>
</html>

I try to revise your code, There are many point to fixed.
First, you need to keep $_POST['name'] and $_POST['phone'] in variable for easy to use in each function.
Like this,
$name = (isset($_POST['name']) ? $_POST['name'] : '');
$phone = (isset($_POST['phone']) ? $_POST['phone'] : '');
You also need to add code below to first line in function that need to use this variable
global $name;
global $phone;
In function display_form you need to check $errors['name'] and $errors['name'] is empty or not before print(echo) the line.
if (isset($errors['name'])) echo $errors['name'];
if (isset($errors['phone'])) echo $errors['phone'];
So, Finally the code should be like the below, I tried this code without error.
<html>
<head><title>Empty Fields</title>
<body>
<div align="center">
<h2>Validating Input</h2>
<?php
$errors = array();
$name = (isset($_POST['name']) ? $_POST['name'] : '');
$phone = (isset($_POST['phone']) ? $_POST['phone'] : '');
if(isset($_POST['submit']))
{
validate_input();
if(count($errors) != 0)
{
display_form();
}
else
{
echo "<b>OK! Go ahead and Process the form!</b><br/>";
}
}
else
{
display_form();
}
function validate_input(){
global $errors;
global $name;
global $phone;
if($name == '')
{
$errors['name'] = "<font color='red'>***Your name?***</font>";
}
if($phone == '')
{
$errors['phone'] = "<font color='red'>***Your phone?</font>";
}
}
function display_form(){
global $errors;
global $name;
global $phone;
?>
<b>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
What is your name?<br/>
<input type="text" name="name" value="<?php echo $name; ?>" /><br/>
<?php if (isset($errors['name'])) echo $errors['name']; ?><br/>
What is your phone number?<br/>
<input type="text" name="phone" value="<?php echo $phone; ?>" /><br/>
<?php if (isset($errors['phone'])) echo $errors['phone']; ?><br/>
<input type="reset" />
<input type="submit" name="submit" /><br/>
</form></b>
<?php
}
?>
</div>
</body>
</html>

Simply use isset($var); to avoid Undefined index: EROOR on php.
echo isset($_POST['name']);
echo isset($_POST['phone']);
wherever you need.

Related

Protect form from spam (PHP) with empty fields (honeypot)

I have a simple contact form in a Wordpress website, that needs some protecting.
I gave it two empty fields named "website" and "email" and hid them with CSS (visibility: hidden;). So far, so good.
The problem now is, I just cannot give the PHP commands
if(isset($_POST['website'])) die();
if(isset($_POST['email'])) die();
the proper position in my PHP file. Can you tell me where to position it correctly?
Here is my PHP file:
<?php
if(isset($_POST['website'])) die();
if(isset($_POST['email'])) die();
if(isset($_POST['submitted'])) {
if(trim($_POST['contactVorname']) === '') {
$vornameError = '*';
$hasError = true;
} else {
$vorname = trim($_POST['contactVorname']);
}
if(trim($_POST['contactName']) === '') {
$nameError = '*';
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
if(trim($_POST['contactEmail']) === '') {
$emailError = '*';
$hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['contactEmail']))) {
$emailError = '*';
$hasError = true;
} else {
$email = trim($_POST['contactEmail']);
}
if(trim($_POST['unternehmen']) === '') {
/* $unternehmenError = '*';
$hasError = true; */
} else {
$unternehmen = trim($_POST['unternehmen']);
}
if(trim($_POST['ort']) === '') {
/* $ortError = '*';
$hasError = true; */
} else {
$ort = trim($_POST['ort']);
}
if(trim($_POST['telefon']) === '') {
/* $telefonError = '*';
$hasError = true; */
} else {
$telefon = trim($_POST['telefon']);
}
if(trim($_POST['betreff']) === '') {
$betreffError = '*';
$hasError = true;
} else {
$betreff = trim($_POST['betreff']);
}
if(trim($_POST['comments']) === '') {
$commentError = '*';
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['comments']));
} else {
$comments = trim($_POST['comments']);
}
}
if(!isset($hasError)) {
$emailTo = get_option('tz_email');
if (!isset($emailTo) || ($emailTo == '') ){
$emailTo = get_option('admin_email');
}
$subject = 'Kontaktformular | '.$vorname.' '.$name;
$body = "\n.: Kontaktformular-E-Mail :. \n\nName: $vorname $name \nE-Mail: $email \n\nUnternehmen: $unternehmen \nOrt: $ort \nTelefon: $telefon \n\nBetreff: $betreff \n\nNachricht: $comments";
$headers = 'From: '.$vorname.' '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
wp_mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
<?php get_header(); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<article class="post" id="post-<?php the_ID(); ?>">
<h2 class="gross"><?php the_title(); ?></h2>
<div id="inhalt">
<div class="seitebeitrag">
<?php if(isset($emailSent) && $emailSent == true) { ?>
<div><p>Vielen Dank für die Nachricht. Wir melden uns so schnell wie möglich zurück.</p></div>
<?php } else { ?>
<?php the_content(); ?>
<form action="" id="contactForm" method="post">
<div id="kf0"> </div>
<div id="kf1">
<p><label for="contactVorname">Vorname *</label><br />
<input type="text" name="contactVorname" id="contactVorname" value="<?php if(isset($_POST['contactVorname'])) echo $_POST['contactVorname'];?>" maxlength="50" />
<?php if(!empty($vornameError)) { ?>
<span class="fehler"><?=$vornameError;?></span>
<?php } ?></p>
<p><label for="contactName">Nachname *</label><br />
<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" maxlength="50" />
<?php if(!empty($nameError)) { ?>
<span class="fehler"><?=$nameError;?></span>
<?php } ?></p>
<p><label for="contactEmail">E-Mail *</label><br />
<input type="text" name="contactEmail" id="contactEmail" value="<?php if(isset($_POST['contactEmail'])) echo $_POST['contactEmail'];?>" maxlength="50" />
<?php if(!empty($emailError)) { ?>
<span class="fehler"><?=$emailError;?></span>
<?php } ?></p>
<p><label for="unternehmen">Unternehmen</label><br />
<input type="text" name="unternehmen" id="unternehmen" value="" maxlength="50" /></p>
<p><label for="ort">Ort</label><br />
<input type="text" name="ort" id="ort" value="" maxlength="50" /></p>
<p><label for="telefon">Telefon</label><br />
<input type="text" name="telefon" id="telefon" value="" maxlength="50" /></p>
<input type="text" id="website" name="website" value="" maxlength="80" /><br />
<input type="text" id="email" name="email" value="" maxlength="80" />
</div>
<div id="kf2">
<p><label for="betreff">Betreff *</label><br />
<input type="text" name="betreff" id="betreff" value="<?php if(isset($_POST['betreff'])) echo $_POST['betreff'];?>" maxlength="50" />
<?php if(!empty($betreffError)) { ?>
<span class="fehler"><?=$betreffError;?></span>
<?php } ?></p>
<p><label for="commentsText">Nachricht *</label><br />
<textarea name="comments" id="commentsText" rows="20" cols="30"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>
<?php if(!empty($commentError)) { ?>
<span class="fehler"><?=$commentError;?></span>
<?php } ?></p>
<p>* Pflichtfelder</p>
</div>
<div id="kf3">
<input type="submit" value="SENDEN" alt="senden" class="btn" /><br /><input type="hidden" name="submitted" id="submitted" value="true" />
</div>
<div id="kf4">
<?php if(isset($hasError) || isset($captchaError)) { ?>
<div><p class="error fehler">* ungültige oder fehlende Daten</p></div>
<?php } ?></div>
</form>
<?php } ?>
<?php wp_link_pages(array('before' => __('Pages: '), 'next_or_number' => 'number')); ?>
</div>
<?php // edit_post_link(__('Edit this entry.'), '<p>', '</p>'); ?>
</article>
<?php // comments_template(); ?>
<?php endwhile; endif; ?>
<?php // get_sidebar(); ?>
<?php get_footer(); ?>
Right now, the form gets totally blocked out, after sending the data, ALTHOUGH the two fields in question are NOT FILLED IN.
$_POST['website'] & $_POST['email'] will always be 'set'. An empty form field still sets the corresponding $_POST entry to an empty string ('') and will always be true to isset. Try using !empty.
if (!empty($_POST['website'])) die();
if (!empty($_POST['email'])) die();
See more here: http://php.net/manual/en/function.empty.php and with a bit more detail here: https://www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/
Be careful using this approach with commonly named fields. They may be automatically filled in by a browser's auto-fill feature meaning you'll be getting false-positives and real users will end up on a blank screen.

PHP: show messages from form validation

Hi I've got a simple form and a validation function.
When I submit the form empty no error messages are showing up. What am I doing wrong? Is there maybe a better solution to output error messages of a form validation?
<?php
include "functions.php";
?>
<html>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<label>Username:</label>
<input type="text" name="username">
<br />
<label>Password:</label>
<input type="password" name="password">
<br />
<input type="submit" value="send">
</form>
<span><?php echo $nameErr ?></span>
<span><?php echo $pwErr ?></span>
</html>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
validateForm();
}
?>
here is the functions.php file:
<?php
function validateForm()
{
if (empty($_POST["username"]))
{
$nameErr = "Name is required";
}
if (empty($_POST['password']))
{
$pwErr = "Password is required";
}
}
?>
Functions.php
<?php
function validateForm()
{
$errors = array();
if (empty($_POST["username"]))
{
$errors[] = "Name is required";
}
if (empty($_POST['password']))
{
$errors[] = "Password is required";
}
return '<span>'.implode('</span>,<span>', $errors).'</span>';
}
?>
main.php
<?php
include "functions.php";
?>
<html>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<label>Username:</label>
<input type="text" name="username">
<br />
<label>Password:</label>
<input type="password" name="password">
<br />
<input type="submit" value="send">
</form>
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
echo validateForm();
}
?>
</html>
You have to declare the $msg variable out of the function, and above everything, before instantiate it. And i used a global method to call it inside the function, and now we got access to this variable scope inside the function we created.
Your new include or require functions.php file should look like this:
<?php
$msg = "";
function validateForm($name, $pwd){
global $msg;
if(isset($_POST[$name]) && empty($_POST[$name])){
$msg .= "Wrong name passed\n";
} elseif(isset($_POST[$pwd]) && empty($_POST[$pwd])){
$msg .= "Wrong password\n";
} else {
$msg .= "Logged\n";
}
}
?>
The html content and the include part:
<?php
require_once 'functions.php';
if(isset($_SERVER["REQUEST_METHOD"]) && $_SERVER["REQUEST_METHOD"] === "POST"){
validateForm('username','password');
}
?>
<html>
<form action="" method="POST">
<label>Username:</label>
<input type="text" name="username">
<br />
<label>Password:</label>
<input type="password" name="password">
<br />
<input type="submit" value="send">
</form>
<span><?php echo isset($msg) ? $msg : NULL; ?></span>
</html>
You must make variables $nameErr and $pwErr inside validateForm() global since you want to echo those variables outside the function. Variables inside a function doesn't have global scope. It works only inside function. Make your variables global like this:
<?php
function validateForm(){
if (empty($_POST["username"]))
{
$nameEr = "Name is required";
$GLOBALS['nameErr']=$nameEr;
}
if (empty($_POST['password']))
{
$pwEr = "Password is required";
$GLOBALS['pwErr']=$pwEr;
}
}
?>
and also echo
<span><?php echo $nameErr ?></span>
<span><?php echo $pwErr ?></span>
after running validateForm() function.
You are calling the function AFTER you show the error messages.
Try calling it right after the declaration, before the echos.
I've also read Vincent comment, its true, you either have to declare the vars as global, or think of something else
Something I think better :
function validateForm()
{
var $errors = array();
if (empty($_POST["username"]))
{
$errors[] = "Name is required";
}
if (empty($_POST['password']))
{
$errors[] = "Password is required";
}
return '<span>'.implode('</span>,<span>', $errors).'</span>';
}
Then use in your view where to want to show errors :
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
echo validateForm();
}
<?php
include "functions.php";
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
validateForm();
}
?>
You got to call the function before assembling your html
If you want this script to work, validation code need to be at begining of the script.
functions.php
function validateForm(&$nameErr, &$pwErr)
{
if (empty($_POST["username"]))
{
$nameErr = "Name is required";
}
if (empty($_POST['password']))
{
$pwErr = "Password is required";
}
}
html
include "functions.php";
$nameErr = "";
$pwErr = "";
if (isset($_POST["username"]))
{
validateForm($nameErr, $pwErr);
}
?>
<html>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<label>Username:</label>
<input type="text" name="username">
<br />
<label>Password:</label>
<input type="password" name="password">
<br />
<input type="submit" value="send">
</form>
<span><?php echo $nameErr ?></span>
<span><?php echo $pwErr ?></span>
</html>

PHP - Displaying form input without re-displaying the form

How do I echo the form input without having to re-display the form after validation? I can only display the input after the form. Here is the code I have
<?php
$postalCode = $_POST['postalCode'];
$postalCodeErr = "";
$postalCodeValidation = '/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/';
$postalCodeIsValid = false;
?>
<html>
<body>
INT322 Lab 3-1
<br />
<br />
<form name="lab3form" action="index.php" method="post">
Postal Code:
<input type="text" name="postalCode" value="<?php if(isset($postalCode)) echo $postalCode; ?>" />
<?php
if(($postalCode != "") && preg_match($postalCodeValidation, $postalCode)) {
$postalCodeIsValid = true;
}
else {
$postalCodeErr = "Invalid Postal Code";
}
if(isset($postalCode)) echo " $postalCodeErr";
?>
<br />
<br />
<input type="submit" name="submit" />
</form>
</body>
</html>
<?php
if($_POST['submit'] && $postalCodeIsValid) {
echo "Postal Code: $postalCode";
}
?>
How about wrapping your form in the else of if($_POST['submit'] && $postalCodeIsValid) { ... } else { ... }
<?php
if($_POST['submit'] && $postalCodeIsValid) {
echo "Postal Code: $postalCode";
}
else {
<form name="lab3form" action="index.php" method="post">
Postal Code:
<input type="text" name="postalCode" value="<?php if(isset($postalCode)) echo $postalCode; ?>" />
<?php
if(($postalCode != "") && preg_match($postalCodeValidation, $postalCode)) {
$postalCodeIsValid = true;
}
else {
$postalCodeErr = "Invalid Postal Code";
}
if(isset($postalCode)) echo " $postalCodeErr";
?>
<br />
<br />
<input type="submit" name="submit" />
</form>
}
?>
UPDATED ANSWER with full code:
<html>
<body>
INT322 Lab 3-1
<br />
<br />
<?php
if(!empty($_POST['submit'])):
$postalCode = $_POST['postalCode'];
if(isValidPostalCode($postalCode)):
echo "Postal Code: $postalCode";
else:
form($postalCode, true);
endif;
else:
form();
endif;
?>
</body>
</html>
<?php
function form($postalCode = null, $hasError = false) { ?>
<form name="lab3form" action="postal.php" method="post">
Postal Code:
<input type="text" name="postalCode" value="<?php if(isset($postalCode)) echo $postalCode; ?>" />
<?php if ($hasError): ?>
<div class="error">Invalid Postal Code</div>
<?php endif; ?>
<br />
<br />
<input type="submit" name="submit" />
</form>
<?php }
function isValidPostalCode($postalCode) {
$postalCodeValidation = '/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/';
return !empty($postalCode) && preg_match($postalCodeValidation, $postalCode);
}
?>
Please note that your regular expression only works with postal codes such as A1B2C3 - I'm not sure if this is the behavior you want.

php get the value from hidden field after redirect

member.php
<?php
if(isset($_POST['submit']))
{
$membername = $_POST['membername'];
if(empty($membername))
{
$errors .= "Please enter member name<br />";
}
if($errors)
{
$action = $_POST['submit'];
echo $errors;
displayForm();
}
else
{
?>
<input type="hidden" name="mname" value="<?php echo $_POST['membername']; ?>" />
<?php
$action = $_POST['submit'];
header("Location: commit.php?action=$action");
exit();
}
}
else
{
displayForm();
}
?>
<?php
function displayForm()
{
?>
<form action = "member.php" action="post">
Member Name <input type="text" name="membername" value="<?php if(isset($row['name'])) echo $row['name'];
else echo ''; ?>" /><br /><input type="text" name="membername" value=
<input type="submit" name="submit" name="add" />
</form>
<?php
}
?>
Commit.php
<?php
echo $_POST['mname']; //HERE
?>
I want to pass the hidden value from member.php. When I run commmit.php, I want to get hidden field value. However, the error is the following:
**Undefined index: mname in member.php in commit.php.
What am I doing wrong?

Keep text in text field after submit

I'm building a form, and I want that all the inserted values will be kept, in case of form submit failure. This is my code:
<?php
$error = "";
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
// Verify $_POST['name'] greater than 4 chars
if ( strlen($name) < 4 ){
$error= 'Name too short!';
}
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" name="myForm" id="idForm">
<input type="text" placeholder="Name" id="name" name="name" value=""/>
<input type="submit" value="submit"/>
</form>
<?php
echo "<h2>Input:</h2>";
echo $name;
if($error) {
// No Update AND refresh page with $name in text field
echo "<br/>" . $error;
} else {
// Update name in DB
}
?>
</body>
</html>
I would like that name field keeps the inserted input text, after submit. I tried to do with php code in input value but doesn't work. Any ideas?
Solved. This is the solution that I was looking for.
I added in value tag of input the following:
<?php if (isset($_POST['name'])) echo $_POST['name']; ?>
Therefore input field would look like:
<input type="text" placeholder="Name" id="name" name="name" value="<?php if (isset($_POST['name'])) echo $_POST['name']; ?>"/>
Thanks for your responses, helped me.
<?php
$error = "";
$name = isset($_POST["name"])?$_POST["name"]:""; //Added condition
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
// Verify $_POST['name'] greater than 4 chars
if ( strlen($name) < 4 ){
$error= 'Name too short!';
}
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" name="myForm" id="idForm">
<input type="text" placeholder="Name" id="name" name="name" value="<?php echo $name; ?>"/>
<input type="submit" value="submit"/>
</form>
<?php
echo "<h2>Input:</h2>";
echo $name;
if($error) {
// No Update AND refresh page with $name in text field
echo "<br/>" . $error;
} else {
// Update name in DB
}
?>
</body>
</html>
You can just echo $_POST['name'] in the value attribute of the input.
Make sure you check POST values to avoid XSS.
I also put up the update DB function, as you don't need to show the form to the user if the name in longer the 4 chars!
<?php
$error = "";
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['name'])){ //change name content only if the post value is set!
$name = filter_input (INPUT_POST, 'name', FILTER_SANITIZE_STRING); //filter value
}
// Verify $_POST['name'] greater than 4 chars
if ( strlen($name) < 4 ){
$error= 'Name too short!';
} else {
// Update name in DB
// Redirect
}
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" name="myForm" id="idForm">
<input type="text" placeholder="Name" id="name" name="name" value="<?php echo $name; ?>"/>
<input type="submit" value="submit"/>
</form>
<?php
echo "<h2>Input:</h2>";
echo $name;
if($error) {
// No Update AND refresh page with $name in text field
echo "<br/>" . $error;
};
?>
</body>
</html>
If you want to keep all values/inputs for further use you could achieve that with php session values.
Besides - you should use $_SERVER['SCRIPT_NAME'] instead of $_SERVER['PHP_SELF']
Mars

Categories