JQuery Post to PHP Inserts data, but json response is null - php

I'm building a simple sign up form with AngularJS and sending the data to a PHP page using JQuery's $.post(). When I send the data, it correctly gets inserted into the database. However, the returned json that I am logging is showing my data fields as null.
Console:
{"status":"success","email":null,"id":null,"sessionId":null}
Javascript:
$.post("admin/addUser.php", {
email: form.email,
password: form.password
}).done(function(data){
console.log(data);
});
PHP:
$email = mysql_real_escape_string($_POST["email"]);
$password = md5(mysql_real_escape_string($_POST["password"]));
$sessionId = md5(uniqid(microtime()) . $_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']);
//Add this user to the database
$sql = mysql_query("INSERT INTO users (email, password, sessionId) VALUES ('".$email."', '".$password."', '".$sessionId."')");
if ($sql){
//Now find the user we just added
$getUser = mysql_query("SELECT * FROM users WHERE email = '".$email."' AND sessionId = '".$sessionId."'");
if ($getUser){
$row = mysql_fetch_array($getUser);
$user = array(
'status' => 'success',
'email' => $row['email'],
'id' => $row['id'],
'sessionId' => $row['sessionId']
);
echo json_encode($user);
}else{
$user = array(
'error' => mysql_error()
);
echo json_encode($user);
}
}else{
$user = array(
'error' => mysql_error()
);
echo json_encode($user);
}

Are you sure that you have only one record in here
$getUser = mysql_query("SELECT * FROM users WHERE email = '".$email."' AND sessionId = '".$sessionId."'");
Try to dump $row and see the response. BTW I would suggest you to add limit
$getUser = mysql_query("SELECT * FROM users WHERE email = '".$email."' AND sessionId = '".$sessionId."' LIMIT 1");

Ok, I dug around and found the answer to this. It was a mistake on my end. I was only storing the password and sessionId as varchar(30). When I was generating the sessionId and checking it against the DB, it was being cut off when it was stored, since I was only allowing 30 chars. I update to 255 and works as expected :-P.

Related

No data passed using UnityWebRequest POST

I'm trying to retrieve some data from a MySQL database through php POST method to Unity.
But somehow, when I use the UnityWebrequest the post variable is always empty.
My C# script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class IDCheck : MonoBehaviour
{
int onlineID = -1;
readonly string urlCheckIdentifier = "http://www.mywebsite.php";
void Start(){
if (Application.internetReachability != NetworkReachability.NotReachable){
StartCoroutine("GetOnlineID");
}
}
void SetID(int _id){
onlineID = _id;
}
IEnumerator GetOnlineID(){
// TEST NUMBER 2
List<IMultipartFormSection> form = new List<IMultipartFormSection>();
form.Add(new MultipartFormDataSection("onlineid", "test"));
/* THIS WAS ATTEMPT NUMBER 1
WWWForm form = new WWWForm();
form.AddField("onlineid", "test");
*/
UnityWebRequest www = UnityWebRequest.Post(urlCheckIdentifier, form);
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError){
Debug.Log("Error on upload");
} else {
Debug.Log(www.downloadHandler.text);
DownloadData data = JsonUtility.FromJson<DownloadData>(www.downloadHandler.text);
bool idFound = (data.succes == false)?false:true;
if (!idFound){
Debug.Log("Didnt work");
Debug.Log(data.succes);
} else {
SetID(data.id);
Debug.Log(onlineID);
}
}
}
}
My PHP script:
<?php
include_once 'dbconnect.php';
// UNIQUE DEVIDE ID IS GIVEN FROM THE APP VIA POST METHOD
$onlineid = $_POST["onlineid"];
// CHECK IF ID EXISTS IN CURRENT USERS TABLE
$query = "SELECT id, username FROM users WHERE uniqueID='$onlineid'";
$result = mysqli_query($dbconnection, $query);
$row = mysqli_fetch_row($result);
if($row){
// IF ID WAS FOUND, RETURN JSON TO THE APP
$dataArray = array('success' => true, 'error' => '', 'id' => $row[1], 'username' => $row[2], 'TESTuniqueIDPassed' => $onlineid);
} else {
// ID WAS NOT FOUND, CREATING NEW ONE.
$query2 = "INSERT INTO users(uniqueID) VALUES ('$id')";
$result2 = mysqli_query($dbconnection, $query2);
// GETTING THE NEWLY CREATED ID FROM THE DB.
$query3 = "SELECT id, username FROM users WHERE uniqueID='$id'";
$result3 = mysqli_query($dbconnection, $query3);
$row3 = mysqli_fetch_row($result3);
// RETURNING JSON WITH THE NEW ID
$dataArray = array('success' => true, 'error' => '', 'id' => $row3[1], 'username' => $row3[2], 'TESTuniqueIDPassed' => $onlineid);
}
header('Content-Type: application/json');
//echo json_encode($dataArray);
echo $onlineid;
?>
As you can see I even tried to just echo the $onlineid which should be populated with the POST method from unity, but that's always returning an empty string.
I've tried google of course but most posts about this subject are pretty old.
The solution to add
www.chunkedTransfer = false;
in front of the yield return call is now depreciated, and another suggested solution was to put
www.useHttpContinue = false;
in front of the yield return also did nothing to solve the problem.
Anybody any ideas where to go from here?
Regards,
Mark
I've tried a couple of things in the meantime while waiting for an anwser.
Stumbled upon an anwser myself so I will post it for the next person to have the same issue:
Your link should start with https instead of http, because Unity does not allow insecure links anymore.
Using MultipartFormDataSection still wont work, but WWWForm will!

