AJAX & PHP form validation - php

Im currently learning my way with ajax. Im trying to make a register / login system with AJAX. I finished the register form and is now working but im having problems with the login one.
ajax/login.php PHP Vaidation for Login
<?php
require_once("../core/config.php");
$username = trim(strip_tags($_POST['username']));
$password= trim(strip_tags($_POST['password']));
$errors = false;
$user_query = $db->query("SELECT * FROM users WHERE username='$username'");
// Empty check -> Username
if(empty($username) && strlen($username) == 0) { $error_username = "<span style='color:red;'> Username is empty </span>"; $errors = true; }
// Empty check -> Password
if(empty($password) && strlen($password) == 0) { $error_password = "<span style='color:red;'> Password is empty </span>"; $errors = true; }
// If exists check
$num = $user_query->num_rows;
if($num < 1) { $error_general = "<span style='color:red;'> User doesn't exist </span>"; $errors = true; } else {
$user = $user_query->fetch_object();
if($user->password != $password) { $error_general = "<span style='color:red;'> Invalid Username or Password </span>"; $errors = true; }
}
//
if($errors == true) {
?>
<?php if(isset($error_general)) { echo $error_general." <br><br>"; } ?>
<?php if(isset($error_username)) { echo $error_username; } ?>
<input type="text" name="login_username" id="login_username" placeholder="Username" value="<?php echo $username; ?>"> <br>
<?php if(isset($error_password)) { echo $error_password; } ?>
<input type="password" name="login_password" id="login_password" placeholder="Password" value="<?php echo $password; ?>">
<br>
<?php } else {
$_SESSION['User'] = true;
header("Location: ". $_SERVER['PHP_SELF']);
}
?>
index.php Form HTML & JS
<!DOCTYPE HTML>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
var loader = $("<div style='text-align: center; float:none; margin: 0 auto;'> <img src='loader-small.gif'> <br> Processing request... </div> <br>");
function process_login() {
var username = $("#login_username").val();
var password =$("#login_password").val();
$(".login_container").html(loader).load("ajax/login.php", {username: username, password: password})
}
</script>
</head>
<body>
<h3> Login </h3>
<form action="" method="POST">
<div class="login_container">
<input type="text" name="login_register" id="login_username" placeholder="Username"> <br>
<input type="password" name="login_password" id="login_password" placeholder="Password">
<br>
</div>
<input type="submit" onclick="process_login(); return false;" name="login_submit" value="Login" style="outline:none;">
</form>
</body>
</html>
When I submit the form with the correct information I get "User doesnt exist", "Username is empty", "Password is empty" and when I submit with wrong information I get "User doesnt exist"
I've been brainstorming for the last 3 hours, yet I have not found a way to fix it

Logical error:
// Empty check -> Username
if(empty($username) || strlen($username) == 0) { $error_username = "<span style='color:red;'> Username is empty </span>"; $errors = true; }
// Empty check -> Password
if(empty($password) || strlen($password) == 0) { $error_password = "<span style='color:red;'> Password is empty </span>"; $errors = true; }
Compare to you code:
// Empty check -> Username
if(empty($username) && strlen($username) == 0) { $error_username = "<span style='color:red;'> Username is empty </span>"; $errors = true; }
// Empty check -> Password
if(empty($password) && strlen($password) == 0) { $error_password = "<span style='color:red;'> Password is empty </span>"; $errors = true; }

Related

Login form validation using php and ajax

