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);
}
}