Slim 3 how to read post variables from body

Dear Friend,

When i install slim 3 with below command

/opt/php-install/bin/php /root/composer.phar require slim/slim “^3.0”

all post variables in ( $value = json_decode($request->getBody()):wink:

give me null values.

URl/index.php/login/wines_add or URl/index.php/login/wines/6

Kindly help to find the way to ready post variables sending in request.

$app->group(’/login’, function () {
$this->post(’/wines_add’,‘addWine’,function ($request,$response,$args){});
$this->put(’/wines/{id}’, ‘updateWine’,function ($request,$response,$args){});
$this->delete(’/wines/{id}’, ‘deleteWine’,function ($request,$response,$args){});

} );

function addWine($request, $response, $args) {
$value = json_decode($request->getBody());

$sql = "INSERT INTO wine (name, grapes, country, region, year, description) VALUES (name, :grapes, :country, :region, :year, :description)";
try {
    $db = getConnection();
    $stmt = $db->prepare($sql);
    $stmt->bindParam("name", $value->name);
    $stmt->bindParam("grapes", $value->grapes);
    $stmt->bindParam("country", $value->country);
    $stmt->bindParam("region", $value->region);
    $stmt->bindParam("year", $value->year);
    $stmt->bindParam("description", $value->description);
    $stmt->execute();
    //$wine->id = $db->lastInsertId();
    //$db = null;
    echo json_encode($value);
    $db = null;
} catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}';
}

}

function updateWine($request, $response, $args) {
$id=$args[‘id’];
//echo “$id”;
// $body = $request->getBody();
// $wine = json_decode($body);
$value = json_decode($request->getBody());
$data = $request->getParams();
#echo “$data”;
#$data = $value->country;
#$paramValue = $app->$this->request->post(‘country’);

  $sql = "UPDATE wine set  name=:data  WHERE id=$id";

// $sql = “select * from wine where name=:data”;
// $sql = “select * from wine where name=‘piper’”;
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam(“data”, $value->country);
// $stmt->bindParam(“id”, $wine->id);
$stmt->execute();
// $wines = $stmt->fetchAll(PDO::FETCH_OBJ);
echo '{“wine”: ’ . json_encode($value) . ‘}’;

    //$db = null;
    echo json_encode($value);
      $db = null;
} catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}';
}

}

In short
I am getting null values for all post variables.like
$value->region etc.

Hello,

Have you looked at the data that is being sent along with the post request? What do you see when you add the following line to the top of the updateWine function:

print htmlspecialchars($request->getBody());

Hi IIvdI,

I am getting null, please find the details.
URl put : http://192.168.0.205:8081/index1.php/login/wines/7
body variables: {“country”:“IN”};
response body raw in rest client : {“country”:“IN”};{“wine”: {“country”:null}}{“country”:null}

Regards
Anupam

Hello Anupum,

Is the semi-colon at the end of the body variables line part of the string you sent? This may be causing the null values, as it is not valid JSON:

json_decode('{"country":"IN"};')); // null
json_decode('{"country":"IN"}')); // stdClass { $country = "IN" }

Hello IIvdl,

yes, you r right. It was due to semi-colon, but i didn’t find this time.
Thanks a ton for highlighting.

Could you help me to find any debugger which will help me to find such error in short of time in future.

Regards
Anupam Narayan

Will appreciate, if somebody help help me to find how to read post variables.

I am trying to use slim validation finally . Referring slim validation url https://github.com/DavidePastore/Slim-Validation

url: http://192.168.0.205:8081/index3.php/bar

sending post variables as :

{“username”:“anupam”,“age”:“56”}

but not getting how to read “username” and age and store as variables so that below code and validation will work .

$app->post(’/bar’, function ($req, $res, $args) {

$value = json_decode($req->getBody());
print htmlspecialchars($req->getBody());

//Here you expect ‘username’ and ‘age’ parameters – here how to read variables i am not sure
#$username = $req->post(‘username’);
#$age = $req->post(‘age’);

if($this->validation->hasErrors()){
//There are errors, read them
$errors = $this->validation->getErrors();
} else {
//No errors
}
});

use Respect\Validation\Validator as v;
$app = new Slim\App();

// Fetch DI Container
$container = $app->getContainer();

// Register provider
$container[‘validation’] = function () {
//Create the validators
$usernameValidator = v::alnum()->noWhitespace()->length(1, 10);
$ageValidator = v::numeric()->positive()->between(1, 20);
$validators = array(
‘username’ => $usernameValidator,
‘age’ => $ageValidator
);

return new \DavidePastore\Slim\Validation\Validation($validators);
};

Hi @llvdl

I tried so many options listed below, but still not able to read variables from array or from object from post request body.

URL : (post) http://192.168.0.205:8081/index3.php/bar
data: {“username”:“anupam”,“age”:“56”}

outcome : {“username”:“anupam”,“age”:“56”}NULL NULL NULL NULL NULL hi

Not getting where i am doing wrong option tried .

$app->post(’/bar’, function ($req, $res, $args) {
$value = json_decode($req->getBody());
$allPostPutVars = $req->getParsedBody();
print htmlspecialchars($req->getBody());
$data = json_decode($allPostPutVars, true);
$username = $req->getParam(‘username’);
$age = $req->getParam(‘age’);
var_dump($username);
var_dump($age);
$username1 = $allPostPutVars[‘username’];
$age1 = $allPostPutVars[‘age’];
$username2 = $data[‘username’];
$age2 = $data[‘age’];
var_dump($username1);
var_dump($age1);
var_dump($data);

echo “hi” ;

Appreciate you help me to fix same.

Regards
Anupam

Hello Anupam,

You are probably getting NULL when calling Request::getParsedBody because there is no content header set in the request indicating that the data posted is JSON. If you add the header “Content-Type: application/json” when making the POST request, the JSON data will be parsed.

If you have no control over the headers that are sent with the POST request, you can add the content type header yourself before calling Request::getParsedBody or call json_decode yourself, e.g.

$data = json_decode($req->getBody());
var_dump($data->username);
var_dump($data->age);

There is a thread on this issue at Parse JSON when no Content Type comes in Request header

Dear llvdl,

Working… :slight_smile:

.