thinkphp5.0 獲取請求信息

若是要獲取當前的請求信息,能夠使用\think\Request類,
除了下文中的php

$request = Request::instance();

也能夠使用助手函數html

$request = request();

獲取URL信息

$request = Request::instance();
// 獲取當前域名
echo 'domain: ' . $request->domain() . '<br/>';
// 獲取當前入口文件
echo 'file: ' . $request->baseFile() . '<br/>';
// 獲取當前URL地址 不含域名
echo 'url: ' . $request->url() . '<br/>';
// 獲取包含域名的完整URL地址
echo 'url with domain: ' . $request->url(true) . '<br/>';
// 獲取當前URL地址 不含QUERY_STRING
echo 'url without query: ' . $request->baseUrl() . '<br/>';
// 獲取URL訪問的ROOT地址
echo 'root:' . $request->root() . '<br/>';
// 獲取URL訪問的ROOT地址
echo 'root with domain: ' . $request->root(true) . '<br/>';
// 獲取URL地址中的PATH_INFO信息
echo 'pathinfo: ' . $request->pathinfo() . '<br/>';
// 獲取URL地址中的PATH_INFO信息 不含後綴
echo 'pathinfo: ' . $request->path() . '<br/>';
// 獲取URL地址中的後綴信息
echo 'ext: ' . $request->ext() . '<br/>';

輸出結果爲:thinkphp

domain: http://tp5.com
file: /index.php
url: /index/index/hello.html?name=thinkphp
url with domain: http://tp5.com/index/index/hello.html?name=thinkphp
url without query: /index/index/hello.html
root:
root with domain: http://tp5.com
pathinfo: index/index/hello.html
pathinfo: index/index/hello
ext: html

 

設置/獲取 模塊/控制器/操做名稱

$request = Request::instance();
echo "當前模塊名稱是" . $request->module();
echo "當前控制器名稱是" . $request->controller();
echo "當前操做名稱是" . $request->action();

輸出結果爲:dom

當前模塊名稱是index
當前控制器名稱是HelloWorld
當前操做名稱是index

 

獲取請求參數

$request = Request::instance();
echo '請求方法:' . $request->method() . '<br/>';
echo '資源類型:' . $request->type() . '<br/>';
echo '訪問地址:' . $request->ip() . '<br/>';
echo '是否AJax請求:' . var_export($request->isAjax(), true) . '<br/>';
echo '請求參數:';
dump($request->param());
echo '請求參數:僅包含name';
dump($request->only(['name']));
echo '請求參數:排除name';
dump($request->except(['name']));

輸出結果爲:函數

請求方法:GET
資源類型:html
訪問地址:127.0.0.1
是否AJax請求:false
請求參數:
array (size=2)
  'test' => string 'ddd' (length=3)
  'name' => string 'thinkphp' (length=8)
  
請求參數:僅包含name
array (size=1)
  'name' => string 'thinkphp' (length=8)
  
請求參數:排除name
array (size=1)
  'test' => string 'ddd' (length=3)

獲取路由和調度信息

$request = Request::instance();
echo '路由信息:';
dump($request->route());
echo '調度信息:';
dump($request->dispatch());

輸出信息爲:url

路由信息:
array (size=4)
  'rule' => string 'hello/:name' (length=11)
  'route' => string 'index/hello' (length=11)
  'pattern' => 
    array (size=1)
      'name' => string '\w+' (length=3)
  'option' => 
    array (size=0)
      empty
      
調度信息:
array (size=2)
  'type' => string 'module' (length=6)
  'module' => 
    array (size=3)
      0 => null
      1 => string 'index' (length=5)
      2 => string 'hello' (length=5)

設置請求信息

若是某些環境下面獲取的請求信息有誤,能夠手動設置這些信息參數,使用下面的方式:spa

$request = Request::instance();
$request->root('index.php');
$request->pathinfo('index/index/hello');
相關文章
相關標籤/搜索