I have here a register HTML form with some elements. I need to validate the elements on server side and client side and I will explain why. For example, in HTML form I have:
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
User name:<input type="text" name="user_name"/><br/>
Email:<input type="text" name="user_email"/><br/>
Password:<input type="text" name="user_password"/><br/>
</form>
I use PHP to check if the email and user already exists in the database. And I can use PHP to identify if the input fields are empty too.
if (isset($_POST['submit']))
{
$user_name = $_POST['user_name'];
$user_email = $_POST['user_email'];
$user_password = $_POST['user_password'];
$exists = "";
$sql = "SELECT user_name from users WHERE user_name = '{$user_name}' LIMIT 1";
$stmt = $connection->prepare($sql);
$stmt->execute();
$num = $stmt->rowCount();
if ($num == 1)
{
$exists .= "u";
}
$sql = "SELECT user_email from users WHERE user_email = '{$user_email}' LIMIT 1";
$stmt = $connection->prepare($sql);
$stmt->execute();
$num = $stmt->rowCount();
if ($num == 1)
{
$exists .= "e";
}
if (empty($user_name) || empty($user_email) || empty($user_password))
{
echo "<script>alert('Please fill all input fields to register!');</script>";
}
else if($exists == "u")
{
echo "<script>alert('This user is already registered in our system.');</script>";
}
else if($exists == "e")
{
echo "<script>alert('This email is already registered in our system.');</script>";
}
else if($exists == "ue")
{
echo "<script>alert('This user and this email are already registered in our system.');</script>";
}
else
{
//Here insert the values in database
}
}
Looks perfect, except for one thing: when I click submit the page is refreshed and all the input fields values are cleaned. This is bad because the user will have to enter all informations again because something was wrong. I know that the reason for this is because I am validating the form after sending it with PHP. To overcome this problem I need to validate the fields before sending the form, logically using JavaScript in the client side. But how about the check in the database? I will need to use PHP for that. If I did not have to check the database I could use JavaScript only. I would have to mix the validations with JavaScript and PHP, I think for that I should use AJAX, but do not know how.
Personally I would do the check at the client level (javascript) not in php but hey if you insists try this
if ($_POST["password_user"] != $_POST["confirm_password"])
echo "<script>alert('The entered passwords doesn't match. Try again.');
document.getElementByID('inputPassword').value = $_POST['password_user'];
document.getElementByID('inputConfirmPassword').value = $_POST['confirm_password'];
</script>";
Also update your HTML input to have ids
Password:<font color="red">*</font>
<input id="inputPassword" type="password" name="password_user"/><br/>
Confirm password:<font color="red">*</font>
<input id="inputConfirmPassword" type="password" name="confirm_password"/><br/>
Edit:
Added good AJAX tutorial:
without JQuery
with JQuery (I personally find this easier to use)
Edit2:
Sample code for PHP (server side) that returns a JSON to be fed back to the client (javascript)
<?php
$canLogin = false;
$responseArray = array();
// your logic here
// ....
if ($canLogin)
{
$responseArray["status"] = "Success";
} else
{
//Use the appropriate HTTP header (default 200), this is sometimes missed by developers
http_response_code(404);
$responseArray["status"] = "Error";
}
return json_encode($responseArray);
?>
Related
I am trying to use jQuery, AJAX, PHP, and MySQL to check if an email entered into a form already exists in a database.
This is my current jQuery code :
$.post('check-email.php', {'suEmail' : $suEmail}, function(data) {
if(data=='exists') {
validForm = false;
$suRememberMeCheckbox.css('top', '70px');
$suRememberMeText.css('top', '68px');
$signUpSubmit.css('top', '102px');
$tosppText.css('top', '115px');
$suBox.css('height', '405px');
$suBox.css('top', '36%');
$errorText.text('The email has been taken.');
return false;
};
});
And this is my PHP code:
<?php include("dbconnect.php") ?>
<?php
$sql = "SELECT email FROM users WHERE email = " .$_POST['suEmail'];
$select = mysqli_query($connection, $sql);
$row = mysqli_fetch_assoc($select);
if (mysqli_num_rows($row) > 0) {
echo "exists";
}
?>
When I go through with the sign up form, when I use an email already in the database, the error text never changes to what I specified, but instead to some other error cases I have coded. Why is this not working! Thanks so much!
Use This Code: Working Perfectly:
<?php
include("dbconnect.php");
$sql = "SELECT email FROM users WHERE email = '" .$_POST['suEmail']."' ";
$select = mysqli_query($connection, $sql);
$row = mysqli_fetch_assoc($select);
if (mysqli_num_rows($select) > 0) {
echo "exists";
}
?>
If its not changing that means you might have a error with your query. Check developer options on your browser under network. There you can see all ajax calls being made. Click on look at the response. Check to see if there was an error with your query.
Also you have to validate the form submission.
Something like.
if($_SERVER['REQUEST_METHOD'] = 'POST')
{
//maybe send a token over with the form to prevent form spoofing
if($_POST['token'] === $_SESSION['token'])
{
// all your code goes in here
// you provably want to check that is a real email also
// check email input against regular expression
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
//if valid email to variable and escape data
$e = sanitizeString($_POST['email']);
}else
{
/// if not a real email to errors array
$reg_errors['email'] = 'Please enter a valid email address!';
}
}
}
You have to use prepare statements in your queries.
I have a dynamic drop down search bar which searches through the members of a data base inside of a form on my webpage. In order to view this webpage you must log in first. When I built the site on my domain everything works just fine. However when I transferred my files over to a different domain and configed it with an identical database everything works perfect, except my dynamic search in this form. If I type my name (sometime the odd different name with work) in the search everything works fine, but if i type anyone else it seems to stay on the page as it should, but it logs me out and reload the login form on top of everything else including my form I was typing on. I am using jQuery .post() to make the search dynamic. I will provide code below
index.php
<script>
// this is the jQuery function used to post to the search document on key up
function searchUserQ(){
var searchTxt = $("input[name='userSearch']").val();
console.log(searchTxt);
if (searchTxt != '') {
$.post("includes/search.php", {searchVal:searchTxt},
function(output){
$("#userResults").html(output);
});
}
}
</script>
<h1 class="editUser">Edit User</h1>
<form class="editUser" action="index.php" method="post">
<h1>Search For Employee</h1>
<input type="text" name="userSearch" id="userSearch" placeholder="Search For Employee By First Name" onkeyup="searchUserQ();" />
<submit type="submit" />
<div id="userResults">
</div>
</form>
Search.php
<?php
// Connect To Secure Login
$cfgProgDir = '../phpSecurePages/';
include($cfgProgDir . "secure.php");
//These are the includes needed to make the php page run
// this file connects to the database
include("connect.inc.php");
if(isset($_POST['searchVal'])){
// turn that the user searched into a varible
$searchQ = $_POST['searchVal'];
// delete any symbols for security
$searchQ = preg_replace("#[^0-9a-z]#i", "", $searchQ);
$output = "";
$link = "";
$searchArray = array();
$searchIndex = 0;
// Search through these columns inside the main database
$userSearchQuery = mysql_query("SELECT * FROM dealerEmployees WHERE
firstName LIKE '%$searchQ%'
");
// count the number of results
$userCount = mysql_num_rows($userSearchQuery);
if($userCount == 0){
// $output = "There Were No Search Results";
}else{
while($row = mysql_fetch_array($userSearchQuery)){
// define dynamic varibles for each loop iteration
$id = $row['id'];
$firstName = $row['firstName'];
$lastName = $row['lastName'];
$address = $row['address'];
$phone = $row['phone'];
$email = $row['email'];
$password = $row['password'];
$permission = $row['permission'];
$photo = "images/" . $row['profilePhoto'];
$output .= "<li><div class='employeeSearch' style=\"background: url('$photo'); width: 75px; height: 75px\"></div><h6>" . $firstName . "</h6>" . " " . "<h6>" . $lastName . "</h6><a href='#' class='employee' data-firstName='$firstName' data-lastName='$lastName' data-address='$address' data-phone='$phone' data-email='$email' data-password='$password' data-permission='$permission' data-id='$id'>Select Employee</a></li>";
}
}
}
echo $output;
Can you try this?
> "SELECT id, firstName, lastName, address, phone, email, password,
> permission profilePhone FROM dealerEmployees WHERE
> firstName = '".$searchQ."' Limit 1"
Maybe the like condition is giving more than 1 result.
Maybe you could make a select count(id) as id from dealerEmployees where firstName = '".$searchQ."' and check the count with an if clausule. Maybe the problem you have is too many users with the same firstName.
So After some testing i found out what was happening. When the search would load the search results it would change the password variable in the session to the password of the user coming up in the search since both variables had the same name, all I needed to do was change the var name of the password variable in the search results to be different than the sessions password.
Thanks for all the help!!!
Please bear with me; trying my best to learn more Ajax. I am trying to Validate whether the Name of Event field in my form already exists in my table, but only if both were created by the same User. For example, if User 1 already has an event called Event1, the validation would check if there was a duplicate event name ONLY under User1.
I have the following snippet in a PHP/HTML form:
<div>Event Name: </div>
<input type="text" name="eventname" id="eventname" onblur="checkeventname()" onkeyup="restrict('eventname')" size="50" maxlength="75" />
<span id="eventnamestatus"></span>
This is my checkeventname function:
function checkeventname(){
var nameofevent = _("eventname").value;
if(nameofevent != ""){
_("eventnamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "eventcreationpage.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("eventnamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+nameofevent);
}
}
And here is the Ajax I put at the top of the page, which I am having trouble with:
<?php
// Ajax calls this NAME CHECK code to execute
if(isset($_POST["eventnamecheck"])){
include_once("php_includes/db_conx.php");
$eventname = preg_replace('#[^a-z0-9]#i', '', $_POST['eventname']);
$sql = "SELECT id FROM users WHERE eventname='$eventname' && eventcreator='$eventcreator' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$eventname_check = mysqli_num_rows($query);
if ($eventname_check < 1) {
echo '<strong style="color:#009900;">' . $eventname . ' is not a duplicate name</strong>';
exit();
} else {
echo '<strong style="color:#F00;">' . $eventname . ' is an event name already under your name</strong>';
exit();
}
}
?>
The webpage itself has the user variable carried over (eventcreationpage.php$eventcreator=User1) I am trying to send over the $eventcreator variable, which would be the User in this case, but I'm not quite sure how to do so.
Set
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
to show that this request will send form data. Next, on your server, you may use $_POST["userid"] to get the userid if you specified it via
ajax.send("userid=" + userid);
To send both userid and eventid, you may use
ajax.send("userid=" + userid + "&eventid=" + eventid);
If you get the userid only from PHP, you could render it into script. That would look like this:
ajax.send("userid=<?php echo $eventcreator; ?>&eventid=" + eventid);
which injects the user's name into the string. Make sure it is properly escaped though, if you allow special characters for user names though.
I have a simple JavaScript function that will not allow a form to be submitted if all the fields are not filled out. On top of that I would like PHP to write out an error message next to just the fields that are empty. The problem is the function activates upon the $_POST and yet my JavaScript function will not allow for $_POST to occur as long as one of the fields are empty.
If I keep the action outside of the $_POST condition then the page will load with the error message already showing. I am fairly new to PHP and JavaScript and would like any insight on perhaps another available condition that I could use to trigger my error messages to appear in my form. I am also open to any other suggestions for error handling. I do prefer to keep my JavaScript present due to it's ability to keep the form from being submitted if it is not properly filled. Unless there is another way to take that action then I have to keep the JavaScript.
PHP:
function cleanCrew ($id, $pswrd) {
$id = stripslashes($id);
$pswrd = stripslashes($pswrd);
$id = strip_tags($id);
$pswrd = strip_tags($pswrd);
return array($id, $pswrd);
}
require_once 'dbServ.php';
$db_server = mysqli_connect($db_host,$db_user,$db_pass,$db_base);
if ($db_server) {
$error_1 = "";
} else{
$error_1 = "connection to database unsuccessful";
}
$error_2 = "";
$error_3 = "";
if ($_POST) {
$user_id = mysqli_real_escape_string($db_server, $_POST['userId']);
$user_pass = mysqli_real_escape_string($db_server, $_POST['pass']);
$id_and_pass = cleanCrew($user_id, $user_pass);
if ($user_id == "" || $user_id == null) {
$error_2 = "please fill in proper User Id";
} else{
$error_2 = " ";
}
if($user_pass == "" || $user_pass == null){
$error_3 = "please fill out password";
} else{
$error_3 = " ";
}
echo $id_and_pass[0];
echo $id_and_pass[1];
}
HTML:
<div id="intro">
<h1 id="the_blog" align="center">The <span id="blog_animate" style="position:relative;">Blog</span></h1>
<div id="log-in"><p id="log">Log In</p><br> <?php echo $error_1; ?>
<form action="blog.php" method="post" onsubmit="return checkForm(this)" name="form1">
<p id="log">User ID :</p> <input type="text" placeholder="johnnyApple175" name="userId"></input><?php echo $error_2 ?><br>
<p id="log">Password:</p> <input type="password" name="pass"></input><?php echo $error_3; ?><br>
<input type="submit" value="submit" class="button" ></input>
</form>
First:
It's always a very good idea to validate the data server side, like you're doing.
Reason is simple: Javascript is client-side and can easily be modified to e.g. bypass those checks. Also, good that you escaped the sent data prior using it in the Database query.
Your problem is, that you're checking for $_POST to exist - it always exists, it's a super global var. You actually want to check if it's empty:
if (!empty($_POST))...
You might want to think over it, if you really want to give detailed information what exactly was wrong. Giving more info is more user friendly, but it makes attacks easier, especially if you don't block the user after X retries.
i have created a signup form which is validated by both javascript and php.Whenever any javascript form validation error occur such as username is required,it is displayed beside the form,But when any php validation error occur such as username already exist,it is displayed on another link.How can i display php validation errors beside the form?
<?php
include('configdb.php');
if(isset($_POST['submit']))
{
checks if the username is in use
if (!get_magic_quotes_gpc()) {
$_POST['username'] = addslashes($_POST['username']);
}
$usercheck = $_POST['username'];
$sql1 = "SELECT username FROM users WHERE username = '$usercheck'";
$result1 = mysqli_query($mysqli,$sql1) or die(mysqli_error());
//if the name exists it gives an error
if (mysqli_num_rows($result1) != 0) {
die('Sorry, the username '.$_POST['username'].' is already in use.');
}
}
Another option if you don't want to use ajax. It can be done with php but user need to reload the page to see error.
To do this, html form code and php validation code must be placed at the same file.
<?php
$error = false;
if(isset($_POST['submit'])){
// your validation
// if something wrong
$error = true;
}
?>
<form action="validation_checking.php" method="post">
<?php
if($error)
{ echo '<p style="color:red;">Sorry, the username '.$_POST['username'].' is already in use.</p>'; }
?>
<input type="text" name="username">
<input type="submit" value="submit">
</form>
You must use ajax to execute php functions without refreshing the page.
Read this