Showing form errors on a dropdown form - php

my title might sound strange so I'll try to explain it better in here.
I have a login form that is hidden when you visit the page. It's located in the upper right corner as a small dropdown form. This is the code without the Jquery since I think it isn't needed for my problem:
<!DOCTYPE html>
<?php
include "core/init.php";
?>
<html>
<head>
<title>Swimstats</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/style.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<header>
<div id="border"></div>
<div id="login">
<div id="userName" class="toggleOff">
<?php
if(logged_in() === true){
echo '<p>Welcome ' . $_SESSION['userID'] . '</p>';
} else {
?>
<p>Have an account? <span id="test">Sign in here!</span></p>
<?php } ?>
</div>
<div id="login-content">
<form class="clearfix" action="checkuser.php" method="post">
<label class="grey" for="email">Email:</label>
<input class="field" type="text" name="email" id="email" size="23" />
<label class="grey" for="password">Password:</label>
<input class="field" type="password" name="password" id="password" size="23" />
<div class="clear"></div>
<input type="submit" name="submit" value="Login" class="bt_login" />
</form>
</div>
</div>
</header>
<script type="text/javascript" src="js/scripts.js"></script>
</body>
</html>
SO a simple dropdown form, but I whenever the user fills in faulty credentials or leaves something empty or whatever I need to show an error under the form or above, doesn't matter. I have the following code to catch the errors:
<?php
include "core/init.php";
if(empty($_POST) === false){
$email = $_POST['email'];
$password = $_POST['password'];
if(empty($email) === true || empty($password) === true){
$errors[] = 'You need to enter your email and password.';
} else if(user_exists($email) === false){
$errors[] = 'Unable to find that email.';
} else {
$login = login($email, $password);
if($login === false){
$errors[] = 'Email/password combination is incorrect!';
} else {
$_SESSION['userID'] = $login;
header('Location: index.php');
exit();
}
}
}
?>
But this method will just bring me to the checkuser.php page and show me the errors there while I have to get the errors show on the form, but I seriously have no clue how to get that.

Ok, found the solution:
Here's my Jquery part:
$(document).ready(function(){
$(".bt_login").click(function(){
email = $("#email").val();
password = $("#password").val();
if(email == '' || password == ''){
$(".errors").html("Please fill in both fields!");
return false;
}
$.ajax({
type: "POST",
url: "checkuser.php",
data: "email=" + email + "&password=" + password,
success: function(html){
if(html == 'true'){
window.location = "index.php";
} else {
$(".errors").html("Wrong username or password!");
}
}
});
return false;
});
});
and my checkuser.php:
<?php
include "core/init.php";
$email = $_POST['email'];
$password = md5($_POST['password']);
$query = "SELECT * FROM user WHERE email = '$email' AND password = '$password'";
$result = mysql_query($query)or die(mysql_error());
$num_row = mysql_num_rows($result);
$row=mysql_fetch_array($result);
if( $num_row >=1 ) {
echo 'true';
$_SESSION['userID']=$row['userID'];
$_SESSION['last_name']=$row['last_name'];
$_SESSION['first_name']=$row['first_name'];
}
else{
echo 'false';
}
?>
Although it may not be the safest solution, it works for now :) Will try to build in more security later.

Related

Undefined index PHP for a registration form

