Error in JSON response from PHP file when hosted online - php

if($tag == 'signin'){
// check for user
$email = mysql_real_escape_string(trim($_POST['username']));
$password = mysql_real_escape_string(trim($_POST['password']));
if(isset($email) && !empty($email) && isset($password) && !empty($password)){
$result = getUserByEmailAndPassword($email, $password);
if ($result != false) {
// user found
$response["error"] = FALSE;
$response['uid'] = $result['uid'];
$response['email'] = $result['email'];
$response['username'] = $result['username'];
$response['password'] = $result['password'];
$response['endyear'] = $result['endyear'];
$response['phone'] = $result['phone'];
$response['currentyear'] = $result['currentyear'];
$response['currentsem'] = $result['currentsem'];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = TRUE;
$response["error_msg"] = "Incorrect email or password!";
header('Content-Type: application/x-www-form-urlencoded');
echo json_encode($response);
}
}else{
$response["error"] = TRUE;
$response["error_msg"] = "Required parameter 'username' or 'password' is missing!";
echo json_encode($response);
}
}
I am using the above php code for my API
am I using header('Content-Type: application/x-www-form-urlencoded'); in the right place?
Also, when I check this request on my Advanced REST client in chrome, the request is just fine. the response is below:
{"tag":"signin","error":false,"uid":"10","email":"example#exmaple.com","username":"jammy","password":"40be4e59b9a2a2b5dffb918c0e86b3d7","endyear":null,"phone":null,"currentyear":null,"currentsem":null}
However, when I run the same thing on any online response checker, the response is all garbage HTML. Same with my application hosted online
I noticed that the chrome extension by default sets the Content-Type to application/x-www-form-urlencoded
The same code used to work fine when I was running my application on xampp on localhost, however, after I uploaded this online, I am facing this issue
Could someone pls help me figure what I am doing wrong

It is not mandatory but if you plan to return JSON, the right header should be
header('Content-Type: application/json');
Otherwise, the receiver of the response may or may not interpret the body response as JSON.

I was able to locate the root cause of the problem. I made a lot of changes to the code only to realize later that this was due to MySQL DB tables
The tables I created on my local used InnoDB engine whereas my hosting provider provided on MyISAM engine.
All the tables created by importing the SQL file had engine set to MyISAM. I hosted the tables on a different provider with InnoDB engine and everything seemed to work fine.
Thank you everyone for trying to help

Related

(Solved) Some locally working sessions and functions suddenly don't work any more on the remote server

