PHP: show messages from form validation - php

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>

Related

Server side error message display from process page to index page in php

I have to display a server-side validation error message which is working perfectly if I write both codes(HTML and PHP) on a single page.
Now I have index.php and process.php pages. I have to pass server-side validation error message from process.php to index.php. Without using Ajax. would you help me in this?
index.php
<?php
include('../../db/connection.php');
$fname_error="";
$email_error="";
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="process.php" method="post">
<input type="text" name="fname" value="<?php if(isset($fname)){echo $fname;} ?>">
<span class="error"><?php echo $fname_error;?></span>
<input type="email" name="email" value="<?php if(isset($email)){echo $email;}?>">
<span class="error"><?php echo $email_error;?></span>
<input type="submit" name="submit">
</form>
</body>
</html>
Process.php
<?php
include('../../db/connection.php');
if (isset($_POST['submit'])) {
$fname=trim($_POST['fname']);
$email=trim($_POST['email']);
if (empty($fname)) {
$fname_error="Name is empty";
}
else
{
if ($fname<3) {
$fname_error="Please enter minimum 3 character";
}
}
if (empty($email)) {
$email_error="Email field is empty";
}
else
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error="Invalid email format";
}
}
// insert code here
}
?>
Use SESSIONS to achive this. Try following Code:
index.php
<?php
session_start();
include('../../db/connection.php');
$fname_error= $_SESSION['fname'];
$email_error= $_SESSION['email_error'];
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="process.php" method="post">
<input type="text" name="fname" value="<?php if(isset($fname)){echo $fname;} ?>">
<span class="error"><?php echo $fname_error;?></span>
<input type="email" name="email" value="<?php if(isset($email)){echo $email;}?>">
<span class="error"><?php echo $email_error;?></span>
<input type="submit" name="submit">
</form>
</body>
</html>
<?php
unset($_SESSION['fname']);
unset($_SESSION['email_error']);
?>
process.php
<?php
session_start();
include('../../db/connection.php');
if (isset($_POST['submit'])) {
$fname=trim($_POST['fname']);
$email=trim($_POST['email']);
if (empty($fname)) {
$_SESSION['fname'] ="Name is empty";
header('location:index.php');
}
else
{
if ($fname<3) {
$_SESSION['fname'] ="Please enter minimum 3 character";
header('location:index.php');
}
}
if (empty($email)) {
$_SESSION['email_error'] ="Email field is empty";
header('location:index.php');
}
else
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$_SESSION['email_error']="Invalid email format";
header('location:index.php');
}
}
// insert code here
}
?>

PHP Sticky Forms

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.

Login page without database connectivity

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

redirect on form submit

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.

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>

Categories