How to replace die() statement? - php

if(!empty($_POST))
{
if(empty($_POST['username'])) {die("Please enter a username.");}
....
Result is blank page - with the above alert.
I want to keep the form on the page. Something like:
if(empty($_POST['username']))?> <div id="info"><?php{echo "Please enter a username"};?></div>
So, just write an info, and stop the code execution from this point.

To Stop execution but you can use:
die( ' <div id="info">Please enter a username</div> ');
To allow the rest of the page to load you can use:
$errors = array();
if(empty($_POST['username'])) {
$errors[] = 'Please enter your username';
}
Then later in your html you can add
foreach($errors as $error){
echo "<div class='error'>$error</div>;
}

Rather than "stopping execution" on a single validation error, get all the errors and display them to the user:
<?php
if (!empty($_POST))
{
// validate form
$errors = array();
if (empty($_POST['username']))
{
$errors['username'] = 'Please enter a username.';
}
if (empty($_POST['address']))
{
$errors['address'] = 'Please enter an address.';
}
if (empty($errors))
{
// save to database then redirect
}
}
?>
<form>
Username:<br />
<input type="text" name="username" value="" /><br />
<?php if (!empty($errors['username'])): ?>
<div class="error">
<?php echo $errors['username'] ?>
</div>
<?php endif ?>
Address:<br />
<input type="text" name="address" value="" /><br />
<?php if (!empty($errors['address'])): ?>
<div class="error">
<?php echo $errors['address'] ?>
</div>
<?php endif ?>
</form>

Set some flag and returns/redirects to the same page. On the same page (script with form), check for the flag set and display the message.

Related

Php "How to remove an instruction after submitting"

my code does work properly I am just having trouble with removing "Please enter your name" and only displaying the welcome message after the user submits their name.
I've tried to use conditional statements that just led to an error
<?php
# filter input
function filter($var) {
return htmlspecialchars(stripslashes(trim($var)));
}# validate name
function validate_name(&$name, &$err){
if(empty($name)){
$err = "Name is required";
return;
}
$name = filter($name);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$err = "Only letters and white space allowed";
}
}//$method = filter_input(INPUT_SERVER, 'REQUEST_METHOD');
$method = $_SERVER["REQUEST_METHOD"];
$err = "";
# If client post a name, then validate the name
if ($method === "POST"){
$name = isset($_POST["name"])? $_POST["name"]: "";
validate_name($name, $err);
}
?>
<!-- The form -->
<form method="post">
<center><label>
<input type="text" name="name" value="<?php echo #$name;?>">
</label></center>
<!-- Show if no error -->
<?php if(empty($err)) { ?>
<span><p class="centered-text">Please enter your name</span>
<?php } else { ?>
<!-- Show if error -->
<span class="error">
<?php echo $err ?>
</span>
<?php } ?>
<br>
<input type="submit" name="submit" value="Submit">
</form>
<?php if(isset($name) && empty($err)){ ?>
<p class=" centered-text">Hi <?php echo $name?>!</p>
<p class="centered-text">Welcome to our store!</p>
<?php } ?>
My expected result is to display "please enter your name" and once the user submits to remove the instruction "please enter your name" and display the welcome message only
<?php
# filter input
function filter($var) {
return htmlspecialchars(stripslashes(trim($var)));
}
# validate name
function validate_name(&$name, &$err){
if(empty($name)){
$err = "Name is required";
return;
}
$name = filter($name);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$err = "Only letters and white space allowed";
}
}//$method = filter_input(INPUT_SERVER, 'REQUEST_METHOD');
$method = $_SERVER["REQUEST_METHOD"];
$err = "";
# If client post a name, then validate the name
if ($method === "POST"){
$name = isset($_POST["name"])? $_POST["name"]: "";
validate_name($name, $err);
}
if(isset($name) && empty($err)){ ?>
<p class=" centered-text">Hi <?php echo $name?>!</p>
<p class="centered-text">Welcome to our store!</p>
<?php } else { ?>
<!-- The form -->
<form method="post">
<center><label>
<input type="text" name="name" value="<?php echo #$name;?>">
</label></center>
<!-- Show if no error -->
<?php if(empty($err)) { ?>
<span><p class="centered-text">Please enter your name</span>
<?php } else { ?>
<!-- Show if error -->
<span class="error">
<?php echo $err ?>
</span>
<?php } ?>
<br>
<input type="submit" name="submit" value="Submit">
</form>
<?php } ?>
The error check should only be done if $name is set. If it's not set, the form hasn't been submitted and you should only show the "Please enter your name" message in that case.
Here's the basic logic (HTML not included to improve clarity):
if (!isset($name)) {
// Name has not been submitted yet, show "Please enter your name" message
else {
if (empty($err)) {
// Name was submitted and validated successfully, show welcome message
} else {
// Name was submitted with errors, show the errors
}
}

setting up ajax validation response

My PHP code for a login form [this part located at the very top on my index.php where I have the login form] looks something like this:
if(isset($_POST['submit'])){
if (!isset($_POST['username'])) $error[] = "Please fill out all fields";
if (!isset($_POST['password'])) $error[] = "Please fill out all fields";
$username = $_POST['username'];
if ( $user->isValidUsername($username)){
if (!isset($_POST['password'])){
$error[] = 'A password must be entered';
}
$password = $_POST['password'];
if($user->login($username,$password)){
$_SESSION['username'] = $username;
header('Location: welcome.php');
exit;
} else {
$error[] = '<div style = "text-align:center">Wrong username/password or your account have not been activated </span>';
}
}else{
$error[] = '<div style = "text-align:center">Username required</span>';
}
and the HTML for the login form is like this:
<form role="form" method="post" action="" >
<?php
//check for any errors
if(isset($error)){
foreach($error as $error){
echo '<p class="bg-danger">'.$error.'</p>';
}
}
if(isset($_GET['action'])){
//check the action
switch ($_GET['action']) {
case 'active':
echo "<h2 class='bg-success'>Your account is now active you may now log in.</h2>";
break;
case 'reset':
echo "<h2 class='bg-success'>Please check your inbox for a reset link.</h2>";
break;
case 'resetAccount':
echo "<h2 class='bg-success'>Password changed, you may now login.</h2>";
break;
}
}
?>
<div class="form-group">
<p align="center">
<font face="Tahoma">Username:</font><font color="#FFFFFF">
</font>
<input type="text" name="username" id="username" class="form-control input-lg" value="<?php if(isset($error)){ echo htmlspecialchars($_POST['username'], ENT_QUOTES); } ?>" tabindex="1">
</div>
<br>
<div class="form-group">
<p align="center">
<font face="Tahoma">Password: </font><font color="#FFFFFF">
</font><input type="password" name="password" id="password" class="form-control input-lg" tabindex="3">
</div>
<br>
<div align="center">
<input type="submit" name="submit" value="Login" class="btn1" tabindex="5">
</div>
</form>
Now, as this form in submitted if there are ERRORS , it will refresh the whole page and back with error messages on right on top of the form fields. How would I be able to use AJAX / jQuery response to validate for ERRORS without refreshing the whole page. ONLY of there are ERRORS I want it pop the error messages without refreshing. And if it's SUCCESS, then it would log the user in. Can someone help me with this ?
I also have a errors.php file that has only this code in it:
<?php if (count($errors) > 0) : ?>
<div class="error">
<?php foreach ($errors as $error) : ?>
<p><?php echo $error ?></p>
<?php endforeach ?>
</div>
<?php endif ?>
I get the concept behind setting up the AJAX method, but IDK how to use it on this code and form. Hope you guys can help.
This is a very broad question with many possible answers, but here's one way to do it.
1. Post your login with AJAX
$.post("loginScript.php", {
username: "username goes here",
password: "password goes here"
}, function(data){
});
2. Echo your results
Your login script should echo out a JSON response that indicates whether the login was successful and if not, what the errors were.
<?php
if(//login conditions)
{
echo json_encode(array(
"success" => true
));
}
else
{
echo json_encode(array(
"success" => false,
"errors" => $errors
));
}
3. Handle the response
$.post("loginScript.php", {
username: "username goes here",
password: "password goes here"
}, function(data){
var json = JSON.parse(data);
if(json.success)
{
//Login was successful
}
else
{
var errors = json.errors;
//Display errors on your page.
}
});

Breaking out of a PHP script

I have a simple form below where I check for zero field values in a submitted form. If I find a zero field I set the $register_failed_message accordingly, identifying the field. At that point I just want to skip the rest of the form processing and display the form because the form includes a
<?=$register_failed_message?>
to tell the user, right on the form, what the problem is.
But it's not clear how to break out of the processing loop and jump down to the form display HTML. I have exits there, now, but that's not going to work because they stop the entire script. I need a goto to ?>.
Is there a standard way to program this kind of thing?
Thanks
<?php
if(!empty($_POST)){
// Form was submitted.
if(empty($_POST['firstName'])) {
$register_failed_message = "Please enter a firstName.";
exit;
}
if(empty($_POST['lastName'])) {
$register_failed = "Please enter a lastName.";
exit;
}
if(empty($_POST['email'])) {
$register_failed = "Please enter an email.";
exit;
}
[Process form]
header("Location: login.php");
exit;
}
?>
<!doctype html>
<!-- HTML5 -->
<html>
<head>
<body>
<div id="content">
<h2 id="heading">Open a Free Account . . .</h2>
<form id='register' action=<?= $_SERVER["PHP_SELF"] ?> autocomplete="off" method="post">
<div id='fname_label' class='label'>First Name:</div>
<input id='fname' type="text" name="firstName" />
<div id='lname_label' class='label'>Last Name:</div>
<input type="text" name="lastName" />
<div id='email_label' class='label'>Email:</div>
<input type="text" name="email" autocomplete="off" />
<input id='register_button' type="submit" value="Open your Free Account" />
</form>
<div id='register_failed'><?=$register_failed_message?></div>
</div>
</div>
</body>
</head>
</html>
There are a couple problems with your code. Firstly, you have two message variables, $register_failed_message and $register_failed, but you only reference one later. Secondly, your messages are going to overwrite each other. If you put them in an array, you can display all the messages, not just one, if necessary.
Here is how you do what you're trying to do, plus those two mistakes fixed.
<?php
$register_failed = array();
if(!empty($_POST)){
// Form was submitted.
if(empty($_POST['firstName'])) {
$register_failed[] = "Please enter a firstName.";
}
if(empty($_POST['lastName'])) {
$register_failed[] = "Please enter a lastName.";
}
if(empty($_POST['email'])) {
$register_failed[] = "Please enter an email.";
}
//If there are no error messages, we can process the form
if(sizeof($register_failed) == 0) { //This means there are 0 messages collected
[Process form]
header("Location: login.php");
exit; //we exit here to get to the other page
}
}
?>
Later:
<div id='register_failed'>
<?php echo implode('<br>',$register_failed); ?>
</div>
<?php
$register_failed_message = '';
if(isset($_POST))
{
// Form was submitted.
$error = array();
if(empty($_POST['firstName']))
{
$error[] = "Please enter a firstName.";
}
if(empty($_POST['lastName']))
{
$error[] = "Please enter a lastName.";
}
if(!preg_match('#^[a-z0-9.!\#$%&\'*+-/=?^_`{|}~]+#([0-9.]+|([^\s]+\.+[a-z]{2,6}))$#si', $_POST['email']))
{
$error[] = "Please enter an email.";
}
if(count($register_failed_message) == 0)
{
header("Location: login.php");
die();
}
$register_failed_message = implode('<br />',$error);
}
?>
You can break out of scripts with "return", but it will stop the page content too.
You can put your script into another file, use "return" to stop your script, and then include it on the page you have provided.
I was going to just suggest break() as I did in the comments, but that is not your best solution here. You really don't want to throw a message "please enter a first name" and have them enter a first name THEN throw ANOTHER message "please enter a last name". So don't break, just gather ALL the error messages and display them:
(also did you notice that you named the the message inconsistently?)
<?php
if(!empty($_POST)){
// Form was submitted.
$register_failed_message = "";
if(empty($_POST['firstName'])) {
$register_failed_message .= "Please enter a firstName.<br />";
}
if(empty($_POST['lastName'])) {
$register_failed_message .= "Please enter a lastName.<br />";
}
if(empty($_POST['email'])) {
$register_failed_message .= "Please enter an email.<br />";
}
header("Location: login.php");
}
?>
Notice how I use .= . This is a handy shortcut that means "append to" instead of "set to".

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