无为清净楼资源网 Design By www.qnjia.com

本文实例讲述了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程序设计有所帮助。

标签:
YII,Framework,request,response

无为清净楼资源网 Design By www.qnjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
无为清净楼资源网 Design By www.qnjia.com

稳了!魔兽国服回归的3条重磅消息!官宣时间再确认!

昨天有一位朋友在大神群里分享,自己亚服账号被封号之后居然弹出了国服的封号信息对话框。

这里面让他访问的是一个国服的战网网址,com.cn和后面的zh都非常明白地表明这就是国服战网。

而他在复制这个网址并且进行登录之后,确实是网易的网址,也就是我们熟悉的停服之后国服发布的暴雪游戏产品运营到期开放退款的说明。这是一件比较奇怪的事情,因为以前都没有出现这样的情况,现在突然提示跳转到国服战网的网址,是不是说明了简体中文客户端已经开始进行更新了呢?