I have a login form that has two inputs email and password. If a user enters incorrect credentials, I have to show them the error. I have done form validation in PHP, so I need to send data from the form and get a response message without refreshing the page. I'm new to ajax, so I don't know how to do it
login.php
<form action="register.php" method="POST" autocomplete="off">
<h1 class="card-title display-4 mt-4 mb-5 text-center">Login</h1>
<div class="form-group">
<input type="email" class="form-control" id="email" placeholder="Email" name="email" />
<div class="email-status"></div>
</div>
<div class="form-group">
<input type="password" class="form-control" id="password" placeholder="Password" name="password" />
<div class="password-status"></div>
</div>
<p class="card-text text-center">Forgot your password?</p>
<span class="d-flex justify-content-center">
<button type="submit" class="btn btn-primary mb-4 w-50" style="border-radius: 20px;" name="login_btn" id="login_btn">Login</button>
</span>
<div class="success"></div>
</form>
<script>
$(document).ready(function() {
$("#login_btn").click(function() {
var email = $("#email").val();
var password = $("#password").val();
$.ajax({
url: 'register.php',
type: 'post',
data: {
email: email,
password: password
},
success: function(response) {
var emailstatus = "";
var passwordstatus = "";
var success = "";
if (response == 1) {
emailstatus = "required";
$(".email-status").text(emailstatus);
} else if (response == 2) {
emailstatus = "invalid";
$(".email-status").text(emailstatus);
} else if (response == 3) {
emailstatus = "match";
$(".email-status").text(emailstatus);
} else if (response == 4) {
passwordstatus = "required";
$(".password-status").text(passwordstatus);
} else if (response == 5) {
passwordstatus = "match";
$(".password-status").text(passwordstatus);
} else {
success = "sometihg went wrong";
$(".success").text(success);
}
}
});
});
});
</script>
register.php for form validation
if (isset($_POST['login_btn'])) {
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$new_password = md5($password);
$result = mysqli_query($conn, "SELECT * FROM users WHERE email = '$email' OR password = '$new_password' LIMIT 1");
$row = mysqli_fetch_assoc($result);
//EMAIL
if (empty($email)) {
$email_status = "Email is required";
echo 1;
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_status = "Enter valid Email ID";
echo 2;
} elseif ($row['email'] != $email) {
$email_status = "Email doesn't exist";
echo 3;
}
//PASSWORD
elseif (empty($password)) {
$password_status = "Password is required";
echo 4;
} elseif ($row['password'] != $new_password) {
$password_status = "Password doesn't match";
echo 5;
} else {
$query = "SELECT * FROM users WHERE email = '$email' AND password = '$new_password'";
$results = mysqli_query($conn, $query);
if (mysqli_num_rows($results) == 1) {
$rows = mysqli_fetch_array($results);
$_SESSION['username'] = $rows['username'];
$_SESSION['success'] = "You are now logged in";
if (isset($_SESSION['login_redirect'])) {
header("Location: " . $_SESSION["login_redirect"]);
unset($_SESSION["login_redirect"]);
} else if (isset($_SESSION['url'])) {
$url = $_SESSION['url'];
header("Location: $url");
} else {
header("Location: homepage.php");
}
exit;
} else {
$success = "Something went wrong";
echo 6;
}
}
}
If I run the above code, the page gets refresh and I'm not getting any response or validation messages
You have to prevent auto form submit. add an Id or a class to your form element and add this code
Inside of document ready
$("#form-id").submit(function(e){
e.preventDefault();
});
And in form element add an Id
<form action="register.php" id='form-id' method="POST" autocomplete="off">
Replace your data object of ajax as follows and your current code will work:
data: {
email: email,
password: password,
login_btn: true
}
You are checking isset of login_btn value which was not pass through the ajax.

how to show php validations error on page

