PHP Routing Part 1:Request


php开发中,如果不是mvc模式,在规划路径的时候通常使用目录结构,或者在根目录下建立有意义的php文件。
例如:

http://www.example.com/user/login.php
http://www.example.com/user.php?actinon=login

但使用MVC模式写站点的的时候,由于php的特性,必须要一个router管理及派发。在谈router之前,首先从request开始谈起.

Request, 请求。用户输入网址按回车,php收到的客户端数据就是Request。我们通过分析request,知道当前用户需要访问哪个页面,哪个动作,哪些数据等等信息。通常情况下request只包含header,但在put状态同时还会包含body部分。

一、 header

在求请求头中,会包含用户浏览器传递到服务端的各种信息,如果用户ip地址、正在访问的url、userAgent、cookie等等参数。可以通过firefox的firebug或者Chrome的调试工具, 点击network。可以查看到当前页的Request信息。如下图所示:
php_request_header_info

header在php中如果访问到?可以从$_SERVER数组中读取HTTP_{$key}的信息。

二、 body

body只有在两种请求状态下会出现:put、delete。并且不是表单提交状态。这一点非常重要,如果是表单提交,那么可以从$_POST中读取。下面会具体讲到。
如何读取?非常简单,直接通过php://input就能读取到数据流。

$fh = fopen("php://input", "r");
$content = stream_get_contents($fh);
fclose($fh);

这种主要出现在resetFul服务中,客户端直接向服务端put/delete json或者xml格式的数据。

三. $_GET

在这里插入一个题外话,在php中一个特殊的数据$_REQUEST,它同时包含了$_GET和_$POST中的数据,如果直接通过$_REQUEST数据是不安全的,此时你没法分清用户传来的数据是post还是get,极大的降低了服务端的安全性。所以不推荐使用$_REQUEST代替$_GET和$_POST读取用户传递的数据信息。
在php.ini中开启magic_quotes_gpc,需要在分析前stripslash。$_GET数据来自于链接?后面的一串字符。以xxx[=yy]形式出现,中间使用‘&’符号相连接。xxx为key,yy为value。在php中就展现成一个数据形式。

array(
'xxx' => 'yy',//xxx=yy
'aaa' => '',//aa
);

在MVC中特别需要注意。一般情况下,一个站点会将域名‘/’后面的字符串全部传给index.php。那么$_GET中就只包含了这个信息。这里要注意一点,这时候链接中带有?后面的字符串,紧紧是字符串,它不会被php自动转化成$_GET中的项。我们只需要从字符串中提取‘?’后面的数据 /user/login?returnurl=http://www.example.com。然后通过parse_str函数分析,然后与$_GET进行合并,

if (ini_get('magic_quotes_gpc') === '1') {
	$query = stripslashes_deep($_GET);
} else {
	$query = $_GET;
}
if (strpos($url, '?') !== false) {
	list(, $querystr) = explode('?', $url);
	parse_str($querystr, $queryArgs);
	$query += $queryArgs;
}

四. $_POST

$_POST只用通过表单,并且表单属性中的method设为post。

五. $_FILES

文件上传处理。文件上传通过页面上表单,并且form属性需要设置encrypt=multipart/form-data,同时form中需要包含一个input type="file",php $_FILES中才会有数据。上传后的数据存储在/tmp(linux)或者/APPDATA/temp(windows)目录下,这个文件在15分钟后会被系统自动回收。

在下一篇会讲到Router,分析url地址,根据设定的规则,自动加载controller文件,控制response,在通过view渲染网页向客户端输出网页。

  1. 我对PHP框架的一些看法 | 月色狼影 - pingback on 2014/03/06 at 15:47
  2. HP Routing Part 2:Router | 月色狼影 - pingback on 2014/03/21 at 19:42

Leave a Comment

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Trackbacks and Pingbacks:

%d bloggers like this: