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
WBOYforward
2023-05-29 21:25:102232browse

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);

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete