The request and response usage of YII framework learning (based on chttprequest response) _php instance

Source: Internet
Author: User
Tags rtrim sendfile sha1 strlen smarty template yii csrf attack

This article describes the request and response usage of YII framework learning. Share to everyone for your reference, specific as follows:

The CHttpRequest is provided in Yii and encapsulates the commonly used method of request. The specific code is as follows:

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, ' validatecsrf
  Token ')); Public Function stripslashes (& $data) {return Is_array ($data)? Array_map (Array ($this, ' stripslashes '), $data): s
  Tripslashes ($data); The Public Function GetParam ($name, $defaultValue =null) {return isset ($_get[$name))? $_get[$name]: (isset 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]: $defaultValu
  E The Public Function Getdelete ($name, $defaultValue =null) {if ($this->_deleteparams===null) $this->_delete params= $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->g Etisputrequest ()?
    $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;
  The Public Function GetUrl () {return $this->getrequesturi (); The Public function gethostinfo ($schema = ') {if ($this->_hostinfo===null) {if ($secure = $this->getiss
      Ecureconnection ()) $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;
  The 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;
  The Public Function Setbaseurl ($value) {$this->_baseurl= $value; The Public Function Getscripturl () {if ($this->_scripturl===null) {$scriptName =basename ($_server[' Scri
      Pt_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 script URL. ');
  return $this->_scripturl;
  The Public Function Setscripturl ($value) {$this->_scripturl= '/'. Trim ($value, '/');
      The 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 '));
    $this->_pathinfo=trim ($pathInfo, '/');
  return $this->_pathinfo; The 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 ' request URI));
  return $this->_requesturi;
  The 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[' R
  Equest_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[' RE
  Quest_method '], ' put '); Public Function Getisajaxrequest () {return isset ($_server[' Http_x_requested_with ']) && $_server[' http_x
  _requested_with ']=== ' XMLHttpRequest ';
  The Public Function getServerName () {return $_server[' server_name '];
  The Public Function Getserverport () {return $_server[' server_port '];
  The Public Function Geturlreferrer () {return isset ($_server[' http_referer '))? $_server[' Http_referer ']:null;
  The Public Function getuseragent () {return isset ($_server[' http_user_agent '))? $_server[' Http_user_agent ']:null; The Public Function getuserhostaddress () {return isset ($_server[' remote_addr '))? $_server[' remote_addr ': ' 127.0.0.1 '
  ; The Public Function Getuserhost () {return isset ($_server[' remote_host '))? $_server[' Remote_host ']:null;
  The Public Function Getscriptfile () {if ($this->_scriptfile!==null) return $this->_scriptfile;
  else return $this->_scriptfile=realpath ($_server[' script_filename '));
  The Public Function Getbrowser ($userAgent =null) {return Get_browser ($userAgent, true);
  The 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;
    The Public Function Setport ($value) {$this->_port= (int) $value;
  $this->_hostinfo=null;
  Private $_secureport; Public Function Getsecureport () {if ($this->_secureport===null) $this->_secureport= $this->getissecure Connection () && isset ($_server[' Server_port ')? (int) $_server[' Server_port '] : 443;
  return $this->_secureport;
    The Public Function Setsecureport ($value) {$this->_secureport= (int) $value;
  $this->_hostinfo=null;
    The Public Function getcookies () {if ($this->_cookies!==null) return $this->_cookies;
  else return $this->_cookies=new ccookiecollection ($this); The public function redirect ($url, $terminate =true, $statusCode =302) {if (Strpos ($url, '/') ===0) $url = $this->g
    Ethostinfo (). $url;
    Header (' Location: '. $url, True, $statusCode);
  if ($terminate) Yii::app ()->end (); The 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) {i
    F (($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 because the file downloading could take long//which may cause timeout to some resources (such as D
      B connection) Yii::app ()->end (0,false);
      Echo $content;
    Exit (0);
  else echo $content;
    The 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)) ===nu
    ll) $options [' MimeType ']= ' text/plain ';
    The 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 ()->itema
      T ($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 (), TR
    UE))); 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 R
      Equests $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 to verified. '));

 }
  }
}

Request operation of the relevant methods, at a glance.

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);
}

We can see that Yii has done the necessary filtering for $_get\$_post\$_request\$_cookie, so we can use the data with ease.

Commonly used are the following methods:

Getting a Get parameter

Public Function GetParam ($name, $defaultValue =null)

Getting a Get parameter

Public Function Getquery ($name, $defaultValue =null)

Get Post Data

Public Function Getpost ($name, $defaultValue =null)

Get the requested URL

Public Function GetUrl ()

Getting host information

Public Function gethostinfo ($schema = ')

Set up

Public Function Sethostinfo ($value)

Get root directory

Public Function Getbaseurl ($absolute =false)

Get current URL

Public Function Getscripturl ()

Get the requested URL

Public Function Getrequesturi ()

Get QueryString

Public Function getquerystring ()

To determine whether it is HTTPS

Public Function getissecureconnection ()

GET request Type

Public Function Getrequesttype ()

Whether it is a POST request

Public Function Getispostrequest ()

Whether it is an AJAX request

Public Function Getisajaxrequest ()

Get Server name

Public Function getServerName ()

Get Service port

Public Function Getserverport ()

Get Reference Path

Public Function Geturlreferrer ()

Get User IP Address

Public Function getuserhostaddress ()

Get user host Name

Public Function Getuserhost ()

Get Execute script Name

Public Function Getscriptfile ()

Get cookies

Public Function getcookies ()

redirect

Public function Redirect ($url, $terminate =true, $statusCode =302)

Set the download file header

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-because the file downloading could take long//which may cause Ti
Meout of some (such as DB connection) Yii::app ()->end (0,false);
Echo $content;
Exit (0);
else echo $content; The Public Function xsendfile ($filePath, $options =array ()) {if (!is_file ($filePath)) is 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 ';
The 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;

 }

To prevent Csrf,yii from providing the appropriate method
(
CSRF (Cross-site request forgery), Chinese name: cross-station request forgery, also known as: one click Attack/session Riding, Abbreviated as: CSRF/XSRF.
CSRF Attack mode detailed hacker prerequisites
)

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 (), 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 to verified. '));

 }
}

For the use of $_get, not only can you use $_get and the related methods provided above, in the action, you can bind to the action's method parameters.

Http://www.yiiframework.com/doc/guide/1.1/zh_cn/basics.controller

Here is a list of the official instructions.

Starting with version 1.1.4, YII provides support for automatic action parameter bindings. That is, the controller action can define a named parameter, and the value of the parameter will be automatically populated from the $_get by Yii.

To illustrate this feature in detail, suppose we need to write a create action for Postcontroller. This action requires two parameters:

Category: An integer that represents the ID of the category that the post is to be published in.
Language: A string that represents the language code used by the post.
When extracting parameters from the $_get, we can no longer have the following boring code:

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 ...
  }
}

Now with the action parameter feature, we can more easily complete the task:

Class Postcontroller extends Ccontroller
{public
  function actioncreate ($category, $language = ' en ')
  {
    $category = (int) $category;
    ... fun code starts here ...
  }
}

Notice that we have added two parameters to the action method Actioncreate. The names of these parameters must be consistent with the names we want to extract from the $_get. This parameter uses the default value en when the user does not specify a $language parameter in the request. Because the $category does not have a default value, a chttpexception (Error code 400) exception is thrown automatically if the user does not provide the category parameter in $_get. Starting from version 1.1.5, YII also supports array type detection for action parameters. This is doing by PHP type hinting using the syntax like the following:

Class Postcontroller extends Ccontroller
{public
  function actioncreate (array $categories)
  {
    // Yii would make sure $categories being an array
  }
}

This is, we add the keyword array in front of $categories in the method parameter declaration. By doing so, the if $_get[' categories ' is a simple string, it'll be converted to an array consisting of that string.

Note:if A parameter is declared without the array type hint, it means the parameter must to be a scalar (i.e., not an array) . In this case, the passing in a array parameter via $_get would cause an HTTP exception.

The use of request you just keep it in the same way you used it in PHP, and it's not going to go wrong in yii.

More about Yii related content readers can view the site topics: "Yii framework Introduction and common skills Summary", "PHP Excellent Development Framework Summary", "Smarty Template Primer Tutorial", "PHP date and Time usage summary", "PHP object-oriented Programming Program", " Summary of PHP string usage, Introduction to PHP+MYSQL database operations, and a summary of PHP common database operations Tips

I hope this article will help you with the PHP program design based on the YII framework.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.