I have a form and all the validations, now I want to show the error messages in front of the text field not in the url. How do I do this?
Here is my PHP code:
<?php
if ((isset($_POST['submit']))){
$email = strip_tags($_POST['email']);
$fullname = strip_tags($_POST['fullname']);
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$fullname_valid = $email_valid = $username_valid = $password_valid = false;
if(!empty($fullname)){
if (strlen($fullname) > 2 && strlen($fullname)<=30) {
if (!preg_match('/[^a-zA-Z\s]/', $fullname)) {
$fullname_valid = true;
# code...
}else {$fmsg .="fullname can contain only alphabets <br>";}
}else{$fmsg1 .="fullname must be 2 to 30 char long <br>";}
}else{$fmsg2 .="fullname can not be blank <br>";}
if (!empty($email)) {
if (filter_var($email , FILTER_VALIDATE_EMAIL)) {
$query2 = "SELECT email FROM users WHERE email = '$email'";
$fire2 = mysqli_query($con,$query2) or die("can not fire query".mysqli_error($con));
if (mysqli_num_rows($fire2)>0) {
$msg .=$email."is already taken please try another one<br> ";
}else{
$email_valid=true;
}
# code...
}else{$msg .=$email."is an invalid email address <br> ";}
# code...
}else{$msg .="email can not be blank <br>";}
if(!empty($username)){
if (strlen($username) > 4 && strlen($username)<=15) {
if (!preg_match('/[^a-zA-Z\d_.]/', $username)) {
$query = "SELECT username FROM users WHERE username = '$username'";
$fire = mysqli_query($con,$query) or die("can not fire query".mysqli_error($con));
if(mysqli_num_rows($fire)> 0){
$umsg ='<p style="color:#cc0000;">username already taken</p>';
}else{
$username_valid = true;
}
# code...
# code...
}else {$msg.= "username can contain only alphabets <br>";}
}else{$msg.= "username must be 4 to 15 char long <br>";}
}else{$msg.="username can not be blank <br>";}
if (!empty($password)) {
if (strlen($password) >=5 && strlen($password) <= 15 ) {
$password_valid = true;
$password = md5($password);
# code...
}else{$msg .= $password."password must be between 5 to 15 character long<br>";}
# code...
}else{$msg .= "password can not be blank <br>";}
if ($fullname_valid && $email_valid && $password_valid && $username_valid) {
$query = "INSERT INTO users(fullname,email,username,password,avatar_path) VALUES('$fullname','$email','$username','$password','avatar.jpg')";
$fire = mysqli_query($con,$query) or die ("can not insert data into database".mysqli_error($con));
if ($fire){
header("Location: dashboard.php");}
}else{
header("Location: createaccount.php?msg=".$msg);
}
}
?>
and this is my html code:
<div class="container">
<form name="signup" id="signup" method="POST">
<h2>sign up</h2>
<div class="form-input">
<input name="email" type="email" name="email" id="email" placeholder="enter email" required="email is required">
</div>
<input name="mobile" type="number" id="mobile" placeholder="enter mobile number" required="mobile is required">
<span id="message"></span>
<div class="form-input">
<input name="fullname" type="full name" id="fullname" name="full name" placeholder="full name" required="what's your fullname">
</div>
<div>
<input name="username" type="username" id="username" name="username" placeholder="username" required="username is required">
</div>
<div>
<input name="password" type="password" id="password" name="password" placeholder="password" required="password is required">
</div>
<div>
<input type="submit" name="submit" id="submit"
value="sign up" class="btn btn-primary btn-block">
forgot password?
<h3>have an account? log in</h3>
</div>
</form>
How do I get the error message in front of my text field, and also how do I get the specified error in front of the specified text field? I don't want to use ajax or javascript. I want to do it with PHP. I have tried this but no luck.
<?php if(isset($errorfname)) { echo $errorfname; } ?>
send msg to get params is not good idea.
Use session
$_SESSION['error_msg'] = $msg
header("Location: createaccount.php");
and add get error in php
$errors = '';
if(isset($_SESSION['error_msg'])) { $errors = $_SESSION['error_msg']; } ?>
and in html show $errors
By looking at your form does not have an action attribute therefore one can concluded that you are submitting the form at the same page as the form PHP_SELF
So if you want to display the error next to the field I would advice that you first declare an empty variables for each text error on top of your page then echo the variables next to each field.
<?php
$emailError = "";
$fullnameError = "";
$usernameError = "";
$passwordError = "";
$errors = 0;
if ((isset($_POST['submit']))) {
$email = strip_tags($_POST['email']);
$fullname = strip_tags($_POST['fullname']);
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$fullname_valid = $email_valid = $username_valid = $password_valid = false;
if (!empty($fullname)) {
if (strlen($fullname) > 2 && strlen($fullname) <= 30) {
if (!preg_match('/[^a-zA-Z\s]/', $fullname)) {
$fullname_valid = true;
# code...
} else {
$fullnameError = "fullname can contain only alphabets <br>";
$errors++;
}
} else {
$fullnameError = "fullname must be 2 to 30 char long <br>";
$errors++;
}
} else {
$fullnameError = "fullname can not be blank <br>";
$errors++;
}
if (!empty($email)) {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$query2 = "SELECT email FROM users WHERE email = '$email'";
$fire2 = mysqli_query($con, $query2) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire2) > 0) {
$emailError = $email . "is already taken please try another one<br> ";
} else {
$email_valid = true;
}
# code...
} else {
$emailError = $email . "is an invalid email address <br> ";
$errors++;
}
# code...
} else {
$emailError = "email can not be blank <br>";
}
if (!empty($username)) {
if (strlen($username) > 4 && strlen($username) <= 15) {
if (!preg_match('/[^a-zA-Z\d_.]/', $username)) {
$query = "SELECT username FROM users WHERE username = '$username'";
$fire = mysqli_query($con, $query) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire) > 0) {
$usernameError = '<p style="color:#cc0000;">username already taken</p>';
$errors++;
} else {
$username_valid = true;
}
} else {
$usernameError = "username can contain only alphabets <br>";
$errors++;
}
} else {
$usernameError = "username must be 4 to 15 char long <br>";
$errors++;
}
} else {
$usernameError = "username can not be blank <br>";
$errors++;
}
if (!empty($password)) {
if (strlen($password) >= 5 && strlen($password) <= 15) {
$password_valid = true;
$password = md5($password);
# code...
} else {
$passwordError = $password . "password must be between 5 to 15 character long<br>";
$errors++;
}
# code...
} else {
$passwordError = "password can not be blank <br>";
$errors++;
}
//if there's no errors insert into database
if ($errors <= 0) {
if ($fullname_valid && $email_valid && $password_valid && $username_valid) {
$query = "INSERT INTO users(fullname,email,username,password,avatar_path) VALUES('$fullname','$email','$username','$password','avatar.jpg')";
$fire = mysqli_query($con, $query) or die("can not insert data into database" . mysqli_error($con));
if ($fire) {
header("Location: dashboard.php");
}
}
}
}
?>
<div class="container">
<form name="signup" id="signup" method="POST">
<h2>sign up</h2>
<div class="form-input">
<input name="email" type="email" name="email" id="email" placeholder="enter email" required="email is required">
<!-- display email error here -->
<?php echo $emailError?>
</div>
<input name="mobile" type="number" id="mobile" placeholder="enter mobile number" required="mobile is required">
<span id="message"></span>
<div class="form-input">
<input name="fullname" type="full name" id="fullname" name="full name" placeholder="full name" required="what's your fullname">
<?php echo $fullnameError?>
</div>
<div>
<input name="username" type="username" id="username" name="username" placeholder="username" required="username is required">
<?php echo $usernameError?>
</div>
<div>
<input name="password" type="password" id="password" name="password" placeholder="password" required="password is required">
<?php echo $passwordError?>
</div>
<div>
<input type="submit" name="submit" id="submit" value="sign up" class="btn btn-primary btn-block">
forgot password?
<h3>have an account? log in</h3>
</div>
</form>
NB: I would advice that you look into password_hash() and
password_verify()to hash your passwords, they provide better
security as compared tomd5()` and make sure your database column is
atleast 60 characters in length.. I would also advice to look into
prepared statements.
The following can help :
How can I prevent SQL injection in PHP?
Using PHP 5.5's password_hash and password_verify function
I think the best way is include from template in result
if ($fire){
header("Location: dashboard.php");
}else{
include("createaccount.php");
}
And in createaccount.php
<div class="container">
<form name="signup" id="signup" method="POST">
<h2>sign up</h2>
<p class="errors"><?= $msg ?></p>
...

Live check doesn't work using PDO

I am using JQuery to check if username is in use, however I have some issues. It is always stuck of "Searching". Image below shows exactly what the issue is.
Register.JS:
$(document).ready(function(){
$('#username').keyup(function() {
var username = $(this).val();
$('#usernameCheck').text('Searching...');
if (username === '') {
$('#usernameCheck').text('');
}else {
$.post('usernamecheck', { username:username }, function(data) {
$('#usernameCheck').text(data);
});
}
});
});
Register.php:
<html>
<head>
<title>Register</title>
<link rel='stylesheet' type='text/css' href='styles.css'>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript" src="JS/register.js"></script>
</head>
</html>
<?php
echo '<form action="register.php?action=registerCheck" method="post" name="formOne">
<br/><input type="text" id="username" placeholder="Username" maxlength="50" title="Maximum 50 charcters or less."><span id="usernameCheck"></span><br/>
<br/><input type="password" name="passwordOne" placeholder="Password" maxlength="60" title="Maximum 60 charcters or less."><br/>
<br/><input type="password" name="passwordTwo" placeholder="Retype Password" maxlength="60" title="Must be the same as the password field above this."><br/>
<br/><input type="text" name="email" placeholder="Email Address" title="Must be correct in-case admins wish to contact you."><br/>
<br/><textarea disabled rows="1" cols="4" name="defSpamCheck">'.$spamCheck.'</textarea><br/>
<br/><textarea rows="1" cols="30" name="userSpamCheck" placeholder="Enter the 4 digit code above." title="Needed to check for bots."></textarea><br/>
<br/><input type="submit" value="Register" onclick="return validate()">
</form>';
}
function registerCheck() {
global $PDO;
// All the validations
if (!isset($_POST['username']) || empty($_POST['username'])) {
echo '<br/>';
echo '<p class="error">You missed out the usernane field.</p>';
echo 'Back';
endPage();
} else if (!isset ($_POST['passwordOne']) || empty ($_POST['passwordOne'])) {
echo '<br/>';
echo '<p class="error">You missed out the password field.</p>';
echo 'Back';
endPage();
} else if (!isset ($_POST['passwordTwo']) || empty ($_POST['passwordTwo'])) {
echo '<br/>';
echo '<p class="error">You missed out the second password field.</p>';
echo 'Back';
endPage();
} else if ($_POST['passwordOne'] != $_POST['passwordTwo']) {
echo '<br/>';
echo '<p class="error">Passwords do not match.</p>';
echo 'Back';
endPage();
} else if (!isset ($_POST['email']) || empty ($_POST['email'])) {
echo '<br/>';
echo '<p class="error">You missed out the email field.</p>';
echo 'Back';
endPage();
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
echo '<br/>';
echo '<p class="error">Email not valid.</p>';
echo 'Back';
endPage();
} else if (!isset ($_POST['userSpamCheck']) || empty ($_POST['userSpamCheck'])) {
echo '<br/>';
echo '<p class="error">You missed out the spam check field.</p>';
echo 'Back';
endPage();
} else if (strlen($_POST['username']) > 50) {
echo '<br/>';
echo '<p class="error">Username has to be 50 characters or less.</p>';
echo 'Back';
endPage();
} else if (strlen($_POST['passwordOne']) && strlen($_POST['passwordTwo']) > 60) {
echo '<br/>';
echo '<p class="error">Password has to be 60 characters or less.</p>';
echo 'Back';
endPage();
} else if (strlen($_POST['username']) < 5) {
echo '<br/>';
echo '<p class="error">Username has to be greater than 5 characters.</p>';
echo 'Back';
endPage();
} else if (strlen($_POST['passwordOne']) && strlen($_POST['passwordTwo']) < 5) {
echo '<br/>';
echo '<p class="error">Password has to be greater than 5 characters</p>';
echo 'Back';
endPage();
} else {
$username = htmlspecialchars($_POST['username']);
// Replace all these with $replace
$sChars = array ("<", ">", "(", ")", "*", "&", "#", ":");
$replace = ' ';
// Trim to remove any blank spaces
trim(str_replace($sChars, $replace, $username));
$password = sha1(htmlspecialchars($_POST['passwordOne']));
$email = htmlspecialchars($_POST['email']);
$stmtOne = $PDO->prepare("SELECT COUNT(`uID`) uUsername FROM `users` WHERE uUsername=? LIMIT 1");
$stmtOne->bindParam(1, $username, PDO::PARAM_INT);
$stmtOne->execute();
$result = $stmtOne->fetch(PDO::FETCH_ASSOC);
if ($result == 1) {
echo '<br/>';
echo '<p class="error">Username already in use, pick another one.</p>';
echo 'Back';
endPage();
}
$stmtTwo = $PDO->prepare("INSERT INTO `users` (uUsername, uPassword, uEmail) VALUES (?, ?, ?)");
if ($stmtTwo->execute(array($username, $password, $email))) {
echo '<br/>';
echo '<p class="norm">Account created! You can now log in.</p>';
header("Refresh:3; URL=login.php");
endPage();
} else {
echo '<br/>';
echo '<p class="error">We could not create your account, please try again later.</p>';
header("Refresh:3; URL=login.php");
endPage();
}
}
}
?>
usernamecheck.php:
<?php
include 'pdo.config.php';
include 'register.php';
global $username;
$stmtOne = $PDO->query("SELECT COUNT(*) uUsername FROM `users` WHERE uUsername='$username'");
$rows = $stmtOne->fetchALL();
$count = count($rows);
if ($count < 1) {
echo 'Username already in use, pick another one';
} else if ($count == 0) {
echo 'Username available';
}
?>
But it won't work, what am I doing wrong?
$count is the number of rows. Your query always returns exactly 1 row, since it's just returning a count. Also, both your if tests are checking if $count is 0 (I think you meant to write $count == 1 for the first one).
$stmtOne = $PDO->prepare("SELECT COUNT(*) uUsername FROM `users` WHERE uUsername = :username");
$stmtOne->exec(array('username' => $username));
$row = $stmtOne->fetch(PDO::FETCH_OBJ);
$count = $row->uUsername;
if ($count == 1) {
echo 'Username already in use, pick another one';
} else if ($count == 0) {
echo 'Username available';
}
Okay, so my code was right but I had a small but critical error.
$(document).ready(function(){
$('#username').keyup(function() {
var username = $(this).val();
$('#usernameCheck').text('Searching...');
if (username === '') {
$('#usernameCheck').text('');
}else {
$.post('usernamecheck', { username:username }, function(data) {
$('#usernameCheck').text(data);
});
}
});
});
Where it's looking for the file, I put "usernamecheck". It was mean't to be usernamecheck.php. I missed out the file extension.

php and mysql allowing successful login for emails with _ and other special characters

hi can someone please help me. i have a login script and when i set a users username to eric#email.com it works fine but if their email is eric_1#email.com and other special characters it echoes out the count error 1 where it says there was one error in the form.
how can i allow my script to succesfully log in user with _ in their email or with any other special characters? im really new to php and mysql and would really be greatful if someone could show me how to fix this.
<?php
if (logged_in())
{
$_SESSION['login_message']="<div class=\"login-overlay\"></div><div class=\"login-box\"><div class=\"loginframe2\">
<h1>Login You In Securely </h1>
<p> PlaytimeBoys.com is login you in securely. Please wait.<br/><br/>
<div class=\"login-logo\">
<img src=\"assets/css/photobox/loading.gif\" width=\"24\" height=\"24\"><div class=\"login-text-logo\">Login You In. Please Wait</div></div>
</div></div>";
header("Location: {$_SERVER['HTTP_REFERER']}");
}
include_once("includes/form_functions.php");
// START FORM PROCESSING
if (isset($_POST['submit'])) { // Form has been submitted.
$errors = array();
// perform validations on the form data
$required_fields = array('email', 'password');
$errors = array_merge($errors, check_required_fields($required_fields, $_POST));
$fields_with_lengths = array('email' => 30, 'password' => 30);
$errors = array_merge($errors, check_max_field_lengths($fields_with_lengths, $_POST));
$email = trim(mysql_prep($_POST['email']));
$password = trim(mysql_prep($_POST['password']));
$hashed_password = md5($password);
if ( empty($errors) ) {
// Check database to see if email and the hashed password exist there.
$query = "SELECT id, email, close_account ";
$query .= "FROM ptb_users ";
$query .= "WHERE email = '{$email}' ";
$query .= "AND password = '{$hashed_password}' ";
$query .= "AND close_account = '0' ";
$query .= "LIMIT 1";
$result_set = mysql_query($query);
confirm_query($result_set);
if (mysql_num_rows($result_set) == 1) {
// email/password authenticated
// and only 1 match
$found_user = mysql_fetch_array($result_set);
$_SESSION['user_id'] = $found_user['id'];
$_SESSION['email'] = $found_user['email'];
$_SESSION['sub_expires'] = $found_user['subscription_expires'];
$result = mysql_query("UPDATE ptb_users SET user_online='Online' WHERE id=".$_SESSION['user_id']."")
or die(mysql_error());
if($result)
{
$_SESSION['login_message']="<div class=\"login-overlay\"></div><div class=\"login-box\"><div class=\"loginframe2\">
<h1>Login You In Securely </h1>
<p>login you in securely. Please wait.<br/><br/>
<div class=\"login-logo\">
<img src=\"assets/css/photobox/loading.gif\" width=\"24\" height=\"24\"><div class=\"login-text-logo\">Login You In. Please Wait</div></div>
</div></div>";
header("Location: {$_SERVER['HTTP_REFERER']}");
}
}else{
// email/password combo was not found in the database
$message = "<div class=\"infobox_out\"><strong>Email / Password combination incorrect.</strong><br />
Please make sure your caps lock key is off and try again.</div>";
echo "<div class=\"infobox-close2\"></div>";
}
} else {
if (count($errors) == 1) {
$message = "<div class=\"infobox_out\">There was 1 error in the form.<div>";
} else {
$message = "<div class=\"infobox_out\">There were " . count($errors) . " errors in the form.<div>";
}
}
} else { // Form has not been submitted.
if (isset($_GET['logout']) && $_GET['logout'] == 1) {
$message = "<div class=\"infobox\">You are now logged out.</div>";
echo "<div class=\"infobox-close3\"></div>";
} else { // Form has not been submitted.
if (isset($_GET['logout']) && $_GET['logout'] == 5) {
$message = "<div class=\"infobox-noprofile2\"><strong>Account Banned -</strong> We could not log you in because your account's<br/> been banned. Contact us at: Support#admin.com.</div>";
echo "<div class=\"infobox-close12\"></div>";
} else { // Form has not been submitted.
if (isset($_GET['logout']) && $_GET['logout'] == 6) {
$message = "<div class=\"infobox-noprofile2\"><strong>Account Warning -</strong> You recently violated a condition in our User Policy. Due to this you are receiving this warning. If you continue to violate any policy<br/> your account will be banned. Review User Policy and<br/>login when ready.</div>";
echo "<div class=\"infobox-close12\"></div>";
} else { // Form has not been submitted.
if (isset($_GET['logout']) && $_GET['logout'] == 2) {
$message = "<div class=\"infobox_out\">Sorry, we've had to log you out. Your session has expired.</div>";
echo "<div class=\"infobox-close2\"></div>";
} else { // Form has not been submitted.
if (isset($_GET['logout']) && $_GET['logout'] == 1) {
$message = "<div class=\"infobox\">You are now logged out.</div>";
echo "<div class=\"infobox-close3\"></div>";
}
}
}
}
}
$email = "";
$password = "";
}
?>
<br/>
<?php if (!empty($message)) {echo "<p class=\"message\">" . $message . "</p>";} ?>
<form action="login.php" rel="shadowbox;height=300;width=500" method="post" >
<div class="row email">
<input type="email" id="email" name="email" placeholder="Email" value="<?php echo htmlentities($email); ?>" />
</div>
<div class="row password">
<input type="password" id="password" name="password" placeholder="Password" value="<?php echo htmlentities($email); ?>" />
</div>
<input type="submit" name="submit" value="Login >" />
</form>
<?php if (!empty($errors)) { display_errors($errors); } ?>
I don't know if I can find you an actual answer, but I can't see you using escape string here, which means your code could be subject to SQL injection. If the problem is something to do with the underscore being a special character, you should do this (you should be doing it anyway, really!)
$myescapedstring = escapestring($mystring)
You should be doing this for anything which is being passed to your database for querying.
You'd implement it like this:
$email = escapestring(trim(mysql_prep($_POST['email'])));
$password = escapestring(trim(mysql_prep($_POST['password'])));
$hashed_password = md5($password);

Ajax not refreshing

I am trying to setup a register box to create new account. I am trying to load the html form through ajax and passing data to a php file.
I want to make the div which is containing the form to reload every time when the "register" button is hit to get the result from the php script and display it out. However, my code seems not working properly (The ajax handling div will not load the form ). Below are my codes:
Register.php:
<?php
session_start();
$email = $_POST['email'];
$email = mysql_real_escape_string($email);
$pwd = $_POST['pwd'];
$repwd = $_POST['repwd'];
$lname = $_POST['lname'];
$fname = $_POST['fname'];
$isValidEmail = 1;
if (substr_count($email, '#') != 1){
$isValidEmail = 0;
}
if($pwd != $repwd){ //check if password and re-entered passwords are the same
$_SESSION['error'] = 1;
$_SESSION['message'] = 'Password and Re-entered Password are different.';
} else if( strlen($pwd) < 6 || strlen($pwd) > 64 ) { //check if password is 6 - 64 characters
$_SESSION['error'] = 1;
$_SESSION['message'] = 'Password must be 6 - 64 characters.';
} else if( strlen($email) > 255) { //check if the email is too long
$_SESSION['error'] = 1;
$_SESSION['message'] = 'Email exceeded maximum length.';
} else if ($isValidEmail != 1){
$_SESSION['error'] = 1;
$_SESSION['message'] = 'Invalid Email.';
} else if (ctype_space($lname) || ctype_space($fname)){
$_SESSION['error'] = 1;
$_SESSION['message'] = 'Please enter your name.';
} else {
if ($mysqli = new mysqli("localhost", "root", "", "my_db")){
$stmt = $mysqli->prepare("SELECT email FROM users WHERE email = ?");
$stmt->bind_param('s',$email);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
$stmt->close();
if ($result == $email) { //check if the input email exists in the database, duplicated user
$_SESSION['error'] = 1;
$_SESSION['message'] = 'Email '.$email.' is already used.';
} else {
$hash = hash('sha256', $pwd);
function createSalt()
{
$string = md5(uniqid(rand(), true));
return substr($string, 0, 3);
}
$salt = createSalt();
$hash = hash('sha256', $salt . $hash);
$stmt = $mysqli->prepare("INSERT INTO users ( email, lastName, firstName, password, salt )
VALUES ( ? , ?, ?, ? ,? )");
$stmt->bind_param('sssss', $email, $lname, $fname, $hash, $salt);
if ($stmt->execute()){
$_SESSION['message'] = 'Registered.';
} else {
$_SESSION['error'] = 1;
$_SESSION['message'] = 'Database query error occured.';
}
$stmt->close();
}
} else {
$_SESSION['error'] = 1;
$_SESSION['message'] = 'Error connecting to the database.';
}
}
header("Location: Home.php");
$mysqli->close();
?>
ajax.js:
$(document).ready(function() {
$('#submit_register').click(function(){
$('#register_form').submit( function(){
$.ajax({
type: 'POST',
url : 'Register.php',
data: $('#register_form').serialize(),
success: function () {
var myURL = "Register_form.php#register_div";
$('#ajaxHandle').load(myURL);
return false;
},
});
});
});
});
Register_form.php:
<!DOCTYPE html>
<html lang="en">
<head>
<?php session_start(); ?>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div class="span-23 prepand-top last" id="register_div" style="background:gray;">
<div id="wrapper_register" class="span-21 last" style="padding-top: 20px; padding-left:20px; padding-bottom:20px;">
<form id="register_form" action="register.php" method="post">
<legend class="large">Register</legend>
<?php
if ($_SESSION['message']){
$class = "";
if ($_SESSION['error']){
$class = "error";
} else {
$class = "success";
}
echo "<div class=\"$class span-4 last\">";
echo $_SESSION['message'];
echo "</div>";
unset ($_SESSION['error']);
unset ($_SESSION['message']);
}
?>
<div class="span-23 prepand-top last">
<p>E-mail address: <br>
<input type="text" name="email" maxlength="255" /></p><br>
<p>Last Name: <br><input type="text" name="lname" maxlength="255" /></p><br>
<p>First Name: <br>
<input type="text" name="fname" maxlength="255" /></p><br>
<p>Password: <br>
<input type="password" name="pwd" /><p class="quiet">6 - 64 characters</p><br>
<p>Re-enter Password: <br><input type="password" name="repwd" /></p><br>
<input id="submit_register" type="submit" value="Register" /><br>
</div>
</form>
</div>
</div>
</body>
</html>
I am doing something wrong? Any advice will be appreciated. Thank you very much!
I think I figured it out. I have put the refreshing jquery code in the wrong place. It worked when I put it within the .submit scope:
$(document).ready(function() {
$('#submit_register').click(function(){
$('#register_form').submit( function(){
$.post(
'Register.php',
$(this).serialize()
);
var myURL = "Register_form.php#register_div";
$('#ajaxHandle').load(myURL);
return false;
});
});
});

Categories