thinkphp 请求信息

如果要获取当前的请求信息,可以使用\think\Request类,
除了下文中的
$request = Request::instance();

也可以使用助手函数
$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/>';

输出结果为:

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


如果当前访问的地址是 http://serverName/index.php/index/hello_world/index
输出结果为:

当前模块名称是index
当前控制器名称是HelloWorld
当前操作名称是index

设置模块名称值需要向module方法中传入名称即可,同样使用于设置控制器名称和操作名称
Request::instance()->module('module_name');

获取请求参数
$request = Request::instance();
echo '请求方法:' . $request->method() . '<br/>';
echo '资源类型:' . $request->type() . '<br/>';
echo '访问ip地址:' . $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
访问ip地址: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)

猜你喜欢

转载自lyz8jj0.iteye.com/blog/2392117