I created a login page connected to a database. However, in order to give a message, I used alert. Now, upon loading the page i immediately get an 'Invalid Username' alert. I want the alert to appear only after the Login Button is pressed.
Also, upon pressing the Login Button, the page goes blank and then the alert appears and then on clicking OK, the html page loads. How do I get the alert on the same page.
The file: login.php
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<form id="Form" method="post">
<input id="Username" name="Username" type="text" placeholder="Username"><br>
<input id="Password" name="Password" type="password" placeholder="Password""><br>
<button id="Button" name="Login" type="submit">Login</button><br>
</form>
</body>
</html>
<?php
$conn=mysqli_connect ('localhost','root','','test');
$uname=$_POST['Username'];
$passw=$_POST['Password'];
$check=mysqli_query($conn,"select Username from members where Username='$uname' and Password='$passw'");
if(mysqli_num_rows($check)==1)
{
echo "<script>alert('Login Successful');</script>";
}
else
{
$check=mysqli_query($conn,"select Username from members where Username='$uname'");
if(mysqli_num_rows($check)==1)
{
echo "<script>alert('Invalid Password');</script>";
}
else
{
echo "<script>alert('Invalid Username');</script>";
}
}
?>
It might be harsh for such a seemingly small thing, but the solution here is to use AJAX. Assuming you dont know AJAX, I'd recommend you to learn it, after using this solution.
You also need jQuery for this.
First off, you need to include put the PHP part in another file, lets say: login.php:
<?php
$conn=mysqli_connect ('localhost','root','','test');
$uname=$_POST['Username'];
$passw=$_POST['Password'];
$check=mysqli_query($conn,"select Username from members where Username='$uname' and Password='$passw'");
if(mysqli_num_rows($check)==1)
{
echo json_encode(array("msg"=>"Login Successful"));
}
else
{
$check=mysqli_query($conn,"select Username from members where Username='$uname'");
if(mysqli_num_rows($check)==1)
{
echo json_encode(array("msg"=>"Invalid Password"));
}
else
{
echo json_encode(array("msg"=>"Invalid Username"));
}
}
?>
Next you'll make a JS file:
$('#form').submit(function(event) {
$.ajax({
method: "POST",
url: "login.php",
data: $("#form").serialize()
})
.done(function( data ) {
alert(data['msg']);
});
}
Sorry if I missed a part but there's a lot to do and learn for you to understand this at all.
Because the PHP is server side code, you are loading the value mysqli_num_rows($check)==1, before your page has been presented to the user, so therefore, no credentials have been entered. If you want to perform an action on the button click, you need to use client side code, such as javascript. Here is a simple solution I have created for you.
This is your "index.php" page where the login form is:
<html>
<head>
<title>Please login</title>
</head>
<body>
<input id="Username" name="Username" type="text" placeholder="Username"><br>
<input id="Password" name="Password" type="password" placeholder="Password""><br>
<button id="Button" name="Login" onclick="checkCredentials();">Login</button><br>
<script type="text/javascript">
function checkCredentials(){
var username = document.getElementById('Username').value; //Get the text from username field
var password = document.getElementById('Password').value; //Get the text from password field
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//Make your alert
var response = JSON.parse(this.responseText);
if(response.status == 200){
alert(response.alert);
/**
* Here, put whatever else you want to do when login is successful!
* My best guess is that you'd redirect the user to a page where a new
* PHP session is started. If you need help with this, please ask :)
**/
} else {
//Login has failed, display the response message
alert(response.alert);
}
}
};
//We're sending the password in plaintext over a GET request. I've done this for simplicity.
//You should NOT send the password in plaintext on the production system. Doing this is insecure. Hash it before you send it.
request.open("GET", "login.php?username="+ username +"password=" + password, true);
request.send();
}
</script>
</body>
</html>
Now that you have your login page created, you can make the login.php page, which is a backend script for checking login details.
<?php
$loginStatus = array("status" => 403, "alert" => "forbidden");
$conn=mysqli_connect ('localhost','root','','test');
$uname=$_GET['username'];
$passw=$_GET['password'];
//Don't use this line in production, you should use a prepared statement instead
$check=mysqli_query($conn,"select Username from members where Username='$uname' and Password='$passw'");
if(mysqli_num_rows($check)==1)
{
$loginStatus = array("status" => 200, "alert" => "Login Successful!");
}
else
{
$check=mysqli_query($conn,"select Username from members where username='$uname'");
if(mysqli_num_rows($check)==1)
{
$loginStatus = array("status" => 403, "alert" => "Invalid Password!");
}
else
{
$loginStatus = array("status" => 403, "alert" => "Invalid Username!");
}
}
echo json_encode($loginStatus);
?>
The code explained:
On your "index.php" there is a peice of javascript which makes a request (in the background) to your auth page (login.php). Login.php returns a JSON array containing information on the login, if it was successful or not, as well as a message which gets displayed in a javascript alert();
What's a prepared statement?
A prepared statement is a database query that works with parameters rather than the values directly. This is much more secure and will help prevent SQL injection to your database. See this question for more info how to do it (stack overflow link)
You only want that PHP to run if the form is submitted. So wrap all your PHP code in an if condition.
if (!empty($_POST)) { .... rest of php code here ... }
Related
I'm just a PHP starter and now I want to learn JQUERY, on my learning process I practice on validating inputs usually I validate my inputs using a pure PHP code only and every time I validate the inputs the page reloads and now I want to improve in doing things I found some articles like http://api.jquery.com/jQuery.ajax/, http://api.jquery.com/jQuery.post/ (can't post other links) but I am more confused because they have different approach and I want to use the approach from the JQUERY tutorial but I haven't found any good tutorials and there is no tutorials on JQUERY's site that is using a database, usually I code like this:
<form method="post">
<label for="Username">Username:</label>
<input id="Username" type="text" name="username">
<?php
session_start();
if(isset($_SESSION['msg'])){
$msg=$_SESSION['msg'];
echo '<label for="Username">'.$msg.'</label>';
?>
<input type="submit" name="reg">
</form>
<?php
if(isset($_POST['reg'])){
$result=//check username from database here
if($result){
$_SESSION['msg']='username not available.';
}
else {
$_SESSION['msg']='username available.';
}
}
?>
Now I want to learn how can I validate inputs directly from the database without reloading the page? I don't know where should I start, what to add in my code. Any help, advice or suggestions will be really a big help for me :)
first, in your form add a onSubmit function
<form name='myform' type='POST' action='http://www.action.fr' onSubmit="return check_form()">
you can do this in ajax like that
function check_form()
{
var user = $('#Username').val(); // Username is the id of your input
var password = $('#password').val(); // password is the id of your input
$.ajax(
{
type:"POST", // or get as you want
url:"myfile.php", // it is the php file which can do the job
data: "user="+user+"&password="+password, // the param to send to your file,
success:function(msg)
{
;// msg is the result of your 'myfile.php', everything you write is in the msg var
}
});
}
in your php file you can get your data like this :
$user = $_POST['user'];
$password = $_POST['password'];
// if your type is get then use $_GET instead of $_POST
tell me if you have any problem with my code.
Write your validation script as though you're expecting a page refresh. Instead of outputting error messages, put them in a JSON array and print the JSON data. Then call the script from the AJAX function. It's really that simple.
<?php
// validate.php
$sampleInput_number = isset($_POST['sampleInput_number']) ? $_POST['sampleInput_number'] : "";
$errors = array();
if (trim($sampleInput_number) == "" || !is_numeric(trim($sampleInput_number)) {
$errors[] = "SampleInput_number must be a number!";
}
// sample input must also match a value from the database
if (!matchesDBValue($sampleInput_number)) {
$errors[] = "SampleInput_number must match a value from the database!";
}
function matchesDBValue($value) {
$retval = false;
// compare to db values here...
return $retval;
}
echo json_encode($errors);
Your form would look something like this:
<form action="" method="post" id="theForm">
<input type="text" name="sampleInput_number" id="sampleInput_number" />
<input type="button" id="formSubmit" value="Submit" />
</form>
And your javascript would look like this:
<script language="javascript" type="text/javascript">
$(#formSubmit).on("click", function() {
$.post("validate.php",
{
sampleInput_number: $("#sampleInput_number").val()
}, function(data) {
// check returned json data
// perform action based on results
if (no_errors) {
$("#theForm").submit();
}
}, "json"
);
});
</script>
Here I am trying to check that username input is available for the user or not. I am doing it in codeigniter.
Here is my view page:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<style type="text/css">
.no{color:red;}
.yes{color:green;}
</style>
<script>
$(document).ready(function(){
// unique user name checking ------------- starts here----------------
$("#username").blur(function(){
var form_data= {
action : 'check_username',
username : $(this).val
};
$.ajax({
type: "POST",
url : "check_unique_username",
data : form_data,
success : function(result) {
$("#message").html(result.message);
alert(result);
}
});
});
// unique username checking -------------- ends here-----------------
});
</script>
</head>
<body>
<form class="RegistrationForm" id="RegistrationForm" method="POST" action="">
<label for="username">User Name</label>
<div>
<input id="username" name="username" size="25" class="required" />
</div>
<input type="button" id="button1" name="button1" value="check availability" />
<div id="message"></div>
</form>
</body>
here is my controller code :
<?php
class Registration extends MX_controller {
function index(){
$this->load->view('registrationPage'); // this will load the registration page.
}
function unique_username() {
$action = $_POST['action'];
if($action=='check_username'){
$u = $this->input->post('username');
$users=array("jhon","neo","margo","hacker","user123");
if(in_array($u,$user)) {
echo json_encode(array('message' => "It is not available!"));
}
else {
echo json_encode(array('message' => "It is available!"));
}
}
}
}
?>
But my code is not working, where I am getting wrong,please help me out..showing only it is available for every username
Edited : I have changed my controller code...
You have not used # while using the id of the div, so use:
$("#message").html(result);
instead of $("message").html(result);
EDIT: An updated answer to an updated question.
It's actually pretty stupid none of us could see it, but the problem is this string: username : $(this).val. The reason is that .val is not jQuery's method that get's the value of a text field, it should be username : $(this).val() (with brackets).
This covers the first JS part, the next problem is a typo, you have url : "check_unique_username",, but it should be url : "registration/unique_username", (didn't have controller name, and had unnecessary check_ prefix while in controller the method was without it).
Next typo is in PHP - if(in_array($u,$user)) {, but we have an array $users, so change this to if(in_array($u,$users)) {, so PHP would not throw a notice.
Next problem is the missing line dataType: 'json', in AJAX request. We must put it so that JS could know what data type we are receiving and parse it in a correct way.
After that it should work. But I have some suggestion for you. Change the PHP, so that it would return not strings, but a boolean value. For example - true, if it's available, false if it's not.
if(in_array($u,$users)) {
echo json_encode(array('message' => false));
} else {
echo json_encode(array('message' => true));
}
That way it would be easier to manipulate this data in your JS code. For example you could add this code to the success part of your AJAX request:
success : function(result) {
if(result.message) {
$("#message").html("It's available!");
$("#button1").removeAttr('disabled');
} else {
$("#message").html("It's not available!");
$("#button1").attr('disabled','disabled');
}
}
And you will have your submit button enabled/disabled. This will make sure a normal user would not be able to submit the form if he entered a username that is taken.
Also I would change the event blur to keyup, that way you will have faster updates, but it's a bit more heavy on the server. Problem with blur event is that your user could fill the username and click on the button anyway, because blur event fires only after the user leaves the element.
Hope this helps!
I've a index.php for login users, and when press submit the following process occurs ...
1.- The user enters a number and password
2.- jQuery.ajax method is used () to connect to the file doLogin.php to process the data and if correct, print "echo 'success'" and make these variables sessiĆ³n: nControl , name, lastname, and typeUser
3.- Then in the method jQuery.ajax () takes "success" and makes a call to dashboard.php thus: "document.location.href = 'dashboard.php'"
Basic structure: Index.php (for login) --> functions.js (process inputs of index.php with jQuer.ajax()) --> dashboard.php(i want receive data from index.php to displa details user)
So the question that arises is:
That method would be best for you, after success in jQuery.ajax method () that sends data to the file dashboard.php? Because such data as name, lastname, typeUser and nControl, I want to print and a div for the user to see the details of your login.
Maybe I can be in JSON format but not how. I hope I have explained!!
// take username and password on button click
$('#submit').on('click', function(e) {
e.preventDefault();
var uname = $.trim($('input[name="username"]').val()),
password = $.trim($('input[name="password"]').val());
if(uname.length && password.length){ // checking that username and password not empty
$.ajax({
url : 'doLogin.php',
data: {username: uname, password: password},
dataType: 'json', // if you get response from server as json
success: function(response) {
// receive the response as json object
if(response.status == 'success') {
alert('You have been successfully authenticated');
/**
* assume that you get other
* data with response
*/
var name = response.name,
lastname = response.lastname,
typeUser = response.typeUser,
nControl = response.nControl;
// make navigation to dashboard.php with data you've got using GET method
// you may have need to location url as you need
window.location = 'dashboard.php?name=' + name + '&lastname=' + lastname + '&typeUser=' + typeUser + '&nControl=' + nControl;
} else {
alert('Error is authentication..');
}
}
});
} else {
// make alert if username or password not provided by user
alert('Please enter password and username both.');
}
});
Didnt have time to test. I dont have php on test server. You'll need the jquery.form.js plugin for JQuery.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
<script type="text/javascript">
$('#loginbutton').click(function(){
$('#error').empty();
$('#loginform').ajaxForm(function(data, textStatus){
$('#error').append(data);
});
});
</script>
<div id="error"></div>
<form id="loginform" method="post" action="login.php">
<input type="text" name="username" />
<input type="password" name="password" />
<button id="loginbutton">Log In</button>
</form>
On login.php page check against database for correct username and password (my php is a little rusty)
$connect = mysql_connect("$server","$username","$password") or die("not connecting");
mysql_select_db("users") or die("no db :'(");
$query = mysql_query("SELECT * FROM $tablename WHERE username='$user' AND password='$password'");
$numrows = mysql_num_rows($query);
if ($numrows!=0)
{
//if row returned send them to home page
<script type="text/javascript">
window.location.replace("dashboard.php");
</script>
}
else
//If not correct login then the error div reports this message
echo "Incorrect Login Information";
}
I have the following ajax call
$.ajax(
{
type: "POST",
url: "Utilities/CheckUsername.php",
data: "un="+ un,
success: function(data)
{
if(data!=1)
{
$('#mike').html(data);
return false;
}
}
});
I want the page to stay if the username is taken, else redirect to whats in the action attribute of the for.
Obviously this isn't working. But why? I would like to not use preventdefault, so that I could get a better understanding of where the problem and solution is.
EDIT:
The server code
<?php
$seed = 'n48sma94r98';
$email = $_POST['un'];
$mysqli = new mysqli('localhost','uml','uml','uml');
if (!$mysqli)
{
printf("Can't connect to MySQL Server. Errorcode: %s\n", mysqli_connect_error());
exit;
}
$query = "Select User_Email as Email from user2 where User_Email = AES_ENCRYPT('$email','$seed') ";
$result = $mysqli->query($query);
if($result->num_rows > 0)
{
echo "1";
}
else
{
echo "2";
}
?>
The entire form minus the meta:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Untitled</title>
<link rel="stylesheet" type="text/css" href="my.css">
<script type="text/javascript" src="Resources/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript">$(document).ready(function(){
$("#login").submit(function() {
var un = $('#username').val();
$.ajax(
{
type: "POST",
url: "Utilities/CheckUsername.php",
data: "un="+ un,
success: function(data)
{
if(data!=1)
{
$('#mike').html(data);
return false;
}
}
});
});
});
</script>
</head>
<body>
<form name="login" id="login" method="post" action="dsds.html">
UserName<input type="text" name="username" id="username"value="">
Password<input type="text" name="password" id="password" value="">
Password Again<input type="text" name="passwordagain" id="passwordagain" value="">
<input type="hidden" name="NewClass" id="NewClass" value="true">
<input type="submit" name="submit" id="submit" value="submit">
</form>
<span id = "mike"></span>
</body>
</html>
Some advice. Name your variables and methods. What is 'un' and 'data'? What do they contain?
Also what type of data is returned? String, HTML, XML, JSON?
If you want to redirect you can use window.location = 'someURL';
To send a form you can do this: $('#form-id').submit();
You could return more meaningful messages, like usernameExists,usernameFound or usernameNotExists,usernameNotFound. Even if you are the only one working on this project, when you go around and ask for help, peeps need to understand your code. It should read like sentences.
I suppose you use
if(data!=1)
to see of the username was taken or not?
Did you try to see the value of data using some sort of a debugger? (or even an alert()).
As I suppose you are not sending a 1 from the server when the username is already taken...
I usually use OK as response indicator (or whatever you call that). If the response (your data) starts with OK it's positive, otherwise the entire message is the error:
In Javascript:
success: function(response) {
if ( 'OK' == response.substr(0, 2) ) {
// Okay, so show something green or do nothing
var message = response.substr(2); // Everything after "OK"
}
else {
// Not okay, so show something red or redirect
var goto = response;
// The entire response message `response` is the target destination
// If you don't want PHP to define the redirect location, just hard code it right here
window.location = goto;
}
}
And in PHP:
$result = $mysqli->query($query);
$usernameExists = $result->num_rows > 0; // A nice boolean
exit( $usernameExists ? '/error.html' : 'OKThis username is fine' );
PS. The return false in the success function does nothing. You can omit that.
edit
Without changing the PHP:
success: function(response) {
if ( '1' !== response ) {
window.location = 'error.html';
}
}
Since response is a string, I'd check for that (and not a number). And it never hurts to check for identicallity (===) instead of equality (==).
I have a simple input form on my site for people to enter in information for submission. The code looks like this in the case they do not enter anything:
this is form.php
if ($_POST['q']) == NULL ){
echo "Please enter your information"
The code works great, but it sends the user to form.php with the echo, where I want this to be echoed on my main page index.html right below the input box - basically so it doesn't navigate away from the page. Is this doable in php or will I need some javascript. I would have searched for ways to do this but I don't know what this method is called.
Thanks!
dont set a action in the url and it will submit to its self, if that still wont work you will need rewrite rules.
If you don't want to navigate away from the page you will need to use Javascript. Add a onSubmit to the form, and then let the function you call there return false, if the input is not complete and the form should not be submitted.
you can make it postback to itsself and then redirect the page to post.php?q=value if there is a value else echo below the input field.
<?php
$qisempty = false;
if(!empty($_POST['q']))
{
header("Location:http://../post.php?q=".$_POST['q']);
}
else
$qisempty = true;
?>
<input name="q" type="text">
<?php if($qisempty) echo "Please enter your information";?>
You can use AJAX for this thing. AJAX is great for this type of problems when you don't want to reload pages to do task in specific place or Div of HTMLpages.
For your problem, You need to create a HTML file with your form in it, and submit it via AJAX. and get your response via same AJAX.
<script type="text/javascript">
function submit_ajax(val1,val2,param1,param2,subfile){
var http = new XMLHttpRequest();
var url = subfile;
var params = val1+"="+param1+"&"+val2+"="+param2;
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
//Remove the alert and use whatever you want to do with http.responsetext like
// document.getElementById("YourDiv").innerHTML=document.getElementById("YourDiv").innerHTML +http.responsetext
}
}
http.send(params);
}
</script>
</head>
<body>
<form>
<input type="text" id="user" value="user" name="user" />
<input type="password" id="password" value="pass" name="pass" />
<button onclick="submit_ajax(user.name,password.name,user.value,password.value, "submit_file.php");">Submit</button>
</form>
<div id="YourDiv">
<!--Something appears here after callback-->
</div>
This was the first page. Now Use your script in your PHP file(probably, submit_file.php) as you want and then echo the text you want in your div by validation or something.. a sample would be
<?php
$username=$_POST['user'];
$password=$_POST['pass'];
if(validateuser($username,$password)){
if(checkuserpass($username,$password){
echo "You were successfully logged in!";
}
echo "Sorry Username/Password Mismatch";
}
else {
echo "There was an error in your input!Please Correct";
}
?>
Hope you got what you wanted...
The simplest way would be assigning the error message to a variable called (e.g $errorMsg)
the printing it on page using a echo or print function.
<?php
if ($_POST['q']) == NULL ){
$errorMsg =' Please enter your information';
}
?>
Place this code where you want the error to appear
<? print $errorMsg; ?>