Creating a simple Password login without the password hardcoded [PHP,Javascript,MySQL] - javascript

I'm trying to create a simple login promt on my local website. I already tried with Javascript, but I don't want the password to be hardcoded. The Users get the password by mail so there is no registration form needed. I searched on the Internet and I think it should work with PHP and Javascript. This is what i've come up with:
<SCRIPT>
function passWord() {
var testV = 1;
var pass1 = prompt('Enter password',' ');
while (testV < 3) {
if (!pass1)
window.open('Website.html',"_self");
if (pass1.toLowerCase() == "password") {
alert('Correct!');
window.open('./test/sitetwo.html',"_self");
break;
}
testV+=1;
var pass1 =
prompt('Wrong Password','Try again');
}
if (pass1.toLowerCase()!="password" & testV ==3)
return " ";
}
</SCRIPT>
<CENTER>
<FORM>
<input type="button" value="Enter Protected Area" onClick="passWord()">
</FORM>
</CENTER>
Does anyone of you know how to code this? Thank you for your help.

Login prompt is just one of possible approaches to hide information on your website. You have to decide first what are you trying to hide. For instance, if you if are providing some paid information to your clients - you can send the information itself by mail (instead of password). If you want to hide some part of site from other people - you can just give it weird url, like site.com/jkhgdsdkgf
Creating login backend with php and database obviously requires your php, mysql (or other database) and server administration skills and completely depends on details of your task, so it's hard to provide a useful advice here.

In my opinion, you should use a database to store all your credentials (like username, password, etc..)
If you don't know how to do it, you should know that if you want to run your php code, you need a php server and somewhere to put your db.
Here is how to set up a php server with Apache
https://www.ultraedit.com/support/tutorials-power-tips/uestudio/local-php-mysql-dev-environment.html
Here is how to set up a db with PhpMyAdmin
https://www.siteground.com/tutorials/phpmyadmin/create-populate-tables/
You need a login.php (where you log in), a test.php page (then you put in it whatever you want) and a check_User.php page (where to control if the credentials are correct).
Login.php
<html>
<head> <title>Login</title> </head>
<body>
<form action="check_User.php" method="post" id="login_form">
<label><b>Username</b></label>
<!-- USERNAME -->
<input type="text" placeholder="Enter Username" name="username" required>
<!-- PASSWORD -->
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>
<!-- LOGIN -->
<button type="submit">Login</button>
</form>
<body>
</html>
check_User.php
<?php
session_start();
$_POST["username"] = htmlspecialchars($_POST["username"]);
$_POST["password"] = htmlspecialchars($_POST["password"]);
$link = mysqli_connect("your_host", "your_db_username", "your_db_password", "your_db_name");
$query = "SELECT username, password
FROM your_db_name
WHERE username = \"".$_POST["username"]."\" AND password = \"".$_POST["password"]."\"
";
mysqli_query($link, $query);
$rows = array();
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC))
$rows[] = $row;
/* correct match */
if(mysqli_affected_rows($link) == 1)
{
$_SESSION["username"] = $_POST["username"];
$_SESSION["password"] = $_POST["password"];
}
if(isset($_SESSION["username"]) && isset( $_SESSION["password"]))
header("Location:test.php");
else {
alert("Wrong username or password");
}
?>
test.php
<?php
session_start();
// not logged in, not showing this page
if((!isset($_SESSION["username"]) || !isset( $_SESSION["password"]))
header("Location:login.php");
?>
<html>
....whatever you want this page to do
</html>

Related

Decode JSON package from PHP using AJAX

I am building a simple login system. I do not want the page to reload when the user submits the form, in case there is an error, and I need to seamlessly display an error message (Like wrong password). When the users submits the data, AJAX passes it onto the submit.php script. This script validates the data and then sets a JSON object to a number 1-3 based on what is wrong or right with the submitted credentials. I don't know how to have the AJAX call, decode the JSON, and then have some if statements that decide what to do based on the value of that JSON.
Below is the code I am using for the form.
HTML:
<form method="post" id="myForm">
<h1 class="title" unselectable="on">Login</h1>
<input placeholder="Username" type="text" name="username" class="form" id="username"/>
</br>
<input placeholder="Password" type="password" name="password" class="form" id="password"/>
</br>
<input class="button" type="button" id="submitFormData" onclick="SubmitFormData();" value="Submit"/>
</br>
</form>
JS/AJAX (Same page):
function SubmitFormData() {
var username = $("#username").val();
var password = $("#password").val();
$.post("submit.php", { username: username, password: password},
function(data) {
$('#results').html(data);
$('#myForm')[0].reset();
});
}
Next is the PHP (submit.php). The PHP will look at the incoming data from the AJAX script, and then assign an error number to a JSON object depending on what is wrong with the credentials.
$username = mysqli_real_escape_string($connect, $_POST["username"]);
$password = mysqli_real_escape_string($connect, $_POST["password"]);
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
if(password_verify($password, $row["password"]))
{
$Obj->error = "three";
$myJSON = json_encode($Obj);
}
else
{
$Obj->error = "two";
$myJSON = json_encode($Obj);
}
}
}
else {
$Obj->error = "one";
$myJSON = json_encode($Obj);
}
//error one=user not found
//error two=wrong password
//error three=all detials are correct
Now, the trouble I am having is back at the main page where the user is. I want the JS to look at the $myJSON variable and decide what to do based on that. I have written some pseudo code below, but I don't know if or how I can do this in JS or AJAX.
decode JSON package
if error=one, do something
if error=two, do something else
if error=three, run a php script that sets some session variables. (Is it possible to run php inside of JS?)
Any help accomplishing these results would be greatly appreciated.
This is a vanilla javascript solution:
const xmlhttp = new XMLHttpRequest;
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
//passes results to a function
start(JSON.parse(this.responseText));
}
}
xmlhttp.open("POST", "PHP WEBSITE URL", true);
//sends the request with a FormData object based on the form
xmlhttp.send(new FormData(document.getElementById("myForm")));
function start(object) {
alert(object);
}
For this to work, your PHP script will have to echo your result object. Example:
if ($_POST["username"] === "correctUsername" && $_POST["password"] === "correctPassword") {
//echo javascript object
echo json_encode(['success'=>true]);
} else {
//echo javascript object
echo json_encode(['success'=>false]);
}
Obviously it needs to be more complex but this is the idea.
I have made login pages before and instead of returning a success I used the current PHP page as the main one and echoed the info to fill the page as well as credentials that can be used with AJAX requests. Hopefully this helps.