<?php
include('connection.php');
$username = $_POST['user'];
$password = $_POST['pass'];
//to prevent from mysqli injection
$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysqli_real_escape_string($con, $username);
$password = mysqli_real_escape_string($con, $password);
$sql = "select *from login where username = '$username' and password = '$password'";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
if($count == 1){
echo "<h1><center> Login successful </center></h1>";
}
else{
echo "<h1> Login failed. Invalid username or password.</h1>";
}
?>
I have to do a website that works like google forms, for school. The thing is that in the signup form I get this error and I don t understand why I'm pretty new to the whole PHP stuff and I didn't find much about this error.
The HTML file
<html>
<head>
<title>PHP Signup system</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="frm">
<h1>Signup</h1>
<form name="f1" action="registration.php" onsubmit="return validation()" method="POST">
<p>
<label> UserName: </label>
<input type="text" id="user" name="Username" />
</p>
<p>
<label> Password: </label>
<input type="password" id="pass" name="Password" />
</p>
<p>
<label> Password: </label>
<input type="password" id="passc" name="Confirm Password" />
</p>
<p>
<label> Email: </label>
<input type="text" id="email" name="Email" />
</p>
<p>
<input type="submit" id="btn" value="Submit" />
</p>
</form>
</div>
<script>
function validation() {
var id = document.f1.user.value;
var ps = document.f1.pass.value;
var psc = document.f1.passc.value;
var em = document.f1.email.value;
if (id.length == "" && ps.length == "") {
alert("User Name and Password fields are empty");
return false;
} else {
if (id.length == "") {
alert("User Name is empty");
return false;
}
if (ps.length == "") {
alert("Password field is empty");
return false;
}
if (em.length == "") {
alert("Email field is empty");
return false;
}
if (ps != psc) {
alert("Passwords do not match");
return false;
}
}
}
</script>
</body>
</html>
It is pretty simple, and it doesn't have to look good, just to work.
EDIT: I got it, the problem was in fact that I misused the post method and names and that after that I forgot to make the connection with the database. credits to the guy in comments
Your post value is not set.
$_POST['foo'] // <== if not set or falsy, returns an undefined index warning
You must check if $_POST is populated before proceeding to execute you backend logic. Place the following at the top of your script and replace foo on your input's name.
if(!isset($_POST['foo']) || !$_POST['foo']){
// $_POST is not set. Notify user then exit!
echo 'Field "foo" is required!';
exit;
}
Or if your submit functions are in the same file of your form, try this:
if(isset($_POST['foo']) && $_POST['foo']){
// place your backend logic here to ensure that the required field(s) are field
}

Is there a way to add priority to a php echo message?

This is jslogin.php
<?php
error_reporting(-1);
session_start();
require_once('config.php');
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
$isValid = true;
if (empty($password)) {
echo 'You need to enter a Password';
$isValid = false;
}
if (empty($username)) {
echo 'You need to enter a Username';
$isValid = false;
}
if (empty($email)) {
echo 'You need to enter a Email Address';
$isValid = false;
}elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "You need to have a valid Email Address";
$isValid = false;
}
if ($isValid) {
$sql = "SELECT * FROM accounts WHERE username=? and password=? and email=? LIMIT 1";
$stmtselect = $db->prepare($sql);
$result = $stmtselect->execute([$username, $password, $email]);
$user = $stmtselect->fetch(PDO::FETCH_ASSOC);
if ($stmtselect->rowCount() > 0) {
$_SESSION['accounts'] = $user;
echo 'You have signed in successfully!';
} else {
echo 'Incorrect Username or Password or Email';
}
}
This is login.php
<?php
error_reporting(-1);
session_start();
if(isset($_SESSION['hello_world_accounts'])){
header("Location: index.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Programming Knowledge Login</title>
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
<div class="container h-100">
<div class="d-flex justify-content-center h-100">
<div class="user_card">
<div class="d-flex justify-content-center">
<div class="brand_logo_container">
<img src="img/logo.png" class="brand_logo" alt="Programming Knowledge logo">
</div>
</div>
<div class="d-flex justify-content-center form_container">
<form method="post">
<div class="input-group mb-2">
<div class="input-group-append">
<span class="input-group-text"><em class="fas fa-user"></em></span>
</div>
<input type="text" name="username" id="username" class="form-control input_user" placeholder="Username" required>
</div>
<div class="input-group mb-2">
<div class="input-group-append">
<span class="input-group-text"><em class="fas fa-key"></em></span>
</div>
<input type="password" name="password" id="password" class="form-control input_pass" placeholder="Password" required>
</div>
<div class="input-group mb-1">
<div class="input-group-append">
<span class="input-group-text"><em class="fas fa-inbox"></em></span>
</div>
<input type="email" name="email" id="email" class="form-control input_pass" placeholder="Email" required>
</div>
<div class="form-group">
<div class="custom-control custom-checkbox">
<input type="checkbox" name="rememberme" class="custom-control-input" id="customControlInline">
<label class="custom-control-label" for="customControlInline">Remember me</label>
</div>
</div>
</div>
<div class="d-flex justify-content-center mt-1 login_container">
<button type="button" name="button" id="login" class="btn login_btn">Login</button>
</div>
</form>
<div class="mt-3 mb-1">
<div class="d-flex justify-content-center links">
Don't have an account? Sign Up
</div>
<div class="d-flex justify-content-center">
Forgot your password?
</div>
</div>
</div>
</div>
</div>
<script src="http://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
$(function(){
$('#login').click(function(e){
var valid = this.form.checkValidity();
if(valid){
var username = $('#username').val();
var password = $('#password').val();
var email = $('#email').val();
}
e.preventDefault();
$.ajax({
type: 'POST',
url: 'jslogin.php',
data: {username: username, password: password, email: email},
success: function(data){
alert(data);
if($.trim(data) === "1"){
setTimeout(' window.location.href = "index.php"', 1000);
}
},
error: function(data){
alert('There were errors while doing the operation.');
}
});
});
});
</script>
</body>
</html>
This is congfig.php
<?php
error_reporting(-1);
$db_user = "root";
$db_pass = "";
$db_name = "hello_world_accounts";
$db = new PDO('mysql:host=localhost;dbname='. $db_name . ';charset=utf8', $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
This is index.php
<?php
error_reporting(-1);
session_start();
if(!isset($_SESSION['hello_world_accounts'])){
header("Location: login.php");
}
if(isset($_GET['logout'])){
session_destroy();
unset($_SESSION);
header("Location: login.php");
}
?>
<!DOCTYPE>
<html lang="en">
<head>
<title>Welcome</title>
</head>
<body>
<p>Welcome to index</p>
Logout
</body>
</html>
everytime i put in my email but not my username and password it says i need to put all three in even when one is already in
why is this happening and how do I fix it?
I thought about priorities but I don't know how or what to do that...
the rest of the code on the page is as follows
Please don't say anything about having the password as plain text.
Here is my test mysql.
My Test MYSQL
Here is my test website.
My Test Website
Here's your original code when run through a formatter. You should notice, as people have pointed out, it is indented like crazy and has a lot of nesting. You are also querying the database on each request, even if the data is invalid.
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$valid = "You need to have a valid Email Address";
$sql = "SELECT * FROM accounts WHERE username=? and password=? and email=? LIMIT 1";
$stmtselect = $db->prepare($sql);
$result = $stmtselect->execute([$username, $password, $email]);
if (stripos($password, '')) {
echo 'You need to enter a Password';
} else {
if (stripos($username, '')) {
echo 'You need to enter a Username';
} else {
if (stripos($email, '')) {
echo 'You need to enter a Email Address';
} else {
if (!stripos($email, '#')) {
echo $valid;
} else {
if (!stripos($email, '.')) {
echo $valid;
} else {
if (!stripos($email, 'com')) {
echo $valid;
} else {
if ($result) {
$user = $stmtselect->fetch(PDO::FETCH_ASSOC);
if ($stmtselect->rowCount() > 0) {
$_SESSION['accounts'] = $user;
echo 'You have signed in successfully!';
} else {
echo 'Incorrect Username or Password or Email';
}
} else {
echo 'There were errors while connecting to database.';
}
}
}
}
}
}
}
Instead, here's a quick attempt at cleaning it up. The major changes are the switch to empty() checks, the usage of elseif, a better email address validator and moving the query to the final else clause.
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if (empty($password)) {
echo 'You need to enter a Password';
} elseif (empty($username)) {
echo 'You need to enter a Username';
} elseif (empty($email)) {
echo 'You need to enter a Email Address';
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "You need to have a valid Email Address";
} else {
$sql = "SELECT * FROM accounts WHERE username=? and password=? and email=? LIMIT 1";
$stmtselect = $db->prepare($sql);
$result = $stmtselect->execute([$username, $password, $email]);
$user = $stmtselect->fetch(PDO::FETCH_ASSOC);
if ($stmtselect->rowCount() > 0) {
$_SESSION['accounts'] = $user;
echo 'You have signed in successfully!';
} else {
echo 'Incorrect Username or Password or Email';
}
}
EDIT
If your intention is to show multiple error messages and not just stop at the first one (as your original code does), then you can use multiple if blocks. Most people would collect the error messages in an array but I'll leave that up to you.
$isValid = true;
if (empty($password)) {
echo 'You need to enter a Password';
$isValid = false;
}
if (empty($username)) {
echo 'You need to enter a Username';
$isValid = false;
}
if (empty($email)) {
echo 'You need to enter a Email Address';
$isValid = false;
}elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "You need to have a valid Email Address";
$isValid = false;
}
if ($isValid) {
$sql = "SELECT * FROM accounts WHERE username=? and password=? and email=? LIMIT 1";
$stmtselect = $db->prepare($sql);
$result = $stmtselect->execute([$username, $password, $email]);
$user = $stmtselect->fetch(PDO::FETCH_ASSOC);
if ($stmtselect->rowCount() > 0) {
$_SESSION['accounts'] = $user;
echo 'You have signed in successfully!';
} else {
echo 'Incorrect Username or Password or Email';
}
}
EDIT
If you don't provide a method on the <form> it defaults to GET. Your code is expecting it to be POST, however. Change the form to <form method="post">.
EDIT
I'm not going to use any of your HTML and instead I'm going to just make a very simple form that POSTs to itself. This is a very common first task you learn when programming in any web language. This page, by itself, ignoring your database, styling and JS logic should work 100% by itself. Once you've proven that you can start enhancing it with sessions and then maybe AJAX. But start simple.
The form doesn't include normal settings like required or optimal types on fields intentionally because I'm just trying to keep it as simple as possible.
I did add in the errors array which removes the need for $isValid because we can now check to see if the error has anything inside of it.
Please try this code all by itself, and once you get how it works, then start modifying it, potentially asking new questions here if you really need to.
<?php
$errors = false;
$email = '';
$username = '';
$password = '';
if ('POST' === $_SERVER['REQUEST_METHOD']) {
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
$errors = [];
if (empty($password)) {
$errors[] = 'You need to enter a Password';
}
if (empty($username)) {
$errors[] = 'You need to enter a Username';
}
if (empty($email)) {
$errors[] = 'You need to enter a Email Address';
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "You need to have a valid Email Address";
}
}
if ($errors) {
echo '<pre>';
echo implode(PHP_EOL, $errors);
echo '</pre>';
}
?>
<form method="post">
<label>Email <input type="text" name="email" value="<?php echo htmlspecialchars($email); ?>"/></label><br/>
<label>Username <input type="text" name="username" value="<?php echo htmlspecialchars($username); ?>"></label><br/>
<label>Password <input type="password" name="password"></label><br/>
<input type="submit" value="Submit">
</form>

Echo in php is not showing up on the web page after form is submitted

I am using foundation 5 and php for this web page.
When I go to the web page and fill in all the spaces and press create account, none of the echos are showing up on the web page. The page just refreshes and just makes a new page like if I just reloaded the page. No text shows up and none of the function are working.
Here is my code:
<?php
error_reporting(0);
#ini_set('display_errors', 0);
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>AskmanProducts</title>
<link rel="stylesheet" href="css/foundation.css" />
<script src="js/vendor/modernizr.js"></script>
<script src="js/signinvaldator.js"></script>
</head>
<body>
<?php
if ($_POST['registerbtn']) {
$getuser = $_POST['user'];
$getemail = $_POST['email'];
$getpass = $_POST['pass'];
$getconfirmpass = $_POST['confirmpass'];
if ($getuser) {
if ($getemail) {
if ($getpass){
if ($getconfirmpass) {
if ($getpass === $getconfirmpass) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
require ("connect.php");
$query = mysql_query("SELECT * FROM users WHERE username='$getuser'");
$numrows = mysql_num_rows($query);
if ($numrows == 0) {
$query = mysql_query("SELECT * FROM users WHERE email='$getemail'");
$numrows = mysql_num_rows($query);
if ($numrows == 0) {
$password = md5(md5("kjfiufj".$getpass."Fj56fj"));
$date = date("F d, Y");
$code = md5(rand());
mysql_query("INSERT INTO users VALUES (
'', '$getuser', '$password', '$getemail', '0', '$code', '$date'
)");
$query = mysql_query("SELECT * FROM users WHERE username='$getuser'");
$numrows = mysql_num_rows($query);
if ($numrows == 1) {
$site = "http://localhost/Projects/project";
$webmaster = "donotreply#askmanproducts.com";
$headers = "From: $webmaster";
$subject = "Activate Your Account";
$message = "Thanks For Registering. Click The Link Below To Activate Your Account.\n";
$message .= "$site/activate.php?user=$getuser&code=$code\n";
$message .= "You Must Activate Your Account To Login.";
if (mail($getemail, $subject, $message, $headers)) {
echo "You have been registered. You must activate your account from the activation link sent to <b>$getemail</b>";
$getuser = "";
$getemail = "";
}
else {
echo "An error has occured. You activation email was not sent.";
}
}
else {
echo "An error has occured. Your account was not created.";
}
}
else {
echo "There is already a user with that email.";
}
}
else {
echo "There is already a user with that username.";
}
mysql_close();
}
else {
echo "You must enter a valid email address to register.";
}
}
else {
echo "Your password do not match.";
}
}
else {
echo "You must confirm your password to register.";
}
}
else {
echo "You must enter your password to register.";
}
}
else {
echo "You must enter your email to register.";
}
}
else {
echo "You must enter your username to register.";
}
}
else {
}
$form = "<form action='register.php' method='post'>
<div class='row' style='margin-top:10%'>
<div align='center'><h2>Create an Account</h2></div>
<br />
<div class='medium-6 medium-centered large-centered large-6 columns'>
<form data-abide>
<div class='name-field'>
<label>Username</label>
<input type='text' name='user' value='$getuser'></input>
<div class='email-field'>
<label>Email</label>
<input type='email' name='email' value='$getemail'></input>
<label for='password'>Password</label>
<input type='password' name='pass' value=''></input>
<label for='confirmPassword'>Confirm Password</label>
<input type='password' name='confirmpass' value=''></input>
<br />
<br />
<button type='submit' name='registerbtn'>Create Account</button>
<a href='login.php' class='button'>Log In</a>
<br />
</form>
</div>
</div>
<script src='js/vendor/jquery.js'></script>
<script src='js/foundation.min.js'></script>
<script>
$(document).foundation();
</script>
</form>";
echo $form;
?>
</body>
</html>
Your form has action='register.php' as its destination. When you do this, by pressing the Submit button, the page will jump to register.php before giving your error checking code any chance to fire.
I recommend you use
action='<?php echo $_SERVER['PHP_SELF']; ?>'
so that your Submit button keeps you on the same page, then when your error checking process passes, use:
header('Location: register.php');
Either that, or pass each of your POST variables to register.php where the error checking is carried out.
In this solution I have altered your code considerably but I use this logic all the time on my sites. I'll explain the code under it.
NOTE:
I did review your processing but did not test... Judging from the initial comments you are getting outdated information regarding programming. your mysql query code is outdated and depreciated and you should be making use of parameterised queries as pointed out in the comments by #Dave below this answer.
I suggest you go to youtube and search for pdo tutorials to learn modern methods of querying mysql. The provided code shows how to process forms through jQuery and a processing php file.
HTML & jQuery
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>AskmanProducts</title>
<link rel="stylesheet" href="css/foundation.css" />
<script src="js/vendor/modernizr.js"></script>
<script src="js/signinvaldator.js"></script>
</head>
<body>
<input type="hidden" name="processRegistrationURL" value="register.php">
<div id="showRegistrationResults" class="row" style="margin-top:10%">
<div align="center"><h2>Create an Account</h2></div>
<br />
<div class="medium-6 medium-centered large-centered large-6 columns">
<form data-abide>
<div class="name-field">
<label>Username</label>
<input type="text" is="user" name="user" value="$getuser"></input>
<div class="email-field">
<label>Email</label>
<input type="email" id="email" name="email" value="$getemail"></input>
<label for="password">Password</label>
<input type="password" id="pass" name="pass" value=""></input>
<label for="confirmPassword">Confirm Password</label>
<input type="password" id="confirmpass" name="confirmpass" value=""></input>
<br />
<br />
<button type="submit" id="registerbtn" name="registerbtn">Create Account</button>
Log In
<br />
</div>
</div>
<script src='js/vendor/jquery.js'></script>
<script src='js/foundation.min.js'></script>
<script>
$(document).foundation();
</script>
<script>
$(function() {
$( "#registerbtn" ).click(function(){
var url = $('#processRegistrationURL').val();
var user = $('#user').val();
var email = $('#email').val();
var pass = $('#pass').val();
var confirmpass = $('#confirmpass').val();
var postit = $.post( url, {
user:user,
email:email,
pass:pass,
confirmpass:confirmpass
});
postit.done(function( data ) {
var result = data.split('|');
if(result[0] == 1){alert(result[1]);}
else if(result[0] == 2){
$('#showRegistrationResults').html(result[1]);
}
});
});
});
</script
</body>
</html>
There are no form tags... the form processing is handled on register.php which is stored in a hidden input <input type="hidden" name="processRegistrationURL" value="register.php">
I have added id to each form and the submit button.
register.php
$getuser = $_POST['user'];
$getemail = $_POST['email'];
$getpass = $_POST['pass'];
$getconfirmpass = $_POST['confirmpass'];
if ($getuser) {
if ($getemail) {
if ($getpass){
if ($getconfirmpass) {
if ($getpass === $getconfirmpass) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
require ("connect.php");
$query = mysql_query("SELECT * FROM users WHERE username='$getuser'");
$numrows = mysql_num_rows($query);
if ($numrows == 0) {
$query = mysql_query("SELECT * FROM users WHERE email='$getemail'");
$numrows = mysql_num_rows($query);
if ($numrows == 0) {
$password = md5(md5("kjfiufj".$getpass."Fj56fj"));
$date = date("F d, Y");
$code = md5(rand());
mysql_query("INSERT INTO users VALUES (
'', '$getuser', '$password', '$getemail', '0', '$code', '$date'
)");
$query = mysql_query("SELECT * FROM users WHERE username='$getuser'");
$numrows = mysql_num_rows($query);
if ($numrows == 1) {
$site = "http://localhost/Projects/project";
$webmaster = "donotreply#askmanproducts.com";
$headers = "From: $webmaster";
$subject = "Activate Your Account";
$message = "Thanks For Registering. Click The Link Below To Activate Your Account.\n";
$message .= "$site/activate.php?user=$getuser&code=$code\n";
$message .= "You Must Activate Your Account To Login.";
if (mail($getemail, $subject, $message, $headers)) {
echo "You have been registered. You must activate your account from the activation link sent to <b>$getemail</b>";
$getuser = "";
$getemail = "";
}
else {
echo "2|An error has occurred. You activation email was not sent. Please refresh this page and try again. If this issue persists please contact administration.";
}
}
else {
echo "2|An error has occurred. Your account was not created. Please refresh this page and try again. If this issue persists please contact administration.";
}
}
else {
echo "1|There is already a user with that email.";
}
}
else {
echo "1|There is already a user with that username.";
}
mysql_close();
}
else {
echo "1|You must enter a valid email address to register.";
}
}
else {
echo "1|Your password do not match.";
}
}
else {
echo "1|You must confirm your password to register.";
}
}
else {
echo "1|You must enter your password to register.";
}
}
else {
echo "1|You must enter your email to register.";
}
}
else {
echo "1|You must enter your username to register.";
}
else {
echo "2|WHATEVER YOU WANT TO RENDER IN #showRegistrationResults";
}
When the button is clicked it fires the jQuery which in turn passes the form submission to register.php
You will notice in each echo there is a 1 or a 2 with a pipe. echo "1|You must enter your password to register.php"; The echo will return to the jQuery as data.
The jQuery then splits the data at the pipe (|). If result[0] == 1 the jQuery fires an alert leaving the form intact for corrections to be made. If result[0] == 2 the jQuery will replace the content of #showRegistrationResults which wraps the form (it will replace the form) with the data returned through the echo.
Review the echos on register.php. The first two replace the form as an error in processing has occurred. All other return an alert message.
You can toggle these as desired.
Improve your password security
You can improve your password security with the following code:
$hash_key = trim(file_get_contents('PATH-TO/key.dat'));
$password = hash_hmac('sha512', $getpass, $hash_key);
key.dat simply contains a key: for example: 72093OT7Yw6g0925T9Ly07G6y7WhI2v5
Hope this helps
Pete

PHP session is not functioning on the index page

I have got my index page which is redirecting fine without the PHP sessions included. When I I do included it and enter the correct username and password it seems to not be able to pass the username session across with the redirection. Therefore it sees the session as empty and redirecting me back to the index page.
here is my Index page
<?php
session_start();
?>
<!DOCTYPE html>
<head>
<meta charset = "utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<title> RBH-PAS system </title>
<link rel = "stylesheet" type ="text/css" href = "pascss/index.css " >
<script type="text/javascript">
$(document).ready(function(){
$(function() {
$("#login1").on("submit", function(event) {
event.preventDefault();
$.ajax({
url: "login.php",
type: "post",
data: $(this).serialize(),
success: function(d) {
var r = d;
if(r==2){window.location ="patient.php"; }
else if(r==1){window.location="clinician.php";}
else{alert("incorrect user details entered");
window.location="index.php";
}
}
});
});
});
});
</script>
</head>
<body>
<h1><CENTER> WELCOME TO PAS DASHBOARD</CENTER></h1>
<div id="login">
<h2><span class="fontawesome-lock"></span>Sign In</h2>
<form id ="login1" name ="login1" method="post">
<fieldset>
<p><label for="username">Username</p>
<p><input type="text" id ="username" name="username" placeholder="Enter username" required></p>
<p><label for="password">Password</label></p>
<p><input type="password" id="password" name="password" placeholder="Enter password" required></p>
<p><input type="submit" id ="submit" value="Sign In" /></p>
</fieldset>
</body>
</html>
and here is my login page, which I do initiate the session in
<?php
require_once"conn.php";
session_start();
if($_SERVER['REQUEST_METHOD']=='POST'){
//recieve credentials from the user
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
//check the variables recieved are not empty
if($username != '' && $password != ''){
$sql = "SELECT *FROM staff WHERE username ='$username' AND password = '$password' ";//create an sql statement
$result = $conn->query($sql);//run sqlm statement
$row = $result->fetch_assoc(); //fetch row of data
if($result->num_rows == 1 ){//check if user exist as a doctor
if($row["role"]== "clinician"){ //check if user exist as a clinician
$send = 1;
echo $send;}
else if($row["role"]== "doctor"){ //check if user exist as a clinician
$send = 2;
echo $send;}
}else{//if user doesn't exist
$_SESSION["myusername"] = '';
$send = 3;
echo $send;}
}
}
else{$conn=null;}
?>
and here is how I check on the other pages for is user logged in
<?php
session_start();
if (!(isset($_SESSION['username']) && $_SESSION['username'] != '')) {
header ("Location: index.php");}
?>
you are never setting $_SESSION['username'] to any value in your login page.

