I have a protected page that requires you to login to access the page content.
Where can I put an else statement that echos "wrong username or wrong password"
if the user does not enter the exact user/password?
The PHP page
<?php
// Define your username and password
$username = "user";
$password = "password";
if ($_POST['txtUsername'] != $username || $_POST['txtPassword'] != $password) {
?>
<h1>Login</h1>
<form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label>User</label>
<input type="text" title="Enter your Username" name="txtUsername" />
<label>Password</label>
<input type="password" title="Enter your password" name="txtPassword" />
<input type="submit" name="Submit" value="Login" />
</form>
<?php
}
else {
?>
<p>This is the protected page. Your private content goes here.</p>
<?php
}
?>
** I have tried entering it after -- else { at the bottom of page
** I have tried entering it after -- if($_POST...$password) {
neither one worked. I attached a image to show you what I mean.
Thanks
It can also be solved by simply setting some validation flags and using those on your views. Using your own code structure template, the following might do the trick:
<?php
// Define your username and password
$username = "user";
$password = "password";
$hasError = true;
$hasSubmitted = false;
if (isset($_POST['Submit'])) {
$hasSubmitted = true;
if ($_POST['txtUsername'] != $username || $_POST['txtPassword'] != $password) {
$hasError = true;
} else {
$hasError = false;
}
}
if ($hasError):
?>
<h1>Login</h1>
<?php if ($hasSubmitted): ?>
<p>*You entered a wrong username or password</p>
<?php endif; ?>
<form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label>User</label><input type="text" title="Enter your Username" name="txtUsername" />
<label>Password</label><input type="password" title="Enter your password" name="txtPassword" />
<input type="submit" name="Submit" value="Login" />
</form>
<?php else: ?>
<p>This is the protected page. Your private content goes here.</p>
<?php endif; ?>
<?php
class ValidateUser
{
public static function Check($user,$pass)
{
$settings[] = ($user == $_POST['txtUsername'])? 1:0;
$settings[] = ($pass == $_POST['txtPassword'])? 1:0;
return (array_sum($settings) == 2)? true:false;
}
}
// if the username and passowrd match up
if(isset($_POST['txtUsername'])) {
$uservalid = ValidateUser::Check('hardcodeuser','hardcodepass');
}
// If user/pass not valid
if($uservalid !== true || !isset($uservalid)) { ?>
<h1>Login</h1>
<?php if(isset($uservalid) && $uservalid !== true) echo 'Invalid Login'; ?>
<form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label>User</label>
<input type="text" title="Enter your Username" name="txtUsername" />
<label>Password</label><input type="password" title="Enter your password" name="txtPassword" />
<input type="submit" name="Submit" value="Login" />
</form>
<?php }
else { ?>
<p>This is the protected page. Your private content goes here.</p>
<?php
} ?>
Try this and read the comment in the code
<?php
if ($_POST['txtUsername'] != $username || $_POST['txtPassword'] != $password) {
?>
<h1>Login</h1>
<form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label>User</label><input type="text" title="Enter your Username" name="txtUsername" />
<label>Password</label><input type="password" title="Enter your password" name="txtPassword" />
<input type="submit" name="Submit" value="Login" />
</form>
<?php
//adde these line to check weather its empty or not
if(!empty($_POST['txtUsername']) && empty($_POST['txtPassword']))
{
//this is complicated part you need check username and password. and they have to
//match.
// i cant help you here, cause i dont know from where you want to check username and password
//but i am giving you if statement.
//simple way you get the username from form, than check wether the username password matches, in the db or not, and if does not matches, we show the error message
//run the query
//check the result
//result return succes then ok
//else show the error
}
else
{
echo 'You need to enter your username and password';
}
}
else {
?>
<p>This is the protected page. Your private content goes here.</p>
<?php
}
?>
<?php
// Define your username and password
$username = "user";
$password = "password";
$loginPageTPL = <<< EOF
<!doctype html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form name="form" method="post" action="{% PHP_SELF %}">
{% ERROR_MESSAGES %}
<label for="username">User</label>
<input id="username" type="text" placeholder="Enter your Username" name="txtUsername" />
<label for="password">Password</label>
<input id="password" type="password" placeholder="Enter your password" name="txtPassword" />
<input type="submit" name="Submit" value="Login" />
</form>
</body>
</html>
EOF;
$loginPageTPL = str_replace('{% PHP_SELF %}', $_SERVER['PHP_SELF'], $loginPageTPL);
if ((isset($_POST['txtUsername'])) && (isset($_POST['txtPassword']))) {
if (($_POST['txtUsername'] == $username) && ($_POST['txtPassword'] == $password)) {
echo "your private content here";
return;
} else {
$loginPageTPL = str_replace('{% ERROR_MESSAGES %}', '<div style="color: red">* you entered a wrong username and password</div>', $loginPageTPL);
echo $loginPageTPL;
}
} else {
$loginPageTPL = str_replace('{% ERROR_MESSAGES %}', '', $loginPageTPL);
echo $loginPageTPL;
}
Related
i have a little problem
I have a form in login.php:
`
<form action="loginscript.php" method="post">
<h2>Login form</h2>
<label for="nick">Podaj imie: </label>
<input type="text" name="nick" id="nick">
<br>
<label for="pass">Podaj haslo: </label>
<input type="password" name="pass" id="pass">
<br>
<p>LOG IN</p>
<input type="submit" name="submit" id="submit">
</form>
`
and i have a loginscript.php file:
`
<?php
session_start();
if (isset($_POST["nick"]) && isset($_POST["pass"])) {
$nick=$_POST["nick"];
$pass=sha1(sha1($_POST["pass"]));
$conn = mysqli_connect("localhost", "root", "", "baza2");
if ($conn) {
$query = mysqli_query($conn, "SELECT * FROM login_table WHERE nick='$nick' AND pass='$pass'");
if (mysqli_num_rows($query)) {
$_SESSION["logged"]=true;
header("Location: main.php");
} else {
header('Location: login.php');
}
mysqli_close($conn);
}
}
?>
`
In the loginscript.php in else i have redirect to login.php page. How can i change maybe p tag from 'LOG IN' to 'USERNAME OR PASSWORD IS WRONG'?
I tried using jquery but that doesn't work, maybe I don't know how. Please help :(
You can't change anything on the target page from there, but what you can do is provide some information to the target page which that page can use. For example, consider this redirect:
header('Location: login.php?failed=true');
Then in the login.php code you can check for the "failed" query string value and conditionally change the output based on that. For example:
<?php
$message = isset($_GET['failed']) ? "USERNAME OR PASSWORD IS WRONG" : "LOG IN";
?>
<form action="loginscript.php" method="post">
<h2>Login form</h2>
<label for="nick">Podaj imie: </label>
<input type="text" name="nick" id="nick">
<br>
<label for="pass">Podaj haslo: </label>
<input type="password" name="pass" id="pass">
<br>
<p><?= $message ?></p>
<input type="submit" name="submit" id="submit">
</form>
you could try the code below.
if (mysqli_num_rows($query)) {
$_SESSION["logged"]=true;
echo "<script type='text/javascript'> document.location = 'main.php';</script>";
} else {
echo "<script>alert('Your Password or username is wrong!');</script>";
}
When I tried logging in to an invalid username, I got no error message. Instead it redirected to the same login page.
Here is the controller:
function cekuser()
{
$username = strip_tags(stripslashes($this->input->post('username', TRUE)));
$password = strip_tags(stripslashes($this->input->post('password', TRUE)));
$u = $username;
$p = md5($password);
$cadmin = $this->Auth_model->check_login($u, $p);
if (!$cadmin) {
redirect('administrator/gagallogin');
} else {
if ($cadmin['level'] == '1') {
$this->session->set_userdata('masuk', true);
$this->session->set_userdata('user', $u);
$this->session->set_userdata('akses', '1');
$idadmin = $cadmin['id'];
$user_nama = $cadmin['nama'];
$this->session->set_userdata('idadmin', $idadmin);
$this->session->set_userdata('nama', $user_nama);
}
}
if ($this->session->userdata('masuk') == true) {
redirect('administrator/berhasillogin');
} else {
redirect('administrator/gagallogin');
}
}
function berhasillogin()
{
redirect('dashboard');
}
function gagallogin()
{
$url = base_url('administrator');
echo $this->session->set_flashdata('msg', 'Username Atau Password Salah');
redirect($url);
}
and here is for the login views:
<form class="form-signin" action="<?php echo base_url() . 'administrator/cekuser' ?>" method="post">
<label for="inputEmail" class="sr-only">NIP</label>
<input class="form-control" type="text" name="username" placeholder="Username" required>
<br />
<label for="inputPassword" class="sr-only">Password</label>
<input class="form-control" type="password" name="password" placeholder="Password" style="margin-bottom:1px;" required>
<br />
<br />
<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
</form>
Is there any solution? Thank you.
You don't echo the flash data, you just set it.
function gagallogin()
{
$url = base_url('administrator');
$this->session->set_flashdata('msg', 'Username Atau Password Salah');
redirect($url);
}
In the form, you set the flash message with PHP. Change your form to a PHP file and do something like this:
<?php if ($this->session->flashdata('msg') { ?>
<p class="text-danger">Error: <?php echo $this->session->flashdata('msg'); ?></p>
<?php } ?>
<form class="form-signin" action="<?php echo base_url() . 'administrator/cekuser' ?>" method="post">
i am trying to make a simple login system, with password recovery option,, so i made a password reset link.
hwoever, it is not working, meaning that form2's button just leads back to form1 (leads back to username and email form && i have three different forms), so i separated it into three different if statements, for each button clicked, but the same issue keeps on happening.
please tell me what is happening and ho to fix it
thank you.
(code is below)
//not actually js, but is php
session_start();
if(isset($_SESSION['username']) && isset($_SESSION['password'])){
header("Location: changepass.php");
}
if(($_SERVER["REQUEST_METHOD"] == "POST")) {
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$db = "test";
$con = new mysqli($dbhost, $dbuser, $dbpass, $db) or die("Connection failed: %s\n". $con -> error);
$GLOBALS['email'] = $_POST['email'];
$GLOBALS['username'] = $_POST['username'];
$result = mysqli_query($con,"SELECT * FROM login WHERE email='" . htmlspecialchars($GLOBALS['email']) . "' and username = '". htmlspecialchars($GLOBALS['username'])."'");
$count = mysqli_num_rows($result);
//Part 1
if($_POST['submit1']) {
if($count==0) {
echo "<script>
document.getElementById('error').innerHTML += 'Invalid Username or Email.';
</script>";
} else {
echo "<script>
document.getElementById('main').style.display = 'none';
</script>";
echo "<script>
document.getElementById('next').style.display = 'inline-block';
</script>";
echo "<script>
document.getElementById('verify').innerHTML += 'A verification email has been sent to you. Copy the verification code and paste it above.';
</script>";
$GLOBALS['token'] = bin2hex(random_bytes(3));
echo $GLOBALS['token'];
$to = $GLOBALS['email'];
$subject = "Password Reset";
$msg = "Hello. Your token is <strong>" . $GLOBALS['token'] . "</strong>. <br>Good day.";
$msg = wordwrap($msg,70);
$headers = "From: email#example.com";
mail($to, $subject, $msg, $headers);
}
}
//Part 2
if($_POST['submit2']) {
if($_POST['code'] != $GLOBALS['token']) {
echo "<script>
document.getElementById('error2').innerHTML += 'Invalid verification code.';
</script>";
} else {
echo "<script>
document.getElementById('next').style.display = 'none';
</script>";
echo "<script>
document.getElementById('final').style.display = 'inline-block';
</script>";
}
}
//Part 3
if($_POST['submit3']) {
$np = $_POST['np'];
$cnp = $_POST['cnp'];
if($np != $cnp) {
echo "<script>
document.getElementById('error3').innerHTML += 'Passwords do not match.';
</script>";
} else {
$sql = "UPDATE login SET password='$cnp' WHERE email=" . $GLOBALS['email'];
$rs = mysqli_query($con, $sql);
if($rs) {
echo "Changed password successfully! Click <a href='login.php'>here</a> to sign in.";
} else {
echo "An unknown error occurred. Please try again.";
}
}
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Reset Password</title>
</head>
<body>
<fieldset>
<legend>Reset Password</legend>
<form name="frmContact" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div id="main">
<label for="email">Email</label>
<input type="email" style="display:inline-block" name="email" id="email" required autofocus />
<br>
<br>
<label for="username">Username</label>
<input type="text" style="display:inline-block" name="username" id="username" required />
<br>
<p id="error" style="color:red"></p>
<p> </p>
<p>
<input type="submit" name="submit1" id="submit1" value="Reset Password" /> Create an Account Sign in
</p>
</div>
</form>
<form name="frmContact2" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div id="next" style="display:none;">
<p id="verify" style="color:green"></p>
<label for="code">Verification Code</label>
<input type="text" style="display:inline-block" maxlength="6" name="code" id="code" required autofocus /> <p style="color:red;display:inline-block" id="validatecode"></p>
<br>
<p id="error2" style="color:red"></p>
<p> </p>
<p>
<input type="submit" name="submit2" id="submit2" value="Reset Password" /> Create an Account Sign in
</p>
</div>
</form>
<form name="frmContact3" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div id="final" style="display:none;">
<label for="np">New Password</label>
<input type="text" style="display:inline-block" name="np" id="np" required autofocus /> <p style="color:red;display:inline-block" id="validatenp"></p>
<br>
<label for="cnp">Confirm New Password</label>
<input type="text" style="display:inline-block" name="cnp" id="cnp" required autofocus /> <p style="color:red;display:inline-block" id="validatecnp"></p>
<br>
<p id="error3" style="color:red"></p>
<p> </p>
<p>
<input type="submit" name="submit3" id="submit3" value="Reset Password" />
</p>
</div>
</form>
</fieldset>
</body>
</html>
Just for sake of debugging remove all extra stuff from that file and focus on 3 if statements
Also try using
if(isset($_POST['submit1']))
Always try to close in onto the problem at hand and remove extra stuff that is in there. It helps make simpler but better decisions.
Problem is: If I write the wrong input for example: under username the number of character must be from 2-25 and I write only one character then error is shown and after I refresh the page the error doesn't go. How to remove the validation error after I refresh the page. There are three files: register.php Account.php and register-handlers.php
register.php
<!DOCTYPE html>
<?php
include("includes/classes/Accounts.php");
$account1 = new Accounts();
include("includes/handlers/register-Handlers.php");
?>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Register your free account</title>
</head>
<body>
<div id="inputContainer">
<form id="loginForm" action="login.php" method="POST">
<h2> Login to your account</h2>
<p>
<label for="loginusername">Username</label>
<input type="text" id="loginusername" placeholder="eg:shaahil" required>
</p>
<p>
<label for="loginpassword">password</label>
<input type="password" id="loginpassword" placeholder="type your password" required>
</p>
<button type="submit" name="LOGINB">Login</button>
</form>
</div>
<form id="registerpage" action="register.php" method="POST">
<h2>Create your free account</h2>
<p>
<?php echo $account1 -> getError("the character must be between 5 to 25 "); ?>
<label for="username1">Username</label>
<input type="text" name="username1" id="username1" placeholder="username" required>
</p>
<p>
<?php echo $account1->getError("your first name must have character between 2 to 25 ");?>
<label for="firstname">First name</label>
<input name="firstname" type="text" id="firstname" placeholder="eg:shaahil" required>
</p>
<p>
<?php echo $account1->getError("your last name must have character between 2 to 25 ");?>
<label for="lastname">Last name</label>
<input name="lastname" type="text" id="lastname" placeholder="eg:abraham" required>
</p>
<p>
<?php echo $account1->getError("invalid password ");?>
<?php echo $account1->getError("abc");?>
<?php echo $account1->getError("the password must be between 5 to 25 characters");?>
<label for="password">Password</label>
<input name="password" type="password" id="password" placeholder="enter your password" required>
</p>
<p>
<label for="password1">Confirm password</label>
<input name="password1" id="password1" type="password" placeholder="Confirm your password" required>
</p>
<p>
<?php echo $account1->getError("Email is invalid");?>
<label for="email1">Email</label>
<input name="email1" type="email" id="email1" placeholder="enter your email" required>
</p>
<button type="submit" name="Registerbutton">Register</button>
</form>
</body>
</html>
register-handlers.php
<?php
function sanitizeFormUsername($inputText){
$inputText = strip_tags($inputText);
$inputText=str_replace(" ","",$inputText);
$inputText=ucfirst(strtolower($inputText));
return $inputText;
}
function sanitizeFormString($inputText){
$inputText = strip_tags($inputText);
$inputText=str_replace(" ","",$inputText);
$inputText=ucfirst(strtolower($inputText));
return $inputText;
}
function sanitizeFormEmail($inputText){
$inputText=strip_tags($inputText);
$inputText=str_replace(" ","",$inputText);
return $inputText;
}
function sanitizeFormPassword($inputText){
$inputText=strip_tags($inputText);
return $inputText;
}
if(isset($_POST['Registerbutton'])){
$username1 = sanitizeFormUsername($_POST['username1']);
$firstname = sanitizeFormUsername($_POST['firstname']);
$lastname = sanitizeFormUsername($_POST['lastname']);
$email1 = sanitizeFormEmail($_POST['email1']);
$password= sanitizeFormPassword($_POST['password']);
$password1= sanitizeFormPassword($_POST['password1']);
$wasSuccessful = $account1->register($username1, $firstname, $lastname, $email1, $password, $password1);
if($wasSuccessful==true){
header("Location: index.php");
}
?>
Accounts.php
<?php
class Accounts{
private $errorArray;
public function __construct(){
$this->errorArray = array();
}
public function register($un1, $fn1, $ln, $em, $ps, $ps1)
{
$this->validateusername($un1);
$this->validatefirstname($fn1);
$this->validatelastname($ln);
$this->validateemail1($em);
$this->validatepasswords($ps,$ps1);
if(empty($this->errorArray) == true){
return true;
}
else {
return false;
}
}
public function getError($error) {
if(!in_array($error, $this->errorArray)) {
$error = "";
}
return " <span class='errorMessage'>$error</span> ";
}
private function validateusername($un){
if(strlen($un) > 25 || strlen($un) < 5 ){
array_push($this->errorArray , "the character must be between 5 to 25 ");
return;
}
}
private function validatefirstname($fn){
if(strlen($fn) > 25 || strlen($fn) < 2){
array_push($this->errorArray , "your first name must have character between 2 to 25 ");
return;
}
}
private function validatelastname($ln){
if(strlen($ln)>25 || strlen($ln)<2){
array_push($this ->errorArray , "your last name must have character between 2 to 25 ");
return;
}
}
private function validatepasswords($ps,$ps1){
if($ps!=$ps1){
array_push($this ->errorArray , "invalid password ");
return;
}
if(preg_match('/[^A-Za-z0-9]/', $ps)) {
array_push($this->errorArray, "abc");
return;
}
if(strlen($ps)>25 || strlen($ps)<5){
array_push($this->errorArray , "the password must be between 5 to 25 characters");
return;
}
}
private function validateemail1($em1){
if(!filter_var($em1,FILTER_VALIDATE_EMAIL)){
array_push($this ->errorArray , "Email is invalid");
return;
}
}
}
?>
This is not an answer, but rather a suggestion.
You are probably better keying your errors array with something like the field name to make error message retrieval easier.
I've adapted one of your validation methods so that it's possible to add multiple errors per field:
<?php
class AccountValidator
{
public $errors;
public function validateLastname($ln)
{
if(strlen($ln)>25 || strlen($ln)<2){
$this ->errors['lastname'][] =
"Your last name must have between 2 and 25 characters.";
return false;
}
}
}
$firstname = 'X';
$lastname = 'O';
$validator = new AccountValidator;
if($validator->validateLastname($lastname) === false)
{
echo
'<ul><li>',
implode('</li><li>', $validator->errors['lastname']),
'</li></ul>';
}
Output:
<ul><li>Your last name must have between 2 and 25 characters.</li></ul>
Can someone help me fix this code? What I want to fix is:
If a person doesn't enter a username or password, I just want the error text (the red messages on the side) without the 'sorry, no access' message on top.
Also, if a person gains access (or doesn't), I want the text fields and submit button go away.
This isn't going to be a real form, so please don't worry about how I'm using a username and password....and if its possible do you think most of my code could stay the same?
Thanks!
<?php
echo '<style type="text/css">
.error
{
color: red;
}
</style>';
$error = false;
if (isset($_POST['submitted']))
{
if (empty($_POST['username']) || empty($_POST['password']))
{
$error = TRUE;
}
if (!$error && $_POST['username']=='test' && $_POST['password']=='abc123') {
echo '<p>Correct. Thank you for entering.<p/>';
}
else
{
echo '<p>Sorry, no access.</p>
';
}
}
?>
<form action="" method="post">
Username: <input type="text" name="username" size="20" value="<?php
if (isset($_POST['submitted']) && !empty($_POST['username']))
{
echo $_POST['username'];
} ?>" />
<?php
if (isset($_POST['submitted']) && empty($_POST['username']))
{
echo '<span class="error">Please enter a username.</span>';
}
?>
<br />Password: <input type="password" name="password" size="20" value="<?php
if (isset($_POST['submitted']) && !empty($_POST['password']))
{
echo $_POST['password'];
} ?>" />
<?php
if (isset($_POST['submitted']) && empty($_POST['password']))
{
echo '<span class="error">Please enter a password.</span>';
}
?>
<br /><input type="submit" value="Log in" />
<br /><input type="hidden" name="submitted" value="true" />
</form>
Try this:
<style type="text/css">
.error {
color: red;
}
</style>
<?php
$submitted = isset($_POST['submitted']);
$userName = isset($_POST['username']) ? $_POST['username'] : null;
$password = isset($_POST['password']) ? $_POST['password'] : null;
if($submitted) {
if (!$userName || !$password) {
echo '<p class="error">Please go back and fill the inputs.</p>';
} elseif($userName == 'test' && $password == 'abc123') {
echo '<p>Correct. Thank you for entering.<p/>';
} else {
echo '<p class="error">Sorry, no access.</p>';
}
} else {
?>
<form action="" method="post">
Username: <input type="text" name="username" size="20" value="<?php echo $userName; ?>" />
<br />
Password: <input type="password" name="password" size="20" value="" />
<br /><input type="submit" value="Log in" />
<br /><input type="hidden" name="submitted" value="true" />
</form>
<?php } ?>
Consider using the onSubmit event on your form.
You need to combine php and javascript here in order to prevent it from submitting. Make a Jscript function that's called by onSubmit. If a value isn't filled in, return false. It'll kill the submit button and print out directly on the screen.
So just take this:
$submitted = isset($_POST['submitted']);
$userName = isset($_POST['username']) ? $_POST['username'] : null;
$password = isset($_POST['password']) ? $_POST['password'] : null;
if($submitted)
{
if (!$userName || !$password) {
echo '<p class="error">Please go back and fill the inputs.</p>';
}
}
And then on your form:
<form action="" method="post" onSubmit="checkForm()">
Then figure out how you're going to check the form with javascript. You can piece together the rest.