how to link php, sql, and Javascript together, - javascript

I'm doing a log in page, i have javascript doing validations ( checking if field is blank) sql storing the data and php doing what php does (idk).... anyway when I press submit it tells me Cannot POST /login.php
is there away to test it on a website and see if it actually works or is the code completely wrong.
<?php
$server = 'localhost';
$username = 'root';
$passowrd = 'cosc_453';
$dbname = 'login'
if(!empty($_POST['user']))
{ $query = mysql_query("SELECT * FROM UserName where userName ='$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
{ $_SESSION['userName'] = $row['pass']; echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE..."; }
else { echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
}
}
}
if(isset($_POST['submit']))
{ SignIn();
} ?>
php external
function validate(){
if ( document.getElementById (user).value=="")
{
alert ("Please enter your user name");
}
else if ( document.getElementById(pass).value=="")
alert("Please enter you password");
else {
alert("Processing Login........");
}
}
javscript external
CREATE TABLE UserName (
UserNameID int(9) NOT NULL auto_increment,
userName VARCHAR(40) NOT NULL,
pass VARCHAR(40) NOT NULL,
PRIMARY KEY(UserNameID) );
INSERT INTO
UserName (userName, pass)
VALUES
("cosc" , "453");
sql external
<!DOCTYPE HTML>
<html>
<head>
<title>Sign-In</title>
<link rel="stylesheet" type="text/css" href="home.css">
<script src ="login.js"></script>
</head>
<body id="body-color">
<div id="Sign-In">
<fieldset style="width:30%">
<legend>LOG-IN HERE</legend>
<form method="Post" action="login.php" submit =" validate()">
User:<br><input type="text" name="user" size="40"><br>
Password:<br><input type="password" name="pass" size="40"><br>
<input id="button" type="submit" name="submit" value="Log-In">
</form>
< /fieldset>
</div>
</body>
</html>

Your mysql do not have a connection to database. And please stop using mysql, use mysqli instead
<?php
$con = mysqli_connect("localhost","root","cosc_453","login");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM UserName WHERE userName ='".$_POST[user]."' AND pass = '".$_POST[pass]."'";
$result = mysqli_query($conn,$sql);
$count_result = mysqli_num_rows($result);
// Login Success URL
if($count_result == 1)
{
// If you validate the user you may set the user cookies/sessions here
#setcookie("logged_in", "user_id");
#$_SESSION["logged_user"] = "user_id";
$_SESSION["secret_id"] = $row['secret_id'];
if($row['level'] == 1)
{
// Set the redirect url after successful login for admin
$resp['redirect_url'] = 'admin/';
}
else if($row['level'] == 2)
{
// Set the redirect url after successful login for user
$resp['redirect_url'] = 'user/';
}
}
else
{
echo "Invalid username or pass";
}
?>

To add onto what Eh Ezani stated, you have an issue in your HTML. Your form attribute reads submit when I believe what you meant is onsubmit. Might want to try something like.
<form method="Post" action="login.php" onsubmit ="return validate()">
User:<br><input type="text" name="user" size="40"><br>
Password:<br><input type="password" name="pass" size="40"><br>
<input id="button" type="submit" name="submit" value="Log-In">
</form>
Also, "Use MySQLi over the older MySQL functions. The "i" stands for "improved". The list of improvements can be found in the docs.
-credited to
Difference between mysqli and mysql?

Related

Why my password_verify does not work on login?

I am learning to create a simple signup and login page which using password_hash and password_verify function.
The sign up page is working fine, and the password_hash are able to encrypt my password in the mysql database. As photo below.
Only thing that is not working is that I cannot make the login to work, its always return to error message saying that the password is invalid. I am not using the hashed password, i am using the password that I entered during sign-up (which is just 123).
Below is my code:
Login Form:
<div class="InnerDiv">
<form method="post" action="">
<div class="form-group">
<label for="exampleInputEmail1">Email</label>
<input name="email" type="email" value="<?php echo #$_POST['email']; ?>" class="form-control input-fields" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email" required="true">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input name="password" type="password" class="form-control input-fields" id="exampleInputPassword1" placeholder="Password" required="true">
</div>
<center>
<button name="submit2" type="submit" class="btn btn-primary btn-login-form">Login</button>
<p data-toggle="modal" data-target="#forgotpassdialog" class="forgot-para">Forgot Password?
</p>
</center>
</form>
</div>
Verify login credentials
<?php
if (isset($_GET['msg'])) {
$var=$_GET['msg'];
echo "<script>alert('$var')</script>";
}
if(isset($_POST['submit2'])){
$email = $_POST["email"];
$password = $_POST["password"];
$data = mysqli_query($sql_con,"select *from students where stdemail = '$email' AND password='$password'");
$datarow = mysqli_num_rows($data);
if ($datarow > 0) {
if (password_verify($email, $password)) {
$row = mysqli_fetch_array($data);
$value3 = $row['id'];
$_SESSION['sid'] = $value3;
echo "<script>window.location='/students/dashboard.php'</script>";
}
}
else{
echo "<script>alert('Invalid password')</script>";
}
}
?>
Any help would be appreciated, let me know if more details is needed.
EDITED: I have tried to substitute the $email with the hashpassword value in the password_verify, but still return invalid message.
<?php
if (isset($_GET['msg'])) {
$var=$_GET['msg'];
echo "<script>alert('$var')</script>";
}
if(isset($_POST['submit2'])){
$email = $_POST["email"];
$password = $_POST["password"];
$data = mysqli_query($sql_con,"select *from students where stdemail = '$email' AND password='$passwordDB'");
$datarow = mysqli_num_rows($data);
if ($datarow > 0) {
if (password_verify($password, $passwordDB)) {
$row = mysqli_fetch_array($data);
$value3 = $row['id'];
$_SESSION['sid'] = $value3;
echo "<script>window.location='/students/dashboard.php'</script>";
}
}
else{
echo "<script>alert('Invalid password')</script>";
}
}
?>
You can't just make up some extra variables and slap them in the code. Your new version is no better than the previous one because you're selecting on a password variable that isn't initialised, and you're not retrieving the hashed password for PHP to check.
There's also the issue of possible SQL injection to address.
So, here's a rewritten version of your code, with some key changes:
Mysqli is set to throw an exception if there's an error.
I've used the OOP structure of MySQLi because it's less verbose and easier to follow
I've restructured your query to used a prepared statement, thus avoiding SQL injection problems
I've reworked your query to retrieve the student ID and hashed password. No other data is required in this code.
the code correctly verifies the user-supplied password against the hashed version retrieved from the database
session_start();
// Set MySQLi to throw an exception if it detects an error
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$sql_con = new mysqli('server', 'usernane', 'userpass', 'database');
if (isset($_POST['submit2'])) {
$email = $_POST["email"];
$password = $_POST["password"];
// set up query to retrieve id and hashed password
$query = "select id, password from students where stdemail = ?";
// Prepare query & bind parameters, execute
$stmt = $sql_con->prepare($query);
$stmt->bind_param('s', $email);
$stmt->execute();
// Bind variable to accept the result
$stmt->bind_result($id, $hashedPassword);
// fetch result. There should only be one, so no loop required.
$data = $stmt->fetch();
// Check we retrieved some data, and if so, check the password.
if ($data && password_verify($password, $hashedPassword)) {
$_SESSION['sid'] = $id;
echo "<script>window.location='/students/dashboard.php'</script>";
} else {
echo "<script>alert('Invalid credentials')</script>";
}
}
} catch(Exception $e) {
echo $e->getMessage();
}
I have run this code on my server - it works. If you have problems check your server connection, and ensure that the passwords in your database have been correctly hashed with password_hash().
Note: for this example the exception handler just displays the exception message. Your live code should not do that, but should handle the exception appropriately.