Need help reading/fixing login.php with Angular and Hashed Passwords

I recently integrated a basic login/register function on my website and need help understanding my login.php code. The basic tutorial I used for the login/register page didnt include password hashing which I am currently trying to integrate myself. Everything was working 100% as expected until I decided to add password hashing. I'm very new to php and how it works so I dont quite get why my code isn't working, but I understand the basic concept/workflow of hashing passwords which is answered in other questions.
A few notes: register is working fine with storing hashed passwords and database connection is successful. Also I have an api service that calls my login.php (code included) which could be the issue.
I tested my SQL querySELECT *, password FROM users where email='jim#gmail.com'and it successfully returns 1 user with all columns.
Edit: I understand this is not SQL injection proof, that is my next step. I am trying to do this correctly, but forgive me if my current code doesn't handle passwords correctly, it is part of the learning process. (this is not a live website)
Applicable Code:
Login.php
<?php
include_once("database.php");
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
if(isset($postdata) && !empty($postdata)){
$pwd = mysqli_real_escape_string($mysqli, trim($request->password));
$email = mysqli_real_escape_string($mysqli, trim($request->username));
$sql = "SELECT *, password FROM users where email='$email'";
if($result = mysqli_query($mysqli,$sql)){
$rows = array();
while($row = mysqli_fetch_assoc($result)){
$rows[] = $row;
}
if(password_verify($pwd, $rows['password'])){
echo json_encode($rows);
}
}
else{
http_response_code(404);
}
}
?>
I have tried to use both $row and $rows on line password_verify($pwd, $rows['password']) just in case I dont understand the retrieved object type.
Register.php
<?php
include_once("database.php");
$postdata = file_get_contents("php://input");
if(isset($postdata) && !empty($postdata)){
$request = json_decode($postdata);
$name = trim($request->name);
$pwd = mysqli_real_escape_string($mysqli, trim($request->pwd));
$email = mysqli_real_escape_string($mysqli, trim($request->email));
$hash = password_hash($pwd, PASSWORD_BCRYPT);
$sql = "INSERT INTO users(name,password,email) VALUES ('$name','$hash','$email')";
if ($mysqli->query($sql) === TRUE) {
$authdata = [
'name' => $name,
'pwd' => '',
'email' => $email,
'Id' => mysqli_insert_id($mysqli)
];
echo json_encode($authdata);
}
}
?>
api.service.ts (shortened)
public userlogin(username, password) {
//alert(username)
return this.httpClient.post<any>(this.baseUrl + '/login.php', { username, password })
.pipe(map(Users => {
this.setToken(Users[0].name);
this.getLoggedInName.emit(true);
return Users;
}));
}
public userregistration(name,email,pwd) {
return this.httpClient.post<any>(this.baseUrl + '/register.php', { name,email, pwd })
.pipe(map(Users => {
return Users;
}));
}
I dont completely understand how the api service is listening for output from login.php but it seems like echo json_encode($rows); line from login.php is the output??
Many thanks in advance for any tips, advice, or solutions!
Well, I figured it out...being new to php, I had a difficult time toubleshooting/debuging. It turns out that the data type for $rows would return null if I tried to reference $rows['password], but $rows is the correct datatype to return my User object. Anyone know why that is?
My solution is to fetch 2 results and create one for the password and one for the user object because running mysqli_fetch_assoc($result); multiple times attempts to fetch the next row in the result-set. I'm not sure if this is good programming practice so feel free to comment your thoughts on this method.
NOTE: THIS CODE IS NOT SQL INJECTION PROOF, DO NOT BLATANTLY IMPLEMENT WITHOUT FURTHER PDO STATEMENTS. AS OTHERS HAVE STATED, PASSWORDS SHOULD NOT BE HANDLED DIRECTLY IN THIS WAY.
login.php
<?php
include_once("database.php");
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
if(isset($postdata) && !empty($postdata)){
$pwd = mysqli_real_escape_string($mysqli, trim($request->password));
$email = mysqli_real_escape_string($mysqli, trim($request->username));
$sql = "SELECT * FROM users where email='$email'";
if($result = mysqli_query($mysqli,$sql)){
//$passchk = mysqli_fetch_assoc($result);
$rows = array();
while($row = mysqli_fetch_assoc($result)){
$rows[] = $row;
}
if($result2 = mysqli_query($mysqli, $sql)){
$passchk = mysqli_fetch_assoc($result2);
if (password_verify($pwd, $passchk['password'])){
echo json_encode($rows);
}
}
}
else{
http_response_code(404);
}
}
?>

Multiple Database requests for login

I have three files that are relevant for this part of my login scenario:
/project/index.html
/project/api/user/login.php
/project/api/objects/user.php
The index.html has a simple login form in it, calling the ./api/user/login.php.
In this form I have a checkbox that is an option for the user in order to stay logged in or not.
If the user has selected this option, with every login, I would like to check if the credentials are correct (login function -> stmt1 in user.php) as well as to update the lastlogin (datetime), the identifier and securitytoken if the checkbox was set (login function -> stmt2 in user.php).
The user.php is included_once in the login.php that gets the values out of the index.html form and sends them to the login() function in the user.php.
Depending on the functions return value, the login.php decides if the login was successful or not.
The login itself (stmt1) works, but the update of lastlogin, identifier and securitytoken (stmt2) doesn't.
login.php
session_start();
// include database and object files
include_once '../config/database.php';
include_once '../objects/user.php';
// get database connection
$database = new Database();
$db = $database->getConnection();
// prepare user object
$user = new User($db);
// set ID property of user to be edited
$user->username = isset($_GET['username']) ? $_GET['username'] : die();
$user->password = base64_encode(isset($_GET['password']) ? $_GET['password'] : die());
$user->remember = isset($_GET['remember']) ? $_GET['remember'] : die();
$stmt1 = $user->login();
if($stmt1->rowCount() > 0){
// get retrieved row
$row1 = $stmt1->fetch(PDO::FETCH_ASSOC);
$_SESSION['userid'] = $row1['uid'];
// create array
$user_arr=array(
"status" => true,
"message" => "Login erfolgreich!",
"uid" => $row1['uid'],
"username" => $row1['username']
);
$stmt2 = $user->login();
$row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
print_r($row2);
// create array
$user_arr=array(
"lastlogin" => $row2['lastlogin']
);
}
else{
$user_arr=array(
"status" => false,
"message" => "Benutzername und/oder Passwort nicht korrekt!",
);
}
// make it json format
print_r(json_encode($user_arr));
?>
user.php
function login(){
// select all query
$query1 = "SELECT
`uid`, `username`, `email`, `password`, `created`, `lastlogin`
FROM
" . $this->table_name . "
WHERE
username='".$this->username."' AND password='".$this->password."'";
// prepare query statement
$stmt1 = $this->conn->prepare($query1);
// execute query
$stmt1->execute();
return $stmt1;
// set up the remain logged in function
if(isset($this->remember)) {
$identifier = random_string();
$securitytoken = random_string();
$remember = ",identifier='".$identifier."',securitytoken='".$securitytoken."'";
setcookie("identifier",$identifier,time()+(3600*24*365)); //1 year valid
setcookie("securitytoken",$securitytoken,time()+(3600*24*365)); //1 year valid
} else {
$remember = "";
}
// update last login
$query2 = "UPDATE
" . $this->table_name . "
SET
`lastlogin` = '".date("Y-m-d H:i:s")."'
".$remember."
WHERE
username='".$this->username."' AND password='".$this->password."'";
// prepare query statement
$stmt2 = $this->conn->prepare($query2);
// execute query
$stmt2->execute();
return $stmt2;
}
function random_string(){
if(function_exists('random_bytes')) {
$bytes = random_bytes(16);
$str = bin2hex($bytes);
} else if(function_exists('openssl_random_pseudo_bytes')) {
$bytes = openssl_random_pseudo_bytes(16);
$str = bin2hex($bytes);
} else if(function_exists('mcrypt_create_iv')) {
$bytes = mcrypt_create_iv(16, MCRYPT_DEV_URANDOM);
$str = bin2hex($bytes);
} else {
//secret key should have >12 random chars
$str = md5(uniqid('SECRET KEY', true));
}
return $str;
}
In the user.php after return $stmt1;
The code is returned and the cookies are not set
I would do this... Check login... If true, save cookies with id and token
And then periodically check if token and id correspond... If so... Just UPDATE the last login time.
Note: your prepared statement is vulnerable!! Dont append the parameters with '.' use placeholders instead, and dont encode the password, is better to hash it... Then compare hashes

PHP get data from jquery

Im trying to write a simple prgram that the server can get data from client.
I write a simple code in my script
var str = "testString";
$.post("http://anonymous.comze.com/test1.php", { string: str });
in the server,
$var = $_POST['string']; // this fetches your post action
$sql2 = "INSERT INTO afb_comments VALUES ('3',$var)";
$result2= mysql_query($sql2,$conn);
The question is var is always null. The sql2 can be executed if I change $var into "1111" for example,
but if I put $var, it doesn't work. Can anyone give some advice?
your are passing string to the query so it should be
$var = $_POST['string']; // this fetches your post action
$sql2 = "INSERT INTO afb_comments VALUES ('3','".$var."')";
$result2= mysql_query($sql2,$conn);
please also check datatype of the that column.
Use this example and learn from this code how to get data
Or
use can also use this link:
http://api.jquery.com/jQuery.get/
$user and $pass should be set to your MySql User's username and password.
I'd use something like this:
JS
success: function(data){
if(data.status === 1){
sr = data.rows;
}else{
// db query failed, use data.message to get error message
}
}
PHP:
<?php
$host = "localhost";
$user = "username";
$pass = "password";
$databaseName = "movedb";
$tableName = "part parameters";
$con = mysql_pconnect($host, $user, $pass);
$dbs = mysql_select_db($databaseName, $con);
//get the parameter from URL
$pid = $_GET["pid"];
if(empty($pid)){
echo json_encode(array('status' => 0, 'message' => 'PID invalid.'));
} else{
if (!$dbs){
echo json_encode(array('status' => 0, 'message' => 'Couldn\'t connect to the db'));
}
else{
//connection successful
$sql = "SELECT `Processing Rate (ppm)` FROM `part parameters` WHERE `Part Number` LIKE `" . mysqli_real_escape_string($pid) . "`"; //sql string command
$result = mysql_query($sql) or die(mysql_error());//execute SQL string command
if(mysql_num_rows($result) > 0){
$rows = mysql_fetch_row($result);
echo json_encode(array('status' => 1, 'rows' => $rows["Processing Rate (ppm)"]);
}else{
echo json_encode(array('status' => 0, 'message' => 'Couldn\'t find processing rate for the give PID.'));
}
}
}
?>
As another user said, you should try renaming your database fields without spaces so part parameters => part_parameters, Part Number => part_number.

FB API inserting user_id that belongs to Open User account

This is easily the most bizarre problem that I've ever run into while using the FB api. Maybe I'm just too much of a n00b with their API, but here goes.
I'm using the login button for my site. Upon click, the user will be presented with a pop up from FB telling them some basic info about my app (basic details, number of active users and permissions that it is requesting)
That's all fine and dandy. If the user accepts the app, the page will be reloaded and their info that is being requested from the app will be inserted into the DB and a session will be created.
session_start();
require_once("model/functions.php");
require_once("controller.php");
require_once("model/facebook_api/src/facebook.php");
$facebook = new Facebook(array(
'appId' => '123456789',
'secret' => '123456789',
'cookie' => true
));
$access_token = $facebook->getAccessToken();
$facebook->setAccessToken($access_token);
if($access_token != "")
{
$user = $facebook->getUser();
if($user != 0)
{
$user_profile = $facebook->api("/".$user);
$fb_id = $user;
$fb_first_name = $user_profile['first_name'];
$fb_last_name = $user_profile['last_name'];
$fb_email = $user_profile['email'];
// The FB user_id and all of their other info is correct. Seriously!!
echo $fb_id."<br />";
print_r($user_profile);
// Query the DB to see if this person's info from FB is in there
$query = "SELECT *
FROM users
WHERE fb_id = :fb_id";
$stmt = $db->prepare($query);
$stmt->execute(array(':fb_id' => $fb_id));
$count = $stmt->rowCount();
if($count == 1)
{
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$_SESSION['id'] = $row['user_id'];
$_SESSION['fb_id'] = $row['fb_id'];
$_SESSION['first'] = $row['first_name'];
$_SESSION['last'] = $row['last_name'];
$_SESSION['email'] = $row['email'];
$_SESSION['photo'] = $row['photo'];
$_SESSION['accuracy'] = $row['accuracy_rate'];
}
} else
{
$img_data = file_get_contents('https://graph.facebook.com/'.$fb_id.'/picture?type=large');
$save_path = 'img/profile_pics/large/';
file_put_contents($save_path.''.$fb_id.'.jpg', $img_data);
$insert = "INSERT INTO
users
(first_name,
last_name,
email,
photo,
fb_id,
accuracy_rate,
date_joined,
date_joined_int)
VALUES
(:first_name,
:last_name,
:email,
:photo,
:fb_id,
:points,
:date_joined,
:date_int)";
$params = array(':first_name' => $fb_first_name,
':last_name' => $fb_last_name,
':email' => $fb_email,
':photo' => $fb_id.'.jpg',
':fb_id' => $fb_id,
':points' => '100',
':date_joined' => date("M j, Y"),
':date_int' => idate('z'));
$stmt = $db->prepare($insert);
$stmt->execute($params)or die('error');
print_r($params);
// Query the DB to see if this person's info from FB is in there
$query = "SELECT *
FROM users
WHERE fb_id = :fb_id";
$stmt = $db->prepare($query);
$stmt->execute(array(':fb_id' => $fb_id));
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$_SESSION['id'] = $row['user_id'];
$_SESSION['fb_id'] = $row['fb_id'];
$_SESSION['first'] = $row['first_name'];
$_SESSION['last'] = $row['last_name'];
$_SESSION['email'] = $row['email'];
$_SESSION['photo'] = $row['photo'];
$_SESSION['accuracy'] = $row['accuracy_rate'];
}
}
} else
{
}
} else
{
}
A row is inserted into the DB each time the page is refreshed. No session is ever created. What's even stranger is that the facebook id that is inserted into the fb_id column in the DB belongs to an account that belongs to a test account that FB uses to test open graph actions that are submitted for approval. I know because after taking a deeper look at the DB, I saw a row in the DB that belonged to an FB open graph actions testers. The ID is "2147483647." That is clearly not the ID that is printed out when I printed out the $user_profile array. Furthermore, after the first time the page is reloaded, an insert query shouldn't even occur because the rowCount returned is set to 1. The insert query is only supposed to be executed if the user is a first time user. Sandbox mode isn't on. I thought might have had something to do with it. But, it didn't.
On an unrelated note, is there a bug with FB's api when it comes to doing
$facebook->api("/me");
That doesn't seem to work.
$facebook->api("/".$user);
seems to work just fine though.
Live example can be found here
Facebook user_id could go beyond the supported Integer length. Discovered this on iPhone SDK for a long ID eg. '10000328862128237'. I suspect that is your problem too as I got the exact same number '2147483647'.

Categories