Error appears before submit in php form - php

I have the following code but unfortunately $error appears as soon as the page loads, before clicking on submit. What am I doing wrong?
(filename= form.php)
<?php
$error="";
if (isset($_POST['submit']) && $_POST['submit'] == "Submit") {
$name = $_POST['name'];
$email = $_POST['email'];
if($name=="" || $email==""){
$error .= "Error: all fields are required";
}
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email)) {
$error .= "<br/> Error: Invalid email address";
}
if (isset($error) && ($error!=="")) {
echo $error;
}
elseif (empty($error)){
// this works no need to write here... send form.
}
}
echo<<<_END
<html><head><body>
<form method='post' action='form.php'>
<p>Name</p> <input type="text" name="name" value='$name'>
<p>Email</p> <input type="text" name="email" value='$email'>
<input type="submit" name="submit" value="Submit">
<input type="reset" name="reset" value="Clear">
</form>
</body>
</html>
_END;
?>

if (isset($error) && (!$error=="")) {
echo $error;
}
if $error is set and $error equals nothing echo $error?
$error is being set when you intialize it to "" in the first line and it is equal to ""
Just noticed the ! in the second part of the if. Do what the person below me said.

Replace (!$error=="")) with ($error!=="")).

Related

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>

Error-message in password is visible on pageload?

