本文实例讲述了YII Framework学习之request与response用法。分享给大家供大家参考,具体如下:
YII中提供了CHttpRequest,封装了请求常用的方法。具体代码如下:
class CHttpRequest extends CApplicationComponent { public $enableCookieValidation=false; public $enableCsrfValidation=false; public $csrfTokenName='YII_CSRF_TOKEN'; public $csrfCookie; private $_requestUri; private $_pathInfo; private $_scriptFile; private $_scriptUrl; private $_hostInfo; private $_baseUrl; private $_cookies; private $_preferredLanguage; private $_csrfToken; private $_deleteParams; private $_putParams; public function init() { parent::init(); $this->normalizeRequest(); } protected function normalizeRequest() { // normalize request if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) { if(isset($_GET)) $_GET=$this->stripSlashes($_GET); if(isset($_POST)) $_POST=$this->stripSlashes($_POST); if(isset($_REQUEST)) $_REQUEST=$this->stripSlashes($_REQUEST); if(isset($_COOKIE)) $_COOKIE=$this->stripSlashes($_COOKIE); } if($this->enableCsrfValidation) Yii::app()->attachEventHandler('onBeginRequest',array($this,'validateCsrfToken')); } public function stripSlashes(&$data) { return is_array($data)"Content-type: $mimeType"); if(ini_get("output_handler")=='') header('Content-Length: '.(function_exists('mb_strlen') "Content-Disposition: attachment; filename=\"$fileName\""); header('Content-Transfer-Encoding: binary'); if($terminate) { // clean up the application first because the file downloading could take long time // which may cause timeout of some resources (such as DB connection) Yii::app()->end(0,false); echo $content; exit(0); } else echo $content; } public function xSendFile($filePath, $options=array()) { if(!is_file($filePath)) return false; if(!isset($options['saveName'])) $options['saveName']=basename($filePath); if(!isset($options['mimeType'])) { if(($options['mimeType']=CFileHelper::getMimeTypeByExtension($filePath))===null) $options['mimeType']='text/plain'; } if(!isset($options['xHeader'])) $options['xHeader']='X-Sendfile'; header('Content-type: '.$options['mimeType']); header('Content-Disposition: attachment; filename="'.$options['saveName'].'"'); header(trim($options['xHeader']).': '.$filePath); if(!isset($options['terminate']) || $options['terminate']) Yii::app()->end(); return true; } public function getCsrfToken() { if($this->_csrfToken===null) { $cookie=$this->getCookies()->itemAt($this->csrfTokenName); if(!$cookie || ($this->_csrfToken=$cookie->value)==null) { $cookie=$this->createCsrfCookie(); $this->_csrfToken=$cookie->value; $this->getCookies()->add($cookie->name,$cookie); } } return $this->_csrfToken; } protected function createCsrfCookie() { $cookie=new CHttpCookie($this->csrfTokenName,sha1(uniqid(mt_rand(),true))); if(is_array($this->csrfCookie)) { foreach($this->csrfCookie as $name=>$value) $cookie->$name=$value; } return $cookie; } public function validateCsrfToken($event) { if($this->getIsPostRequest()) { // only validate POST requests $cookies=$this->getCookies(); if($cookies->contains($this->csrfTokenName) && isset($_POST[$this->csrfTokenName])) { $tokenFromCookie=$cookies->itemAt($this->csrfTokenName)->value; $tokenFromPost=$_POST[$this->csrfTokenName]; $valid=$tokenFromCookie===$tokenFromPost; } else $valid=false; if(!$valid) throw new CHttpException(400,Yii::t('yii','The CSRF token could not be verified.')); } } }
request操作的相关方法,一目了然。
public function init() { parent::init(); $this->normalizeRequest(); } protected function normalizeRequest() { // normalize request if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) { if(isset($_GET)) $_GET=$this->stripSlashes($_GET); if(isset($_POST)) $_POST=$this->stripSlashes($_POST); if(isset($_REQUEST)) $_REQUEST=$this->stripSlashes($_REQUEST); if(isset($_COOKIE)) $_COOKIE=$this->stripSlashes($_COOKIE); } if($this->enableCsrfValidation) Yii::app()->attachEventHandler('onBeginRequest',array($this,'validateCsrfToken')); } public function stripSlashes(&$data) { return is_array($data)"htmlcode">public function getParam($name,$defaultValue=null)获取get参数
public function getQuery($name,$defaultValue=null)获取post数据
public function getPost($name,$defaultValue=null)获取请求的url
public function getUrl()获取主机信息
public function getHostInfo($schema='')设置
public function setHostInfo($value)获取根目录
public function getBaseUrl($absolute=false)获取当前url
public function getScriptUrl()获取请求的url
public function getRequestUri()获取querystring
public function getQueryString()判断是否是https
public function getIsSecureConnection()获取请求类型
public function getRequestType()是否是post请求
public function getIsPostRequest()是否是ajax请求
public function getIsAjaxRequest()获取服务器名称
public function getServerName()获取服务端口
public function getServerPort()获取引用路径
public function getUrlReferrer()获取用户ip地址
public function getUserHostAddress()获取用户主机名称
public function getUserHost()获取执行脚本名称
public function getScriptFile()获取cookie
public function getCookies()重定向
public function redirect($url,$terminate=true,$statusCode=302)设置下载文件头
public function sendFile($fileName,$content,$mimeType=null,$terminate=true) { if($mimeType===null) { if(($mimeType=CFileHelper::getMimeTypeByExtension($fileName))===null) $mimeType='text/plain'; } header('Pragma: public'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header("Content-type: $mimeType"); if(ini_get("output_handler")=='') header('Content-Length: '.(function_exists('mb_strlen') "Content-Disposition: attachment; filename=\"$fileName\""); header('Content-Transfer-Encoding: binary'); if($terminate) { // clean up the application first because the file downloading could take long time // which may cause timeout of some resources (such as DB connection) Yii::app()->end(0,false); echo $content; exit(0); } else echo $content; } public function xSendFile($filePath, $options=array()) { if(!is_file($filePath)) return false; if(!isset($options['saveName'])) $options['saveName']=basename($filePath); if(!isset($options['mimeType'])) { if(($options['mimeType']=CFileHelper::getMimeTypeByExtension($filePath))===null) $options['mimeType']='text/plain'; } if(!isset($options['xHeader'])) $options['xHeader']='X-Sendfile'; header('Content-type: '.$options['mimeType']); header('Content-Disposition: attachment; filename="'.$options['saveName'].'"'); header(trim($options['xHeader']).': '.$filePath); if(!isset($options['terminate']) || $options['terminate']) Yii::app()->end(); return true; }为了防止csrf,yii提供了相应的方法
(
CSRF(Cross-site request forgery),中文名称:跨站请求伪造,也被称为:one click attack/session riding,缩写为:CSRF/XSRF。
《CSRF的攻击方式详解 黑客必备知识》
)public function getCsrfToken() { if($this->_csrfToken===null) { $cookie=$this->getCookies()->itemAt($this->csrfTokenName); if(!$cookie || ($this->_csrfToken=$cookie->value)==null) { $cookie=$this->createCsrfCookie(); $this->_csrfToken=$cookie->value; $this->getCookies()->add($cookie->name,$cookie); } } return $this->_csrfToken; } protected function createCsrfCookie() { $cookie=new CHttpCookie($this->csrfTokenName,sha1(uniqid(mt_rand(),true))); if(is_array($this->csrfCookie)) { foreach($this->csrfCookie as $name=>$value) $cookie->$name=$value; } return $cookie; } public function validateCsrfToken($event) { if($this->getIsPostRequest()) { // only validate POST requests $cookies=$this->getCookies(); if($cookies->contains($this->csrfTokenName) && isset($_POST[$this->csrfTokenName])) { $tokenFromCookie=$cookies->itemAt($this->csrfTokenName)->value; $tokenFromPost=$_POST[$this->csrfTokenName]; $valid=$tokenFromCookie===$tokenFromPost; } else $valid=false; if(!$valid) throw new CHttpException(400,Yii::t('yii','The CSRF token could not be verified.')); } }对于$_GET的使用,不仅仅可以使用$_GET和以上提供的相关方法,在action中,可以绑定到action的方法参数。
http://www.yiiframework.com/doc/guide/1.1/zh_cn/basics.controller
这里就一并罗列官方给出的说明。
从版本 1.1.4 开始,Yii 提供了对自动动作参数绑定的支持。 就是说,控制器动作可以定义命名的参数,参数的值将由 Yii 自动从 $_GET 填充。
为了详细说明此功能,假设我们需要为 PostController 写一个 create 动作。此动作需要两个参数:
category: 一个整数,代表帖子(post)要发表在的那个分类的ID。
language: 一个字符串,代表帖子所使用的语言代码。
从 $_GET 中提取参数时,我们可以不再下面这种无聊的代码了:class PostController extends CController { public function actionCreate() { if(isset($_GET['category'])) $category=(int)$_GET['category']; else throw new CHttpException(404,'invalid request'); if(isset($_GET['language'])) $language=$_GET['language']; else $language='en'; // ... fun code starts here ... } }现在使用动作参数功能,我们可以更轻松的完成任务:
class PostController extends CController { public function actionCreate($category, $language='en') { $category=(int)$category; // ... fun code starts here ... } }注意我们在动作方法 actionCreate 中添加了两个参数。 这些参数的名字必须和我们想要从 $_GET 中提取的名字一致。 当用户没有在请求中指定 $language 参数时,这个参数会使用默认值 en 。 由于 $category 没有默认值,如果用户没有在 $_GET 中提供 category 参数, 将会自动抛出一个 CHttpException (错误代码 400) 异常。 Starting from version 1.1.5, Yii also supports array type detection for action parameters. This is done by PHP type hinting using the syntax like the following:
class PostController extends CController { public function actionCreate(array $categories) { // Yii will make sure $categories be an array } }That is, we add the keyword array in front of $categories in the method parameter declaration. By doing so, if $_GET['categories'] is a simple string, it will be converted into an array consisting of that string.
Note: If a parameter is declared without the array type hint, it means the parameter must be a scalar (i.e., not an array). In this case, passing in an array parameter via $_GET would cause an HTTP exception.
request的使用你只要保持和以前在php中的使用方式一样,在yii中是不会出错的
更多关于Yii相关内容感兴趣的读者可查看本站专题:《Yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
更新日志
- 群星《天域原音·聆听雪域藏歌STS+SRS》[WAV+CUE]
- 尤长靖.2020-AZORAland·我是尤长靖【香蕉娱乐】【FLAC分轨】
- 群星.1995-台北爱情故事【飞碟】【WAV+CUE】
- 群星.2024-锦绣安宁电视剧原声带【D-Jin.Music】【FLAC分轨】
- 群星《闪光的夏天 第4期》[320K/MP3][97.82MB]
- 群星《闪光的夏天 第4期》[FLAC/分轨][553.31MB]
- 群星《奔赴!万人现场 第4期》[320K/MP3][80.75MB]
- 林琳《独角戏HQ》WAV
- FIM-《Super-Sound-3》声霸3[WAV+CUE]
- 喇叭花-绝版天碟《我的碟“MyDisc”》[正版原抓WAV+CUE]
- 陈慧琳.1999-真感觉【正东】【WAV+CUE】
- 徐玮.1986-走自己的路(喜玛拉雅复刻版)【同心圆】【WAV+CUE】
- 林海峰.2003-我撑你【EMI百代】【WAV+CUE】
- 群星《奔赴!万人现场 第4期》[FLAC/分轨][454.89MB]
- 腾讯音乐人《未来立体声·Stereo Future VOL.12》[320K/MP3][62.37MB]