How do I display the error messages in signup form? - php

How do I display the error messages (you did not complete all of the required fields and this username is already taken) without going to a new page to display them (like using die instead of echo), while still not continuing the process? In other words, I don't want the user to be sent to a new page to see "you did not...," I want the error to show either below or above the on this page, but I want the error message to disallow the data from being added to the database(the next command, or a couple commands down).
//if submit is clicked
if (isset($_POST['submit'])) {
//then check if all fields are filled
if (empty($_POST['username']) | empty($_POST['password']) | empty($_POST['firstname']) | empty($_POST['MI']) | empty($_POST['lastname']) | empty($_POST['email']) | empty($_POST['phonenumber']) | empty($_POST['country']) ) {
echo('You did not complete all of the required fields. '); }
$username = $_POST['username'];
$password = $_POST['password'];
$usernamesquery = mysqli_query($connection, "SELECT * FROM users WHERE username='$username'");
if(mysqli_num_rows($usernamesquery) > 0) {
echo('This username is already taken. ');
}
} ?>

//if submit is clicked
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$usernamesquery = mysqli_query($connection, "SELECT * FROM users WHERE username='$username'");
//then check if all fields are filled
if (empty($_POST['username']) | empty($_POST['password']) | empty($_POST['firstname']) | empty($_POST['MI']) | empty($_POST['lastname']) | empty($_POST['email']) | empty($_POST['phonenumber']) | empty($_POST['country']) ) {
echo('You did not complete all of the required fields. '); }
elseif(mysqli_num_rows($usernamesquery) > 0) {
echo('This username is already taken. ');
}
else{
echo "code to submit values to database"
}
} ?>

