问题
I'm making (and testing) my small PHP API. Both GET/POST methods are all fine while submitting the JSON
as data-type.
Problem in PUT
- I cannot submit the
JSON
data viaPUT
method. When i do, the Server-side got empty data. - But when i DO NOT use
json
as data-type, (and just use the plain text data), then i can receive and parse the data, successfully. <----(( This is something weird! ))
Here are my tested cases.
Client Side (Submissions)
(Submit via PHP) submit.php:
$data = array("fruit"=>"watermelon", "destination"=>"germany");
$data = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/api.php");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data)));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$respond = curl_exec($ch);
curl_close($ch);
print_r($respond);
(Submit via Postman):
Server Side (Receiving / Parsing)
api.php:
$decoded_input = json_decode(file_get_contents("php://input"), true);
parse_str($decoded_input, $putdata);
header('Content-type: application/json');
echo json_encode( $putdata );
Output
[]
Question
So it seems like receiving/parsing at the Server-side is the issue.
- How to submit JSON data-type via the PUT method?
- Are there some settings in my Server Side (
Apache + PHP
) to enable (to allow) thejson
data-type inPUT
method?
** I just can't get JSON works via the PUT method. Thanks all for kind helps.
回答1:
<?php
$decoded_input = json_decode(file_get_contents("php://input"), true);
//Here you have usual php array stored in $decoded_input. Do some stuff with it.
header('Content-type: application/json');
echo json_encode($decoded_input);
回答2:
Sorry, can't comment, Rep to low.
Some weeks ago i also played around with simple API calls and i made a little function to handle them.
public function callAPI($method, $url, $data = false) {
$ch = curl_init ();
switch ($method) {
case "POST" :
curl_setopt ( $ch, CURLOPT_POST, 1 );
if ($data) {
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, array (
'Content-Type: application/json',
'Content-Length: ' . strlen ( $data )
));
}
break;
case "PUT" :
curl_setopt ( $ch, CURLOPT_PUT, 1 );
break;
case "GET" :
//No settings required
break;
}
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
$responde = curl_exec ( $ch );
curl_close ( $ch );
return $responde;
}
Seems like there is another setting required for PUT
curl_setopt ( $ch, CURLOPT_PUT, 1 );
AFAIK your option curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
only changes the string which is sent, not the actual method
Soruce: https://curl.haxx.se/libcurl/c/CURLOPT_CUSTOMREQUEST.html
来源:https://stackoverflow.com/questions/38451617/php-how-to-submit-json-via-the-put-method