I’ve tried to send a POST request from my Dart application to a PHP file on my server that only checks if $_POST[‘username’] is set, what happens is that the request seems to reach the server but the server refuses to “read it”:
This is what the server sees when a request is received (seen by using: file_get_contents(‘php://input’))
{"username":"testUsername"}
but if I try to do something like:
isset($_POST['username'])
this always returns false.
Here is the method I use to send the POST request:
import 'dart:convert'; import 'package:http/http.dart' as http; final String url = "my.domain.com"; final String unencodedPath = "/subfolder/myfile.php"; final Map<String, String> headers = {'Content-Type': 'application/json; charset=UTF-8'}; final Map<String,String> body = {'username': 'testUsername'}; Future<http.Response> makePostRequest(String url, String unencodedPath , Map<String, String> header, Map<String,String> requestBody) async { final response = await http.post( Uri.http(url,unencodedPath), headers: header, body: jsonEncode(requestBody), ); print(response.statusCode); print(response.body); } makePostRequest(url, unencodedPath, headers, body);
why does isset($_POST[‘username’]) not see my POST sent value?
Advertisement
Answer
Your post request from flutter side is correct
isset($_POST['username'])
will return null as username is part of the json object, It would have worked if :
username = {"username":"testUsername"}
your request satisfied the above format.
To check for data you can do is :
if(!isset($_POST)){ // Takes raw data from the request $json = file_get_contents('php://input'); // Converts it into a PHP object $data = json_decode($json); //add your check here that is $data["username"] as bellow isset($data["username"]) }
You can also check for valid json using other methods.