Passing post data to php function

I am new to this site and to programming.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Login page</title>
<script> //This is the client side form validation with Javascript
//This code is executed on the client's browser
function validateForm()
{
var x=document.getElementById("username").value;
if (x==null || x=="") //check that the name field is not blank
{
alert("Your username must be filled out");
return false;
}
var y =document.getElementById("password").value;
if (y==null || y=="") //check that the project field is not blank
{
alert("Your password must be filled out");
return false;
}
}
</script>
<?php //This is the server side form validation with PHP
//This code executes on the web server
//Write your server side form validation code here
//checks form is submitted
I am trying to get the data up from the username and password to proccess through this function. I have been messing around with it for hours now and have finally giving up. Any help would be nice.
function checkUserData($inputData) {
$inputData = htmlspecialchars($inputData);
$inputData = trim($inputData);
$username = stripslashes($inputData);
return $inputData;
}
?>
</head>
<body>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>"onsubmit="return validateForm()">
Username: <input type="text" name="uname" id="username" /><br/>
Password: <input type="text" name="pwd" id="password" maxlength="6" /><br/>
<input type="submit" value="Login"/>
<input type="Reset" value="Reset"/>
</form>
</body>
</html>
I don't know if you are missing something in your post or you forgot to add the whole code to it. But you are not getting any post variables at all. So in order to get the data and validate you need to do this
$username = $_POST['uname'];
checkUserData($username);
It is not 100% clear from your post what you are trying to do
Are you trying to return $uname?
function checkUserData($inputData) {
return stripslashes(trim(htmlspecialchars($inputData)));
}
echo checkUserData($_POST['uname']);
I couldn't quite understand what you were trying to do with your php. Let me know if this solved your problem or not, and I will elaborate on my answer.
I think you have do use the server variable $_POST.
Example:
<?php
//Check if request is POST
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$username = checkUserData($_POST['uname']);
$password = checkUserData($_POST['pwd']);
}
function checkUserData($inputData) {
$inputData = htmlspecialchars($inputData);
$inputData = trim($inputData);
$inputData = stripslashes($inputData);
return $inputData;
}
?>
Hope this helps
For checking all the posted form fields, you may use:
foreach($_POST as $key => $val)
{
checkUserData($val);
}

