It's a problem with the http protocol. I work on the backend. Now I found a problem with the android programmer. He said that the data has been sent through POST request, but my php needs to use the json data type to receive the data, but I Many people I see on the Internet use $_POST[] to obtain data.
Questions
1. Do you really need php or json data type to receive data? So how to write the PHP code?
2. Is there a way for their Android Post request to send data to add a name? Just like our web site, it has a name.
Username username
Password userpass is an example. Please help. Thank you
巴扎黑2017-05-16 13:09:19
php receives post data, usually $_POST can be used, if not, use file_get_contents("php://input");
The data he requested is in json format. It is very simple to process it with PHP. You only need to use json_decode() to parse it and it will become an array in PHP.
Variables such as username and password can be packaged in json.
phpcn_u15822017-05-16 13:09:19
1. It is recommended to use the following code
$c = file_get_contents('php://input'); //解析获取的二进制流 获取的数据格式是json
$j = json_decode($c, true); //解析json数据,加第二个参数true 是数组 不然是对象
2. Must be able to add
淡淡烟草味2017-05-16 13:09:19
Use $_POST for regular data, use file_get_contents('php://input') for XML and the like;
Don't use $GLOBALS["HTTP_RAW_POST_DATA"], it is obsolete in 7.0.
PHP中文网2017-05-16 13:09:19
This problem is easy to solve. First of all, there are two ways to pass the post request parameters:
form form submission
Submit in json format
The backend and the Android side just need to discuss a way to receive data. It is not as complicated as the author said
我想大声告诉你2017-05-16 13:09:19
What framework does the author use? If you use laravel or lumen, directly connect Request::getContent(), and then json_decode(). If you want to implement it yourself, you can refer to laravel's implementation method:
public function getContent($asResource = false)
{
$currentContentIsResource = is_resource($this->content);
if (PHP_VERSION_ID < 50600 && false === $this->content) {
throw new \LogicException('getContent() can only be called once when using the resource return type and PHP below 5.6.');
}
if (true === $asResource) {
if ($currentContentIsResource) {
rewind($this->content);
return $this->content;
}
// Content passed in parameter (test)
if (is_string($this->content)) {
$resource = fopen('php://temp', 'r+');
fwrite($resource, $this->content);
rewind($resource);
return $resource;
}
$this->content = false;
return fopen('php://input', 'rb');
}
if ($currentContentIsResource) {
rewind($this->content);
return stream_get_contents($this->content);
}
if (null === $this->content || false === $this->content) {
$this->content = file_get_contents('php://input');
}
return $this->content;
}