I'm trying to create a login environment that has a user input their credentials, which is then checked against a MySQL DB (with appropriate errors returned if wrong credentials) with JS (using jquery,ajax, and Perl) which, on successful login, would display a dynamic page for the user (user portal)
I can't pass the userID to the last cgi page.
below are my codes:
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>login</title>
<link rel="stylesheet" type="text/css" media="screen, projection" href="http://www.blueprintcss.org/blueprint/screen.css" />
<link rel="stylesheet" type="text/css" media="screen, projection" href="http://www.blueprintcss.org/blueprint/plugins/buttons/screen.css" />
<link rel="stylesheet" type="text/css" media="print" href="http://www.blueprintcss.org/blueprint/print.css" />
<!--[if IE]><link rel="stylesheet" type="text/css" media="screen, projection"
href="http://www.blueprintcss.org/blueprint/ie.css"><![endif]-->
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="login.js"></script>
<style type="text/css">
#loginContent { width: 350px; margin: 100px auto; }
button[type] { margin: 0.5em 0; }
#loginForm{
width:25%;
padding: 5px 5px;
margin:auto;
}
</style>
</head>
<body>
<h2>Please have pop-ups enabled for this site</h2>
<div id="loginResult" style="display:none;"></div>
<form id="loginForm" name="loginForm" method="post" action="">
<fieldset>
<legend>Enter Information</legend>
<p>
<label for="username">Username</label>
<br />
<input type="text" id="username" name="username" class="text" size="20" />
</p>
<p>
<label for="password">Password</label>
<br />
<input type="password" id="password" name="password" class="text" size="20" />
</p>
<p>
<button type="submit" class="button positive">Login</button>
</p>
</fieldset>
</form>
</body>
</html>
login.js
$(document).ready(function(){
$("form#loginForm").submit(function() { // loginForm is submitted
var username = document.getElementById("username").value; //$('#username').attr('value'); // get username
var password = document.getElementById("password").value; //$('#password').attr('value'); // get password
if (username && password) { // values are not empty
$.ajax({
type: "GET",
url: "/cgi-bin/login.pl", // URL of the Perl script
contentType: "application/json; charset=utf-8",
dataType: "json",
// send username and password as parameters to the Perl script
data: "username=" + username + "&password=" + password,
// script call was *not* successful
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('div#loginResult').text("responseText: " + XMLHttpRequest.responseText
+ ", textStatus: " + textStatus
+ ", errorThrown: " + errorThrown);
$('div#loginResult').addClass("error");
}, // error
// script call was successful
// data contains the JSON values returned by the Perl script
success: function(data){
if (data.error) { // script returned error
$('div#loginResult').text("data.error: " + data.error);
$('div#loginResult').addClass("error");
} // if
else { // login was successful
$('form#loginForm').hide();
$('div#loginResult').text("data.success: " + data.success
+ ", data.userid: " + data.userid);
$('div#loginResult').addClass("success");
window.open("/cgi-bin/portal.pl");
} //else
} // success
}); // ajax
} // if
else {
$('div#loginResult').text("enter username and password");
$('div#loginResult').addClass("error");
} // else
$('div#loginResult').fadeIn();
return false;
});
});
login.pl
#!C:\Strawberry\perl\bin\perl.exe
use CGI;
use DBI;
use strict;
use warnings;
# read the CGI params
my $cgi = CGI->new;
my $username = $cgi->param("username");
my $password = $cgi->param("password");
# connect to the database
my $db = 'bakery_users';
my $host = 'localhost';
my $user = 'root';
my $pass = 'P#ssw0rd';
my $dbh = DBI->connect ("DBI:mysql:database=$db:host=$host", $user, $pass) or die "Can't connect to database: $DBI::errstr\n";
# check the username and password in the database
my $statement = qq{SELECT id FROM users WHERE username=? and password=?};
my $sth = $dbh->prepare($statement)
or die $dbh->errstr;
$sth->execute($username, $password)
or die $sth->errstr;
my ($userID) = $sth->fetchrow_array;
# create a JSON string according to the database result
my $json = ($userID) ?
qq{{"success" : "login is successful", "userid" : "$userID"}} :
qq{{"error" : "username or password is wrong"}};
# return JSON string
print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json;
And this is the garbage portal cgi page that needs to know the user so I can serve some specific information
#!C:\Strawberry\perl\bin\perl.exe
use CGI;
use strict;
use warnings;
my $cgi = CGI->new; #new CGI routine
print $cgi->header('text/html'); #create HTTP header
print "<html> <head>\n";
print "<title>Hello, world!</title>";
print "</head>\n";
print "<body>\n";
print "<h1>Hello, world!</h1>\n";
print "</body> </html>\n";
Most of the login files are modified from the IBM developer page on simple CGI user login page with mySQL
I was able to pass over CGI parameters with another Perl module, CGI:Session.
by adding
my $session = new CGI::Session(undef, undef) or die CGI::Session->errstr;
$session->param("username", $username);
my $cookie = $cgi->cookie(CGISESSID => $session->id);
print $cgi->header( -cookie=>$cookie );
to my login.pl file and adding the following block to my portal.cgi
my $sid = $cgi->cookie('CGISESSID') || $cgi->param('CGISESSID') || undef; #loads previous cookie
my $session = load CGI::Session(undef, $sid);
my $user = $session->param("username");
This creates a local cookie in the temp dir and is read to find the "username" variable I passed into it on the login.pl page
Related
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.
I'm attempting to use ajax to send input from an html form and try to fine the email in a MySQL database. I tested the search and it works just fine (using dummy data.) I have my PHP files running on WAMP. I checked Chrome to see if the email/password are showing and they are.
Here is my code:
HTML & Ajax
<html>
<head>
<!--initialize jquery from js folder-->
<script src ="js/jquery-3.3.1.min.js"></script>
</head>
<body>
<!--output of the json-->
<div>
<!--set the id to DOM to show output-->
<ul id="DOM">
</ul>
</div>
<form>
<label><b>Email</b></label>
<input type="text" placeholder="Enter email" id="email"
required>
<br/>
<label><b>Password</b></label>
<input type="text" placeholder="Enter password" id="passwrd"
required>
<br/>
<button type="button" id="submit">Login</button>
</form>
insert
delete
show data
login
<!--Implementation of jquery/ajax-->
<script type="text/javascript">
$('#submit').on('click',function(e){
e.preventDefault()
var data = {
email: $("#email").val(),
passwrd: $("#passwrd").val()
}
$.ajax({
url : "http://localhost/api/login.php",
type : "POST",
dataType : "json",
data : JSON.stringify(data),
//on success it will call this function
success : function(data){
alert(data.toString());
//if fail it will give this error
}, error : function(e){
alert("failed to work:" +JSON.stringify(e));
}
});
});
</script>
</body>
</html>
PHP
include "db.php";
header('Content-type: application/json');
//$con->escape_string
$email = isset($_POST['email']);
//$email = "fk5829#wayne.edu";
$result = $con->query("SELECT * FROM users WHERE email='$email'");
echo "$email";
if($result->num_rows == 0){ //if the user doesnt exist
$_SESSION['message'] = "user doesnt exist";
echo ' / user not exist / ';
}
else{ //user exists
$user = $result->fetch_assoc();
if(password_verify(isset($_POST['passwrd']), $user['passwrd'])){
//Verify the password entered
//if password correct, link information from DB to session
//variables
$_SESSION['f_name']= $user['f_name'];
$_SESSION['l_name']= $user['l_name'];
$_SESSION['email']= $user['email'];
$_SESSION['authorized']= $user['authorized'];
//Will be used to check if users session is logged
//in/allowed to do things
$_SESSION['logged_in'] = true;
//return to Success
return $_SESSION['logged_in'];
exit("Success");
}
else{
$_SESSION['message'] = "You have entered the wrong password,
please try again";
}
echo ' / user exists / ';
}
echo ' / After the check / ';
My question is this: Why is the email from the form id "email" not getting stored in $email? is it on my ajax request side? or is it in my PHP file when im trying to $_POST?
Any direction is appreciated.
I tried this function and got it to work. Maybe you can try this too.
<script type="text/javascript">
$('#submit').on('click',function(e){
e.preventDefault()
$.post('http://localhost/api/login.php', {email:$("#email").val(),passwrd:$("#passwrd").val()},
function(data){
alert(data.toString());
}).fail(function(e){
alert("failed to work:" +JSON.stringify(e));
});
});
</script>
I have a php script and I would like it to be called with ajax, I have had an error coming from the ajax which says "Error:email=my_email&password=myPassword".
Here is the PHP script
<?php
session_start(); //starts a session in order to be-able to save session variables and to read them
require "db_config.php"; //Allows us to use the database connection from db_config.php in this file
if ($_SERVER["request_method"] == "post"){ //checks if the form was submitted
$email = $_POST["email"]; //fetching the email address which was inserted in the login.html form
$password = $_POST["password"]; //fetching the password which was inserted in the login.html form
/*
querying the database, to check whether there is a result with the email and password entered by the user
*/
$checkForUser = mysqli_query($db_connection, "SELECT * FROM `tbl_users` WHERE email = '$email' and Password = '$password' LIMIT 1");
/*
checking if the query resulted in one row, if there is a row
it means there is a user with this email and password, which means these are the correct creadentials
*/
$rows = mysqli_num_rows($db_connection, $checkForUser);
if ($rows == 1){
//this means: correct credentials
//the next few lines fetch the information from the result
while($row = mysqli_fetch_assoc($checkForUser)){
$_SESSION["user_id"] = $row["userId"]; //creates a session variable containing the users id
$_SESSION["users_name"] = $row["firstName"]. " ".$row["lastName"]; //creates a session variable containing the users name
}
echo "You are now logged in: ". $_SESSION["users_name"];
}else{
//this means: incorrect credentials
echo "Incorrect Username or password"; //prints out error message
}
}
?>
Here is main.js
$(document).ready(function() {
$('#loginForm').submit(function() {
var data = $(this).serialize();
$.ajax({
url: "../php/login.php",
type: "POST",
data: data,
success: function(data) {
$('*').html(data);
},
error: function() {
alert('ERROR: ' + data);
}
});
return false;
});
});
Here is the login.html page which may be helpful
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/main.css">
<link rel="stylesheet" type="text/css" href="css/responsive.css">
<script src="js/jquery.js"></script>
<script src="js/main.js"></script>
<meta name="copyright" content="Yudi Moszkowski">
<title>Login | Your Site Name</title>
</head>
<body>
<div id="loginContainer">
<div class="logo"><img src="img/yourLogo.png"></div>
<form action="php/login.php" method="post" id="loginForm">
<input type="text" name="email" placeholder="Email" id="loginEmail" class="loginInput" required="true">
<input type="password" name="password" placeholder="Password" id="loginPassword" class="loginInput" required="true"/>
<input type="submit" value="Login" name="loginSubmit" id="loginSubmit">
</form>
<div id="loginOptions"><p id="noAccount">Not signed up? Signup</p><p id="forgotPass">Forgot password?</p></div>
</div>
</body>
</html>
Thanks for your time :)
it seem that you type wrong url :
in html action, u use "php/login.php" and in ajax call, u use same url with "../" before it. if you explain the location of login.php and this html file, it will be helpful to solve your problem.
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?
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.