jquery mobile w/ php login form

I am newbie using jquery mobile with php. I have a little problem on my login form with submit button after I submited, it head to 'home.php' page but url didn't go to home.php too. (it's still /login.php) . how can i fix this?
<?php
include 'core/config.init.php'; //include all sql connect,function etc.
if(logged_in() === true)
{
header('Location: home.php');
}
if(empty($_POST) === false)
{
$check_user = true;
$check_pass = true;
$username = $_POST['username'];
$password = $_POST['password'];
if(empty($username) === true || empty($password) === true)
{
$error = 'You need to enter username and password!';
$check_user = false;
$check_pass = false;
}
else if(user_exists($username) === false )
{
$check_user = false;
}
$login = login($username, $password);
if($login === false)
{
$error = 'Username/password is incorrect!';
$check_pass = false;
}
else
{
setcookie("username", "$username", time()+1720000);
header('Location: home.php');
}
}
//print_r($error);
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.1.1/jquery.mobile-1.1.1.min.css" />
<link rel="stylesheet" href="core/css/login.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.1.1/jquery.mobile-1.1.1.min.js"></script>
<script type="text/javascript" src="core/jquery/jquery-latest.js"></script>
<script src="core/jquery/login.js"></script>
</head>
<body>
<div data-role="page" data-theme="a">
<div id = "header-text-area">
<span id= "header-text">Login</span>
</div>
<div data-role="content" style="padding: 15px">
<form action="login.php" method="POST">
<div data-role="fieldcontain" class="ui-hide-label">
<input name="username" id="textinput1" placeholder="Username" value="test" type="text" />
</div>
<div data-role="fieldcontain" class="ui-hide-label">
<input name="password" id="textinput2" placeholder="Password" value="test" type="password" />
</div>
<div id = "submit-area">
<input type="submit" data-theme="b" value="Submit" id = "sub1"/>
</div>
</form>
</div>
</div>
</body>
You need to add data-ajax="false" to the form tag. This will submit the form to your action URL without using Ajax navigation that is built into jquery mobile. Also, you should use the full URL in the form action. (jquery mobile sometimes gets confused)
After each call to
header("Location: home.php");
you need to add a line like this:
exit();
this should solve your problem.

Categories