How to show error messages in HTML page in PHP? - 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>

Related

In php validation when wrong data is found the page get refreshed and the data's already entered will became empty.How to prevent the loss?

I am a very beginner in php.I tried a form validation in php while validating my form.when wrong data is found the browser will show an alert box, when i click it the browser reloads the page and the details already entered in the form get refreshed and i need to enter it from the first.
How to avoid the page refresh while validating.
sorry for my poor english
Thank you in advance
This is my php form coding
formvalidate.php
<html>
<head>
<title>USER REGISTRATION</title>
</head>
<body>
<form name="registrationform" id="formid" method="get";>
name:<input type="text" id="n1" name="name"> <br><br>
username:<input type="text" id="u1" name="username"> <br><br>
password:<input type="password" id="p1" name="password"> <br><br>
confirm password:<input type="password" id="p2" name="password2"> <br><br>
Address :<textarea name="address" id= "a1"rows="4" cols="40"> </textarea><br><br>
phone :<input id="ph" type="numbers" name="phone" ><br><br>
<input type="submit" name="register" value="register" >
<input id="button" type="button" value="cancel">
<?php
$servername="localhost";
$username="root";
$password="";
$dbname="userlogin";
$conn=mysqli_connect($servername,$username,$password,$dbname);
if(!$conn)
{
die("connection failed".mysqli_connect_error());
}
?>
<?php
if (isset($_GET['register'])) {
if(empty($_GET['name']))
{
echo'name should not empty';
}
if ( empty($_GET['username'])) {
echo 'user name should not be empty';
} else {
$name1=$_GET['name'];
$uname=$_GET['username'];
$sql = "select * from contact where username='$uname'";
$result=mysqli_query($conn,$sql);
if($result->num_rows==1)
{
echo"username already exists";
}
else
{
echo"username available";
}
return false;
}
if((empty($_GET['password']))||(empty($_GET['confirmpassword'])))
{
echo'password and confirm password should not be empty';
return false;
}
else{
$pwd=$_GET['password'];
$cpwd=$_GET['confirmpassword'];
if($pwd.length==6){
echo'password should not lesser than 6';
}
else
{
if($pwd==$cpwd){
echo'password accepted';
}
else
{
echo 'password does not matched';
return false;
}
}
}
if(empty($_GET['address']))
{
echo'address should not be empty';
return false;
}
if(empty($_GET['phone']))
{
echo'phone should not be empty';
return false;
}
}
?>
</body>
</form>
</html>
You could perform the check at the start of page, something like;
$sParam1 = "";
if (isset ($_GET['param1']) ){
$sParam1 = (string)$_GET['param1'];
}
Leave the form at the bottom of the page and echo the variables in the value param;
<form method="get">
<input type="text" name="param1" value="<?php echo htmlspecialchars($sParam1); ?>" />
</form>
Yoy can also set something like
if(isset($_GET['name'] ){echo "value=$_GET[name]";}
for each of the input attributes.
Though i believe you should use POST attribute in form rather tham GET.
Also, you have not set the 'action' attribute for the form !

How to display php form result in the html if php processing is not in the same page without using ajax?

Lets say i have this form in form.php file.
<form action="process.php" method="POST">
<input type="text" name="message">
<input type="submit" value="Submit">
</form>
<span class="result"></span>
process.php contains
<?php
if(isset($_POST['message'])){
$message = $_POST['message'];
if(!empty($message)){
echo 'Your message: '.$message;
}else{
echo 'Please enter some message.';
}
}
Now if i want to display the output of process.php inside the form.php's span tag of class result i either need to use ajax, or session/cookie or file handling. Is there any other way?
You can simply place the code in the process.php file inside the forms span tag.
<form action="form.php" method="POST">
<input type="text" name="message">
<input type="submit" value="Submit">
</form>
<span class="result">
<?php
if(isset($_POST['message']))
{
$message = $_POST['message'];
if(!empty($message))
{
echo 'Your message: '.$message;
}
else
{
echo 'Please enter some message.';
}
}
?>
</span>
Try this. It will post the form values in same page
<form action="form.php" method="POST">
<input type="text" name="message">
<input type="submit" value="Submit">
</form>
<span class="result"></span>
<?php
if(isset($_POST['message'])){
$message = $_POST['message'];
if(!empty($message)){
echo 'Your message: '.$message;
}else{
echo 'Please enter some message.';
}
}
OK this is one way of doing it: In form.php,
<form action="process.php" method="POST">
<input type="text" name="message">
<input type="submit" value="Submit">
</form>
<?php
$var = $_GET['text'];
echo "<span class=\"result\"> $var </span>";
?>
Then in process.php do this:
<?php
if(isset($_POST['message'])){
$message = $_POST['message'];
if(!empty($message)){
// echo 'Your message: '.$message;
header("location: form.php?text=$message")
}else{
echo 'Please enter some message.';
}
}
?>
There are a few drawbacks using this method:
Variable $message is passed through the URL and so should not be too long as URLs have length limits
Using $_GET[] makes message visible on the URL so passwords and other sensitive information should no be used as the message.
I hope this helps.

Make errors show on top of a form

How do I make error show on top of form so that if $user->success == true, it wont show my form then. Removing that last else would help, but then form shows after success. One way is to redirect that. Maybe tehre
if (isset($_POST["submit"]))
{
if ($_POST["formid"] == $_SESSION["formid"])
{
$_SESSION["formid"] = '';
$User->signin($_POST['username'], $_POST['password']);
}
else
$User->CheckUser();
if ($User->success == true) {
include ('in.php');
}
if ($User->error)
echo "<p>" . $User->error . "</p>";
else
echo 'Don\'t process form';
$_SESSION["formid"] = md5(rand(0,10000000));
} else {
?>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
Username:
<input id="username" name="username" type="text" /><br />
Password:
<input id="password" name="password" type="password" /><br />
<input type="hidden" name="formid" value="<?php echo $_SESSION["formid"]; ?>" />
<input type="submit" name="submit" />
<br />
Register
</form>
<?php }?>
Perhaps the simplest approach is to just create a variable $show_form to use to determine whether form is to be shown,
$show_form = true;
if(isset($_POST['submit'])) {
// do your form processing here.
// If you decide everything is good and you don't want to show the form,
// just add this line:
$show_form = false;
} // don't use else here
if (true === $show_form) {
?>
<form>...</form>
<?
}
?>
add this code before your form tag
<?php if (isset($User->error) AND $User->error)?>
<p><?php echo $User->error?></p>
<?php?>

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')

How do I validate forms and present error messages using PHP?

Let's say we have this form:
<form action="submit.php" method="post">
Username: <input type="text" name="username" />
Password: <input type="password" name="password" />
<input type="Submit" value="Login" />
</form>
How do I validate this form using submit.php, and how do I present an error message if it doesn't pass validation? With Javascript validation I would just change the innerHTML of some element to the error message, but this is not possible with PHP. As you can see I'm a total newbie, so please help me out.
In ugly form:
<?php
$errors = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$pw = $_POST['password'];
if (empty($username)) {
$errors[] = "Please enter your username";
}
if (empty($pw)) {
$errors[] = "Please provide your password";
}
if (!canLogin($username, $pw)) {
$errors[] = "Invalid login. Try again";
}
if (count($errors) == 0) {
... login is ok, go do something else
}
}
# Display error conditions, if there are any
if (count($errors) > 0) {
echo "<p>The following errors must be corrected:</p><ul><li>";
echo implode("</li><li>", $errors);
echo "</ul>";
}
?>
<form ...>
<input .... value="<?php echo htmlspecialchars($username) ?>" />
<input ...>
</form>
You could always have the form's action submit to itself (same PHP script) and perform your validation there and if it passes continue to another url. And then in your form write some conditionals to insert a CSS class to highlight the field thats in error or show a message.

Categories