Yii2中request的使用

时间:2022-10-04 20:06:14
</pre><div class="container"><div class="line number1 index0 alt2"><code class="php variable"></code></div><p>yii2做了很多来处理request请求。这里做笔记记录一下。</p> <p>1、普通的get和pst请求</p><p><pre name="code" class="php">$request = Yii::$app->request;

$get = $request->get();
// equivalent to: $get = $_GET;

$id = $request->get('id');
// equivalent to: $id = isset($_GET['id']) ? $_GET['id'] : null;

$id = $request->get('id', 1);
// equivalent to: $id = isset($_GET['id']) ? $_GET['id'] : 1;
//添加了默认值

$post = $request->post();
// equivalent to: $post = $_POST;

$name = $request->post('name');
// equivalent to: $name = isset($_POST['name']) ? $_POST['name'] : null;

$name = $request->post('name', '');
// equivalent to: $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、获取请求头信息


// $headers is an object of yii\web\HeaderCollection $headers = Yii::$app->request->headers;
// 返回header头部所有信息

$accept = $headers->get('Accept');
if ($headers->has('User-Agent')) { // 获取User-Agent }
获取用户客户端信息
$userHost = Yii::$app->request->userHost; $userIP = Yii::$app->request->userIP;