0

This might be stupid but I hope you guys could enlighten me why this works

Image: POST using RAW But using x-www-form-urlencoded makes all value null

Image: POST using x-www-form urlencoded

here's the php side

<?php
// required headers
header("Access-Control-Allow-Origin: http://localhost/mediapp/");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// files needed to connect to database
include_once 'config/database.php';
include_once 'Objects/user.php';

// get database connection
$database = new Database();
$db = $database->getConnection();

// instantiate user object
$user = new User($db);

// get posted data
$data = json_decode(file_get_contents("php://input"));

I also tried changing the content type but results are still the same. Am I not using POSTMAN properly, do I need to change something in php side? I need it to also work with x-www-form-url-encoded

jtyg
  • 11
  • 1
  • 5

1 Answers1

0

x-www-form-urlencoded will send the body like

firstname=mikey&lastname=dalisay

that why json_decode() return null, use parse_str to convert it to PHP object

parse_str(file_get_contents("php://input"), $data);
var_dump($data);
echo $data['firstname'];

if you want to accept both raw and x-www-form-urlencoded you can write like

$reqBody = file_get_contents("php://input");
$data = json_decode($reqBody);
if(!$data){
  parse_str($reqBody, $data);
}
ewwink
  • 18,382
  • 2
  • 44
  • 54