[SOLVED]: This code is functional, i made a mistake by displaying an old version of my .php page into the browser, which didn't have the updated code below. I would like to echo an error 'error' produced from my php code which is meant to validate a sign in form, into the page of the sign in form, the error appears in the URL only , for example : signin.php?error= User name is incorrect. So i would like the same message to appear within the sign in form itself , i tried to use $_GET['error'] and echo'ed it within my form,
<form method="post" onsubmit=" return formSubmit() " action="signinphp.php">
<div class="userimage">
<img class="userlogo" src="image/userlogo.png" alt="Picture- User Profile picture">
</div><br>
<?php if (isset($_GET['error'])){?>
<p class="error"><?php echo $_GET['error'];?></p>
<?php } ?>
<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" >
</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" >
</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" onclick="check(this.form)" type="submit" value="Sign in">
</div> <br>
<div class="account-link">
Didn't create an account yet? Create Account
</div>
</form>
PHP
<?php
if (isset($_POST['staffname'])&& isset($_POST['password'])){
function validate($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$staffname = validate($_POST['staffname']);
$pass= validate($_POST['password']);
if (empty($staffname)){
header("Location:signin2.php?error=Staff name and password are required!");
exit();
} else if (empty($pass)){
header ("Location:signin2.php?error=Staff name and password are required!");
exit();
} else {
if ($staffname == "staffmember" && $pass== "letmein!123"){
echo "Logged in!";
header("Location: log-it-reportsbeta.php");
exit();
}
else if ($staffname == "admin" && $pass== "heretohelp!456"){
echo "Logged in!";
header("Location: sql_select_updated.php");
exit();
}
}
}
else{
header("Location: signin2.php");
exit();
}
but it did not work , i provided my form code below and the php code for the form validation, please take a look , thank you.
You may wanna use an extra condition to get an error message instead of passing the whole error string in your URL.
In your php script :
if (empty($staffname)){
header("Location:signin2.php?error=1");
exit();
} else if (empty($pass)){
header ("Location:signin2.php?error=2");
exit();
}
In your form :
if (isset($_GET['error'])) {
if ($_GET['error'] == 1) {
$message = "Staff name and password are required!";
}
else if ($_GET['error'] == 2) {
$message = "Another error message";
}
echo '<p class="error">'.$message.'</p>';
}
index.php
This is the login form
<div class="modal-body">
<form action="loginPDO.php" method="post">
<?php if(isset($message))
{
echo '<label class="text-danger">'.$message.'</label>';
} ?>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Username:</label>
<input type="text" name="username" id="username" placeholder="Enter Username" class="form-control">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Password:</label>
<input type="password" name="password" id="password" placeholder="Enter Password" class="form-control">
</div>
<div class="form-group">
<button type="submit" name="login" id="login" class="btn btn-primary">Login</button>
<button type="button" class="btn btn-info">Register</button>
</div>
</form>
</div>
loginPDO.php
<?php
include 'dbconnection.php';
if(isset($_POST["login"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
{
$message = '<label>All fields are required</label>';
header("location:index.php");
}
else
{
$query = "SELECT * FROM users WHERE username = :username AND password = :password";
$statement = $conn->prepare($query);
$statement->execute(
array(
'username' => $_POST["username"],
'password' => $_POST["password"]
)
);
$count = $statement->rowCount();
if($count > 0)
{
$_SESSION["username"] = $_POST["username"];
header("location:dashboard.php");
}
else
{
$message = '<label>Wrong Data</label>';
header("location:index.php");
}
}
}
?>
Hi Guys, I want to know how to display the alert message once the user inputs incorrect credentials
For example, Imagine the user inputs wrong credentials once the user clicks the login button it automatically appears the alert message above Username.
$message just exists in file loginPDO.php and ...
$message = '<label>Wrong Data</label>';
header("location:index.php");
Is not sufficient to pass the $message variable to index.php.
As said in comments you can try
// file loginPDO.php
$message = '<label>Wrong Data</label>';
header("location:index.php?error=" . urlencode("Wrong Data"));
// file index.php
<?php
$message = isset($_GET['error']) ? $_GET['error'] : null; // get the error from the url
if(!empty($message)) {
echo '<label class="text-danger">'.$message.'</label>';
} ?>
i have a working login form that shows up via button click, i can log in but it doesnt show the errors
button that shows login form with the function(in a seperate file):
<button type="button" class="btn btn-lg btn-success" name="button" onclick="signin()" id="signin">Login</button>
function signin()
{
jQuery('#login-form').css("display","block");
jQuery('#reg-form').css("display","none");
jQuery('#signin').css("display","none");
jQuery('#signup').css("display","block");
}
the modal with php(included to the file where the button is):
<?php
$email = ((isset($_POST['Email']))?$_POST['Email']:'');
$password = ((isset($_POST['Password']))?$_POST['Password']:'');
$errors = array();
?>
<div class="" id="login-form" style="display:none">
<img class="Lpic" src="img/loginpic.png">
<br>
<div class="fieldtext">
<h2 class="text-center">Login</h2>
</div>
<br>
<div>
<?php
if($_POST)
{
//form validation
if(empty($_POST['Email']) || empty($_POST['Password']))
{
$errors[] = 'Please enter email and password';
}
//check if email exists
$query = $db->query("SELECT * FROM users WHERE Email = '$email'");
$user = mysqli_fetch_assoc($query);
$userCount = mysqli_num_rows($query);
if($userCount < 1)
{
$errors[] = 'Unknown email, pleas verify';
}
if(password_verify($password, $user['Password']))
{
$errors[] = 'Password doesn\'t match, try again';
}
if(!empty($errors))
{
echo display_errors($errors);
}else{
//log user in
$user_id = $user['ID'];
login($user_id);
}
}
?>
</div>
<form action="Login.php" method="post">
<div class="inputfield">
<div class="form-group">
<label for="Email">Email</label>
<input type="email" name="Email" id="Email" value="<?=$email;?>">
</div>
<div class="form-group">
<label for="Password">Password</label>
<input type="password" name="Password" id="Password" value="<?=$password;?>">
</div>
</div>
<div class="form-group">
<input type="submit" value="Login" class="btn btn-success btn-block">
</div>
</form>
</div>
PS: login() is a function that logs in the user, any suggestions on how to show the errors without using alert??? TIA
Well it’s definitely not the prettiest solution, but you can instead of using the display_errors() function render the form validation messages in html whenever the $errorsarray is not empty.
Something like this:
if(!empty($errors)) {
echo ‘<div id=“errors”>’;
foreach ($error in $errors) {
echo $error . “<br>”;
}
echo ‘</div>‘;
}
Sorry that i couldn’t comletely write the code, its hard to code on the phone...
I hope you get the idea.
try setting the following at the top of your php file
ini_set('display_errors', 1);
error_reporting(E_ALL);
hope this helps.
You might also want to look at this answer
I have two PHP pages: index.php and thankyou.php. In index.php, there is a form. I am validating form with Javascript and ajax and the form values are being inserted into database. After database query I am redirecting this form to Thankyou.php. What i want is to pass form field values to thankyou.php. Please find below the complete code. :
Sql query running in header :-
?php
error_reporting(0);
include_once('cc/connect.php');
if($_SERVER['REQUEST_METHOD'] === 'POST')
{
$str="insert into registration(fname,lname,email,mobile_number,code,designation,organization,comps,city,affid,date_time,status)values('".mysql_escape_string($_POST['txtfname'])."','".mysql_escape_string($_POST['txtlname'])."','".mysql_escape_string($_POST['txtemail'])."','".mysql_escape_string($_POST['txtmobilenumber'])."','".mysql_escape_string($_POST['txtcode'])."','".mysql_escape_string($_POST['desig'])."','".mysql_escape_string($_POST['org'])."','".mysql_escape_string($_POST['comps'])."','".mysql_escape_string($_POST['txtcity'])."','".mysql_escape_string($_POST['txtaff'])."',now(),0)";
$rslt=mysql_query($str);
if(!$rslt)
{
echo '<script type="text/javascript">
alert("We are experiencing some issues, please try later");
</script>
';
}
else
{
echo '<script type="text/javascript">
window.location.href="thankyou.php";
</script>
';
}
}
?>
Javascript Validation :-
<script type="text/javascript">
function validate_form()
{
var pattern =/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var mob=/^(\+91[\-\s]?)?[89]\d{9}$/;
if(document.getElementById('txtfname').value=="" || document.getElementById('txtfname').value==null)
{
alert("Please enter First Name");
document.getElementById('txtfname').focus();
return false;
}
if(document.getElementById('txtlname').value=="" || document.getElementById('txtlname').value==null)
{
alert("Please enter Last Name");
document.getElementById('txtlname').focus();
return false;
}
if(document.getElementById('txtemail').value=="" || document.getElementById('txtemail').value==null)
{
alert("Please enter the Email");
document.getElementById('txtemail').focus();
return false;
}
if(!pattern.test(document.getElementById('txtemail').value))
{
alert("Please enter the valid Email");
document.getElementById('txtemail').focus();
return false;
}
if(document.getElementById('txtmobilenumber').value=="" || document.getElementById('txtmobilenumber').value==null)
{
alert("Please enter the Mobile Number");
document.getElementById('txtmobilenumber').focus();
return false;
}
if(document.getElementById('txtcode').value=="" || document.getElementById('txtcode').value==null)
{
alert("Please enter verification code");
document.getElementById('txtcode').focus();
return false;
}else
{
check_existence(document.getElementById('txtcode').value,6);
}
if(document.getElementById('comps').value=="" || document.getElementById('comps').value==null)
{
alert("Please enter Company strength");
document.getElementById('comps').focus();
return false;
}
if(!isNaN(document.getElementById('comps').value))
{
alert("Please select the valid Company strength");
document.getElementById('comps').value='';
document.getElementById('comps').focus();
return false;
}
if(document.getElementById('org').value=="" || document.getElementById('org').value==null)
{
alert("Please enter Organization");
document.getElementById('org').focus();
return false;
}
if(document.getElementById('txtcity').value=="" || document.getElementById('txtcity').value==null)
{
alert("Please enter the city");
document.getElementById('txtcity').focus();
return false;
}
if(!isNaN(document.getElementById('txtcity').value))
{
alert("Please enter the valid city");
document.getElementById('txtcity').value='';
document.getElementById('txtcity').focus();
return false;
}
}
function check_existence(val,caseno)
{
var pattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var mob=/^(\+91[\-\s]?)?[789]\d{9}$/;
var xmlhttp;
if(caseno=="1")
{
if(!pattern.test(document.getElementById('txtemail').value))
{
alert("Please enter the valid email");
document.getElementById('txtemail').value='';
document.getElementById('txtemail').focus();
return false;
}
}
if(caseno=="2")
{
if(!mob.test(document.getElementById('txtmobilenumber').value))
{
alert("Please enter the valid mobile number");
document.getElementById('txtmobilenumber').value='';
document.getElementById('txtmobilenumber').focus();
return false;
}
}
if(caseno=="3")
{
if(!mob1.test(document.getElementById('txtname').value))
{
alert("Please enter the valid mobile number");
document.getElementById('txtname').value='';
document.getElementById('txtname').focus();
return false;
}
}
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if(xmlhttp.responseText=="1")
{
alert("Email address already exists");
document.getElementById('txtemail').value='';
document.getElementById('txtemail').focus();
}
if(xmlhttp.responseText=="2")
{
alert("Verification code has been sent to your mobile");
document.getElementById('txtcode').focus();
}
if(xmlhttp.responseText=="3")
{
document.forms["formsms"].submit();
}
if(xmlhttp.responseText=="4")
{
alert("Please enter the valid verification code");
document.getElementById('txtcode').focus();
}
if(xmlhttp.responseText=="5")
{
alert("Mobile Number already exists");
document.getElementById('txtmobilenumber').value='';
document.getElementById('txtmobilenumber').focus();
}
}
}
xmlhttp.open("GET","ajax_file.php?caseno="+caseno+"&val="+val,true);
xmlhttp.send();
}
</script>
Form Code :-
<div class="form-content">
<form class="form-box register-form form-validator" id="formsms" name="formsms" method="post">
<div class="form-group">
<label>First name: <span class="required">*</span></label>
<input class="form-control" type="text" name="txtfname" id="txtfname" required>
</div>
<div class="form-group">
<label>Last name: <span class="required">*</span></label>
<input class="form-control" type="text" name="txtlname" id="txtlname" required>
</div>
<div class="form-group">
<label>Email: <span class="required">*</span></label>
<input class="form-control" type="email" name="txtemail" id="txtemail" onchange="return check_existence(this.value,1);" required>
</div>
<div class="form-group">
<div style="float:left; width:270px;" >
<label>Mobile: <span class="required">*</span></label>
<input class="form-control" type="text" name="txtmobilenumber" id="txtmobilenumber" onchange="return check_existence(this.value,2);" required>
</div>
<div style="float:right">
<label>Verification Code: <span class="required">*</span></label>
<input class="form-control" type="text" name="txtcode" id="txtcode" required>
</div>
</div>
<div style="clear:both;"></div>
<div class="form-group">
<label>Select Graduation: <span class="required">*</span></label>
<select class="form-control" name="comps" id="comps">
<option>Select...</option>
<option value="BA">BA</option>
<option value="BBA">BBA</option>
<option value="BCom">BCom</option>
<option value="BSC">BSC</option>
<option value="BTech">BTech</option>
<option value="Other">Other</option>
</select>
</div>
<div class="form-group">
<label>Graduation%: <span class="required">*</span></label>
<input class="form-control" type="text" name="org" id="org" required>
</div>
<div class="form-group">
<label>City: <span class="required">*</span></label>
<input class="form-control" type="text" name="txtcity" id="txtcity" required>
</div>
<div class="buttons-box clearfix">
<input type="button" id="btnsubmit" name="btnsubmit" class="btn btn-default" value="Submit" onclick="return validate_form()"/>
<span class="required"><b>*</b> Required Field</span>
<br>
</div>
</form><!-- .form-box -->
</div>
The simplest way is to use PHP sessions. These will store data from one interaction with the user, to be retrieved on another interaction.
In connect.php, add:
session_start();
In index.php, after you've validated and saved info in the DB, save the data that you want to pass between pages in the $_SESSION array
$_SESSION['fname'] = $_POST['txtfname'];
....
It's actually better to save things to session after you've done all string manipulation (eg: after applying mysql_escape_string).
Now, whenever the user makes another request, you can find the data in that same array. So on thankyou.php
$fname = $_SESSION['fname'];
...
Here is a basic intro to sessions.
This next note goes beyond your question but it's one really important lesson: sessions rely on cookies to recognize a user when he makes another visit. This means that a savvy user can manipulate this cookie and break his session or try to present himself as someone else in order to bypass your security restrictions. Once you're comfortable with the basics, look into how to use sessions securely!
This sounds like a typical case when $_SESSION may come in handy. In this Case (since you are doing your thing with AJAX), you may want to handle the Session in your AJAX Processing PHP File... (header.php?) Well here's how:
<?php
// FILE-NAME: header.php //<== THE AJAX PROCESSING SCRIPT
//FIRST CHECK IF SESSION EXIST BEFORE STARTING IT:
if (session_status() == PHP_SESSION_NONE || session_id() == '') {
session_start();
}
error_reporting(0);
include_once('cc/connect.php');
if($_SERVER['REQUEST_METHOD'] === 'POST') {
// JUST START SETTING UP THE SESSION DATA IF DATA WAS POSTED...
$_SESSION['fname'] = htmlspecialchars(trim($_POST['txtfname']));
$_SESSION['lname'] = htmlspecialchars(trim($_POST['txtlname']));
$_SESSION['email'] = htmlspecialchars(trim($_POST['txtemail']));
$_SESSION['mobile_number'] = htmlspecialchars(trim($_POST['txtmobilenumber']));
$_SESSION['code'] = htmlspecialchars(trim($_POST['txtcode']));
$_SESSION['designation'] = htmlspecialchars(trim($_POST['desig']));
$_SESSION['organization'] = htmlspecialchars(trim($_POST['org']));
$_SESSION['comps'] = htmlspecialchars(trim($_POST['comps']));
$_SESSION['city'] = htmlspecialchars(trim($_POST['txtcity']));
$_SESSION['affid'] = htmlspecialchars(trim($_POST['txtaff']));
$_SESSION['date_time'] = date("Y-m-d", time());
$_SESSION['status'] = "0";
$str="insert into registration(fname,lname,email,mobile_number,code,designation,organization,comps,city,affid,date_time,status)values('".mysql_escape_string($_POST['txtfname'])."','".mysql_escape_string($_POST['txtlname'])."','".mysql_escape_string($_POST['txtemail'])."','".mysql_escape_string($_POST['txtmobilenumber'])."','".mysql_escape_string($_POST['txtcode'])."','".mysql_escape_string($_POST['desig'])."','".mysql_escape_string($_POST['org'])."','".mysql_escape_string($_POST['comps'])."','".mysql_escape_string($_POST['txtcity'])."','".mysql_escape_string($_POST['txtaff'])."',now(),0)";
$rslt=mysql_query($str);
//... THE REST OF YOUR CODE...
}
Then, inside of thankyou.php, you can do this:
<?php
// FILE-NAME: thankyou.php
//FIRST CHECK IF SESSION EXIST BEFORE STARTING IT:
if (session_status() == PHP_SESSION_NONE || session_id() == '') {
session_start();
}
// TO GET THE EMAIL, FIRST & LAST NAMES HERE, YOU CAN SIMPLE DO LIKE SO:
$email = isset( $_SESSION['email'] )? $_SESSION['email'] : "";
$firstName = isset( $_SESSION['fname'] )? $_SESSION['fname'] : "";
$lastName = isset( $_SESSION['lname'] )? $_SESSION['lname'] : "";
// ASSUMING YOU WANT TO THANK THE USER BY NAME:
// YOU MAY DO SOMETHING LIKE SO:
$thankYou = "<div class='thank-you'>" . PHP_EOL;
$thankYou .= "<p class='appreciation'>Thank you, " ;
$thankYou .= "<span class='user-name'>{$firstName} {$lastName}</span>";
$thankYou .= " for your E-Mail... bla...bla..</p>" .PHP_EOL;
$thankYou = "</div>" . PHP_EOL;
echo $thankYou;
I am currently working on PHP forgot password reset, which partially doing the job but seeking some assistance to improve it further.
1st issue: It is not displaying the correct email address on the
submission form. It updates the password correctly but doesn't
display correct email address.
2nd issue: Also if the user makes an error while submitting the form on reloading the page doesn't update the password hence the user has to go back to his email to click back on the link.
<?php
include('../config/connection.php');
if(isset($_POST['submit'])){
$password = mysqli_real_escape_string($dbc,$_POST['password']);
$Rpassword = mysqli_real_escape_string($dbc,$_POST['Rpassword']);
$acode=$_POST['encrypt'];
$passmd = md5(SHA1($password));
if (empty($password) OR empty($Rpassword)) {
$error = 'One or either field is missing';
} if ($password != $Rpassword) {
$error = 'Passwords don\'t match';
} if(strlen($password)<6 OR strlen($Rpassword)>20) {
$error = 'Password must be between 6 to 20 characters';
}
else {
$query = mysqli_query($dbc,"select * from users where passreset='$acode'") or die(mysqli_error($dbc));
if (mysqli_num_rows ($query)==1)
{
$query3 = mysqli_query($dbc,"UPDATE users SET password='$passmd',passreset=0 WHERE passreset='$acode'")
or die(mysqli_error($dbc));
$sent = 'Password has been Changed successfully, Please sign in for loging in.';
}
else
{
$error = 'Please click back on the Forgot password link to reset your password ';
}
}
}
?>
<body>
<?php if(!isset($_POST['submit']) OR $error != '' OR isset($error)) { ?>
<?php if(isset($error) AND $error !='')
{
echo '<p style="color:#c43235">'.$error.'</p>';
}
?>
<form action="reset.php" method="post" role="form">
<div class="form-group">
<label for="password">Email</label>
<input type="text" class="form-control" id="email" name="email" value="
<?php
$acode=$_POST['encrypt'];
$query5 = mysqli_query($dbc,"SELECT * FROM users where passreset='$acode'") or die(mysqli_error($dbc));
$list = mysqli_fetch_array($query5); /* Error-----*/
$val = $list['email'];
echo $val;?>" >
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Password" >
</div>
<div class="form-group">
<label for="password">Re-enter Password</label>
<input type="password" class="form-control" id="password" name="Rpassword" placeholder="Password" >
</div>
<input type="hidden" class="form-control" name="encrypt" value="<?php echo $_GET['encrypt'];?>" >
<button class="btn btn-success" type="submit" name="submit" />Submit</button>
</form>