Avatar of derrida
derrida
 asked on

php creating an api post problem

Hi
it is the first time i learn how to write an api. i have the folder structure of: apihub/v1/api.php

the GET part works: i get all the customers and a customer according to an id. i have issue with POST variables.

i read that instead of reading POST array one should use : file_get_contents("php://input")

so i have this code:
    $customer = json_decode(file_get_contents("php://input"));

    var_dump($this->get_request_method());
    var_dump($customer);

Open in new window


and when i use the chrome extension i get NULL, but if i don't use the json_decode i so get the json string. what am i missing here? and how can i use that, cause according to it i want to write the query to the database.
post data stringgetting null with the decode
best regards
PHP

Avatar of undefined
Last Comment
gr8gonzo

8/22/2022 - Mon
SOLUTION
gr8gonzo

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Abhijeet Rananaware

Try to verify data your are posting is in a correct format. I was getting the same error when the issue was with the  JSON format.

http://json.parser.online.fr/
Ray Paseur

Have you tried var_dump($_POST)?  Or maybe var-dump($_REQUEST)?  The latter should also include the $_GET and $_COOKIE information.
derrida

ASKER
hi
gr8gonzo good explanation, yet with your separation, i still get NULL. and with the chrome browser extention i do use: application/x-www-form-urlencoded

ray: i attach the image of bar_dump post. the values are there. so somehow the json_decode return NULL and i don't understand why.
should i just use regular post array, in order to query the database? therefore skeep the decode or totally the file_get_contents? again, the question is why i get the NULL.

post values
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
Ray Paseur

json_decode return NULL and i don't understand why.
PHP has ways of discerning the errors in JSON strings.

It would be easier for us to help you if you would post the test data and code snippets instead of pictures  of test data and code!  We could use copy / paste to ensure we were working with the same test data set you're using.  Please have a look at var_export().

Here is my teaching example showing how to decode json strings and detect errors, if any.
<?php // demo/json_decode_show_errors.php
/**
 * JSON stands for JavaScript Object Notation
 * http://json.org/
 *
 * JSON support in PHP does not have very good error handling
 *
 * JSON strings are all UTF-8
 * http://www.experts-exchange.com/articles/11880/Unicode-PHP-and-Character-Collisions.html
 *
 * PHP man page references
 * http://php.net/manual/en/json.constants.php
 * http://php.net/manual/en/function.json-decode.php
 * http://php.net/manual/en/function.json-encode.php
 * http://php.net/manual/en/function.json-last-error.php
 * http://php.net/manual/en/function.json-last-error-msg.php
 */
error_reporting(E_ALL);
echo '<pre>';

// SEE TEST DATA AT http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_28523915.html#a40339939
$jso = <<<EOD
{"id":"tag:search.twitter.com,2005:389903668427763712","objectType":"activity","actor":{"objectType":"person","id":"id:twitter.com:91239297","link":"http://www.twitter.com/OGkush103","displayName":"WalkingLick74","postedTime":"2009-11-20T01:21:39.000Z","image":"https://si0.twimg.com/profile_images/378800000593715086/755411d8bdc495472c2d7ed50e319582_normal.jpeg","summary":"Self-Made, Self Paid..... I always had the mind to get it like a man, head first bout my younging Ean! #YOLO","links":[{"href":null,"rel":"me"}],"friendsCount":468,"followersCount":677,"listedCount":0,"statusesCount":25504,"twitterTimeZone":"Alaska","verified":false,"utcOffset":"-28800","preferredUsername":"OGkush103","languages":["en"],"location":{"objectType":"place","displayName":"Boston George Crib"},"favoritesCount":26},"verb":"post","postedTime":"2013-10-15T00:00:53.000Z","generator":{"displayName":"Twitter for iPhone","link":"http://twitter.com/download/iphone"},"provider":{"objectType":"service","displayName":"Twitter","link":"http://www.twitter.com"},"link":"http://twitter.com/OGkush103/statuses/389903668427763712","body":"You a killer you on twitter, You'n do NO talking","object":{"objectType":"note","id":"object:search.twitter.com,2005:389903668427763712","summary":"You a killer you on twitter, You'n do NO talking","link":"http://twitter.com/OGkush103/statuses/389903668427763712","postedTime":"2013-10-15T00:00:53.000Z"},"favoritesCount":0,"location":{"objectType":"place","displayName":"Mississippi, US","name":"Mississippi","country_code":"United States","twitter_country_code":"US","link":"https://api.twitter.com/1.1/geo/id/43d2418301bf1a49.json","geo":{"type":"Polygon","coordinates":[[[-91.65500899999999,30.146096],[-91.65500899999999,34.996099],[-88.097888,34.996099],[-88.097888,30.146096]]]}},"geo":{"type":"Point","coordinates":[31.99686058,-88.72688823]},"twitter_entities":{"hashtags":[],"symbols":[],"urls":[],"user_mentions":[]},"twitter_filter_level":"medium","twitter_lang":"en","retweetCount":0,"gnip":{"matching_rules":[{"tag":null}],"language":{"value":"en"}}}
EOD;

// IF DECODING SUCCEEDS
$obj = json_decode($jso);
if ($obj)
{
    // SHOW SOME PARTS OF THE OBJECT
    $x = $obj->objectType;
    $y = $obj->actor->displayName;
    echo PHP_EOL . "$x $y" . PHP_EOL;

    // ACTIVATE THIS TO SHOW THE ENTIRE OBJECT
    // var_dump($obj);
}

// IF DECODING FAILS?
if (!$obj) echo json_last_error_message();

function json_last_error_message()
{
    static $errors = array
    ( JSON_ERROR_NONE           => null
    , JSON_ERROR_DEPTH          => 'Maximum stack depth exceeded'
    , JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch'
    , JSON_ERROR_CTRL_CHAR      => 'Unexpected control character found'
    , JSON_ERROR_SYNTAX         => 'Syntax error, malformed JSON'
    , JSON_ERROR_UTF8           => 'Malformed UTF-8 characters, possibly incorrectly encoded'
    )
    ;
    // ADD THESE AT PHP 5.5+ OR USE json_last_error_msg()
    if (defined('JSON_ERROR_RECURSION'))        $errors[JSON_ERROR_RECURSION]        = 'One or more recursive references in the value to be encoded';
    if (defined('JSON_ERROR_INF_OR_NAN'))       $errors[JSON_ERROR_INF_OR_NAN]       = 'One or more NAN or INF values in the value to be encoded';
    if (defined('JSON_ERROR_UNSUPPORTED_TYPE')) $errors[JSON_ERROR_UNSUPPORTED_TYPE] = 'A value of a type that cannot be encoded was given';

    $error = json_last_error();

    return array_key_exists($error, $errors)
    ? $errors[$error]
    : "Unknown error ({$error})"
    ;
}

Open in new window

ASKER CERTIFIED SOLUTION
Ray Paseur

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
gr8gonzo

Did you try the parse_str line I mentioned? Again, your screenshots show that you are posting form content, not JSON, so try:

$raw = file_get_contents("php://input");
parse_str($raw, $_POST);
var_dump($raw);
var_dump($_POST);
derrida

ASKER
good explanation and code example
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
gr8gonzo

So the issue is resolved? What was the fix?