Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST, PHP - Handling Client's POST Data Character Encoding

In my RESTful service written in PHP, in order to update a resource, the client sends raw JSON via POST in the request content (not from a form, which means Content-Type: application/json)

How should I handle the request in order to prevent character encoding problems?

Should I convert the data sent by the client to UTF-8 before handling it, or should I just assume it's utf-8?

I'm asking this question since JSON can be encoded in different ways.

Thank you.

like image 440
Taru Avatar asked May 17 '26 07:05

Taru


1 Answers

I would recommend you write your PHP code to assume all incoming JSON data is encoded as UTF-8, since that's the default in the spec, and certainly the default in most JSON codecs.

It would be a good idea though to make it explicit in your API documentation that UTF-8 is assumed for application/json content. And if a client wants to transmit JSON encoded differently, instruct them to pass a different Content-Type header that specifies the non-default encoding, with a header like this: Content-Type: application/json; charset=UTF-16.

like image 79
Brian Kelly Avatar answered May 19 '26 21:05

Brian Kelly