獲取請求參數的幾種方法
- 通過繼承
think\Controller
基類,在控制器中直接使用$this->request
namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
public function index()
{
$params = $this->request->param();
return json($params);
}
}
namespace app\index\controller;
use think\Request;
class Index
{
protected $request;
public function __construct(Request $request)
{
$this->request = $request;
}
public function index()
{
$params = $this->request->param();
return json($params);
}
}
namespace app\index\controller;
use think\Request;
class Index
{
public function index(Request $request)
{
$params = $request->param();
return json($params);
}
}
namespace app\index\controller;
use think\Request;
class Index
{
public function index()
{
$request = Request::instance();
$params = $request->param();
return json($params);
}
}
獲取請求信息
方法 |
作用 |
domain |
獲取當前域名 |
baseFile |
獲取當前入口文件 |
url |
獲取當前URL地址 不含域名 |
url(true) |
獲取包含域名的完整URL地址 |
baseUrl |
獲取當前URL地址 不含QUERY_STRING |
root |
獲取URL訪問的ROOT地址 |
root(true) |
獲取URL訪問的ROOT地址 |
pathinfo |
獲取URL地址中的PATH_INFO信息 |
path |
獲取URL地址中的PATH_INFO信息,不含後綴 |
ext |
獲取URL地址中的後綴信息 |
方法 |
作用 |
model() |
模塊 |
controller() |
控制器 |
action() |
操作方法 |
變量類型方法(‘變量名/變量修飾符’,‘默認值’,‘過濾方法’)
方法 |
描述 |
param |
獲取當前請求的變量 |
get |
獲取 $_GET 變量 |
post |
獲取 $_POST 變量 |
put |
獲取 PUT 變量 |
delete |
獲取 DELETE 變量 |
session |
獲取 $_SESSION 變量 |
cookie |
獲取 $_COOKIE 變量 |
request |
獲取 $_REQUEST 變量 |
server |
獲取 $_SERVER 變量 |
env |
獲取 $_ENV 變量 |
route |
獲取 路由(包括PATHINFO) 變量 |
file |
獲取 $_FILES 變量 |
if (Request::instance()->isGet()) echo "當前爲 GET 請求";
if (Request::instance()->isPost()) echo "當前爲 POST 請求";
if (Request::instance()->isPut()) echo "當前爲 PUT 請求";
if (Request::instance()->isDelete()) echo "當前爲 DELETE 請求";
if (Request::instance()->isAjax()) echo "當前爲 Ajax 請求";
if (Request::instance()->isPjax()) echo "當前爲 Pjax 請求";
if (Request::instance()->isMobile()) echo "當前爲手機訪問";
if (Request::instance()->isHead()) echo "當前爲 HEAD 請求";
if (Request::instance()->isPatch()) echo "當前爲 PATCH 請求";
if (Request::instance()->isOptions()) echo "當前爲 OPTIONS 請求";
if (Request::instance()->isCli()) echo "當前爲 cli";
if (Request::instance()->isCgi()) echo "當前爲 cgi";
- 獲取請求頭信息
- 獲取全部頭信息
Request::instance()->header()
- 獲取單個頭信息
Request::instance()->header('user-agent')
注意:HTTP請求頭信息的名稱不區分大小寫,並且_會自動轉換爲-,所以下面的寫法都是等效的:
$agent = Request::instance()->header('user-agent');
$agent = Request::instance()->header('User-Agent');
$agent = Request::instance()->header('USER_AGENT');