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.
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 press the Login button it refreshes the page and doesn't do anything. I tried entering wrong Server IP just to check the error, but I guess it's not responding to the login button and directly refreshing the page.
Unable to call a PHP function in the HTML file, tried using the same code in a different code and it's working fine there but not here:
<title> Database Login </title>
<body>
</head>
<body>
<span>
<div class="heading">
<h3><img src="http://zicom.com/img/ilayashop-1482233381.jpg" alt="Zicom Logo" >
<h1><b>MAaaS Login<b></h1><br>
</span>
</div>
<div class='admin'>
<form method='post' action=''>
<p class='main'> Enter your Details </p>
<p> Enter User Name <input type="text" name="name" id="userInput"></p>
<p> Enter password <input type="password" name="pass" id="userInput"> </p>
<br>
<input id="login" type="submit" name="submit" value="Login">
</form>
</div>
<?php
if($_POST){
$UN = $_POST['name'];
$PS = $_POST['pass'];
$scon=odbc_connect("Driver={SQL Server};Server=XXXXXXX; Database=Sampledata;","XX","XXXXX");
$query="SELECT [password] FROM [Simcarddata].[dbo].[MasterUser] Where username='$UN'";
$rs=odbc_exec($scon,$query);
if (!$rs)
{
$msg="SQL statement failed with error:\n";
$msg.=odbc_error($scon).": ".odbc_errormsg($scon)."\n";
} else {
$number_of_rows = odbc_num_rows($rs);
$msg="$number_of_rows records found.\n";
}
while(odbc_fetch_row($rs))
{
$field1 = odbc_result($rs,1);
// print ("$PS and $field1");
if ($PS == $field1){
print ("TRUE");
header("Location: /test.php");
}
else {
print ("Incorrect Username or password");
}
}
odbc_close($scon);
header("Refresh:2");
}
?>
</body>
</html>
I just tidied up the HTML tags a little and used a better method of checking for POST data - but I think the issue was the badly formed HTML was confusing the form
<html>
</head>
<title> Database Login </title>
</head>
<body>
<span>
<div class="heading">
<h3><img src="http://zicom.com/img/ilayashop-1482233381.jpg" alt="Zicom Logo" ></h3>
<h1><b>MAaaS Login<b></h1>
<br>
</div>
</span>
<div class='admin'>
<form method='post'>
<p class='main'> Enter your Details </p>
<p>Enter User Name <input type="text" name="name" id="userInput"></p>
<p>Enter password <input type="password" name="pass" id="userInput"></p>
<br>
<input id="login" type="submit" name="submit" value="Login">
</form>
</div>
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['name'], $_POST['pass'] ) ){
$UN = $_POST['name'];
$PS = $_POST['pass'];
$scon=odbc_connect("Driver={SQL Server};Server=XXXXXXX;Database=Sampledata;","XX","XXXXX");
$query="SELECT [password] FROM [Simcarddata].[dbo].[MasterUser] Where username='$UN'";
$rs=odbc_exec( $scon, $query );
if (!$rs) {
$msg="SQL statement failed with error:\n";
$msg.=odbc_error($scon).": ".odbc_errormsg($scon)."\n";
} else {
$number_of_rows = odbc_num_rows($rs);
$msg="$number_of_rows records found.\n";
}
while( odbc_fetch_row( $rs ) ) {
$field1 = odbc_result($rs,1);
if ($PS == $field1){
print ("TRUE");
header("Location: /test.php");
} else {
print ("Incorrect Username or password");
}
}
odbc_close($scon);
header("Refresh:2");
}
?>
</body>
</html>
if ($_SERVER['REQUEST_METHOD'] === 'POST') use this please instead of if($_POST) or use if(isset($_POST))
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;
}
I have a project where I need to create registration form and insert it to the database.
I am currently stuck every time I tried to registered, it pop out a message saying "please enter a valid email format". Is it something to do regarding with the regex for the email?
Below is the code
<?php
require_once('sqlconnect.inc.php');
session_start();
if (isset($_POST["Register"]))
{
$email = $_POST['email'];
$memberName = $_POST['membername'];
$passw = $_POST['password'];
$conPassw = $_POST['conpassword'];
if($email=='')
{
echo "<p>Please enter the Email address</p>";
echo "Back to Registration Page!";
exit();
}
if($memberName=='')
{
echo "<p>Please enter the Member Name</p>";
echo "Back to Registration Page!";
exit();
}
if($passw=='')
{
echo "<p>Please enter Password</p>";
echo "Back to Registration Page!";
exit();
}
if($conPassw=='')
{
echo "<p>Please enter Confirm Password</p>";
echo "Back to Registration Page!";
exit();
}
else {
$email = $_POST['email'];
$pattern = '/^[_A-z0-9-]+((\.|\+)[_A-z0-9-]+)*#[A-z0-9-]+(\.[A-z0-9-]+)*(\.[A-z]{2,4})$/';
if (preg_match($pattern, $email))
{
echo "<p>Please enter a valid email format<p>";
}
else{
$memberName = strtolower(trim($_POST['membername']));
$_SESSION['name'] = $_POST['membername'];
$pattern1 = '/^[a-z][a-z ]*$/i';
if (preg_match($pattern1, $memberName))
{
echo "<p>Member name must contain only letters, space and hypen</p>";
}
else{
$pattern2 = '^[a-zA-Z0-9]+$';
if (preg_match($pattern2, $passw))
{
echo "<p>Password must only contain numbers and letters!</p>";
}
else{
if($passw<>$conPassw)
{
echo "<p>Passwords does not match!</p>";
$passw="";
$conPassw="";
}
else{
$conn = #mysqli_connect($host, $user, $pswd, $dbnm);
if (!$conn)
die ("<p>Couldn't connect to the server!<p>");
$SelectDatabase = #mysqli_select_db($conn,"s7259476_db")
or die("<p>The database is not available.</p>");
$insertDatabase = "INSERT INTO team VALUES('NULL','$email','$password','$memberName',CURDATE(),0)";
$queryResult = #mysqli_query($conn, $insertDatabase)
or die ("<p>Email already exists.Please enter another email id</p>");
echo"<p>Data entered into friends table successfully</p>";
echo "<p>Welcome"." ".$_SESSION['name']."</p>";
}
}
}
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/chtml-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en" >
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="Web Programming :: Assignment 2" />
<meta name="Keywords" content="Web, programming" />
<title>Register Page</title>
</head>
<body>
<form id='register' action='signup.php' method='POST'>
<fieldset >
<legend><h1>My Team System Registration Page</h1></legend>
<?php $email = isset($_POST['email']) ? filter_var($_POST['email'], FILTER_SANITIZE_STRING) : ''; ?>
<?php $memberName = isset($_POST['membername']) ? filter_var($_POST['membername'], FILTER_SANITIZE_STRING) : ''; ?>
<div class="elements">
<label for='email' >Email:</label>
<input type='text' name='email' id='email' maxlength="50" value="<?php echo $email; ?>" />
</div>
<br />
<div class="elements">
<label for='membername' >Member Name:</label>
<input type='text' name='membername' id='membername' maxlength="50" value="<?php echo $memberName; ?>" />
</div>
<br />
<div class="elements">
<label for='password' >Password:</label>
<input type='password' name='password' id='password' maxlength="50" />
</div>
<br />
<div class="elements">
<label for='conpassword' >Confirm Password:</label>
<input type='password' name='conpassword' id='conpassword' maxlength="50" />
</div>
<br />
<div class="submit">
<input type='submit' name='Register' value='Register' />
<input type='reset' name='Submit' value='Clear' />
<br />
<div class="elements">
Home
</fieldset>
</form>
</body>
</html>
Don't use a regex to validate an email address. PHP has filter_var for that, which is quick and easy to use. Email addresses are notoriously painful to validate properly with a regex (there is a regex that validates them properly somewhere, and it is HUGE!).
Some typical code for validating an email address with filter_var might look like this:
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo "Invalid email address";
}
I am trying to create a login and I am having some issues. When I log on my code prompts me for authentication (as it should if I type the wrong password) but I have the password hard coded for now. Even when I type the correct password is doing not open the link to the so I can access the page.
Note below my code:
website config files
<?php
define('WEB_ROOT' , '/mjcrawle/bank/');
define('ABSOLUTE_PATH' , '/home/mjcrawle/main/bank/');
define('URL_ROOT' , 'http://tomcat.cit.iupui.edu/mjcrawle/main/');
define('APP_ROOT' , 'http://tomcat.cit.iupui.edu/mjcrawle/main/bank/');
?>
Login process file
<?php
/*Required Fields*/
require_once('websiteconfig.inc.php');
/*FUNCTIONS*/
/*VERRIFY EMAIL ADDRESS AND PASSWORD AND MATCH IN SYSTEM*/
function validateLogin($emailaddress='', $password=''){
/*INITIALIZES VARIABLES*/
$email_key = 'betty#abc.com';
$password_key = '1234';
$auth_match = 0;
/* CHECK FOR MATCH */
if($emailaddress == $email_key && $password == $password_key){
$auth_match = 1;
}
return $auth_match;
}
/*CLEAN FORM DATA*/
function sanitize($form_var) {
$clean_data = strtolower(trim($form_var));
return $clean_data;
}
/*PAGE VARIABLES*/
$auth_status = 0;
/*DETERMINE FORM HAS BEEN SUBMITTED*/
if(array_key_exists('submit', $_POST)) {
/*SANITIZE FORM DATA*/
$emailaddress = sanitize($_POST['emailaddress']);
$password = sanitize($_POST['password']);
/*VALIDATE FORM DATA*/
$auth_status = validateLogin($emailaddress, $password);
}
?>
</div><div class="container" id="shadow">
<div>
<?php
include(ABSOLUTE_PATH . 'header.inc.php');
if($auth_status == 1){
/*AUTHENTICATION SUCCESS*/
echo '<h4>Welcome Back, Betty!</4>' . "\n\n";
echo '<ul>' . "\n";
echo "\t" . '<li>Online Banking</li>' . "\n\n";
echo '</ul>';
} elseif($auth_status == 0){
/*AUTHENTICATION FAILED*/
echo '<h4 class="error">Authentication Error!</h4>' . "\n\n";
echo '<p>Incorrect e-mail address and/or password submitted. Please try again.</p>';
}
?>
<div>
</div><!--End of main content-->
<?php
include(ABSOLUTE_PATH . 'footer.inc.php');
?>
This is my login form
<div id="login_form">
<form id="login" method="post" action="processlogin.php">
<label for="emailaddress"> E-mail Address: </label>
<input type="text" id="emailaddress" name"emailaddress" maxlength="100" tabindex="1" />
<label for="password"> Password: </label>
<input type="password" id="password" name="password" maxlength="13" tabindex="2" />
<input type="submit" id="login_submit" name="submit" value="login"/>
</form>
</div>
This is my main index page:
<?php
require_once('websiteconfig.inc.php');
?>
<div>
<h1 class="h1" align="center">
1%'er Savings <bold> & </bold> Loan </h1>
</h1>
</hr>
</div><!--End of Body--> <?php require_once('footer.inc.php'); ?> </div><!--end of header-->
This is my header
Home Login Page /_assets/stylesheets/style.css" />
/_assets/images/bkrnd_top.png">
/_assets/images/bkgrnd_tl.png" width="205"
height="61">
/_assets/images/logo.png" width="160"
height="61">
/_assets/images/background_headerarea.png">
HOME |
TBA | TBA |
TBA | TBA |
TBA
You have an error in your code. Your login form is missing a =
<input type="text" id="emailaddress" name="emailaddress" maxlength="100" tabindex="1" />
You had name"emailaddress"