problem with sending ajax form data to php

i cant send a form data with ajax to php. It always refresh the page. Im using bootstrap modal to register form and i want to display error message (if have) on the top of form. Always refresh the page and if i again click to reg button to open the modal i see the error message. How i can do it without refresh the page? Any idea how can i do it?
form:
<?php echo display_error(); ?>
<form id="regform" class="form-signin" action="#" method="post">
<input type="text" id="username" class="form-control" placeholder="username" name="username" required autofocus>
<input type="email" id="email" class="form-control" placeholder="email" name="email"required autofocus>
<input type="password" id="pass1" class="form-control" placeholder="password" name="password_1" required>
<input type="password" id="pass2" class="form-control" placeholder="password again" name="password_2" required>
</br>
<button class="btn btn-lg btn-primary btn-block" type="submit" name="register_btn">Register</button>
</form>
js ajax
$('#register_btn').click(function(){
var data = {};
data.username = $('#username').val();
data.email = $('#email').val();
data.password_1 = $('#pass1').val();
data.password_2 = $('#pass2').val();
$.ajax({
type: "POST",
url: "functions.php",
data: data,
cache: false,
success: function (response) {
}
});
return false;
});
});
functions.php
include 'db_config.php';
session_start();
// connect to database
// variable declaration
$username = "";
$email = "";
$errors = array();
// call the register() function if register_btn is clicked
if (isset($_POST['register_btn'])) {
register();
}
// REGISTER USER
function register(){
global $db, $errors;
// receive all input values from the form
$username = e($_POST['username']);
$email = e($_POST['email']);
$password_1 = e($_POST['password_1']);
$password_2 = e($_POST['password_2']);
// form validation: ensure that the form is correctly filled
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($email)) {
array_push($errors, "Email is required");
}
if (empty($password_1)) {
array_push($errors, "Password is required");
}
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
if (isset($_POST['user_type'])) {
$user_type = e($_POST['user_type']);
$query = "INSERT INTO users (username, email, user_type, password)
VALUES('$username', '$email', '$user_type', '$password')";
mysqli_query($db, $query);
$_SESSION['success'] = "New user successfully created!!";
header('location: home.php');
}else{
$query = "INSERT INTO users (username, email, user_type, password)
VALUES('$username', '$email', 'user', '$password')";
mysqli_query($db, $query);
// get id of the created user
$logged_in_user_id = mysqli_insert_id($db);
$_SESSION['user'] = getUserById($logged_in_user_id); // put logged in user in session
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
}
}
function display_error() {
global $errors;
if (count($errors) > 0){
echo '<div class="error">';
foreach ($errors as $error){
echo $error .'<br>';
}
echo '</div>';
}
}
The JQuery selector you are using is using an ID, change the button from name="register_btn" to id="register_btn".
EDIT: Further looking at your code, you are missing the prevent default on the button, I would change the listener to the form instead and prevent default. The form is submitting to the current page which is the default behavior, which is why it looks like the page is just reloading.
See the below link for my code I use for form posts via AJAX:
http://aspintech.ca/journal/?entry_id=77

PHP and JS Login form says user doesn't exist error

I've managed to make a successful registration form that submits the information to the database using PDO queries, and it successfully creates a session after the user registers etc.
When it comes to logging in on the login form, I keep getting the error message "The user does not exist" although it does exist in the database. I can't seem to comprehend why that error is occurring since I used similar code for the registration.
The following is the HTML/PHP code for the front-end of the site.
<?php
//allow the config
define('__CONFIG__', true);
//require the config
require_once "inc/config.php"; //possibly have to change the location
?>
<!DOCTYPE html>
<html>
<head>
<!-- UIKit CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-rc.24/css/uikit.min.css" />
<title>Login Page</title>
<base href="/"/>
</head>
<body>
<div class="uk-section uk-container">
<div class="uk-grid uk-child-width-1-3#s uk-child-width-1-1" uk-grid></div>
<h2><b><center>Login</center></b></h2>
<form style="border: 3px solid #ddd; border-radius: 10px; padding: 10px;" class="uk-form-stacked js-login">
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text"><b>Email:</b></label>
<div class="uk-form-controls">
<input class="uk-input" id="form-stacked-text" type="email" required='required' placeholder="Insert Email">
</div>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text"><b>Password:</b></label>
<div class="uk-form-controls">
<input class="uk-input" id="form-stacked-text" type="Password" required='required' placeholder="Insert Password">
</div>
</div>
<div class="uk-margin uk-alert uk-alert-danger js-error" style='display: none;'></div>
<div class="uk-margin">
<label><center>Don't have an account? <a href='comp1687/register.php'>Create one now!</a></center></label>
<center><button class="uk-button uk-button-default" type="submit"><b>LOGIN</b></button></center>
</div>
</form>
</div>
<?php require_once "inc/footer.php"; ?>
</body>
</html>
The following is the login.php AJAX code used for validations.
<?php
// Allow the config
define('__CONFIG__', true);
// Require the config
require_once "../inc/config.php"; //possibly have to change the location
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Always return JSON format
// header('Content-Type: application/json');
$return = [];
$email = Filter::String( $_POST['email'] );
$password = $_POST['password'];
$user_found = User::Find($email, true);
if($user_found) {
// User exists, try and sign them in
$user_id = (int) $user_found['user_id'];
$hash = (string) $user_found['password'];
if(password_verify($password, $hash)) {
// User is signed in
$return['redirect'] = 'dashboard.php?message=welcome'; //possibly have to change the location
$_SESSION['user_id'] = (int) $user_id;
} else {
// Invalid user email/password combo
$return['error'] = "Invalid user email/password combo";
}
} else {
// They need to create a new account
$return['error'] = "You do not have an account. <a href='register.php'>Create one now?</a>";
}
echo json_encode($return, JSON_PRETTY_PRINT);
} else {
///Kill the script. Redirect the user.
exit('Invalid URL');
}
?>
And finally, the main.js code is as follows
.on("submit", "form.js-login", function(event) {
event.preventDefault();
var _form = $(this);
var _error = $(".js-error", _form);
var dataObj = {
email: $("input[type='email']", _form).val(),
password: $("input[type='password']", _form).val(),
};
if(dataObj.email.length < 6) {
_error
.text("Please enter a valid email address")
.show();
return false;
} else if (dataObj.password.length < 8) {
_error
.text("Please enter a password that is at least 8 characters long.")
.show();
return false;
}
// Assuming the code gets this far, we can start the ajax process
_error.hide();
$.ajax({
type: 'POST',
url: 'ajax/login.php',
data: dataObj,
dataType: 'json',
async: true,
})
.done(function ajaxDone(data) {
// Whatever data is
if(data.redirect !== undefined) {
window.location = data.redirect;
console.log('data');
} else if(data.error !== undefined) {
_error
.html(data.error)
.show();
console.log('data');
}
})
.fail(function ajaxFailed(e) {
//this failed
console.log(e);
})
.always(function ajaxAlwaysDoThis(data) {
//always do
console.log('Always');
})
return false;
})
The user find class with the find function
public static function Find($email, $username, $return_assoc = false) {
$con = DB::getConnection();
// Make sure the user does not exist.
$email = (string) Filter::String( $email );
$findUser = $con->prepare("SELECT user_id, password FROM users WHERE email = (:email) AND username = (:username) LIMIT 1");
$findUser->bindParam(':email', $email, PDO::PARAM_STR);
$findUser->bindParam(':username', $username, PDO::PARAM_STR);
$findUser->execute();
if($return_assoc) {
return $findUser->fetch(PDO::FETCH_ASSOC);
}
$user_found = (boolean) $findUser->rowCount();
return $user_found;
}
You're passing 'true' as a second variable to the User::Find method, which you are then interpreting as a string literal in the MySQL query. ('true')
Are you using E-mail as a username, or a separate username field? I can't find that in your HTML. If you are just using e-mail, you can get rid of the second parameter in the Find method, and remove both:
AND username = (:username)
$findUser->bindParam(':username', $username, PDO::PARAM_STR);
//Are you receiving some correct ouput from your php code?
//To check it, after this code,
else {
// They need to create a new account
$return['error'] = "You do not have an account. <a href='register.php'>Create one now?</a>";
}
// Add this two lines:
var_dump($user_found);
var_dump($return);
die();
// And send me the output.

Redirect to an application page Not on the same server after login

I have a HTML5 app with a log in screen. When I enter the details, it goes out to an external server, runs a php file called login.php and check the details.
If the details are correct I need it to redirect back to the HTML5 app to the page with id #home on the index.html file.
If the index.html and login.php are both sitting together on the server, a header method going to work fine. But now, the html file is resting on a mobile phone as a HTML5 app, which reaches out to the server (which is possible - I have the server url). Checks for credentials and redirects. How is it going to redirect back to my app on the phone? There is no URL for the app on the phone.
Attempted with ajax too but nothing happens.
P.S: If you plan to flag this, read through and understand the issue first. Some text match doesn't mean its the same question.
First page on the app where you enter log in details:
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="scripts.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
</head>
<body>
<div data-role="page" id="loginForm">
<form id="form1" name="form1" method="POST" action="http://www.examplewebsite.com/login.php">
<input type="text" name="user" id="user" placeholder="Username"/>
<input type="password" name="pass" id="pass" placeholder="Password" />
<input type="submit" name="submit" value="Login" />
</form>
</div>
<div data-role="page" id="home">
<h1>Logged In</h1>
</div>
</body>
</html>
Script to check Log in. This php file rests on the server side.
//DB Log in credentials
$hostName = 'localhost';
$dbUser = 'fakeuser';
$dbPass = 'fakepass';
$dbName = 'fakedb';
$userTable = "faketable";
//Connect to DB
$conn = mysql_connect($hostName, $dbUser, $dbPass) or die("not connecting");
$dbSelect = mysql_select_db($dbName) or die("no db found");
//Obtain input username and password from the client
$username = $_POST["user"];
$password = $_POST["pass"];
//Check for MySql Injections
if(ctype_alnum($username) && ctype_alnum($password)){
$query1 = mysql_query("SELECT * FROM $userTable WHERE username='$username'");
//query will return 1 if the username exists in the database
$numrows = mysql_num_rows($query1);
if($numrows == 1){
//checking if the password matches the username now
$query2 = "SELECT password FROM $userTable WHERE username='$username'";
$result2 = mysql_query($query2);
$row = mysql_fetch_array($result2, MYSQL_ASSOC);
$pass = $row['password'];
if($password == $pass){
//If successful, redirect to the #home page
//anything I can do here to redirect back to #home on my app?
}
else
echo "Password incorrect";
}
else
echo "username incorrect" . $numrows;
}
else{
echo "Not alpha Numeric Input!!";
}
Attempted Ajax portion
var isLogged = false;
/**
* Method used to log into the application
*/
$(document).on("pageinit", "#loginForm", function () {
$("#form1").on("submit", function (event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "http://www.examplewebsite.com/login.php",
data: $("#form1").serialize(),
success: function (data) {
console.log(data);
if (data.loggedIn) {
isLogged = true;
$.mobile.changePage("#home");
} else {
alert("You entered the wrong username or password. Please try again.");
}
}
});
});
});
Where is loggedIn defined? You never get into this scope if (data.loggedIn) { }, or?
Have you tried to "return" a json encoded array and actually use that data?
As I see it you are not really using the different errors the user might run into, i.e. "Password incorrect", "username incorrect" and "Not alpha Numeric Input!!".
You might want to do something like:
if (data.loggedIn) { /* Went well */ }
else if (data.passIncorrect) { /* Password incorrect */ }
else if (data.userIncorrect) { /* User incorrect */ }
else if (data.passIncorrect) { /* NaN */ }
You might be able to find more info on the subject here or here.
I don't know if this is any help what so ever and I might even be off on a tangent here.

