一、问题现象
提交表单后,通过 request->param() 或 $this->request->param() 获取不到 post 数据,得到的是空数组。
二、问题原因
表单中没有设置 enctype 属性
立即学习“PHP免费学习笔记(深入)”;
在表单提交时,如果 enctype 属性没有设置,那么默认的数据传输方式是 application/x-www-form-urlencoded。现在,数据将被放置在 HTTP 请求头部而非请求体中。所以,在获取 post 数据时,我们需要使用 $this->request->post() 或者 request()->post()。
接口调用时没有设置请求头
在接口调用时,我们需要设置相应的请求头,比如 Content-Type:application/json,否则服务器无法解析数据。如果没有设置 Content-Type,则服务器默认为 application/x-www-form-urlencoded,而此时 post 的数据会放在 http 请求头中,而不是请求体中,导致无法正确获取 post 数据。
三、解决方法
设置 enctype 属性
在表单中添加 enctype="multipart/form-data",这样就能够正确获取 post 数据了。
设置请求头
在接口调用时,可以使用 curl 设置请求头。示例代码如下:
$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);
以上就是thinkphp获取不到post数据如何解决的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号