欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

YII Framework学习之request与response用法(基于CHttpRequest响应)

程序员文章站 2023-12-17 09:55:28
本文实例讲述了yii framework学习之request与response用法。分享给大家供大家参考,具体如下: yii中提供了chttprequest,封装了请求常...

本文实例讲述了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)?array_map(array($this,'stripslashes'),$data):stripslashes($data);
  }
  public function getparam($name,$defaultvalue=null)
  {
    return isset($_get[$name]) ? $_get[$name] : (isset($_post[$name]) ? $_post[$name] : $defaultvalue);
  }
  public function getquery($name,$defaultvalue=null)
  {
    return isset($_get[$name]) ? $_get[$name] : $defaultvalue;
  }
  public function getpost($name,$defaultvalue=null)
  {
    return isset($_post[$name]) ? $_post[$name] : $defaultvalue;
  }
  public function getdelete($name,$defaultvalue=null)
  {
    if($this->_deleteparams===null)
      $this->_deleteparams=$this->getisdeleterequest() ? $this->getrestparams() : array();
    return isset($this->_deleteparams[$name]) ? $this->_deleteparams[$name] : $defaultvalue;
  }
  public function getput($name,$defaultvalue=null)
  {
    if($this->_putparams===null)
      $this->_putparams=$this->getisputrequest() ? $this->getrestparams() : array();
    return isset($this->_putparams[$name]) ? $this->_putparams[$name] : $defaultvalue;
  }
  protected function getrestparams()
  {
    $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;
  }
  public function geturl()
  {
    return $this->getrequesturi();
  }
  public function gethostinfo($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;
  }
  public function sethostinfo($value)
  {
    $this->_hostinfo=rtrim($value,'/');
  }
  public function getbaseurl($absolute=false)
  {
    if($this->_baseurl===null)
      $this->_baseurl=rtrim(dirname($this->getscripturl()),'\\/');
    return $absolute ? $this->gethostinfo() . $this->_baseurl : $this->_baseurl;
  }
  public function setbaseurl($value)
  {
    $this->_baseurl=$value;
  }
  public function getscripturl()
  {
    if($this->_scripturl===null)
    {
      $scriptname=basename($_server['script_filename']);
      if(basename($_server['script_name'])===$scriptname)
        $this->_scripturl=$_server['script_name'];
      else if(basename($_server['php_self'])===$scriptname)
        $this->_scripturl=$_server['php_self'];
      else if(isset($_server['orig_script_name']) && basename($_server['orig_script_name'])===$scriptname)
        $this->_scripturl=$_server['orig_script_name'];
      else if(($pos=strpos($_server['php_self'],'/'.$scriptname))!==false)
        $this->_scripturl=substr($_server['script_name'],0,$pos).'/'.$scriptname;
      else if(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
        throw new cexception(yii::t('yii','chttprequest is unable to determine the entry script url.'));
    }
    return $this->_scripturl;
  }
  public function setscripturl($value)
  {
    $this->_scripturl='/'.trim($value,'/');
  }
  public function getpathinfo()
  {
    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));
      else if($baseurl==='' || strpos($pathinfo,$baseurl)===0)
        $pathinfo=substr($pathinfo,strlen($baseurl));
      else if(strpos($_server['php_self'],$scripturl)===0)
        $pathinfo=substr($_server['php_self'],strlen($scripturl));
      else
        throw new cexception(yii::t('yii','chttprequest is unable to determine the path info of the request.'));
      $this->_pathinfo=trim($pathinfo,'/');
    }
    return $this->_pathinfo;
  }
  public function getrequesturi()
  {
    if($this->_requesturi===null)
    {
      if(isset($_server['http_x_rewrite_url'])) // iis
        $this->_requesturi=$_server['http_x_rewrite_url'];
      else if(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);
      }
      else if(isset($_server['orig_path_info'])) // iis 5.0 cgi
      {
        $this->_requesturi=$_server['orig_path_info'];
        if(!empty($_server['query_string']))
          $this->_requesturi.='?'.$_server['query_string'];
      }
      else
        throw new cexception(yii::t('yii','chttprequest is unable to determine the request uri.'));
    }
    return $this->_requesturi;
  }
  public function getquerystring()
  {
    return isset($_server['query_string'])?$_server['query_string']:'';
  }
  public function getissecureconnection()
  {
    return isset($_server['https']) && !strcasecmp($_server['https'],'on');
  }
  public function getrequesttype()
  {
    return strtoupper(isset($_server['request_method'])?$_server['request_method']:'get');
  }
  public function getispostrequest()
  {
    return isset($_server['request_method']) && !strcasecmp($_server['request_method'],'post');
  }
  public function getisdeleterequest()
  {
    return isset($_server['request_method']) && !strcasecmp($_server['request_method'],'delete');
  }
  public function getisputrequest()
  {
    return isset($_server['request_method']) && !strcasecmp($_server['request_method'],'put');
  }
  public function getisajaxrequest()
  {
    return isset($_server['http_x_requested_with']) && $_server['http_x_requested_with']==='xmlhttprequest';
  }
  public function getservername()
  {
    return $_server['server_name'];
  }
  public function getserverport()
  {
    return $_server['server_port'];
  }
  public function geturlreferrer()
  {
    return isset($_server['http_referer'])?$_server['http_referer']:null;
  }
  public function getuseragent()
  {
    return isset($_server['http_user_agent'])?$_server['http_user_agent']:null;
  }
  public function getuserhostaddress()
  {
    return isset($_server['remote_addr'])?$_server['remote_addr']:'127.0.0.1';
  }
  public function getuserhost()
  {
    return isset($_server['remote_host'])?$_server['remote_host']:null;
  }
  public function getscriptfile()
  {
    if($this->_scriptfile!==null)
      return $this->_scriptfile;
    else
      return $this->_scriptfile=realpath($_server['script_filename']);
  }
  public function getbrowser($useragent=null)
  {
    return get_browser($useragent,true);
  }
  public function getaccepttypes()
  {
    return isset($_server['http_accept'])?$_server['http_accept']:null;
  }
  private $_port;
  public function getport()
  {
    if($this->_port===null)
      $this->_port=!$this->getissecureconnection() && isset($_server['server_port']) ? (int)$_server['server_port'] : 80;
    return $this->_port;
  }
  public function setport($value)
  {
    $this->_port=(int)$value;
    $this->_hostinfo=null;
  }
  private $_secureport;
  public function getsecureport()
  {
    if($this->_secureport===null)
      $this->_secureport=$this->getissecureconnection() && isset($_server['server_port']) ? (int)$_server['server_port'] : 443;
    return $this->_secureport;
  }
  public function setsecureport($value)
  {
    $this->_secureport=(int)$value;
    $this->_hostinfo=null;
  }
  public function getcookies()
  {
    if($this->_cookies!==null)
      return $this->_cookies;
    else
      return $this->_cookies=new ccookiecollection($this);
  }
  public function redirect($url,$terminate=true,$statuscode=302)
  {
    if(strpos($url,'/')===0)
      $url=$this->gethostinfo().$url;
    header('location: '.$url, true, $statuscode);
    if($terminate)
      yii::app()->end();
  }
  public function getpreferredlanguage()
  {
    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($languages as $language=>$pref)
          return $this->_preferredlanguage=clocale::getcanonicalid($language);
      }
      return $this->_preferredlanguage=false;
    }
    return $this->_preferredlanguage;
  }
  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') ? mb_strlen($content,'8bit') : strlen($content)));
    header("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)?array_map(array($this,'stripslashes'),$data):stripslashes($data);
}

可以看到yii对$_get\$_post\$_request\$_cookie进行了必要的过滤处理,所以可以放心的使用数据。

常用的有如下方法:

获取get参数

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') ? mb_strlen($content,'8bit') : strlen($content)));
header("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的方法参数。

这里就一并罗列官方给出的说明。

从版本 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程序设计有所帮助。

上一篇:

下一篇: