0

i have a backend code using PHP to check login credential. i send username and password to PHP using http post. but i cannot get the values using file_get_contents('php://input') in PHP. i tried echo "content: " . file_get_contents('php://input'); and the result is blank.

login.php:

<?php
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Access-Control-Allow-Origin, Accept");

include 'connect.php'; // this is for $conn variable
$json = file_get_contents('php://input');
$obj = json_decode($json, true);
$username = $obj['username'];
$password = md5($obj['password']);
    

$sql = "SELECT * FROM dummy_user WHERE username = '$username' AND password = '$password'";
$res = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($res);

if(mysqli_num_rows($res) > 0){
    $response = array(
        "status" => "success",
        "id" => $row['user_id'],
        "username" => $row['username'],
        "first_name" => $row["first_name"] ,
        "last_name" => $row["last_name"],
        "role" => $row["role"]
    );
    echo json_encode($response);
}
?>

and this is my dart code:

onPressed: () async {
                          final Map<String, String> data = ({
                            'username': usernameController.text,
                            'password': passwordController.text
                          });
                          final jsonEncoded = json.encode(data);
                          http.Response response = await http.post(
                              Uri.parse(
                                  'domain.com/api/login.php'),
                              headers: <String, String>{
                                'Content-Type': 'application/json; charset=UTF-8'
                              },
                              body: jsonEncoded);
                          final result = jsonDecode(response.body);

                          if (result["status"] == "success") {
                            Fluttertoast.showToast(
                                msg: "Login success! Welcome, " +
                                    result["username"],
                                toastLength: Toast.LENGTH_SHORT,
                                gravity: ToastGravity.CENTER,
                                timeInSecForIosWeb: 1,
                                backgroundColor: Colors.grey,
                                textColor: Colors.white,
                                fontSize: 16.0);
                            SharedPreferences prefs =
                                await SharedPreferences.getInstance();
                            prefs.setBool("isLoggedIn", true);
                            prefs.setString("userId", result["id"].toString());
                            Navigator.pushReplacementNamed(context, "/main");
                          } else {
                            Fluttertoast.showToast(
                                msg: "Credential not recognized",
                                toastLength: Toast.LENGTH_SHORT,
                                gravity: ToastGravity.CENTER,
                                timeInSecForIosWeb: 1,
                                backgroundColor: Colors.grey,
                                textColor: Colors.white,
                                fontSize: 16.0);
                     }
}
  • Your Uri.parse URI doesn't have a transport scheme. I'm assuming you changed it to "domain.com" to post, but make sure it starts with 'http://' or "https://'. Also check "domain.com" isn't getting redirected by the server. I think "php://input" doesn't always (never?) work with redirection. A guess: if you don't have a transport specified you're getting "http://" as a default and the server is doing a redirect to "https://" and that's causing php://input to be null. – Pat9RB Oct 13 '21 at 16:07
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Oct 13 '21 at 17:16
  • **Never store passwords in clear text or using MD5/SHA1!** Only store password hashes created using PHP's [`password_hash()`](https://php.net/manual/en/function.password-hash.php), which you can then verify using [`password_verify()`](https://php.net/manual/en/function.password-verify.php). Take a look at this post: [How to use password_hash](https://stackoverflow.com/q/30279321/1839439) and learn more about [bcrypt & password hashing in PHP](https://stackoverflow.com/a/6337021/1839439) – Dharman Oct 13 '21 at 17:16
  • @Pat9RB i am using http as the transport. the api works perfectly in postman tho – Rajesh Abdullah Oct 14 '21 at 01:51
  • thanks for the concern of password hashing comments. but this post is about not it. – Rajesh Abdullah Oct 14 '21 at 01:52

1 Answers1

0

The problem is simple. You are passing a Content-Type header to your PHP file which is there already.

Simply remove this line of code from your header in dart file:

'Content-Type': 'application/json; charset=UTF-8'

or remove this line of code from your PHP file:

header('Content-Type: application/json');

Dharman
  • 30,962
  • 25
  • 85
  • 135
willypede
  • 181
  • 1
  • 11