I need a registration button that sends data to a mySQL server to also Redirect on click

So i am making a registration page on my website. At the moment it is more just a test then anything. I have it working more or less and when a user attempts to sign up it works just fine HOWEVER there is no change on the page. I have created a Confirmation page but no matter what i try i can't seem to get the button to redirect as well.
<form name="register" method="post" action="register.php">
Username:<input name="user" type="text" id="user">
<br>
Password:<input name="pass" type="password" id="pass">
<br>
Repeat Password:<input name="rpass" type="password" id="rpass">
<br>
<input type="submit" name="submit" value="Register">
</form>
From what i can tell in the last few hours of research the reason onclick and wrapping the button in a link does not work is because the type="submit" instead of "button". Is there any way do make this button redirect? If not with HTML perhaps with a JS or PHP ?
<?php
session_start(); //Must Start a session.
require "config.php"; //Connection Script, include in every file!
//Check to see if the user is logged in.
//'isset' check to see if a variables has been 'set'
if(isset($_SESSION['username'])){
header("location: members.php");
}
//Check to see if the user click the button
if(isset($_POST['submit']))
{
//Variables from the table
$user = $_POST['user'];
$pass = $_POST['pass'];
$rpass = $_POST['rpass'];
//Prevent MySQL Injections
$user = stripslashes($user);
$pass = stripslashes($pass);
$rpass = stripslashes($rpass);
$user = mysqli_real_escape_string($con, $user);
$pass = mysqli_real_escape_string($con, $pass);
$rpass = mysqli_real_escape_string($con, $rpass);
//Check to see if the user left any space empty!
if($user == "" || $pass == "" || $rpass == "")
{
echo "Please fill in all the information!";
}
else
{
//Check too see if the user's Passwords Matches!
if($pass != $rpass)
{
echo "Passwords do not match! Try Again";
}
//CHECK TO SEE IF THE USERNAME IS TAKEN, IF NOT THEN ADD USERNAME AND PASSWORD INTO THE DB
else
{
//Query the DB
$query = mysqli_query($con,"SELECT * FROM members WHERE username = '$user'") or die("Can not query the TABLE!");
//Count the number of rows. If a row exist, then the username exist!
$row = mysqli_num_rows($query);
if($row == 1)
{
echo "Sorry, but the username is already taken! Try again.";
}
//ADD THE USERNAME TO THE DB
else
{
$add = mysqli_query($con,"INSERT INTO members (id, username, password) VALUES (null, '$user' , '$pass') ") or die("Can't Insert! ");
}
}
}
}
?>
As I commented, simply do
else
{
$add = mysqli_query($con,"INSERT INTO members (id, username, password) VALUES (null, '$user' , '$pass') ") or die("Can't Insert! ");
header("location: thankyou.html");
}

Categories