I am currently working on a PHP based web-interface, with a login system.
But for some reason when I hit login, it seems to get to the login.php and return a response back.
But the thing is, the response is not what I need to have, and furthermore logging in is still not happening.
The HTML based login form (Within a modal):
<form class="form" method="post" action="<?php echo Utils::resolveInternalUrl('backend/Login.php') ?>" id="loginForm">
<div class="form-group">
<label for="loginUsername">Username:</label> <input type="text" class="form-control" name="loginUsername" id="loginUsername" />
</div>
<div class="form-group">
<label for="loginPassword">Password:</label> <input type="password" class="form-control" name="loginPassword" id="loginPassword"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Login</button>
</div>
</form>
Javascript/jQuery related to login:
var form = $('#loginForm');
form.submit(function (e) {
e.preventDefault();
$.ajax({
'data': form.serialize(),
'type': $(this).attr('method'),
'url': $(this).attr('action'),
'dataType': 'JSON',
success: function (data) {
alert("Success: " + data)
},
error: function (error) {
alert("Error: " + error)
}
})
})
PHP backend, related to login:
if($_SERVER['REQUEST_METHOD'] == "POST") {
$database = Database::getDefaultInstance();
if(isset($_POST['loginUsername']) && isset($_POST['loginPassword'])) {
$connection = $database->getConnection();
$username = $_POST['loginUsername'];
$password = $_POST['loginPassword'];
echo $username . ":" . $password;
$stmt = $connection->query("SELECT * FROM banmanagement.users;");
if($stmt->fetch()) {
session_start();
$_SESSION['username'] = $username;
$_SESSION['sessionId'] = Utils::randomNumber(32);
echo json_encode("Successfully logged in as ${username}.");
exit;
} else {
echo json_encode("No user exists with the name \"${username}\".");
exit;
}
} else {
echo json_encode("Username and/or password is not provided.");
exit;
}
} else {
echo json_encode("Submit method is not POST.");
exit;
}
The result of it:
Click here for screenshot
Edit:
Changed SQL query to: SELECT COUNT(*) FROM banmanagement.users WHERE username=:username;
Edit 2:
Per suggestion, I have used var_dump the output var_dump($_POST) is: array(0) { }.
$stmt = $connection->query("SELECT * FROM banmanagement.users;");
I'm assuming you're using PDO on the backend. If so, you don't need the semicolon in your query. That's why your fetch is failing.
$stmt = $connection->query("SELECT * FROM banmanagement.users");
Ok, so that wasn't it. I was reading the wrong braces. Have you tried var_dump($_POST) to see what, if anything, is being sent?
Related
I'm checking this form for errors using PHP code which is on the same index.php file:
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<?php if(!empty($formErrors)){ ?>
<div id="errors">
<?php
foreach($formErrors as $error)
{ echo '* ' . $error . '.<br/>';}
?>
</div>
<?php } ?>
<input type="text" name="firstname">
<input type="submit" value="send">
</form>
The PHP code is as follows:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$fname = $_POST['firstname'];
$formErrors = array();
if(strlen($fname) < 2 ){
$formErrors[] = "First name must be longer than 1 character";
}
}
?>
Everything is working fine up to this point, except that I want to prevent the page from scrolling to the top upon form submission. Therefore i used ajax to solve this problem:
$("form").submit(function(e){
e.preventDefault();
$.ajax({
type: $(this).attr("method"),
url: $(this).attr("action"),
data: $(this).serialize()
});
});
Now the form errors won't display anymore, which is not what I want. How can I show the errors again while not discarding ajax? Thanks.
Although this isn't the best way, you can echo the JSON from the file and display those errors in your ajax function like below:
FrontEnd(ajax):
$("form").submit(function(e){
e.preventDefault();
$.ajax({
type: $(this).attr("method"),
url: $(this).attr("action"),
data: $(this).serialize() + '&ajax=1',
dataType:'json',
success: function(res){
if(res.success === false){
$('#errors').html('<ul><li>' + res.errors.join('</li><li>') + '</li></ul>');
}else{
$('#errors').html('');
}
}
});
});
Backend:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$fname = $_POST['firstname'];
$formErrors = array();
if(strlen($fname) < 2 ){
$formErrors[] = "First name must be longer than 1 character";
}
// add this additional check
if(($_POST['ajax'] ?? 'N/A') == '1'){
echo json_encode(['success' => false,'errors' => $formErrors]);
exit; // since we will only send the JSON back to the browser, not the entire form
}
}
?>
Change your form code to this(adding a errors div always by default):
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<div id="errors"></div>
<input type="text" name="firstname">
<input type="submit" value="send">
</form>
I have never worked with $_COOKIES, and now I've been given the task to make it work.
I have been following a couple of tutorials online.
Found here: http://www.phpnerds.com/article/using-cookies-in-php/2
And then here:https://www.youtube.com/watch?v=Dsem42810H4
Neither of which worked for me.
Here is how my code ended up. I shortened it as much as I could.
Starting with the index.php page, which contains the initial login form:
<form role="form" action="index.php" method="post" id="loginForm" name="loginForm">
<input type="text" class="form-control" id="username" name="username"
value="<?php if(isset($_COOKIE['username'])) echo $_COOKIE['username']; ?>" />
<input type="password" class="form-control" id="password" name="password"
value="<?php if(isset($_COOKIE['password'])) echo $_COOKIE['password']; ?>"/>
<button type="button" id="loginSubmit" name="loginSubmit" class="btn btn-primary btn-block btn-flat">Sign In</button>
<input type="checkbox" id="rememberme"
<?php if(isset($_COOKIE['username'])){echo "checked='checked'";} ?> value="1" />
</form>
Here is the JavaScript used to send the form values:
$('#loginSubmit').on('click', function()
{
var username = $('#username').val();
var password = $('#password').val();
var rememberme = $('#rememberme').val();
// skipping the form validation
$.post('api/checkLogin.php', {username: username, password: password, rememberme:rememberme}, function(data)
{
// the data returned from the processing script
// determines which page the user is sent to
if(data == '0')
{
console.log('Username/Password does not match any records.');
}
if(data == 'reg-user")
{
window.location.href = "Home.php";
}
else
{
window.location.href = "adminHome.php";
}
});
});
Here is the processing script, called checkLogin.php. This is where I attempt to set the $_COOKIE:
<?php
include ("../include/sessions.php");
if(isset($_POST['username']) && isset($_POST['password']))
{
$username = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['username'])));
$password = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['password'])));
$rememberme = $_POST['rememberme'];
$select = "SELECT username, fullname, password FROM users WHERE username = '".$username."'";
$query = mysqli_query($dbc, $select);
$row = mysqli_fetch_array($query);
$dbusername = htmlentities(stripslashes($row['username']));
$dbfullname = htmlentities(stripslashes($row['fullname']));
$dbpassword = htmlentities(stripslashes($row['password']));
if(password_verify($password, $dbpassword))
{
// setting sessions here
$_SESSION['username'] = $username;
$_SESSION['fullname'] = $dbfullname;
// here is where I attempt to set the $_COOKIE
if(isset($remember))
{
setcookie('username', $_POST['username'], time()+60*60*24*365);
setcookie('password', $_POST['password'], time()+60*60*24*365);
}
else
{
setcookie('username', $_POST['username'], false);
setcookie('password', $_POST['password'], false);
}
echo $username; // this gets sent back to the JavaScript
mysqli_free_result($query);
}
else
{
// username/password does not match any records
$out = 0;
echo $out;
}
}
?>
So now that I have attempted to set the $_COOKIE, I can try to print it to the home page, like so:
<?php echo 'cookie ' . $_COOKIE["username"]; ?>
To which does not work, because all I see is the word 'cookie'.
Besides that, when I log out, I am hoping to see the login form already filled out, which is the overall task I have been trying to complete, but have been unsuccessful at doing so.
I have this "register users" file in which I have a form, I'll simplify in here what I have:
<form action="" method="POST">
<label for="user" class="control-label">User </label>
<input type="text" name="user" class="form-control" id="user" value="" required=""/>
<label for="user" class="control-label">Password1 </label>
<input type="text" name="password1" class="form-control" id="password1" value="" required=""/>
<label for="user" class="control-label">Password2 </label>
<input type="text" name="password2" class="form-control" id="password2" value="" required=""/>
<button type="button" value="signUp" name="submit" class="btn btn-lg btn-primary btn-block" onClick="register()">Sign up!</button>
As you can see, there is an event in there, in a JS file. This file has all the vaidations of the inputs and it works just fine (I don't think it's relevant, so I won't post it). It also has the AJAX call to the PHP file that will insert the data into the database.
function register(){
if(validationRegister()){
$.ajax({
url: "http://localhost/myProject/extras/processSignUp.php",
type: "POST",
data: {"user": user,
"password": password,
"password2": password2,
},
dataType: "html",
cache: false,
beforeSend: function() {
console.log("Processing...");
},
success:
function(data){
if(data == "Registered"){
window.location.href = "http://localhost/myProject/index.php";
}else{
window.location.href = "http://localhost/myProject/signUp.php";
}
}
});
}else{
alert("Incorrect data");
}
}
And this is the PHP file:
<?php
include_once "connection.php"; --> this has all the data for the connection to the database
if($_POST['user'] == '' || $_POST['password'] == '' || $_POST['password2'] == ''){
echo 'Fill all the information';
}else{
$sql = 'SELECT * FROM `user`';
$rec = mysqli_query($con, $sql);
$verify_user = 0;
while($result = mysqli_fetch_object($rec)){
if($result->user == $_POST['user']){
$verify_user = 1;
}
}
if($verify_user == 0){
if($_POST['password'] == $_POST['password2']){
$user = $_POST['user'];
$password = $_POST['password'];
$sql = "INSERT INTO user (user,password) VALUES ('$user','$password')";
mysqli_query($con, $sql);
echo "Registered";
}else{
echo "Passwords do not match";
}
}else{
echo "This user has already been registered";
}
}
?>
The PHP code, works great when used on its own (it used to be at the beginning of the form file, surrounded by if($_POST['submit']){}) But now I want to use it in a separate file, and use AJAX, and I'm unable to register a user :/ the value of data is never "Registered"... Any ideas?
Thanks in advance! :)
Please never run this code in a live environment, your code is open to SQL injection and you NEED to hash passwords.
This line:
if($_POST['user'] == '' or $_POST['password']){
Looks to be your issue. You want to be testing $_POST['password'] somehow, like $_POST['password'] == '' or !isset($_POST['password']).
Your logic is also horribly constructed, you may want to go look at a few tutorials. e.g. why are you fetching ALL your users just to test if one exists, do that logic in the SQL code itself to avoid fetching an entire table for no reason.
I have a sample script that will authenticate my users to access the page. My issue is when I post the values the js file does reflect that the data has been serialized but when it is posted to the php file to check if the database record exists the users still gets access to the page whether the login in details are correct or wrong. For some reason it seems not to take my `$_POST['pass'] and my $_POST['user_email'] values. But if I manually type in the user email and password in the php file to replace the variables it will works.
HTML form
<form class="login" id="login-form" name="login-form" method="post">
<p class="title">LOGIN</p>
<input type="text" placeholder="Email" id="user_email" name="user_email" autofocus/>
<i class="fa fa-user"></i>
<input type="password" placeholder="Password" id="pass" name="pass" />
<i class="fa fa-key"></i>
<button>
<i class="spinner" style="outline:none;"></i>
<span class="state">Log in</span>
</button>
</form>
My js file to post the values. I added the console.log just to test see what values are been taken in by the script
$('document').ready(function()
{
var working = false;
$('.login').on('submit', function(e) {
e.preventDefault();
if(working)return
working = true;
var $this = $(this),
$state = $this.find('button > .state');
$this.addClass('loading');
$state.html('Authenticating');
var data = $("#login-form").serialize();
console.log(data);
$.ajax({
type : 'POST',
url : 'login_process.php',
data : data,
success : function(response) {
console.log(response);
if(response=="ok"){
setTimeout(function() {
$this.addClass('ok');
$state.html('Welcome');
setTimeout(function() {
$state.html('Log in');
$this.removeClass('ok loading');
working = false;
}, 4000);
setTimeout(function() {
window.location.href = "/Home.aspx";
}, 4000);
}, 3000);
//$("#btn-login").html('<img src="btn-ajax-loader.gif" /> Signing In ...');
//setTimeout(' window.location.href = "home.php"; ',4000);
} else {
console.log('ERROR IN LOGINING IN');
}
}
});
return false;
});
});
PHP file 'login_process'
<?php
session_start();
require_once 'dbconfig.php';
if(isset($_POST['pass']))
{
$user_email = urldecode(trim($_POST['user_email']));
$user_password =trim($_POST['pass']);
//$password = md5($user_password);
$password = $user_password;
try {
$stmt = $db_con->prepare("SELECT * FROM tbl_users WHERE user_email=:email");
$stmt->execute(array(":email"=>$user_email));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
if($row['user_password']==$password){
echo "ok"; // log in
$_SESSION['user_session'] = $row['user_id'];
}
else{
echo "email or password does not exist."; // wrong details
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
You are missing the dataType make with dataType : 'json' just after data, You can return the result in json by json_encode() ti debug result
I'm new to ajax concept. Here i'm trying to insert the user details(signup form) into the database. it inserted the datas into the db succesfully. But, ajax is my problem.
1) i didn't get any error message if form fields are empty. you can see my below codes i've done validation on post.php page. but, it doesn't return the error values. 2) it stores the empty values into database. 3) if datas stored successfully i want to get the success message & if datas failed to store in db i want to get the error message. How should i do these all things?
Ajax.js
$(function () {
$('form').on('submit', function (e) {
$.ajax({
type: 'POST',
url: 'post.php',
data: $('form').serialize(),
success: function(msg) {
if(msg=='error_n')
{
$("#e_name").html('Name required');
}
if(msg=='error_m')
{
$("#e_mobile").html('Mobile required');
}
//success and error alert
if(data="inserted")
{
alert("insertion success");
}
else
{
alert("falid to insert into database");
}
}
});
e.preventDefault();
});
});
Post.php
<?php
include_once('config.php');
$name = trim($_POST["name"]);
$mobile = trim($_POST["mobile"]);
if($name == "")
{
echo 'error_n';
}
if($mobile == "")
{
echo 'error_m';
}
try
{
$stmt = $conn->prepare("INSERT INTO sample ( Name, Mobile ) VALUES ( ?, ? )");
$conn->errorInfo();
$stmt->bindParam('1', $name, PDO::PARAM_STR);
$stmt->bindParam('2', $mobile, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
'Query failed to insert into database' .$e->getMEssage();
}
?>
Homepage.php
<p>register here</p>
<div id="light" class="white_content">
Close
<form>
<input type="hidden" name="form" value="values" />
name : <input name="name" id="name" type="text" /><span id="e_name"></span> <br />
mobile : <input name="mobile" id="mobile" type="text" /><span id="e_mobile"></span> <br />
<input type="submit" value="submit" />
</form>
</div>
<div id="fade" class="black_overlay"></div>
After your error messages are returned, you need to stop the script execution. Your current code still tries to add the values and hence overrides your custom error messages. Most probably then your PHP returns your exception message and which is not what your JavaScript is expecting.
if($name == "")
{
echo 'error_n';
die(); // Stop here
}
if($mobile == "")
{
echo 'error_m';
die(); // Stop here
}
Also add echo 'inserted'; when your database insert is successful.