How to redirect to another page not on the server when login successful [duplicate]

This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 7 years ago.
I have a HTML5 app on my phone. When I input the correct username and password, it should go to an external server, log on to that database, check credentials and redirect me to another page(Home Page) on my phone when the credentials are correct.
I am able to reach the server and check credentials, but how do I redirect back to the Home Page which is in the app?
Did some reading and found ajax to be a viable option. But even then, am not entirely sure how to do the redirect. I have written the ajax section too and attached below. Please advice how I can adjust it to work.
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.");
}
}
});
});
});
header("Location: thefile.php");
Replace thefile.php with your file to be redirected.!
You can use the "Location:" header or you can use the "META REFRESH" tag with an expiration of 0.

Phone Number Not Inserted Into Database

I'm creating a simple form, which takes a couple of fields as input, runs some AJAX checks and submits to SQL database via PHP. I'm able to insert all other fields EXCEPT the phone number. Here's a snippet of the codes:
HTML ---
<form name="signupform" id="signupform" onSubmit="return false;">
<div>Phone Number: </div>
<input id="phon" type="text" maxlength="20">
<button id="signupbtn" onClick="signup()">Create Account</button>
<span id="status" style="color: red"></span>
</form>
JS ---
function signup() {
var status = document.getElementById("status");
var phone = document.getElementById("phon").value;
status.innerHTML = phone; //testing, doesn't display anything
var ajax = ajaxObj("POST", "index.php"); // accepted
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "Succesfully signed-up!"){ ///returned from php file
status.innerHTML = ajax.responseText;
}
}
}
ajax.send("phone="+phone); //shoots variable to php
}
PHP ---
if(isset($_POST["phone"])) {
$phone = $_POST['phone'];
echo $phone; //was testing, again, nothing shows
$sql = "INSERT INTO users(phone) VALUES('$phone')";
}
$query2 = mysqli_query($con, $sql);
echo 'successfully_updated';
NOTE: I tried to check if JS and PHP are receiving the phone number, but it's not displaying anything (other form elements such as name and email are displayed, though, tested that already). But later-on, in the PHP code, it isn't showing any error when checked against "if (isset($_POST["phone"])), it inserts the other elements of the form without trouble. No clue why that's happening, any ideas please? My guess is that since JS doesn't reflect the value, that's where the error lies.
Been searching and trying in vain since hours! Any help would be great, thanks!
using jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
phoneNum = $("#phon").val();
$("#signupbtn").click(function(){
$.ajax({url:"./index.php",data:{phone:phoneNum},success:function(result){
alert(result);
}});
});
});
</script>
status.innerHTML = phone; //testing, doesn't display anything
must be
document.getElementById("status").innerHTML = phone;
why not write $query2 = mysqli_query($con, $sql) or die(mysqli_error());
That way, you can see what the error occurs
Please try this
$sql = "INSERT INTO users(phone) VALUES('".$phone."')";

Updating database using AJAX form

