1.创建控制器
2.请求处理
public function actionIndex()
{
//全局类 Yii 的静态属性 $app 中的 request 组件
$request = \Yii::$app->request;
$id = $request->get('id');
//$id = $request->get('id', 20); //如果 id 没有值,默认为20
$request->post('name', 'aaa');
if ($request->isGet) {
// if ($request->isPost) {
echo 'is get';
} else {
echo 'no get';
}
echo $request->userIP;
var_dump($id);
}
3.响应处理
public function actionResponse()
{
$response = \Yii::$app->response;
//$response->statusCode = '404';
// $response->headers->add('pragma', 'no-cache');
// $response->headers->set('pragma', 'max-age=5');
// $response->headers->remove('pragma');
//跳转
// $response->headers->add('location', 'http://www.baidu.com');
// $this->redirect('http://www.baidu.com', 302);
//文件下载
// $response->headers->add('content-disposition',"attachment;filename='a.jpg'");
$response->sendFile('./robots.txt');//目录为入口文件下
}
$this->redirect(array('test3/test1','name'=>'wjh')); // 站内重定向
$this->redirect(array('test3/test1','name','age'));
// 1 => string 'name'
// 2 => string 'age'
$this->redirect('http://www.baidu.com'); //跳转到站外
4.Session 处理**
public function actionSession()
{
$session = \Yii::$app->session;
$session->open(); //打开session
//判断 session 是否开启
if ($session->isActive) {
echo 'session is active';
} else {
echo 'session no active';
}
//$session->set('key1', 'value1');
//echo $session->get('key1');
// $session->remove('key1');//删除
//$session['user'] = '张三';//以数组形式保存,因为实现了 ArrayAccess 类
// unset($session['user']);
// $session['user'] = '张三';
echo $session['user'];
}
**5.Cookie **
public function actionCookie()
{
$cookies = \Yii::$app->response->cookies;
$cookie_data = array(
'name' => 'user',
'value' => '张三',
);
// $cookies->add(new Cookie($cookie_data));
// $cookies->remove('user');
//从请求对象中获取cookie
$cookies = \Yii::$app->request->cookies;
echo $cookies->getValue('user');
//如果 users 没有,则使用 20 作为返回值
echo $cookies->getValue('users' ,20);
}
设置 cookie :
Response->cookie->add();
服务器设置 cookie ,初始化 Cookie 对象, 设置键值对,name,value
获取 cookie :
$request = Yii::$app->request;
$cookie = $request->cookies;
$age = $cookie->getValue('age');