I'm new to PHP programming and I'm trying to test out a login page alongside JSON and MySQL. I managed to make most of it functional but I can't seem to find a way to make the query in which I verify the username and password to work.
Please help.
Here's the code:
login.js:
$(document).ready(function(){
$('#errorLogin').hide();
$('#formLogin').submit(function(e){
var username=$('#inputUser').val();
var password=$('#inputPassword').val();
$.ajax({
type:'get',
dataType: 'json',
url: 'dist/php/connection-login.php',
data: {
user: username,
pass: password
},
success: function(e){
console.log(e);
}
});
});
});
connection-login.php:
<?php
$con = new mysqli("localhost", "root", "root", "solucionar_manutencoes_db");
$lg_user=$_GET['user'];
$lg_password=$_GET['pass'];
if (mysqli_connect_errno()) trigger_error(mysqli_connect_error());
$qry = mysqli_query($con, "SELECT * FROM tb_login WHERE lg_user = '$lg_user' AND lg_password = '$lg_password';");
$result = mysqli_fetch_assoc($qry);
$row = mysqli_fetch_assoc($result);
if ($row != 0) {
$response["success"] = 1;
echo json_encode($response);
}
else {
$response["failed"] = 0;
echo json_encode($response);
}
?>
Your PHP should be more like:
connect.php - make sure this is a separate secure page
<?php
function db(){
return new mysqli('localhost', 'root', 'root', 'solucionar_manutencoes_db');
}
?>
I would change your JavaScript AJAX to a POST request, unless you have a reason for it.
connection-login.php
<?php
sesson_start(); include 'connect.php';
if(isset($_POST['user'], $_POST['pass'])){
$db = db(); $r = array();
$prep = $db->prepare('SELECT `lg_user` FROM login WHERE `lg_user`=? && lg_user=?');
$prep->bind_param('ss', $_POST['user'], $_POST['pass']); $prep->execute();
if($prep->num_rows){
$prep->bind_result($lg_user); $r['user'] = $lg_user;
$_SESSION['logged_in'] = $lg_user;
}
echo json_encode($r);
}
?
Now if your JavaScript AJAX result does not contain the a e.user then they are not logged in. Of course, you would probably want to store the original password as a SHA1 or stronger and use AES_ENCRYPTION or better for Personal Information, along with SSL.
I see several errors in your code. The first is that you are executing mysqli_fetch_assoc twice: once on the result, and then again on the array the first call returned. The next is that the $response variable was never declared. Here is the fixed PHP script:
<?php
$con = mysqli_connect("localhost", "root", "root", "solucionar_manutencoes_db");
$lg_user=$_GET['user'];
$lg_password=$_GET['pass'];
if (mysqli_connect_errno()) trigger_error(mysqli_connect_error());
$qry = mysqli_query($con, "SELECT * FROM tb_login WHERE lg_user = '$lg_user' AND lg_password = '$lg_password';");
$results = mysqli_fetch_assoc($qry);
$response = [];
if (count($results) != 0) {
$response["success"] = 1;
echo json_encode($response);
}
else {
$response["failed"] = 0;
echo json_encode($response);
}
?>
In your JavaScript make sure to use e.preventDefault() inside #formLogin's submit handler to prevent page reload when that form is submitted.
Related
I'm doing a login with ajax, html and php.
I've already debbuged the php, it's ok and it's returning the json variable I need in the ajax call.
I have this ajax function:
$(document).ready(function(){
$('#login').submit(function() {
var username=$("#username").val();
var password=$("#password").val();
$.ajax({
url: 'login.php',
data: {
username: username,
password: password
},
type: 'post',
dataType: 'json',
success:function(response){
alert(response);
if(response.validacion == "ok"){
alert("Bienvenidos"),
localStorage.loginstatus = "true",
window.location.assign("home.php");
}
if(response.validacion == "error"){
window.location.assign("login.html"),
alert("Datos de usuario incorrectos, inténtelo nuevamente");
}
}
});
});
});
This is the login.php code: (I know it's really bad save password in cookies, but this is my solution for now)
<?php
session_start();
?>
<?php
include 'conexion.php';
if(isset($_POST['username'] && $_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
}
$sql = "SELECT * FROM User WHERE username = '$username' OR Email ='$username'";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_array(MYSQLI_ASSOC);
$hash = $row['password'];
if (password_verify($password, $hash)) {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $row['username'];
$_SESSION['start'] = time();
setcookie("COOKIE_INDEFINED_SESSION", TRUE, time()+31622400);
setcookie("COOKIE_DATA_INDEFINED_SESSION[username]", $username, time()+31622400);
setcookie("COOKIE_DATA_INDEFINED_SESSION[password]", $password, time()+31622400);
echo "Sesión abierta indefinidamente.<br/>";
$respuesta["validacion"] = "ok";
$respuesta["id"] = $row["idUser"];
$respuesta["username"] = $row["username"];
}else{
$respuesta["validacion"] = "error";
$respuesta["mensaje"] = "Contraseña incorrecta";
}mysqli_close($connection);
}else{
$respuesta["validacion"] = "error";
$respuesta["mensaje"] = "Usuario incorrecto";
}mysqli_close($connection);
// encoding array to json format
echo json_encode($respuesta);
?>
I did and inspect element, the username and password are ok, login.php is called, but when I continue the inspection from the line 20, this works until the line 25 aprox and skips to the line 44, the success:function(function) is skipped and the "response" variable is undefined but the login.php is returnint this variable ok:
What am I doing wrong? (sorry for my english, I'm spanish speaker)
Ok, I've solved the problem so I'm going to post what I've done for those who have the same problem:
the function success:function(response) is taking ALL the "echo" from the login.php, so the first "echo" when the login is ok, is the trouble and response become an undefined var.
When I post with the wrong credentials, I only have one echo (the json_encode) and I had not problem with the ajax. So the solution will be this, in the php, after the if(password_verify):
if (password_verify($password, $hash)) {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $row['username'];
$_SESSION['start'] = time();
setcookie("COOKIE_INDEFINED_SESSION", TRUE, time()+31622400);
setcookie("COOKIE_DATA_INDEFINED_SESSION[username]", $username, time()+31622400);
setcookie("COOKIE_DATA_INDEFINED_SESSION[password]", $password, time()+31622400);
$respuesta["validacion"] = "ok";
$respuesta["id"] = $row["idUser"];
$respuesta["username"] = $row["username"];
}else{
$respuesta["validacion"] = "error";
$respuesta["mensaje"] = "Contraseña incorrecta";
}
}else{
$respuesta["validacion"] = "error";
$respuesta["mensaje"] = "Usuario incorrecto";
}
mysqli_close($connection);
// encoding array to json format
echo json_encode($respuesta);
?>
In order to get the value from the response, you need to JSON.parse() it first to allow your self to use response.validacion
my PHP code was working fine until I decided to use jquery for my signup page to handle and check the fields, it's working there is no error, everything is submitted to the server correctly so there is no problem with the code PHP nor jquery, but the header("location: ../****.php") no longer send me to another page after I hit submit, instead it loads the new page on top of the old one without refreshing.
This is my jquery code for the signup page:
<script>
$(document).ready(function() {
$("#myForm").submit(function(event){
event.preventDefault();
var username = $("#signup-username").val();
var pwd = $("#signup-pwd").val();
$(".form-message").load("includes/user-signup.inc.php",{
username: username,
pwd: pwd
});
});
});
</script>
and this is my PHP code in my include page:
<?php
if (isset($_POST['submit'])){
include_once 'dbh.inc.php';
$username= mysqli_real_escape_string($conn, $_POST['username']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
$errorEmpty = $errorValid = false;
if(empty($username)|| empty($pwd)){
echo "Fill in all Fields!";
$errorEmpty = true;
}
else{
$stmt = $conn->prepare("SELECT * FROM users WHERE username=?");
$stmt->bind_param("s", $uid);
$uid = $username;
$stmt->execute();
$result = $stmt->get_result();
$usernamecheck = mysqli_num_rows($result); // check if the results
$rowNum = $result->num_rows;
if($rowNum > 0){
echo "Username is taken!";
$errorValid = true;
}
else{
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
$stmt = $conn->prepare("INSERT INTO users (username, pwd) VALUES (?, ?)");
$stmt->bind_param("ss",$uid, $password);
$uid = $username;
$password = $hashedPwd;
$stmt->execute();
$result = $stmt->get_result();
header("location: ../user-login.php");
}
}
}else{
header("location: ../user-signup.php");
exit();
}
?>
<script>
$("#signup-username, #signup-pwd").removeClass("input-error");
var errorEmpty = "<?php echo $errorEmpty; ?>";
var errorValid = "<?php echo $errorValid; ?>";
if (errorEmpty == true $$ errorValid == true){
$("#signup-username, #signup-pwd").addClass("input-error");
if (errorFEmpty == false && errorValid == false){
$("#signup-username, #signup-pwd,").val("");
}
</script>
how do I fix this?
$(".form-message").load("includes/user-signup.inc.php",{
username: username,
pwd: pwd
});
When the above code gets to the point where header("Location: file.php");
It'll fetch that file into $(".form-message")
To Avoid this you can use ajax to post data and javascript inbuilt redirection
$.ajax({
type: "POST",
url: "includes/user-signup.inc.php",
data: "username="+ username +"&pwd="+ pwd,
success: function(data) {
window.location.href = "../****.php";
}
});
Hope this answer was helpful.
Your code operates exactly as it should.
$(document).ready(function() {
$("#myForm").submit(function(event){
// THIS LINE RIGHT HERE
event.preventDefault();
******************
$(".form-message").load("includes/user-signup.inc.php",{
******************
});
});
});
Event prevent default stops the redirect action. Additionally you then use jquery to load the contents of the file into the DOM element with the class:
.form-message
Remove event.preventDefault();
login.js
$http({
url: 'http://ipadress/login.php',
method: 'POST',
data: {
'var_id': $scope.form.txt_id,
'var_pass': $scope.form.txt_pass
}
}//http
login.php
<?php
session_start();
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
mysql_connect("localhost","root","password");
mysql_select_db("db");
$data = file_get_contents("php://input");
$dataJsonDecode = json_decode($data);
$var_id = $dataJsonDecode->var_id;
$var_pass = $dataJsonDecode->var_pass;
$sql = "SELECT * FROM user WHERE user_login = '".($id)."' and user_pass = '".md5($pass)."'";
$query = mysql_query($sql);
$result = mysql_fetch_array($query);
$resource = mysql_query($sql);
$count_row = mysql_num_rows($resource);
if (!$result) {
$results = '{"results":"not match"}';
} else {
$_SESSION["users_login"] = $result["users_login"];
session_write_close();
if($count_row > 0){
$results = '{"results":"match"}';
} else {
$results = '{"results":"Error"}';
}
}
echo $results;
?>
$http.get('http://ipaddress/data_user.php')
.then(function (response) {
console.log(response.data.results);
$scope.myData = response.data.results;
}, function (error) {
console.log(error);
});
user_data.php
<?php
session_start();
if($_SESSION['users_login'] == ""){
$results = '{"results":"Please Login"}';
echo $results;
}
else{
mysql_connect("localhost","root","password");
mysql_select_db("db");
mysql_query( "SET NAMES UTF8" );
$sql = "SELECT * FROM users WHERE users_login = '".$_SESSION["users_login"]."' ";
$query = mysql_query($sql);
$count_row = mysql_num_rows($query);
if($count_row > 0){
while($result = mysql_fetch_array($query)){
$rows[] = $result;
}
$data = json_encode($rows);
$totaldata = sizeof($rows);
$results = '{"results": '.$data.'}';
}
echo $results;
}
?>
I have problem with login. My $results = please login.
First check what $result["users_login"] contains..
You are getting the please login because you don't have the session data.
I am not sure about your approach, but don't mix php session and Ionic, You can create a kind of API to check user credentials from your ionic App, or else handle it in the ionic app.
Session normally used in websites to pass data through out the page, not for API calls. Think of scenario 10 users access your app simultaneously, How you going to use the Session to verify them?
My advise is, instead of using PHP sessions, you can handle your sessions inside your app using the session storage
Read this. There are plenty of plugin available. OR you can create your as shown here
Good Luck!!
I am trying to insert values from an input field into a database with ajax as part of a conversation system.I am using an input form as follows.
<input data-statusid="' .$statuscommentid. '" id="reply_'.$statusreplyid.'" class="inputReply" placeholder="Write a comment..."/>
with the following jquery I carry out a function when the enter key is pressed by the user.
$(document).ready(function(){
$('.inputReply').keyup(function (e) {
if (e.keyCode === 13) {
replyToStatus($(this).attr('data-statusid'), '1',$(this).attr("id"));
}
});
});
within this function is where I am having the problem ,I have no problems calling the function with jquery but I have done something wrong with the ajax and I don't know what?
$.ajax({ type: "POST", url: $(location).attr('href');, data: dataString, cache: false, success: function(){ $('#'+ta).val(""); } });
Additionally this is the php I am using to insert into the database
<?php //status reply input/insert
//action=status_reply&osid="+osid+"&user="+user+"&data="+data
if (isset($_POST['action']) && $_POST['action'] == "status_reply"){
// Make sure data is not empty
if(strlen(trim($_POST['data'])) < 1){
mysqli_close($db_conx);
echo "data_empty";
exit();
}
// Clean the posted variables
$osid = preg_replace('#[^0-9]#', '', $_POST['sid']);
$account_name = preg_replace('#[^a-z0-9]#i', '', $_POST['user']);
$data = htmlentities($_POST['data']);
$data = mysqli_real_escape_string($db_conx, $data);
// Make sure account name exists (the profile being posted on)
$sql = "SELECT COUNT(userid) FROM user WHERE userid='$userid' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
if($row[0] < 1){
mysqli_close($db_conx);
echo "$account_no_exist";
exit();
}
// Insert the status reply post into the database now
$sql = "INSERT INTO conversation(osid, userid, postuserid, type, pagetext, postdate)
VALUES('$osid','$userid','$postuserid','b','$pagetext',now())";
$query = mysqli_query($db_conx, $sql);
$id = mysqli_insert_id($db_conx);
// Insert notifications for everybody in the conversation except this author
$sql = "SELECT authorid FROM conversation WHERE osid='$osid' AND postuserid!='$log_username' GROUP BY postuserid";///change log_username
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$participant = $row["postuserid"];
$app = "Status Reply";
$note = $log_username.' commented here:<br />Click here to view the conversation';
mysqli_query($db_conx, "INSERT INTO notifications(username, initiator, app, note, date_time)
VALUES('$participant','$log_username','$app','$note',now())");
}
mysqli_close($db_conx);
echo "reply_ok|$id";
exit();
}
?>
Thanks in advance for any help it will be much appreciated
Why didn't you set the proper URL for Ajax calls instead of using location.href?
var ajax = ajaxObj("POST", location.href);
In additional, I guess ajaxObj is not defined or well coded. You are using, jQuery, why don't you try jQuery ajax?
http://api.jquery.com/jquery.ajax/
var ajax = ajaxObj("POST", location.href);
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "reply_ok"){
var rid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g,"<br />").replace(/\r/g,"<br />");
_("status_"+sid).innerHTML += '<div id="reply_'+rid+'" class="reply_boxes"><div><b>Reply by you just now:</b><span id="srdb_'+rid+'">remove</span><br />'+data+'</div></div>';
_("replyBtn_"+sid).disabled = false;
_(ta).value = "";
alert("reply ok!");
} else {
alert(ajax.responseText);
}
ajax.send("action=status_reply_ok&sid="+sid+"&user="+user+"&data="+data);
}
}
I have a question re. receiving data from php-function to ajax.
Ajax (in html-file):
function showUser(name) {
$.ajax({
type: 'POST',
url: '/api.php',
data: {
name : "\""+name+"\"",
func_id : "1"
},
dataType: 'json',
success: function(data)
{
if (data == null) {
console.log("Something went wrong..");
} else {
console.log(data);
Php (separate php-file):
<?php
error_reporting(E_ALL);
//MySQL Database connect start
$host = "localhost";
$user = "root";
$pass = "root";
$databaseName = "TFD";
$con = mysqli_connect($host, $user, $pass);
if (mysqli_connect_errno()) {
echo "Failed to connect to database: " . mysqli_connect_error();
}
$dbs = mysqli_select_db($con, $databaseName);
//MySQL Database connect end
$func_id = $_POST['func_id'];
function showUser() {
global $con;
$name = $_POST['name'];
$sql = "SELECT * FROM users WHERE first_name=$name";
$result = mysqli_query($con, $sql);
$array = mysqli_fetch_row($result);
mysqli_close($con);
echo json_encode($array);
}
if ($func_id == "1") {
showUser();
}
?>
The question: Everything works if I don't have the showUser-function in the php, i.e. I receive correct output to ajax if I have all php code in the "root" directly, but when I put that part in a function I don't get anything sent to ajax. The Network-panel in Chrome shows correct query from the sql so $array contains correct data, but I don't receive it in ajax.
Is there a fix for this?
Thanks!
The reason may be that the variables inside a function're visible only for function itself. Try this way:
$name = $_POST['name'];
function showUser($name) {
global $con;
$sql = "SELECT * FROM users WHERE first_name=$name";
$result = mysqli_query($con, $sql);
$array = mysqli_fetch_row($result);
mysqli_close($con);
echo json_encode($array);
}
Note: If you'll use 'mysql_escape_string' to prevent sql injections, don't forget to connect to db first, otherwise 'mysql_escape_string' will return empty string.