0

I'm trying to get the email and password from a flutter app using PHP but for some reason i'm getting null results, any idea how I can do it?

Seems that the PHP code actually works fine if the username and password are in the URL itself, however, does not work if I try to follow the example below.

PHP:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET');

echo $email = $_GET["email"];
echo $password = $_GET["password"];

Flutter:

Future<void> login(String email, String password) async {

     final url = Uri.parse(
         'example.com/file.php');
     final response = await http.post(
       url,
       body: json.encode(
         {
           'email': email,
           'password': password,
         },
       ),
     );
  }

ramenknight
  • 134
  • 8

3 Answers3

1

I'm not familiar with Flutter, put it seems you are posting (POST) your vars. So it should mabe be:

echo $email = $_POST["email"];
echo $password = $_POST["password"];

Or it is in the body of the request:

$body = file_get_contents('php://input');
$payload = json_decode($body,true);
$email = $payload['email'];
$password = $payload['password'];
Onki Hara
  • 270
  • 1
  • 9
0

Flutter

class _LoginState extends State<Login> {
final _loginFormKey = GlobalKey<FormState>();
late String email, password;
TextEditingController emailController = TextEditingController();
TextEditingController passwordController = TextEditingController();


DropdownMenuItem<String> buildMenuItem(String item) => DropdownMenuItem(
    value: item,
    child: Padding(
      padding: const EdgeInsets.all(8.0),
      child: Text(item),
    ),
  );

Future loginfunc(email, password) async {
final bool? isValid = _loginFormKey.currentState?.validate();

if (isValid == true) {
  debugPrint('Everything looks good!');
  debugPrint(email);
  debugPrint(password);
  debugPrint(value);

  Map<String, String> headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Charset': 'utf-8'
  };
  Map<String, dynamic> body = {
    "email": email,
    "password": password,
  };
  //var bodyEncoded = json.encode(body);
  var bodyEncoded = body.keys.map((key) => "$key=${body[key]}").join("&");
  var url = "/login.php";
  var response = await http.post(Uri.parse(ApiConstant.baseUrl + url),
      headers: headers,
      encoding: Encoding.getByName('utf-8'),
      body: bodyEncoded);
  var data = json.decode(response.body);
  print(response.statusCode);

  // String emailAPI = data['email'];
  // String nameAPI = data['name'];
  if (data == "Success") {
    // setState(() {
    //   //savePref(emailAPI, nameAPI);
    // });

    SharedPreferences preferences = await SharedPreferences.getInstance();
    var useremail = preferences.setString('useremail', email);

    Fluttertoast.showToast(
        msg: "Login successfull",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.green,
        textColor: Colors.white,
        fontSize: 16.0);
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const Home(),
      ),
    );
  }
  
  else if (data == "No usertype") {
    Fluttertoast.showToast(
        msg: "Please fill type of user",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0);
  } else {
    Fluttertoast.showToast(
        msg: "Invalid credentials",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0);
  }
}
}
duaboola
  • 1
  • 2
0

PHP

<?php 

include "config.php";
$email =  $_POST['email'];
$password =  $_POST['password'];
$usertype = $_POST['usertype'];



    if (!empty($email) && !empty($password))

    {
        
        //print json_encode($email);
        $sql = "SELECT * FROM users WHERE email = '$email' AND password ='$password' AND usertype = '$usertype'";
        
    

        $result = mysqli_query($db,$sql);
        $row=mysqli_fetch_assoc($result);
        $count = mysqli_num_rows($result);
        
        
        if ($count > 0)
        {
            
            echo json_encode("Success");
        }
        else
        { 
            echo json_encode("Error");
        }
    }
}




?>
duaboola
  • 1
  • 2