Yii框架请求

$request = Yii::$app->request;

$get = $request->get(); 
// 等价于: $get = $_GET;

$id = $request->get('id');   
// 等价于: $id = isset($_GET['id']) ? $_GET['id'] : null;

$id = $request->get('id', 1);   
// 等价于: $id = isset($_GET['id']) ? $_GET['id'] : 1;

$post = $request->post(); 
// 等价于: $post = $_POST;

$name = $request->post('name');   
// 等价于: $name = isset($_POST['name']) ? $_POST['name'] : null;

$name = $request->post('name', '');   
// 等价于: $name = isset($_POST['name']) ? $_POST['name'] : '';

 2、请求方法

$request = Yii::$app->request;

if ($request->isAjax) { /* 该请求是一个 AJAX 请求 */ }
if ($request->isGet)  { /* 请求方法是 GET */ }
if ($request->isPost) { /* 请求方法是 POST */ }
if ($request->isPut)  { /* 请求方法是 PUT */ }

 3、请求URL

request 组件提供了许多方式来检测当前请求的URL。

假设被请求的URL是 http://example.com/admin/index.php/product?id=100, 你可以像下面描述的那样获取URL的各个部分:

  • yii\web\Request::url:返回 /admin/index.php/product?id=100, 此URL不包括host info部分。
  • yii\web\Request::absoluteUrl:返回 http://example.com/admin/index.php/product?id=100, 包含host infode的整个URL。
  • yii\web\Request::hostInfo:返回 http://example.com, 只有host info部分。
  • yii\web\Request::pathInfo:返回 /product, 这个是入口脚本之后,问号之前(查询字符串)的部分。
  • yii\web\Request::queryString:返回 id=100,问号之后的部分。
  • yii\web\Request::baseUrl:返回 /admin, host info之后, 入口脚本之前的部分。
  • yii\web\Request::scriptUrl:返回 /admin/index.php, 没有path info和查询字符串部分。
  • yii\web\Request::serverName:返回 example.com, URL中的host name。
  • yii\web\Request::serverPort:返回 80, 这是web服务中使用的端口。

4、http头

// $headers 是一个 yii\web\HeaderCollection 对象
$headers = Yii::$app->request->headers;

// 返回 Accept header 值
$accept = $headers->get('Accept');

// 增加一个 Pragma 头,已存在的Pragma 头不会被覆盖。
$headers->add('Pragma', 'no-cache');

// 设置一个Pragma 头. 任何已存在的Pragma 头都会被丢弃
$headers->set('Pragma', 'no-cache');

// 删除Pragma 头并返回删除的Pragma 头的值到数组
$values = $headers->remove('Pragma');

 

if ($headers->has('User-Agent')) { /* 这是一个 User-Agent 头 */ }

 

 5、客户端信息

$userHost = Yii::$app->request->userHost;
$userIP = Yii::$app->request->userIP;

 

posted @ 2017-04-20 16:27  pengcx  阅读(272)  评论(0编辑  收藏  举报