I began to learn code only three months ago, so it's possible for all the mystery to be just a beginner's mistake. Let's summarize the problem:
I made a CMS that still run well on localhost (wampserver with PHP 7.3) but suddenly stopped to run well on my domain (OVH hoster). What is mysterious is that the problem occurred when, after having relocated the CMS on a subdomain (it still worked then), I regenerated the LetsEncrypt SSL certificates (at this point it stopped working).
I contacted the hoster: apparently the SSL certificates are fine. The pages that stopped working all use session variables : captcha, forgot, login, logout, registration.
So I checked many session variables problems threads here, but it still didn't help for my situation.
For example: I tried to var_dump some session variables on the subdomain: nothing strange, it shows exactly what is expected. I then wondered if it was a CHMOD problem so I checked if all the files were actually CHMOD 644 : they are. I tried to revert back to PHP 7.2 : changed nothing. I even removed some .htaccess files to check if they were so poorly setted it caused the problem: changed nothing (I put them back since).
My hosting plan won't allow me to access php.ini to compare the server version with my local version. So I'm kind of stuck.
Update
I have a new hypothesis: the server doesn't handle my POST methods as it handled them before. In the developer tools, the echoed POST method file was just "/".
I added the following condition to my ifItIsMethod function (the function is described at the end of this post):
if(empty($_SERVER['CONTENT_TYPE'])) {
$_SERVER['CONTENT_TYPE'] = "application/x-www-form-urlencoded";
}
and now the POST method file returns "index", which sounds like a progress. I'll edit tomorrow my .htaccess files to set the post_max_size, but the new hypothesis is HTTP (or IIS) messing up with POST.
Day 7:
setting the attribute "name" to "submit" in the input field doesn't change the result
editing the post_max_size in .htaccess is forbidden by the hoster (it returns a 500 Internal Server Error)
var_dump($_POST) echoes what is normally expected (nothing from the form is missing)
So I var_dumped each variable of my (very basic) login_user function:
function login_user($username, $password)
{
global $connection;
$username = escape($username);
$password = escape($password);
$query = "SELECT * FROM users WHERE user_name = '{$username}' ";
$select_user_query = mysqli_query($connection, $query);
if (!$select_user_query) {
die("QUERY FAILED");
}
while($row = mysqli_fetch_assoc($select_user_query)) {
$db_id = $row['user_id'];
$db_name = $row['user_name'];
$db_password = $row['user_password'];
$db_firstname = $row['user_firstname'];
$db_lastname = $row['user_lastname'];
$db_email = $row['user_email'];
$db_role = $row['user_role'];
}
$password_verify = password_verify($password, $db_password);
if($username === $db_name && $password_verify === true) {
$_SESSION['user_id'] = $db_id;
$_SESSION['user_name'] = $db_name;
$_SESSION['user_firstname'] = $db_firstname;
$_SESSION['user_lastname'] = $db_lastname;
$_SESSION['user_email'] = $db_email;
$_SESSION['user_role'] = $db_role;
redirect("admin");
} else {
redirect("index");
}
}
$row has all the expected informations
$_SESSION has nothing...
... but it's because password_verify() returns "false"
The new hypothesis was then: maybe a change in the server messed up with the password decryption, let's just try to change it.
But the forgot page is also broken! And this functionnality doesn't use password_verify.
Its PHP part is as follows:
if(ifItIsMethod("post")) {
if(isset($_POST['email'])) {
$email = escape($_POST['email']);
$length = 50;
$token = bin2hex(openssl_random_pseudo_bytes($length));
if(email_exists($email)) {
$query = "UPDATE users SET token = ? WHERE user_email = ?";
$stmt = mysqli_prepare($connection, $query);
mysqli_stmt_bind_param($stmt, "ss", $token, $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
$mail = new PHPMailer(true);
$mail->isSMTP(true);
$mail->Host = SMTP_HOST;
$mail->Username = SMTP_USER;
$mail->Password = SMTP_PASSWORD;
$mail->Port = SMTP_PORT;
$mail->SMTPAuth = true;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->isHTML(true);
$mail->CharSet = "UTF-8";
$mail->setFrom('postmaster#raphaelbadawi.fr', 'RB Blog Postmaster');
$mail->addAddress($email);
$mail->Subject = "RB Blog - Réinitialisation de votre mot de passe utilisateur";
$mail->Body = "<h4>Bonjour,</h4><p>Cliquez sur le lien suivant pour réinitialiser votre mot de passe : <a href='https://blog.raphaelbadawi.fr/reset.php?email=" . $email . "&token=". $token ."'>lien</a>.</p><small>L'équipe RB Blog</small>";
if($mail->send(true)) {
$emailSent = true;
}
} else {
$msg = "Cette adresse ne correspond à aucun utilisateur connu";
}
}
}
And here is the ifItisMethod function:
function ifItIsMethod($method = null) {
if(empty($_SERVER['CONTENT_TYPE'])) {
$_SERVER['CONTENT_TYPE'] = "application/x-www-form-urlencoded";
}
if($_SERVER['REQUEST_METHOD'] == strtoupper($method)) {
return true;
} else {
return false;
}
}
I don't know what to do next.
Day 8 :
Checked the SQL tables just in case: token is text, password is varchar 255, seems fine.
Day 8.5 :
PROBLEM SOLVED! The database contained passwords that were hashed locally. Rehashing them using the remote server basically solved the login. The forgot function was buggy because of an obsolete $_GET check I forgot to mute at the top of the page (in the first version of this function, the token was passed through the URL).
I wanted to thank you all for all the time and mind you put into this issue. It did help eliminate some hypothesis. Without you I would surely still be at it. Thanks!
Sounds like the cookie issue.
With PHP your session ID is kept in a cookie, but cookies can be restricted by it's domain, expiry time (which can be affected by the server and end up being time in the past) and the path. Please make sure those match the new server setup.
This is the usual problem with cookies/sessions when migrating

Login system: $_POST['username'] and $_POST['password'] are always empty

Let me first start by saying that I have searched endlessly on Google for help and have literally spent the past x hours debugging the same error but I just can't figure it out.
I am following this tutorial on how to create a login system for my Android app. When I run my app on Genymotion, I am able to enter my login credentials but as soon as I hit the login button my app crashes. I ran my app again in debug mode and the cause of this was because of the following exception:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
Correct me if im wrong, but I think what is happening is that my JSONParser is trying to parse an empty object. This could be because my PHP file is always returning empty and I don't know why that is.
if(isset($_POST['username'])) {
$password=$_POST["username"];
}
if(isset($_POST['password'])) {
$password=$_POST["password"];
}
if (!empty($_POST))
{
if (empty($_POST['username']) || empty($_POST['password']))
{
// Create some data that will be the JSON response
$response["success"] = 0;
$response["message"] = "One or both of the fields are empty .";
//die is used to kill the page, will not let the code below to be executed. It will also
//display the parameter, that is the json data which our android application will parse to be
//shown to the users
die(json_encode($response));
}
$query = " SELECT * FROM login WHERE username = '$username'and password='$password'";
$sql1=mysql_query($query);
$row = mysql_fetch_array($sql1);
if (!empty($row))
{
$response["success"] = 1;
$response["message"] = "You have been sucessfully login";
die(json_encode($response));
}
else
{
$response["success"] = 0;
$response["message"] = "invalid username or password ";
die(json_encode($response));
}
}
else
{
$response["success"] = 0;
$response["message"] = " One or both of the fields are empty ";
die(json_encode($response));
}
I think you forgot to set the JSON header.
If you are returning JSON , You need to change the code like this
$data = $response;
header('Content-Type: application/json');
echo json_encode($data);

Not getting the JSON data in PHP

I am creating an android application and submit the user details from Android application to php at server side by JSON. But at server side I am not getting the JSON data. At server side php the JSON comes from android application is seems null. I am using POST method for this. I know that my POST method code is wrong in PHP at server side. But I have no idea to solve this.
Here is my PHP code for getting JSON. Every time I get same message:
Required fields missing
Code:
<?php
/*
* Following code will create a new user row
* All user details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
print_r($_POST);
// check for required fields
if (isset($_POST['Firstname']) && isset($_POST['Lastname']) && isset($_POST['Username']) && isset($_POST['Email']) && isset($_POST['Password']) && isset($_POST['Country']) && isset($_POST['Mobile'])) {
echo('bhargavi');
$Firstname = $_POST['Firstname'];
$Lastname = $_POST['Lastname'];
$Username = $_POST['Username'];
$Email = $_POST['Email'];
$Password = $_POST['Password'];
$Country = $_POST['Country'];
$Mobile = $_POST['Mobile'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO users(Firstname,Lastname,Username,Email,Password,Country,Mobile) VALUES('$Firstname','$Lastname','$Username','$Email','$Password','$Country','$Mobile')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "User successfully Registered.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
Probably you should decode the json string before checking $_POST['Firstname'] etc...
Let's say you send from the app a string called data. On php you should do something like that:
$data = json_decode($_POST['data']);
and then check if $data contains the data you neeed by doing:
if (isset($data->Firstname) && isset($data->Lastname) etc...){
...
...
}
If I can give you an advice it would be better if you check data integrity directly from your app instead of doing it on your server, it would give the chance to spare some server resources...
As Jay Blanchard already mentioned don't use mysql like that or you'll be exposed to mysql injection...

Connecting desktop app to online database via php

I've read a lot of posts on this general subject but I still can't seem to figure it out.
I'm building a Mac/PC desktop application. When a user first authorizes the app, I want to store their info in an online Mysql database. I'm using the JUCE library to call and handle a php file online which in turn handles the updating of the online database. On my desktop app:
String url = "http://www.syntorial.com/onlinePHPFileToCall.php?email=" + email + "&computer=" + SystemStats::getComputerName();
URL authURL(url);
InputStream *input = authURL.createInputStream(true);
String result = input->readString();
And the php file:
<?php
$result = "";
$mysqli = new mysqli('localhost','username','password','dbname');
if (mysqli_connect_errno())
{
$result = "connection failed";
}
else
{
$mysqli->select_db("UserInfo");
$email = $_GET['email'];
$computer = $_GET['computer'];
$query = "UPDATE UserInfo SET computer = '$computer' WHERE email = '$email'";
if ($queryResult = $mysqli->query($query))
{
$result = "true";
}
else
{
$result = "false";
}
}
echo $result;
?>
The result comes back "true" on my desktop app, but the information doesn't actually get saved into the database. If instead of
InputStream *input = authURL.createInputStream(true);
I use:
authURL.launchInDefaultBrowser();
it opens up the php file in a browser and everything works fine. Any ideas what I'm doing wrong?
Joe,
Seems like one of your first question on this forum. So Welcome. You mentioned you want to store information in an online database. But while connecting you added db information about your local via
mysqli('localhost',
. Update localhost to point to an online database by finding its ip address/servername, username and password. Also you will have to ensure the computer where you run this application can connect to that online db.
Here is what I am ran on my local and worked for me.
<?php
$result = "";
$mysqli = new mysqli('localhost','root','','test');
if (mysqli_connect_errno())
{
$result = "connection failed";
}
else
{
$email = "xyz#yahoo.com";
$computer = "1mycomp";
$query = "UPDATE so1 SET computer = '$computer' WHERE email = '$email'";
/*
Printing the query to check what is being executed.
Remove the below line after program works.
*/
echo $query;
if ($queryResult = $mysqli->query($query))
{
$result = "true";
}
else
{
$result = "false";
}
}
echo $result;
Turns out the "true" argument in CreateInputStream was telling it to use POST data instead of GET so the call was ignoring the GET data. Thanks the help.

php application working on local not on live/production server

I have an attendance management system application written with PHP. The package works fine on my local machine but when I tried to host it on a production server, the home page is loading but I'm not able to login with any user account/data.
<?php
session_start();
include_once("include\config.php");
if (isset($_POST['textfield1'])&&isset($_POST['textfield2'])){
$login = $_POST["textfield1"];
$pwd = $_POST["textfield2"];
$recordset = mysql_query("select * from users");
while($record = mysql_fetch_array($recordset)){
if($login == $record["ulogin"] && $pwd == $record["upassword"])
{
$_SESSION["ulogin"] = $record["ulogin"];
$_SESSION["uid"] = $record["uid"];
if($record["utype"] == 1){
$_SESSION["utype"] = $record["utype"];
header("Location:admin.php?uid=".$record["uid"]);
exit;
}else{
header("Location:home.php");
exit;
}
}
}
}
header("Location:login.php?invalid=1");
?>
This is my user password verification code
base connection. Everything works fine. Please help me out.
Confirm DB is on server. Confirm your config. One quick MYSQL tip(if you are using it): if information_schema table shows, then you DB is not properly configured.

Categories