I have a file, form.php, that has a small form for searching the database for people by first and last name. The form uses a JavaScript function to send variables to search_name.php through AJAX and information queried from mydatabase as values in a form.
I want to be able to update the information on the form in the #result element with the results from the search.
I tried doing a small example that did no have the form returned through AJAX and it worked but for some reason I am not able to do it in my bigger project.
Can anyone please help. I have looked for examples and information but I'm new to AJAX and PHP and can't figure out why this is happening.
form.php
<script language="JavaScript" type="text/javascript">
function ajax_post(){
var fn = document.getElementById("first_name").value;
var ln = document.getElementById("last_name").value;
var errorMsg ="";
if (fn==null || fn=="" ){
errorMsg +="Enter First Name \n";
document.getElementById("first_name").focus();
}
if (ln==null || ln=="" ){
errorMsg +="Enter Last Name \n";
document.getElementById("last_name").focus();
}
if(errorMsg != ""){
alert(errorMsg);
document.getElementById("first_name").focus();
return false;
}else{
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "search_name.php";
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("result").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("result").innerHTML = "processing...";
}
}
</script>
</head>
<body>
<div class="left" id="search">
First Name: <input id="first_name" name="first_name" type="text" />
<br /><br />
Last Name: <input id="last_name" name="last_name" type="text" />
<br /><br />
<input name="myBtn" type="submit" value="Search" onClick="javascript:ajax_post();return">
<br /><br />
</div>
<div id="result"></div>
search_name.php
<?php $form_profile = '<form method="POST" action=""><table width="450px"><tr><td><label for="firstname" >First Name: </label></td><td><input type="text" id="first_name" name="first_name" maxlength="50" size="30" value="'.$first_name.'"/></td></tr><tr><td><label for="lastname" >Last Name: </label></td><td><input type="text" id="last_name" name="last_name" maxlength="50" size="30" value="'.$last_name.'"/></td></tr><tr><td><label for="headline">Headline</label></td><td><input type="text" id= "headline" name="headline" maxlength="50" size="30" value="'.$profile_headline.'"/></td></tr></table><input type="submit" id="submit" name="submit" value="Save and Update"></form>'; ?>
<?php
//check if form has been submitted
if(isset($_POST['submit'])){
$first_name= $_POST['first_name'];
$last_name= $_POST['last_name'];
$headline= $_POST['headline'];
$summary= $_POST['summary'];
$title_array= $_POST['title'];
$company_array= $_POST['company'];
$start_month_array= $_POST['start_month'];
$start_year_array= $_POST['start_year'];
$end_month_array= $_POST['end_month'];
$end_year_array= $_POST['end_year'];
if($first_name && $last_name){
//connect to server
$link = mysql_connect("localhost", "root", "########");
if($link){
mysql_select_db("mydatabase",$link);
}
//check if person exists
$exists = mysql_query("SELECT * FROM profile WHERE firstname = '$first_name' AND lastname = '$last_name'") or die ("The query could not be complete.");
if(mysql_num_rows($exists) != 0){
//update
mysql_query("UPDATE profile SET headline='$headline' WHERE firstname = '$first_name' AND lastname = '$last_name'") or die("Update could not be applied");
echo "Success!!";
}else echo "That alumni is not in the database";
}else echo "You must provide a first and last name.";
}
?>
As Timmy mentioned there is no submit value being posted (that only happens automatically if the post was triggered via a form). Also, you are trying to grab $_POST['first_name'] when you're sending 'firstname' (same goes for last_name vs lastname).
It's important to use some sort of developer tool when you are working with JavaScript / AJAX. I personally use Chrome Developer Tools (Press F12 in Chrome https://developers.google.com/chrome-developer-tools/). This will show you what the request / response actually looks like so you can figure out what your issues are. Based on what your front end it doing, I quickly rewrote the PHP script you are posting to:
<?php
//check if form has been submitted
if(isset($_POST['firstname']) || isset($_POST['lastname'])){
$first_name= $_POST['firstname'];
$last_name= $_POST['lastname'];
/*
$headline= $_POST['headline'];
$summary= $_POST['summary'];
$title_array= $_POST['title'];
$company_array= $_POST['company'];
$start_month_array= $_POST['start_month'];
$start_year_array= $_POST['start_year'];
$end_month_array= $_POST['end_month'];
$end_year_array= $_POST['end_year'];
*/
//connect to server
$link = mysql_connect("localhost", "root", "########");
if($link){
mysql_select_db("mydatabase",$link);
}
//check if person exists
$exists = mysql_query("SELECT * FROM profile WHERE firstname LIKE $first_name.'%' AND lastname LIKE $last_name.'%'") or die ("The query could not be completed.");
if(mysql_num_rows($exists) != 0){
//update
//mysql_query("UPDATE profile SET headline='$headline' WHERE firstname = '$first_name' AND lastname = '$last_name'") or die("Update could not be applied");
echo "Success!!";
} else {
echo "That alumni is not in the database";
}
} else {
echo "You must provide a first and last name.";
}
?>
I fixed the bad variable names and commented out the ones that are not being sent over at the moment. I also updated your MySQL query to use the LIKE string comparison function which is much better for searching. This way if someone doesn't know the last name, or only a portion, they can still finish the lookup. More on string comparison functions here: http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html. A copy and paste of the code should solve your problems for now.
Your javascript here:-
var vars = "firstname="+fn+"&lastname="+ln;
is not including "submit" which your PHP script requires to search the database, here:-
if(isset($_POST['submit'])){
So if you just add +"&submit=true" to the end of your vars variable, it should fix the given problem.
var vars = "firstname="+fn+"&lastname="+ln+"&submit=true";
Of course, you will see a lot of Undefined index warnings as your PHP script looks for lots of other variables that aren't sent initially =)
Hope this is of some help!

Categories

Resources