<?php
if($_POST) {
//not empty
//atleast 6 characters long
$errors = array();
//start validation
if(empty($_POST['email'])) {
$errors['email1'] = "<p style='color:red;font-family: BCompset, Arial, Helvetica, sans-serif;font-size:30px;'>Please write down your email!</p>";
}
//check errors
if(count($errors) == 0) {
//redirect to success pages
header("Location: success.php");
exit();
}
}
?>
<form action="" method="POST" class="searchform" dir="ltr">
<input type="text" name="email" placeholder="Your email address"/>
<button name="submit" type="submit" class="btn btn-default"><i class="fa fa-arrow-circle-o-right"></i></button>
<p><?php if(isset($errors['email1'])) echo $errors['email1']; ?></p>
<?php if(count($errors) == 0){
echo "<p id='para' dir='rtl'>
You can add your email to get the latest updates.</p>";
} ?>
</form>
I want to show the paragraph with id='para' (line 31) when the form is not submitted yet and if the user clicked on submit button without entering his email address ,the error message will pop up and that paragraph will not be shown anymore.. To do this I set the if(count($errors) == 0) but I get the Undefined variable error message on line 31. Maybe because I can not take a variable from action scripts until the form is not submitted. Any solution to my problem please?
Try this code:-
<?php
$errors = array();
if($_POST)
{
//not empty
//atleast 6 characters long
//start validation
if(empty($_POST['email']))
{
$errors['email1'] = "<p style='color:red;font-family: BCompset, Arial, Helvetica, sans-serif;font-size:30px;'>Please write down your email!</p>";
}
//check errors
if(count($errors) == 0)
{
//redirect to success pages
header("Location: success.php");
exit();
}
}
?>
<form action="" method="POST" class="searchform" dir="ltr">
<input type="text" name="email" placeholder="Your email address"/>
<button name="submit" type="submit" class="btn btn-default"><i class="fa fa-arrow-circle-o-right"></i></button>
<p><?php if(isset($errors['email1'])) echo $errors['email1']; ?></p>
<?php if(count($errors) == 0){echo "<p id='para' dir='rtl'>You can add your email to get the latest updates.</p>";}?>
</form>
The problem is that your <form> is outside the if($_POST), so it will be shown whether or not $_POST was set. But $errors is only set inside the if. There are two simple ways to fix this:
Move the initialization of $errors to before the if.
Use if(empty($errors) instead of if(count($errors) == 0). empty() doesn't complain if the variable isn't set.
Related
<form method="POST" onsubmit=" return formSubmit() " action="log-it-reports.php">
<div class="userimage">
<img class="userlogo" src="image/userlogo.png" alt="Picture- User Profile picture">
</div><br>
<div class="error" id= "errorMsg"></div><br>
<div class="error" id= "errorMsg1"></div>
<div class="field">
<label class="stafflabel"> Staff Name </label>
<input class="area" placeholder="staffmember or admin" onclick=" return userValidation()" onchange=" return userValidation()" id="staff" name="staffname" type="text" value="<?php echo $staffname;?>" >
</div> <br>
<div class="error" id= "errorMsg2"></div>
<div class="field">
<label class="passlabel"> Password </label>
<input class="area" placeholder="password" onclick=" return userValidation()" onchange=" return userValidation()" id="pass" name="password" type="password" value="<?php echo $password;?>" >
</div><br>
<div class="checkbox">
<input type="checkbox" class="remember-me">
<label class="remember" for="remember-me">Remember me </label>
<a class="pass-link" href="#"> Forgot password?</a>
</div><br><br><br>
<div class="field">
<input class="btn" type="submit" value="Sign in">
</div> <br>
<div class="account-link">
Didn't create an account yet? Create Account
</div>
</form>
I would like to validate a sign in form with predefined usernames (admin, staffmember) and passwords (heretohelp!456 , letmein!123) in the serverside using php, my approach to it is using if statements to check for the posted input , firstly, is this a good approach or there is a better way to do it ? secondly, i'm getting an error in my code that says : syntax error, unexpected 'else' (T_ELSE)
the brackets i have seem to match, the error shows in lines : 15, 32 of this snippet
<?php
$staffname = $_POST['staff'];
$password = $_POST['pass'];
$error = "";
// validating staff member:
if (isset($_POST['submit'])) {
if ($staffname == "staffmember") {
if ($password == "letmein!123") {
$error = "" ;
}
// redirect to the logs report page when successful
header("location: log-it-reports.php");
else {
$error = "* You have entered a wrong password!";
}
}
else {
$error = "You have entered a wrong staff name!";
}
}
// validating admin:
if (isset($_POST['submit'])) {
if ($staffname == "admin") {
if ($password == "heretohelp!456") {
$error = "" ;
}
// redirect to the logs report page when successful
header("location: update-log-reports.php");
else {
$error = "* You have entered a wrong password!";
}
}
else {
$error = "You have entered a wrong staff name!";
}
}
?>
I have fixed your code, so at least it is somewhat DRY and solves your syntax issues as pointed out by people in the comments.
Any decent PHP editor (use Vscode with the inteliphense plugin if you need something free) will show you syntax errors when you code and help you with PHP syntax. If you do use it, make sure you read the instructions and disable the default php plugins as per it's instructions.
<?php
// validating staff member:
$staffname = $_POST['staff'] ?? '';
$password = $_POST['pass'] ?? '';
$error = "";
if (isset($_POST['submit'])) {
if ($staffname == "staffmember") {
if ($password == "letmein!123") {
// redirect to the logs report page when successful
header("location: log-it-reports.php");
exit;
} else {
$error = "* You have entered a wrong password!";
}
} else if ($staffname == "admin") {
if ($password == "heretohelp!456") {
// redirect to the logs report page when successful
header("location: update-log-reports.php");
exit;
} else {
$error = "* You have entered a wrong password!";
}
} else {
$error = "You have entered a wrong staff name!";
}
// Maybe you want to actually send the error back to the browser if there was one?
echo "<p>$error</p>";
}
Pro tip: Your scripts should omit the php end tag ie. ?>. You never need it at the end of any PHP script, and having it included scripts can create output when you don't want or expect it. You only need to use the end tag when you have a script that has a mixture of PHP and html, and you are going in and out of PHP blocks. If PHP is the last thing in a script, then leave off the ?>
Something I added for your $_POST assignments: The Null coalescing operator. This handles the problem of someone submitting your form but leaving off either of the required fields.
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.
}
});
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>
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')
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.