Requests是 yii\web\Request 对象的表示,它提供了HTTP头,请求参数,Cookies等信息。
get() 和 post()方法返回请求组件的请求参数。
示例 −
$req = Yii::$app->request; /* * $get = $_GET; */ $get = $req->get(); /* * if(isset($_GET['id'])) { * $id = $_GET['id']; * } else { * $id = null; * } */ $id = $req->get('id'); /* * if(isset($_GET['id'])) { * $id = $_GET['id']; * } else { * $id = 1; * } */ $id = $req->get('id', 1); /* * $post = $_POST; */ $post = $req->post(); /* * if(isset($_POST['name'])) { * $name = $_POST['name']; * } else { * $name = null; * } */ $name = $req->post('name'); /* * if(isset($_POST['name'])) { * $name = $_POST['name']; * } else { * $name = ''; * } */ $name = $req->post('name', '');
第1步 - 添加一个 actionTestGet 函数到基本应用程序模板的控制器 SiteController 中。
public function actionTestGet() { var_dump(Yii::$app->request->get()); }
第2步 - 现在打开URL=> http://localhost:8080/index.php?r=site/test-get&id=1&name=zaixian&message=welcome ,
你会看到以下内容。
要检索的另一个请求方法的参数 (PATCH, DELETE, etc.), 使用 yii\web\Request::getBodyParam() 方法。
要获得当前请求的HTTP方法,使用Yii::$app→request→method 属性.
第3步 - 修改 actionTestGet 函数,如下面的代码。
public function actionTestGet() { $req = Yii::$app->request; if ($req->isAjax) { echo "the request is AJAX"; } if ($req->isGet) { echo "the request is GET"; } if ($req->isPost) { echo "the request is POST"; } if ($req->isPut) { echo "the request is PUT"; } }
第4步 - 转到 http://localhost:8080/index.php?r=site/test-get .
你会看到结果如下所示:

所请求的组件提供了很多属性来检查请求的URL。
第5步 - 修改 actionTestGet 函数如下。
public function actionTestGet() { //the URL without the host var_dump(Yii::$app->request->url); //the whole URL including the host path var_dump(Yii::$app->request->absoluteUrl); //the host of the URL var_dump(Yii::$app->request->hostInfo); //the part after the entry script and before the question mark var_dump(Yii::$app->request->pathInfo); //the part after the question mark var_dump(Yii::$app->request->queryString); //the part after the host and before the entry script var_dump(Yii::$app->request->baseUrl); //the URL without path info and query string var_dump(Yii::$app->request->scriptUrl); //the host name in the URL var_dump(Yii::$app->request->serverName); //the port used by the web server var_dump(Yii::$app->request->serverPort); }
第6步-在Web浏览器地址栏中输入URL=>http://localhost:8080/index.php?r=site/testget&id=1&name=zaixian&message=welcome,
你会看到以下内容。
第7步 - 要获得HTTP头信息, 需要使用 yii\web\Request::$headers 属性. 修改 actionTestGet 这样的动作。
public function actionTestGet() { var_dump(Yii::$app->request->headers); }
第8步-如果你打开网址URL=>http://localhost:8080/index.php?r=site/testget&id=1&name=zaixian&message=welcome,
你会看到如图所示的代码输出。
要获得主机名和客户机的IP地址,使用 userHost 和userIP 属性。

第9步 - 需要像这样修改 actionTestGet 函数。
public function actionTestGet() { var_dump(Yii::$app->request->userHost); var_dump(Yii::$app->request->userIP); }