Home >PHP Framework >ThinkPHP >How to solve the problem that thinkphp cannot obtain post data
When I was using ThinkPHP to develop a project recently, I encountered a problem: after submitting the form, the post data could not be obtained. This is a common problem during the development process. Sometimes we will feel very confused, especially when we have found many methods on the Internet and still cannot solve the problem. This article will briefly introduce how to solve this problem.
1. Problem phenomenon
After submitting the form, the post data cannot be obtained through request->param() or $this->request->param(). What is obtained is Empty array.
2. Cause of the problem
When the form is submitted, if the enctype attribute is not set, then the default data transmission The method is application/x-www-form-urlencoded. At this time, the post data will be placed in the http request header instead of the request body. Therefore, when getting post data, we need to use $this->request->post() or request()->post().
When calling the interface, we need to set the corresponding request header, such as Content-Type: application/json, otherwise the server cannot Analytical data. If Content-Type is not set, the server defaults to application/x-www-form-urlencoded, and at this time the post data will be placed in the http request header instead of the request body, resulting in the inability to obtain the post data correctly.
3. Solution
Add enctype="multipart/form-data" to the form so that it can be obtained correctly post data.
When calling the interface, you can use curl to set the request header. The sample code is as follows:
$data = array( 'username' => 'admin', 'password' => '123456' ); $url = 'http://www.example.com/login'; $ch = curl_init(); $header = array( 'Content-Type: application/json', 'Content-Length: '.strlen(json_encode($data)) ); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $res = curl_exec($ch); curl_close($ch);
4. Summary
Failure to obtain post data is a common problem. This situation is generally caused by incorrect data transmission methods or incorrect request header settings. If you encounter this problem, you can solve it one by one according to the above methods. Of course, you can also use other methods, such as using php://input or $_POST to obtain post data. Finally, I hope this article can solve similar problems that readers encounter during the development process.
The above is the detailed content of How to solve the problem that thinkphp cannot obtain post data. For more information, please follow other related articles on the PHP Chinese website!