How do i prevent the error-message from showing before the 'submit'-button is clicked?
For some reason the content of 'else'-statement is visible on pageload - the message "NO" should only appear after typing something else than 'a' in this.. what am i doing wrong?
<form method="POST">
<input type="text" class="textfield" id="cursor" name="pass">
<input type="submit" class="button" name="submit" value="OK">
</form>
<?php
$pass = $_POST['pass'];
if($pass == 'a') {
echo "YES";
}
else{
echo "NO";
}
?>
Add this PHP code:
<?php
if(isset($_POST['pass'])) {
// your check here
}
?>
Test to see if the submit button is in the submitted data.
if (isset( $_POST['submit'] )) {
<form method="POST">
<input type="text" class="textfield" id="cursor" name="pass">
<input type="submit" class="button" name="submit" value="OK">
</form>
<?php
$pass = $_POST['pass'];
//You need to check if the form is submitted
if($_POST['submit']){
if(isset($pass) && !empty($pass) && $pass == 'a') {
echo "YES";
}
else{
echo "NO";
}
?>

Php Input Validation not responding

I am new to the web developing world.Please bare w/ me for having some mistakes and insufficient knowledge.
I'm trying to study the validation process of a users input. Below is my Code:
<?php
if($_POST['formSubmit'] == "Search")
{
$errorMessage = "";
if(empty($_POST['formName']))
{
$errorMessage .= "<li>No Input</li>";
}
$varName = $_POST['formName'];
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
}
?>
<form action="index.php" method="post">
<input type="text" name="formName" value="<?=$varName;?>">
<input type="Submit" name="formSubmit" value=" Search">
</form>
What I think should happen is when the user click the search button without inputting anything an error message will pop-up, but I don't understand why its not responding or echoing the error message, i've check the names and values but Alas, Appreciate all the help/suggestions you could give tnx.
Thanks for the reply everyone, got it into working ^_^
Your $_POST['formSubmit'] doesn't contain Search. It contains Search (with space in front of it).
Because of that PHP will never validate your form.
This works:
<?php
if($_POST['formSubmit'] == "Search")
{
$errorMessage = "";
if(empty($_POST['formName']))
{
$errorMessage .= "<li>No Input</li>";
}
$varName = $_POST['formName'];
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
}
?>
<form action="index.php" method="post">
<input type="text" name="formName" value="<?=$varName;?>">
<input type="Submit" name="formSubmit" value="Search">
</form>
you need to use isset() function
<?php
if(isset($_POST['formSubmit']))
{
$errorMessage = "";
if(empty($_POST['formName']))
{
echo $errorMessage .= "No Input";
}
else
{
$varName = $_POST['formName'];
}
}
?>
<form action="index.php" method="post">
<input type="text" name="formName" value="<?=$varName;?>">
<input type="Submit" name="formSubmit" value="Search">
</form>
You giving wrong name to your submit button .
<input type="Submit" name="formSubmit" value=" Search">
it should be
<input type="Submit" name="formSubmit" value="Search">
Change this line
if($_POST['formSubmit'] == "Search")
to
if(isset($_POST['formSubmit']))
I am making some corrections. Please use this.
<?php
if($_POST['formSubmit'] == "Search") {
$errorMessage = "";
if(empty($_POST['formName'])) {
$errorMessage .= "<li>No Input</li>";
} else {
$varName = $_POST['formName'];
}
if(!empty($errorMessage)) {
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
}
?>
<form action="index.php" method="post">
<input type="text" name="formName" value="<?=$varName;?>">
<input type="Submit" name="formSubmit" value="Search">
</form>
Corrected the condition if($_POST['formSubmit'] == "Search")
IF $_POST['formName'] is empty then no need for assigning so put it inside else condition.

How to show error messages in HTML page in PHP?

I have following login form (login.php) in which I am asking for username and password.
<form action="processlogin.php" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Login">
</form>
Following is the code snippet from my processlogin.php file
if(!$_POST["username"] || !$_POST["password"])
{
$msg = "You left one or more of the required fields.";
echo $msg;
//header("Location:http://localhost/login.php");
}
This code checks whether all the mandatory fields are filled on not. If not, it shows the error message.
Till now everything is fine.
My problem is that, error message is shown in plain white page. I want to show it above the login form in login.php file. How should I change my code to get
my functionality.
I would prefer Jquery Validation or Ajax based Authentication. But still you can do it this way:
Put your Error Message in Session like this :
$_SESSION['Error'] = "You left one or more of the required fields.";
Than simple show it like this:
if( isset($_SESSION['Error']) )
{
echo $_SESSION['Error'];
unset($_SESSION['Error']);
}
In this case you can assign multiple messages in different Operations.
header("Location:http://localhost/login.php?x=1")
In the login.php
if(isset($_GET('x'))){
//your html for error message
}
Hope it helps you,
In processlogin.php,
if(!$_POST["username"] || !$_POST["password"])
{
$msg = "You left one or more of the required fields.";
$msgEncoded = base64_encode($msg);
header("location:login.php?msg=".$msgEncoded);
}
in login.php file,
$msg = base64_decode($_GET['msg']);
if(isset($_GET['msg'])){
if($msg!=""){
echo $msg;
}
}
You can display the message in table or span above the form.
<span>
<?php if(isset($_REQUEST[$msg]))
echo $msg;
?>
</span>
<form>
</form>
And also don't echo $msg in the form's action page.
Try this:
html:
<form action="processlogin.php" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Login">
<span>
<?php if(isset($_GET['msg']))
echo $_GET['msg'];
?>
</span>
</form>
php:
if(!$_POST["username"] || !$_POST["password"])
{
$msg = "You left one or more of the required fields.";
header("Location:http://localhost/login.php?msg=$msg");
}
Use only one page (your login.php) to display the form and also to validate its data if sent. So you don't need any $_SESSION variables and you have all in one and the same file which belongs together.
<?php
$msg = null;
if(isset($_GET['send'])) {
if(!$_POST["username"] || !$_POST["password"]){
$msg = "You left one or more of the required fields.";
//header("Location:http://localhost/login.php");
}
}
?>
<?php echo ($msg !== null)?'<p>ERROR: ' . $msg . '</p>':null; ?>
<form action="?send" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Login">
</form>
use these functions:
<?php
session_start();
define(FLASH_PREFIX,'Flash_')
function set_flash($key,$val){
$_SESSION[FLASH_PREFIX.$key]=$val;
}
function is_flash($key){
return array_key_exits(FLASH_PREFIX.$key,$_SESSION);
}
function get_flash($key){
return $_SESSION[FLASH_PREFIX.$key];
}
function pop_flash($key){
$ret=$_SESSION[FLASH_PREFIX.$key];
unset($_SESSION[FLASH_PREFIX.$key]);
return $ret;
}
?>
And when you want to send a message to another page use
set_flash('err_msg','one field is empty');
header('location: another.php');
exit();
another.php
<html>
.
.
.
<body>
<?php if(is_flash('err_msg')){?>
<span class="err_msg"><?php echo pop_flash('err_msg'); ?></span>
<?php } ?>
.
.
.
</body></html>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST")
{
if(!$_POST["username"] || !$_POST["password"])
{
$msg = "You left one or more of the required fields.";
echo $msg;
//header("Location:http://localhost/login.php");
}
}
?>
<form action="<?php echo $PHP_SELF;?>" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Login">
</form>

loading blank page despite form action location upon error

I am creating a simple form that a user submits and email. I am trying to pose an error if the form is blank or it's not a valid email and if successful, then reload the page with a success message.
When I submit blank it reloads the page without an error, and if I enter anything in ( valid or invalid email ) it reloads the page white, despite the form action being correct. I've been stuck on this and need help. Thanks.
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/includes/system/init.php');
if(isset($_POST['submit'])) {
$email = $_POST['email'];
if(empty($_POST['email']) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error = "Please enter a valid email";
}else{
$success = true;
mysql_query("INSERT INTO survey
(email) VALUES('".$_POST['email']."' ) ")
or die(mysql_error());
}
}
?>
<div class="email-survey">
<?php if(isset($success)) { ?>
<div class="success">Thank You!</div>
<?php } ?>
<?php if(isset($error)) { ?>
<div class="error">
<?php echo $error; ?>
</div>
<?php } ?>
<form name="settings" action="/survey-confirm.php" method="post">
<input type="text" name="email" /> <br />
<input type="submit" name="submit" value="submit" />
</form>
</div>
<?php
function control($type, $text)
{
echo '<div class="'.$type.'">'.$text.'</div>';
}
require_once($_SERVER['DOCUMENT_ROOT'] . '/includes/system/init.php');
if(isset($_POST['submit'])) {
$email = $_POST['email'];
if(empty($_POST['email']) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
control('error', 'Type valid mail!');
}else{
control('success', 'All done!');
mysql_query("INSERT INTO survey
(email) VALUES('".$_POST['email']."' ) ")
or die(mysql_error());
}
}
else
{echo 'echo '<form name="settings" action="/survey-confirm.php" method="post">
<input type="text" name="email" /> <br />
<input type="submit" name="submit" value="submit" />
</form>
</div>';}
?>
This is small function named control, you can call this and put your custom div name and text to show user.
control('THIS IS DIV NAME','THIS IS MESSAGE FOR USER')

Categories