Home > PHP Framework > ThinkPHP > How to solve the problem that thinkphp cannot obtain post data

How to solve the problem that thinkphp cannot obtain post data

WBOY
Release: 2023-05-29 21:25:10
forward
2231 people have browsed it

1. Problem

After submitting the form, use request->param() or $this->request->param() The post data cannot be obtained and an empty array is obtained.

2. Cause of the problem

  1. #The enctype attribute is not set in the form

When the form is submitted , if the enctype attribute is not set, the default data transmission method is application/x-www-form-urlencoded. Data will now be placed in HTTP request headers instead of the request body. Therefore, when getting post data, we need to use $this->request->post() or request()->post().

  1. No request header is set when the interface is called

When the interface is called, we need to set the corresponding request header, such as Content-Type: application /json, otherwise the server cannot parse the 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

  1. Set the enctype attribute

Add enctype=" in the form multipart/form-data", so that the post data can be obtained correctly.

  1. Set request header

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);
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template