YII Framework学习之request与response用法(基于CHttpRequest响应)
本文实例讲述了YIIFramework学习之request与response用法。分享给大家供大家参考,具体如下:
YII中提供了CHttpRequest,封装了请求常用的方法。具体代码如下:
classCHttpRequestextendsCApplicationComponent
{
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;
publicfunctioninit()
{
parent::init();
$this->normalizeRequest();
}
protectedfunctionnormalizeRequest()
{
//normalizerequest
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'));
}
publicfunctionstripSlashes(&$data)
{
returnis_array($data)?array_map(array($this,'stripSlashes'),$data):stripslashes($data);
}
publicfunctiongetParam($name,$defaultValue=null)
{
returnisset($_GET[$name])?$_GET[$name]:(isset($_POST[$name])?$_POST[$name]:$defaultValue);
}
publicfunctiongetQuery($name,$defaultValue=null)
{
returnisset($_GET[$name])?$_GET[$name]:$defaultValue;
}
publicfunctiongetPost($name,$defaultValue=null)
{
returnisset($_POST[$name])?$_POST[$name]:$defaultValue;
}
publicfunctiongetDelete($name,$defaultValue=null)
{
if($this->_deleteParams===null)
$this->_deleteParams=$this->getIsDeleteRequest()?$this->getRestParams():array();
returnisset($this->_deleteParams[$name])?$this->_deleteParams[$name]:$defaultValue;
}
publicfunctiongetPut($name,$defaultValue=null)
{
if($this->_putParams===null)
$this->_putParams=$this->getIsPutRequest()?$this->getRestParams():array();
returnisset($this->_putParams[$name])?$this->_putParams[$name]:$defaultValue;
}
protectedfunctiongetRestParams()
{
$result=array();
if(function_exists('mb_parse_str'))
mb_parse_str(file_get_contents('php://input'),$result);
else
parse_str(file_get_contents('php://input'),$result);
return$result;
}
publicfunctiongetUrl()
{
return$this->getRequestUri();
}
publicfunctiongetHostInfo($schema='')
{
if($this->_hostInfo===null)
{
if($secure=$this->getIsSecureConnection())
$http='https';
else
$http='http';
if(isset($_SERVER['HTTP_HOST']))
$this->_hostInfo=$http.'://'.$_SERVER['HTTP_HOST'];
else
{
$this->_hostInfo=$http.'://'.$_SERVER['SERVER_NAME'];
$port=$secure?$this->getSecurePort():$this->getPort();
if(($port!==80&&!$secure)||($port!==443&&$secure))
$this->_hostInfo.=':'.$port;
}
}
if($schema!=='')
{
$secure=$this->getIsSecureConnection();
if($secure&&$schema==='https'||!$secure&&$schema==='http')
return$this->_hostInfo;
$port=$schema==='https'?$this->getSecurePort():$this->getPort();
if($port!==80&&$schema==='http'||$port!==443&&$schema==='https')
$port=':'.$port;
else
$port='';
$pos=strpos($this->_hostInfo,':');
return$schema.substr($this->_hostInfo,$pos,strcspn($this->_hostInfo,':',$pos+1)+1).$port;
}
else
return$this->_hostInfo;
}
publicfunctionsetHostInfo($value)
{
$this->_hostInfo=rtrim($value,'/');
}
publicfunctiongetBaseUrl($absolute=false)
{
if($this->_baseUrl===null)
$this->_baseUrl=rtrim(dirname($this->getScriptUrl()),'\\/');
return$absolute?$this->getHostInfo().$this->_baseUrl:$this->_baseUrl;
}
publicfunctionsetBaseUrl($value)
{
$this->_baseUrl=$value;
}
publicfunctiongetScriptUrl()
{
if($this->_scriptUrl===null)
{
$scriptName=basename($_SERVER['SCRIPT_FILENAME']);
if(basename($_SERVER['SCRIPT_NAME'])===$scriptName)
$this->_scriptUrl=$_SERVER['SCRIPT_NAME'];
elseif(basename($_SERVER['PHP_SELF'])===$scriptName)
$this->_scriptUrl=$_SERVER['PHP_SELF'];
elseif(isset($_SERVER['ORIG_SCRIPT_NAME'])&&basename($_SERVER['ORIG_SCRIPT_NAME'])===$scriptName)
$this->_scriptUrl=$_SERVER['ORIG_SCRIPT_NAME'];
elseif(($pos=strpos($_SERVER['PHP_SELF'],'/'.$scriptName))!==false)
$this->_scriptUrl=substr($_SERVER['SCRIPT_NAME'],0,$pos).'/'.$scriptName;
elseif(isset($_SERVER['DOCUMENT_ROOT'])&&strpos($_SERVER['SCRIPT_FILENAME'],$_SERVER['DOCUMENT_ROOT'])===0)
$this->_scriptUrl=str_replace('\\','/',str_replace($_SERVER['DOCUMENT_ROOT'],'',$_SERVER['SCRIPT_FILENAME']));
else
thrownewCException(Yii::t('yii','CHttpRequestisunabletodeterminetheentryscriptURL.'));
}
return$this->_scriptUrl;
}
publicfunctionsetScriptUrl($value)
{
$this->_scriptUrl='/'.trim($value,'/');
}
publicfunctiongetPathInfo()
{
if($this->_pathInfo===null)
{
$pathInfo=$this->getRequestUri();
if(($pos=strpos($pathInfo,'?'))!==false)
$pathInfo=substr($pathInfo,0,$pos);
$pathInfo=urldecode($pathInfo);
$scriptUrl=$this->getScriptUrl();
$baseUrl=$this->getBaseUrl();
if(strpos($pathInfo,$scriptUrl)===0)
$pathInfo=substr($pathInfo,strlen($scriptUrl));
elseif($baseUrl===''||strpos($pathInfo,$baseUrl)===0)
$pathInfo=substr($pathInfo,strlen($baseUrl));
elseif(strpos($_SERVER['PHP_SELF'],$scriptUrl)===0)
$pathInfo=substr($_SERVER['PHP_SELF'],strlen($scriptUrl));
else
thrownewCException(Yii::t('yii','CHttpRequestisunabletodeterminethepathinfooftherequest.'));
$this->_pathInfo=trim($pathInfo,'/');
}
return$this->_pathInfo;
}
publicfunctiongetRequestUri()
{
if($this->_requestUri===null)
{
if(isset($_SERVER['HTTP_X_REWRITE_URL']))//IIS
$this->_requestUri=$_SERVER['HTTP_X_REWRITE_URL'];
elseif(isset($_SERVER['REQUEST_URI']))
{
$this->_requestUri=$_SERVER['REQUEST_URI'];
if(isset($_SERVER['HTTP_HOST']))
{
if(strpos($this->_requestUri,$_SERVER['HTTP_HOST'])!==false)
$this->_requestUri=preg_replace('/^\w+:\/\/[^\/]+/','',$this->_requestUri);
}
else
$this->_requestUri=preg_replace('/^(http|https):\/\/[^\/]+/i','',$this->_requestUri);
}
elseif(isset($_SERVER['ORIG_PATH_INFO']))//IIS5.0CGI
{
$this->_requestUri=$_SERVER['ORIG_PATH_INFO'];
if(!empty($_SERVER['QUERY_STRING']))
$this->_requestUri.='?'.$_SERVER['QUERY_STRING'];
}
else
thrownewCException(Yii::t('yii','CHttpRequestisunabletodeterminetherequestURI.'));
}
return$this->_requestUri;
}
publicfunctiongetQueryString()
{
returnisset($_SERVER['QUERY_STRING'])?$_SERVER['QUERY_STRING']:'';
}
publicfunctiongetIsSecureConnection()
{
returnisset($_SERVER['HTTPS'])&&!strcasecmp($_SERVER['HTTPS'],'on');
}
publicfunctiongetRequestType()
{
returnstrtoupper(isset($_SERVER['REQUEST_METHOD'])?$_SERVER['REQUEST_METHOD']:'GET');
}
publicfunctiongetIsPostRequest()
{
returnisset($_SERVER['REQUEST_METHOD'])&&!strcasecmp($_SERVER['REQUEST_METHOD'],'POST');
}
publicfunctiongetIsDeleteRequest()
{
returnisset($_SERVER['REQUEST_METHOD'])&&!strcasecmp($_SERVER['REQUEST_METHOD'],'DELETE');
}
publicfunctiongetIsPutRequest()
{
returnisset($_SERVER['REQUEST_METHOD'])&&!strcasecmp($_SERVER['REQUEST_METHOD'],'PUT');
}
publicfunctiongetIsAjaxRequest()
{
returnisset($_SERVER['HTTP_X_REQUESTED_WITH'])&&$_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
}
publicfunctiongetServerName()
{
return$_SERVER['SERVER_NAME'];
}
publicfunctiongetServerPort()
{
return$_SERVER['SERVER_PORT'];
}
publicfunctiongetUrlReferrer()
{
returnisset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:null;
}
publicfunctiongetUserAgent()
{
returnisset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:null;
}
publicfunctiongetUserHostAddress()
{
returnisset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:'127.0.0.1';
}
publicfunctiongetUserHost()
{
returnisset($_SERVER['REMOTE_HOST'])?$_SERVER['REMOTE_HOST']:null;
}
publicfunctiongetScriptFile()
{
if($this->_scriptFile!==null)
return$this->_scriptFile;
else
return$this->_scriptFile=realpath($_SERVER['SCRIPT_FILENAME']);
}
publicfunctiongetBrowser($userAgent=null)
{
returnget_browser($userAgent,true);
}
publicfunctiongetAcceptTypes()
{
returnisset($_SERVER['HTTP_ACCEPT'])?$_SERVER['HTTP_ACCEPT']:null;
}
private$_port;
publicfunctiongetPort()
{
if($this->_port===null)
$this->_port=!$this->getIsSecureConnection()&&isset($_SERVER['SERVER_PORT'])?(int)$_SERVER['SERVER_PORT']:80;
return$this->_port;
}
publicfunctionsetPort($value)
{
$this->_port=(int)$value;
$this->_hostInfo=null;
}
private$_securePort;
publicfunctiongetSecurePort()
{
if($this->_securePort===null)
$this->_securePort=$this->getIsSecureConnection()&&isset($_SERVER['SERVER_PORT'])?(int)$_SERVER['SERVER_PORT']:443;
return$this->_securePort;
}
publicfunctionsetSecurePort($value)
{
$this->_securePort=(int)$value;
$this->_hostInfo=null;
}
publicfunctiongetCookies()
{
if($this->_cookies!==null)
return$this->_cookies;
else
return$this->_cookies=newCCookieCollection($this);
}
publicfunctionredirect($url,$terminate=true,$statusCode=302)
{
if(strpos($url,'/')===0)
$url=$this->getHostInfo().$url;
header('Location:'.$url,true,$statusCode);
if($terminate)
Yii::app()->end();
}
publicfunctiongetPreferredLanguage()
{
if($this->_preferredLanguage===null)
{
if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])&&($n=preg_match_all('/([\w\-_]+)\s*(;\s*q\s*=\s*(\d*\.\d*))?/',$_SERVER['HTTP_ACCEPT_LANGUAGE'],$matches))>0)
{
$languages=array();
for($i=0;$i<$n;++$i)
$languages[$matches[1][$i]]=empty($matches[3][$i])?1.0:floatval($matches[3][$i]);
arsort($languages);
foreach($languagesas$language=>$pref)
return$this->_preferredLanguage=CLocale::getCanonicalID($language);
}
return$this->_preferredLanguage=false;
}
return$this->_preferredLanguage;
}
publicfunctionsendFile($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')?mb_strlen($content,'8bit'):strlen($content)));
header("Content-Disposition:attachment;filename=\"$fileName\"");
header('Content-Transfer-Encoding:binary');
if($terminate)
{
//cleanuptheapplicationfirstbecausethefiledownloadingcouldtakelongtime
//whichmaycausetimeoutofsomeresources(suchasDBconnection)
Yii::app()->end(0,false);
echo$content;
exit(0);
}
else
echo$content;
}
publicfunctionxSendFile($filePath,$options=array())
{
if(!is_file($filePath))
returnfalse;
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();
returntrue;
}
publicfunctiongetCsrfToken()
{
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;
}
protectedfunctioncreateCsrfCookie()
{
$cookie=newCHttpCookie($this->csrfTokenName,sha1(uniqid(mt_rand(),true)));
if(is_array($this->csrfCookie))
{
foreach($this->csrfCookieas$name=>$value)
$cookie->$name=$value;
}
return$cookie;
}
publicfunctionvalidateCsrfToken($event)
{
if($this->getIsPostRequest())
{
//onlyvalidatePOSTrequests
$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)
thrownewCHttpException(400,Yii::t('yii','TheCSRFtokencouldnotbeverified.'));
}
}
}
request操作的相关方法,一目了然。
publicfunctioninit()
{
parent::init();
$this->normalizeRequest();
}
protectedfunctionnormalizeRequest()
{
//normalizerequest
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'));
}
publicfunctionstripSlashes(&$data)
{
returnis_array($data)?array_map(array($this,'stripSlashes'),$data):stripslashes($data);
}
可以看到yii对$_GET\$_POST\$_REQUEST\$_COOKIE进行了必要的过滤处理,所以可以放心的使用数据。
常用的有如下方法:
获取get参数
publicfunctiongetParam($name,$defaultValue=null)
获取get参数
publicfunctiongetQuery($name,$defaultValue=null)
获取post数据
publicfunctiongetPost($name,$defaultValue=null)
获取请求的url
publicfunctiongetUrl()
获取主机信息
publicfunctiongetHostInfo($schema='')
设置
publicfunctionsetHostInfo($value)
获取根目录
publicfunctiongetBaseUrl($absolute=false)
获取当前url
publicfunctiongetScriptUrl()
获取请求的url
publicfunctiongetRequestUri()
获取querystring
publicfunctiongetQueryString()
判断是否是https
publicfunctiongetIsSecureConnection()
获取请求类型
publicfunctiongetRequestType()
是否是post请求
publicfunctiongetIsPostRequest()
是否是ajax请求
publicfunctiongetIsAjaxRequest()
获取服务器名称
publicfunctiongetServerName()
获取服务端口
publicfunctiongetServerPort()
获取引用路径
publicfunctiongetUrlReferrer()
获取用户ip地址
publicfunctiongetUserHostAddress()
获取用户主机名称
publicfunctiongetUserHost()
获取执行脚本名称
publicfunctiongetScriptFile()
获取cookie
publicfunctiongetCookies()
重定向
publicfunctionredirect($url,$terminate=true,$statusCode=302)
设置下载文件头
publicfunctionsendFile($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')?mb_strlen($content,'8bit'):strlen($content)));
header("Content-Disposition:attachment;filename=\"$fileName\"");
header('Content-Transfer-Encoding:binary');
if($terminate)
{
//cleanuptheapplicationfirstbecausethefiledownloadingcouldtakelongtime
//whichmaycausetimeoutofsomeresources(suchasDBconnection)
Yii::app()->end(0,false);
echo$content;
exit(0);
}
else
echo$content;
}
publicfunctionxSendFile($filePath,$options=array())
{
if(!is_file($filePath))
returnfalse;
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();
returntrue;
}
为了防止csrf,yii提供了相应的方法
(
CSRF(Cross-siterequestforgery),中文名称:跨站请求伪造,也被称为:oneclickattack/sessionriding,缩写为:CSRF/XSRF。
《CSRF的攻击方式详解黑客必备知识》
)
publicfunctiongetCsrfToken()
{
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;
}
protectedfunctioncreateCsrfCookie()
{
$cookie=newCHttpCookie($this->csrfTokenName,sha1(uniqid(mt_rand(),true)));
if(is_array($this->csrfCookie))
{
foreach($this->csrfCookieas$name=>$value)
$cookie->$name=$value;
}
return$cookie;
}
publicfunctionvalidateCsrfToken($event)
{
if($this->getIsPostRequest())
{
//onlyvalidatePOSTrequests
$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)
thrownewCHttpException(400,Yii::t('yii','TheCSRFtokencouldnotbeverified.'));
}
}
对于$_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中提取参数时,我们可以不再下面这种无聊的代码了:
classPostControllerextendsCController
{
publicfunctionactionCreate()
{
if(isset($_GET['category']))
$category=(int)$_GET['category'];
else
thrownewCHttpException(404,'invalidrequest');
if(isset($_GET['language']))
$language=$_GET['language'];
else
$language='en';
//...funcodestartshere...
}
}
现在使用动作参数功能,我们可以更轻松的完成任务:
classPostControllerextendsCController
{
publicfunctionactionCreate($category,$language='en')
{
$category=(int)$category;
//...funcodestartshere...
}
}
注意我们在动作方法actionCreate中添加了两个参数。这些参数的名字必须和我们想要从$_GET中提取的名字一致。当用户没有在请求中指定$language参数时,这个参数会使用默认值en。由于$category没有默认值,如果用户没有在$_GET中提供category参数,将会自动抛出一个CHttpException(错误代码400)异常。Startingfromversion1.1.5,Yiialsosupportsarraytypedetectionforactionparameters.ThisisdonebyPHPtypehintingusingthesyntaxlikethefollowing:
classPostControllerextendsCController
{
publicfunctionactionCreate(array$categories)
{
//Yiiwillmakesure$categoriesbeanarray
}
}
Thatis,weaddthekeywordarrayinfrontof$categoriesinthemethodparameterdeclaration.Bydoingso,if$_GET['categories']isasimplestring,itwillbeconvertedintoanarrayconsistingofthatstring.
Note:Ifaparameterisdeclaredwithoutthearraytypehint,itmeanstheparametermustbeascalar(i.e.,notanarray).Inthiscase,passinginanarrayparametervia$_GETwouldcauseanHTTPexception.
request的使用你只要保持和以前在php中的使用方式一样,在yii中是不会出错的
更多关于Yii相关内容感兴趣的读者可查看本站专题:《Yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。