Maybe you wanna use something like this javascript function to check for empty fields and not matching passwords (change variable names accordingly please as I took this from a little project I made):
function signup(){ //Call it on button click
var u = _("username").value;
var e = _("emailAddress").value;
var p1 = _("password").value;
var p2 = _("passwordConfirm").value;
var c = _("country").value;
var g = _("gender").value;
var status = _("status");
if(u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == ""){
status.innerHTML = "Please, fill in every single field in the form...";
} else if(p1 != p2){
status.innerHTML = "The passwords do not match...";
} else if( _("terms").style.display == "none"){
status.innerHTML = "You must view our Terms & Conditions in order to proceed...";
} else { } //Redirect to a page or use Ajax to do other functions your site may need.
Notice var status = _("status");, this is where the messages will be shown on your page, you may want to add something like <span id="status"></span> to your HTML code.
Similarly to check for an available username or email on your database, you can try the following Ajax and Javascript function:
<?php
// Ajax calls this NAME CHECK code to execute
if(isset($_POST["usernamecheck"])){
include_once("php_includes/db_con.php"); //database connection file
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['usernamecheck']); //checks the texfield doesnt have any funny unusual characters
$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1"; //change table name accordingly to yours
$query = mysqli_query($db_con, $sql);
$uname_check = mysqli_num_rows($query);
//This is just some extra conditions if you wish to add
if (strlen($username) < 3 || strlen($username) > 16) {
echo '<strong style="color:#F00;">3 - 16 characters please</strong>';
exit();
}
if (is_numeric($username[0])) {
echo '<strong style="color:#F00;">Usernames must begin with a letter</strong>';
exit();
}
//This if statement will check if the username is ok to use or is taken.
if ($uname_check < 1) {
echo '<strong style="color:#009900;">' . $username . ' is OK</strong>';
exit();
} else {
echo '<strong style="color:#F00;">' . $username . ' is taken</strong>';
exit();
}
}
?>
//////////// Javascript function, these can be on the same php file.
function checkusername(){
var u = _("username").value;
if(u != ""){
_("usernamesats").innerHTML = 'Checking Availability...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("usernamesats").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
}
Notice that for you to see the warnings your username textfield must look like this: <label>Username:</label>
<input id="username" type="Text" onBlur="checkusername()" maxlength="16">
This onBlur="checkusername()" will call the JS function.
and also add somewhere after the texfield this <span id="usernamesats"></span> to display the warnings. This should all do the trick. Oh and you may want to add the Ajax file:
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
somewhere in your js folder (if you have one).
Sorry if this may be a bit long and confusing but it did the work for me, I'm sure there are other ways to do it, just thought these seemed easier to understand for me.
Check this website http://www.developphp.com/list_php_video.php for more info, there are some great tutorials there to get you started with PHP and MySQL, most of this code was done following the tutorials there :) Good Luck!

Related

Why is my else condition being executed twice?

I went through this login system with multi-users. It's working fine since it doesn't allow my status_id users '2' to login (inactive status), but when this happens I get the echo message twice on screen.
What am I doing wrong?
I want to validate both user/password, user_type (admin/user) and user_status (1-active, 2-inactive).
<?php
include 'database/connect.php';
if (isset($_POST["submit"])) {
$email = $_POST["txtemail"];
$pass = $_POST["txtpass"];
$query = mysqli_query($con, "SELECT user_email,user_password,user_type_id, status_id FROM user");
while ($row = mysqli_fetch_array($query)) {
$db_email = $row["user_email"];
$db_pass = $row["user_password"];
$db_type = $row["user_type_id"];
$db_user_status = $row['status_id'];
if ($email == $db_email && $pass == $db_pass && $db_user_status == '1') {
session_start();
$_SESSION["email"] = $db_email;
$_SESSION["type"] = $db_type;
if ($_SESSION["type"] == '1') {
header("Location:admin/home_admin.php");
} else {
header("Location:user/home_user.php");
}
} else {
echo "Ups. Algo de errado aconteceu.";
}
}
}
Looking at your code, if the conditions specified inside the loop fails then the else will execute.
So if your user table holds 3 records and all 3 records doesn't satisfy the condition specified it will execute else statement and 3 times.
This might be the reason.
Well it looks like you are looping through every user inside your user table, so the posted email and password can only be right for one user and for the rest of them your program will go through the else statement

Login count in php

I have a login script I want if user attempt 3 invalid password then the username associated to them would be disabled or blocked for a day / 24hrs.
Since I make a if condition in php login code where status=3 alert your account is blocked for a day.
status is my database column name which count the value of invalid login of user from 1 to 3 maximum.
But issue is my here that is how I make the status automatically count or increase like 1, 2, 3 in user invalid login.
How to I add this function with my login code
I have not idea about that. On YouTube there is not any video regards this even in other website.
Stackoverflow is my last hope where someone helps user.
Please have a look at this question and help to create satatus count automatic when user inter invalid password.
My login PHP is : https://pastebin.com/QpwDtjBg
Thank you in advance
You're gonna want to use PHP's $_SESSION object.
In the code block where you detect bad user/pass combos, add an iterator to the session.
First, add a session entry to the top of your script (Or wherever you define global variables), for bad_logins, and start your session.
session_start();
$_SESSION['bad_logins'] = 0;
Then in the part of your code where you detect a bad login, increment the bad logins by 1.
$_SESSION['bad_logins']++;
This will allow you to then check for bad attempts with an if statement
if($_SESSION['bad_logins'] > 3) {
// Do something here.
}
The script you linked has some other issues you may want to address prior to adding this in though.
You just need to add an update to the field 'status' on the database with 1, 2 or 3, on the IF condition:
if($data == NULL || password_verify($password, $data['Password']) == false) {
And read that same field, when the submit form is sent every single time... if it is already 3, then just skip to the IF condition
if($data['Status'] == "//auto count//")
Something like this (haven't tested the code) and the code should be function based, at least...
`
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
if(isset($_POST['submit'])) {
$messages = array(
'INVALID_EMAIL' => "<div class='alert-box warning error'><span>Invalid format, re-enter valid email.</span></div>",
'ALL_FIELDS_REQUIRED' => "All field is mandatory! case sensitive.",
'VERIFY_EMAIL' => "Please verify your email!",
'INVALID_COMBINATION' => "Invalid username or password combinations.",
'BLOCKED' => "you are blocked for a day. <a href='#'><span>Know why?<span></a>",
);
$msg = "";
$error = false;
$con = new mysqli("localhost", "softwebs_softweb", "test#123", "softwebs_cms");
$email = $con->real_escape_string(htmlspecialchars($_POST['username']));
$password = $con->real_escape_string(htmlspecialchars($_POST['password']));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$msg = $messages['INVALID_EMAIL'];
$error = true;
}
if ($email == "" || $password == "") {
$msg = $messages['ALL_FIELDS_REQUIRED'];
$error = true;
}
if(!$error) {
$sql = $con->query("SELECT * FROM users where Email_ID = '$email' ");
if ($sql->num_rows > 0) {
$data = $sql->fetch_array();
// Blocked
if ($date['status'] === 3) {
$msg = $messages['BLOCKED'];
$error = true;
}
if ($data['isEmailConfirm'] == "0") {
$msg = $messages['VERIFY_EMAIL'];
$error = true;
}
if ($data == NULL || password_verify($password, $data['Password']) == false) {
$msg = $messages['INVALID_COMBINATION'];
$error = true;
// Update the status + 1
$sql = $con->query("UPDATE users SET status = " . $statusData['status'] + 1 . " WHERE Email_ID = '$email' ");
}
}
}
if($error && trim($msg) !== "") {
$msg = "<div class='alert-box error'><span>$msg</span></div>";
} else {
session_start();
$_SESSION['login']=$_POST['username'];
$_SESSION['id']=$data['id'];
header('location: ./account/dashboard.php');
}
}
?>
`

PHP and AJAX Log in validation

I need some help troubleshooting my code that's used for Log In validation. It's a combo of AJAX and PHP.
Here's the AJAX code that's directly in the login page.
<script language="javascript">
$(document).ready(function()
{
$("#login_form").submit(function()
{
$("#msgbox").removeClass().addClass('messagebox').text('Validating....').fadeIn(1000);
$.post("/ajax_login.php",{ user_name:$('#username').val(),password:$('#password').val()
,rand:Math.random() } ,function(data)
{
if (data=='no')
{
$("#msgbox").fadeTo
(200,0.1,function()
{
$(this).html('Incorrect Username or Password.')
.addClass('messageboxerror').fadeTo(900,1);
}
);
}
else if(data=='yes')
{
$("#msgbox").fadeTo
(200,0.1,function()
{
$(this).html('Logging in.....').addClass('messageboxok').fadeTo
(900,1, function()
{
document.location='/mainpage.php';
}
);
}
);
}
else
{
$("#msgbox").fadeTo
(200,0.1,function()
{
$(this).html('User is already logged in.').
addClass('messageboxerror').fadeTo(900,1);
}
);
}
});
return false;
});
$("#password").blur(function()
{
$("#login_form").trigger('submit');
});
});
</script>
PHP CODE:
<?
//Log In credentials
if ($rehash==$dboPW && $user_name == $dboUN && $logged=='Y'){echo "alreadyLogged"; exit;}
if ($rehash==$dboPW && $user_name == $dboUN && $logged=='N')
{
echo "yes";
$_SESSION['login'] = $username;
$_SESSION['password'] = $rehash;
$loggedUpdate=mysql_query("UPDATE Users SET LOGGED='Y' WHERE username='$user_name'");
exit;
}
else
{echo "no";}
?>
To summarize this process, someone logs in and the PHP script checks
if the username and password is valid AND that the person is NOT logged in already - returns value of 'yes'
if the username and password is valid AND that the person IS logged in already - returns value of 'alreadyLogged'
Invalid username or password - returns value of 'no'
This gets passed to AJAX, which SHOULD display the correct messages based on the return values from the php script. For reference (using the above summary):
AJAX should return: Logging in...
AJAX should return: User is already logged in.
AJAX should return: Invalid Username or Password.
The problem is this: If someone logs in correctly and IS NOT already logged in, message 2 appears instead of message 1. (I think that message 1 may appear but it disappears so fast).
I think the culprit is AJAX but unfortunately I'm not as familiar with it as I am with PHP.
I think the problem is with your php code.Your ajax code looks fine
try this
if ($rehash==$dboPW && $user_name == $dboUN && $logged=='Y')
{
echo "alreadyLogged"; exit;
}
elseif ($rehash==$dboPW && $user_name == $dboUN && $logged=='N')
{
}
I think it is the php problem,it occur an error and return the error message. if ajax_login.php does not return "yes" or "no" it will show the second message, whatever it returns.
Just need modify your PHP. try this :
//Log In credentials
// check if post if (isset($_POST)) {
// must initially to use check if on loggin
session_start();
// set variable post
$username = $_POST['user_name'];
$password = $_POST['password']; // change if use sha1 or md5
$rand = $_POST['rand'];
// check query database
$query = mysql_query("SELECT * FROM Users WHERE username='$username' AND password='$password'");
$user = mysql_fetch_array($query);
$row = mysql_num_rows($query);
if ($row > 0) {
if ($user['LOGGED'] == 'Y') {
echo "yes";
$_SESSION['login'] = $username;
$_SESSION['password'] = $rehash;
$loggedUpdate = mysql_query("UPDATE Users SET LOGGED='Y' WHERE username='$user_name'");
exit;
} elseif ($user['LOGGED'] == 'N') { // you can use 'else'
echo "alreadyLogged";
exit;
}
} else {
// invalid value password and username
echo "no";
exit;
} }

PHP IF body and ELSE body both executing

This is a very strange problem.. I've looked all around for a solution..
Here is my code. It is part of an account settings page on a website I am creating. The code has to do with the user changing his first name:
// if there are post vars, user has changed something
if($_POST) {
if(isset($_POST['firstname'])) {
$firstname = trim($_POST['firstname']);
if(strlen($firstname) < 2 || strlen($firstname) > 15) {
$msg = "<span class='errmsg'>Could not complete your request. First name must be between 2 and 15 characters.</span>";
}
else {
// connect to db
require_once('modules/config.php');
// update table
$query = sprintf("UPDATE Users SET FirstName = '%s' WHERE Email = '%s'",
mysql_real_escape_string($firstname),
mysql_real_escape_string($_SESSION['email']));
mysql_query($query);
// set success message
$msg = "<span class='sucmsg'>First name successfully changed.</span>";
// reset the firstname session var
$_SESSION['firstname'] = $firstname;
}
}
}
EDIT: Added the closing brace that Dagon mentioned.
I think you're missing } at the end.
else {
is actually closing:
if(isset($_POST['firstname'])) {
instead of
if(strlen($firstname) < 2 || strlen($firstname) > 15) {
I don't know whether this will solve your problem, try it...
if(in_array(strlen($firstname), range(2, 15)))

validation not appearing

I have 2 problems. First problem is that it comes up with a notice stating roomChosen is undefined, this is a php error, and second of all, it doesn;t show a javascript error if room number in textbox does not match with a room number in database.
Please look at the application here: application
enter in 'info101' in the courseId text box and then click submit. You will see all features in the page. At bottom you will see a "Prepare Questions" button, click it and you will see all validation messages including an empty room textbox below. Now type in a room number such as 42 which is incorrext as it is not in database, if you then click on "Prepare Questions" button again, you will see not message stating room is not valid.
Why is it not working and why am I getting a notice you will see on top?
Below is showing the relevant code in the correct order it is displayed in:
Javascript validation of the room textbox:
function validation() {
var isDataValid = true;
var roomTextO = document.getElementById("room");
var errRoomMsgO = document.getElementById("roomAlert");
if (roomTextO.value == "") {
errRoomMsgO.innerHTML = "Please Enter in a Room Number";
isDataValid = false;
} else if (!trimmedRoomText.length) {
errRoomMsgO.innerHTML = "Please Enter in a Room Number";
isDataValid = false;
//above is if room textbox is empty
} else if(roomTextO.getAttribute("roomthere") == false) {
errRoomMsgO.innerHTML = "This Room is Invalid";
//above is if room number in textbox does not match database, which at moment it isn't working
} else {
errRoomMsgO.innerHTML = "";
}
return isDataValid;
}
PHP code of trying to see if value in room textbox matches value in database
<?php
$username="xxx";
$password="xxx";
$database="mobile_app";
$room_there = true;
$roomresult = mysql_query( "SELECT Room FROM Room WHERE Room = " . (int) $_POST['roomChosen']);
if (isset($_POST['roomChosen'])) {
$roomresult = mysql_query( "SELECT Room FROM Room WHERE Room = " . (int) $_POST['roomChosen']);
} else {
$room_there = false;
}
if( mysql_num_rows( $roomresult ) == 0 ) $room_there = false;
?>
Below is Html of Room Textbox and submit button which is in a tag
<p><input type="text" id="room" name="roomChosen" roomthere="<?php echo $room_there; ?>" />
//message displayed if room number is in database or not
<br/><span id="roomAlert"></span></p>
// submit button
<p><input class="questionBtn" type="button" value="Prepare Questions" name="prequestion" onClick="myClickHandler()"/></p>
Finally below is the javascript handler for the submit button after it is clicked:
function myClickHandler(){
if(validation()){
showConfirm(); // this is a function for a confirmation box
}
}
Below is an edit for one of the answers below on how I am using the isset:
if ($_POST['roomChosen'] [isset()]){
$roomresult = mysql_query( "SELECT Room FROM Room WHERE Room = " . (int) $_POST['roomChosen']);
if( mysql_num_rows( $roomresult ) == 0 ) $room_there = false;
}
1) You need to check if $_POST['roomChosen'] isset() prior to attempting to use it.
2) Try:
roomTextO.getAttribute("roomthere") != 1;
First of all add isset() check for $_POST['roomChosen'].
if (isset($_POST['roomChosen']))
{
$roomresult = mysql_query( "SELECT Room FROM Room WHERE Room = " . (int) $_POST['roomChosen']);
}
else
{
$room_there = false;
}
Use php to get all the room numbers in database,
put them in a JS array.
For example:
<?php
$query = ....
while($data = mysql_fetch_array($query))
$js_var = $data.",";
?>
<script>
var str = <?=$js_var?>;
var myRooms =new Array();
myRooms = str.split(",");
</script>
Now you can use the js to check if the posted value exists in the array or not.

Categories