├── CNAME ├── README.md ├── css └── core.css ├── images ├── divider.png ├── forkme_right_darkblue.png ├── terminal.png └── wood.jpg ├── index.html ├── js └── jquery │ ├── jquery-1.7.2.min.js │ └── jquery.smooth-scroll-1.4.5.min.js └── php-best-practices.md /CNAME: -------------------------------------------------------------------------------- 1 | phpbestpractices.justjavac.com -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | PHP 最佳实践(译) 2 | ============ 3 | 4 | 原文: [PHP Best Practices-A short, practical guide for common and confusing PHP tasks](https://phpbestpractices.org) 5 | 6 | 译者:[夏永锋](https://weibo.com/u/1855563263) 7 | 8 | [开始阅读](https://phpbestpractices.justjavac.com) 9 | -------------------------------------------------------------------------------- /css/core.css: -------------------------------------------------------------------------------- 1 | /* html5doctor.com Reset v1.6.1 (http://html5doctor.com/html-5-reset-stylesheet/) - http://cssreset.com */ 2 | html,body,div,span,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,abbr,address,cite,code,del,dfn,em,img,ins,kbd,q,samp,small,strong,sub,sup,var,b,i,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,figcaption,figure,footer,header,hgroup,menu,nav,section,summary,time,mark,audio,video{margin:0;padding:0;border:0;outline:0;font-size:100%;vertical-align:baseline;background:transparent} 3 | body{line-height:1} 4 | article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section{display:block} 5 | nav ul{list-style:none} 6 | blockquote,q{quotes:none} 7 | blockquote:before,blockquote:after,q:before,q:after{content:none} 8 | a{margin:0;padding:0;font-size:100%;vertical-align:baseline;background:transparent} 9 | ins{background-color:#ff9;color:#000;text-decoration:none} 10 | mark{background-color:#ff9;color:#000;font-style:italic;font-weight:bold} 11 | del{text-decoration:line-through} 12 | abbr[title],dfn[title]{border-bottom:1px dotted;cursor:help} 13 | table{border-collapse:collapse;border-spacing:0} 14 | hr{display:block;height:1px;border:0;border-top:1px solid #ccc;margin:1em 0;padding:0} 15 | input,select{vertical-align:middle} 16 | html{ 17 | background: url('../images/wood.jpg'); 18 | } 19 | body{ 20 | font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; 21 | color: #333333; 22 | width: 940px; 23 | margin: auto; 24 | font-size: 14px; 25 | line-height: 20px; 26 | padding: 20px; 27 | } 28 | article{ 29 | background: #fafafa; 30 | border: 1px solid #dddddd; 31 | padding: 20px; 32 | width: 700px; 33 | margin-left: 250px; 34 | border-radius: 5px; 35 | } 36 | footer{ 37 | margin-top: 20px; 38 | text-align: center; 39 | width: 700px; 40 | margin-left: 240px; 41 | text-shadow: 1px 1px 0px rgba(255,255,255,.8); 42 | } 43 | code{ 44 | white-space: pre; 45 | font-family: monospace; 46 | } 47 | em { 48 | font-style: normal; 49 | color: #F1D; 50 | } 51 | h1{ 52 | font-size: 60px; 53 | line-height: 60px; 54 | margin-bottom: 20px; 55 | color: rgba(255,255,255,1); 56 | text-shadow: 1px 1px 1px rgba(0, 0, 0, .5); 57 | } 58 | h1 span{ 59 | display: block; 60 | font-size: 30px; 61 | line-height: 30px; 62 | } 63 | h2{ 64 | font-size: 30px; 65 | line-height: 30px; 66 | margin-bottom: 10px; 67 | } 68 | h3{ 69 | font-size: 20px; 70 | line-height: 28px; 71 | margin: 10px 0px; 72 | } 73 | h4{ 74 | font-size: 18px; 75 | line-height: 26px; 76 | margin-top: 20px; 77 | } 78 | * + p, 79 | * + article ol, 80 | * + article ul, 81 | * + article li{ 82 | margin-top: 10px; 83 | } 84 | article ol li{ 85 | margin-left: 20px; 86 | } 87 | p + h2{ 88 | margin-top: 50px; 89 | } 90 | section + section:before{ 91 | content: url('../images/divider.png'); 92 | display: block; 93 | margin: 60px auto; 94 | height: 43px; 95 | text-align: center; 96 | opacity: .5; 97 | } 98 | ul{ 99 | margin-left: 15px; 100 | } 101 | .terminal{ 102 | font-family: Monospace; 103 | } 104 | nav{ 105 | display: block; 106 | width: 230px; 107 | background: transparent; 108 | position: absolute; 109 | top: 130px; 110 | } 111 | nav.sticky{ 112 | position: fixed; 113 | top: 5px; 114 | } 115 | nav ol{ 116 | list-style-type: none; 117 | } 118 | nav ol li + li a, 119 | nav ol li:first-child a{ 120 | border-top: 1px solid #dddddd; 121 | } 122 | nav ol li:last-child a{ 123 | border-bottom: 1px solid #dddddd; 124 | } 125 | nav ol li:first-child a{ 126 | border-top-right-radius: 5px; 127 | border-top-left-radius: 5px; 128 | } 129 | nav ol li:last-child a{ 130 | border-bottom-right-radius: 5px; 131 | border-bottom-left-radius: 5px; 132 | } 133 | nav ol li a{ 134 | background: #ffffff; 135 | display: block; 136 | padding: 10px 20px; 137 | text-decoration: none; 138 | border-left: 1px solid #dddddd; 139 | border-right: 1px solid #dddddd; 140 | line-height: 12px; 141 | font-size: 12px; 142 | } 143 | a:link, 144 | nav ol li a:visited{ 145 | color: #4273DC; 146 | } 147 | nav ol li a:hover{ 148 | color: #2F436C; 149 | background: #f4f4f4; 150 | } 151 | nav ol li a.highlighted, 152 | nav ol li a.highlighted:hover{ 153 | color: #ffffff; 154 | background: #4273DC; 155 | text-shadow: 1px 1px 0px rgba(0, 0, 0, .5); 156 | border-left: 1px solid #4273DC; 157 | border-right: 1px solid #4273DC; 158 | } 159 | nav ol li:first-child a.highlighted{ 160 | border-top: 1px solid #4273DC; 161 | } 162 | nav ol li:last-child a.highlighted{ 163 | border-bottom: 1px solid #4273DC; 164 | } 165 | * + code.terminal{ 166 | margin-top: 10px; 167 | } 168 | code.terminal{ 169 | color:#fff; 170 | background-color:#444; 171 | background-image: url('../images/terminal.png'); 172 | border: 1px solid #888; 173 | font-family:'Courier New', Courier, Fixed; 174 | background-position:10px 15px; 175 | background-repeat:no-repeat; 176 | text-align:left; 177 | font-size: 14px; 178 | line-height: 20px; 179 | padding:10px 10px 10px 40px; 180 | text-shadow: 1px 1px 0px rgba(0, 0, 0, .8); 181 | box-shadow: 1px 1px 0px rgba(255, 255, 255, .5) inset; 182 | border-radius: 5px; 183 | display: block; 184 | white-space: normal; 185 | } 186 | code.terminal.multiline span{ 187 | display: block; 188 | } 189 | code.terminal:before, 190 | code.terminal.multiline span:before{ 191 | display: inline; 192 | margin-right: 5px; 193 | color: #56DA55; 194 | font-weight: bold; 195 | } 196 | code.terminal:not(.multiline):before{ 197 | content:'user@localhost:'; 198 | } 199 | code.terminal[data-hostname]:not(.multiline):before{ 200 | content:'user@'attr(data-hostname)':'; 201 | } 202 | code.terminal.multiline span:before{ 203 | content:'user@localhost:'; 204 | } 205 | code.terminal.multiline span[data-hostname]:before{ 206 | content:'user@'attr(data-hostname)':'; 207 | } 208 | code.terminal.multiline span + span{ 209 | margin-top: 5px; 210 | } 211 | .v-fork-me { 212 | position: fixed; 213 | right: 0; 214 | top: 0; 215 | z-index: 999; 216 | } 217 | /* */ 218 | pre>code { 219 | margin:0; 220 | padding:0; 221 | white-space:pre; 222 | border:none; 223 | background:transparent 224 | } 225 | .highlight pre, pre { 226 | background-color:#333; 227 | border:1px solid #ddd; 228 | font-size:13px; 229 | line-height:19px; 230 | overflow:auto; 231 | padding:6px 10px; 232 | border-radius:3px 233 | } 234 | pre code, pre tt { 235 | margin:0; 236 | padding:0; 237 | background-color:transparent; 238 | border:none 239 | } 240 | .highlight { 241 | background: #333; 242 | color: #F6F3E8; 243 | } 244 | .highlight .c { 245 | color:#7C7C7C; 246 | } 247 | .highlight .err { 248 | color:#a61717; 249 | background-color:#e3d2d2 250 | } 251 | .highlight .k { 252 | color:#96CBFE; 253 | } 254 | .highlight .o { 255 | font-weight:bold 256 | } 257 | .highlight .cm { 258 | color:#7C7C7C; 259 | } 260 | .highlight .cp { 261 | color:#999999; 262 | font-weight:bold 263 | } 264 | .highlight .c1 { 265 | color:#7C7C7C; 266 | } 267 | .highlight .cs { 268 | color:#999999; 269 | font-weight:bold; 270 | } 271 | .highlight .gd { 272 | color:#000000; 273 | background-color:#ffdddd 274 | } 275 | .highlight .gd .x { 276 | color:#000000; 277 | background-color:#ffaaaa 278 | } 279 | .highlight .ge { 280 | font-style:italic 281 | } 282 | .highlight .gr { 283 | color:#aa0000 284 | } 285 | .highlight .gh { 286 | color:#999999 287 | } 288 | .highlight .gi { 289 | color:#000000; 290 | background-color:#ddffdd 291 | } 292 | .highlight .gi .x { 293 | color:#000000; 294 | background-color:#aaffaa 295 | } 296 | .highlight .go { 297 | color:#888888 298 | } 299 | .highlight .gp { 300 | color:#555555 301 | } 302 | .highlight .gs { 303 | font-weight:bold 304 | } 305 | .highlight .gu { 306 | color:#800080; 307 | font-weight:bold 308 | } 309 | .highlight .gt { 310 | color:#aa0000 311 | } 312 | .highlight .kc { 313 | font-weight:bold 314 | } 315 | .highlight .kd { 316 | font-weight:bold 317 | } 318 | .highlight .kn { 319 | font-weight:bold 320 | } 321 | .highlight .kp { 322 | font-weight:bold 323 | } 324 | .highlight .kr { 325 | font-weight:bold 326 | } 327 | .highlight .kt { 328 | color:#445588; 329 | font-weight:bold 330 | } 331 | .highlight .m { 332 | color:#009999 333 | } 334 | .highlight .s { 335 | color:#d14 336 | } 337 | .highlight .n { 338 | color:#333333 339 | } 340 | .highlight .na { 341 | color:#FFD2A7 342 | } 343 | .highlight .nb { 344 | color:#0086B3 345 | } 346 | .highlight .nc { 347 | color:#445588; 348 | font-weight:bold 349 | } 350 | .highlight .no { 351 | color:#008080 352 | } 353 | .highlight .ni { 354 | color:#800080 355 | } 356 | .highlight .ne { 357 | color:#990000; 358 | font-weight:bold 359 | } 360 | .highlight .nf { 361 | color:#990000; 362 | font-weight:bold 363 | } 364 | .highlight .nn { 365 | color:#555555 366 | } 367 | .highlight .nt { 368 | color:#000080 369 | } 370 | .highlight .nv { 371 | color:#C6C5FE 372 | } 373 | .highlight .ow { 374 | font-weight:bold 375 | } 376 | .highlight .w { 377 | color:#bbbbbb 378 | } 379 | .highlight .mf { 380 | color:#FF73FD 381 | } 382 | .highlight .mh { 383 | color:#FF73FD 384 | } 385 | .highlight .mi { 386 | color:#FF73FD 387 | } 388 | .highlight .mo { 389 | color:#FF73FD 390 | } 391 | .highlight .sb { 392 | color:#d14 393 | } 394 | .highlight .sc { 395 | color:#d14 396 | } 397 | .highlight .sd { 398 | color:#d14 399 | } 400 | .highlight .s2 { 401 | color:#d14 402 | } 403 | .highlight .se { 404 | color:#d14 405 | } 406 | .highlight .sh { 407 | color:#d14 408 | } 409 | .highlight .si { 410 | color:#d14 411 | } 412 | .highlight .sx { 413 | color:#d14 414 | } 415 | .highlight .sr { 416 | color:#009926 417 | } 418 | .highlight .s1 { 419 | color:#A8FF60 420 | } 421 | .highlight .ss { 422 | color:#990073 423 | } 424 | .highlight .bp { 425 | color:#999999 426 | } 427 | .highlight .vc { 428 | color:#008080 429 | } 430 | .highlight .vg { 431 | color:#008080 432 | } 433 | .highlight .vi { 434 | color:#008080 435 | } 436 | .highlight .il { 437 | color:#009999 438 | } 439 | .highlight .gc { 440 | color:#999; 441 | background-color:#EAF2F5 442 | } -------------------------------------------------------------------------------- /images/divider.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/justjavac/PHP-Best-Practices-zh_CN/e47bb486a63c220f4c2e721ee7af3deec5fb4bb2/images/divider.png -------------------------------------------------------------------------------- /images/forkme_right_darkblue.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/justjavac/PHP-Best-Practices-zh_CN/e47bb486a63c220f4c2e721ee7af3deec5fb4bb2/images/forkme_right_darkblue.png -------------------------------------------------------------------------------- /images/terminal.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/justjavac/PHP-Best-Practices-zh_CN/e47bb486a63c220f4c2e721ee7af3deec5fb4bb2/images/terminal.png -------------------------------------------------------------------------------- /images/wood.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/justjavac/PHP-Best-Practices-zh_CN/e47bb486a63c220f4c2e721ee7af3deec5fb4bb2/images/wood.jpg -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | PHP 最佳实践: 一份简短的关于 PHP 容易混淆知识点的实用指南 5 | 6 | 7 | 8 | 9 | 10 | 45 | 46 | 47 |

PHP 最佳实践(译)一份简短的关于 PHP 容易混淆知识点的实用指南

48 | 72 |
73 |
74 |

最后修订日期 & 维护者

75 |

由我,Alex Cabal,维护该文档。 76 | 我编写 PHP 程序已有很长一段时间了,当前我经营着 Scribophile,由认真作家组成的一个在线写作团体, 77 | Writerfolio,为自由职业者提供的一个易用写作工具集,以及 Standard Ebooks,一个图文并茂、无数字版权管理的公共领域电子书出版商。 78 | 有时我是个为吸引我的项目或客户而工作的自由职业者。

79 |

如果你认为我在某些事情上能够帮到你,或者对本文档有点建议或纠正存在的错误,请给我写封邮件。 80 |

81 |

82 | 原文: PHP Best Practices-A short, practical guide for common and confusing PHP tasks 83 |

84 | 85 |
86 |
87 |

简介

88 |

PHP 是一门复杂的语言,经过多年折腾,使其不同版本之间高度不一致,有时还有些 bug。 89 | 每个版本都有自己独有的特性、多余和怪异之处,也很难跟踪哪个版本有哪些问题。 90 | 这也就很好理解为什么有时它会遭到那么多的厌恶。

91 | 92 |

尽管如此,如今它还是 Web 开发方面最流行的语言。 93 | 因其悠久的历史,对于实现密码哈希和数据库访问诸如此类的基本任务你能够找到很多教程。 94 | 但问题在于,5 个教程,你就很有可能找到 5 种完全不同的完成任务的方式,那么哪种是「正确」的方式呢? 95 | 其他方式有难以捉摸的 bug 或者陷阱? 96 | 确实很难搞明白,所以你经常要在互联网上反复查找尝试确认正确的答案。

97 | 98 |

这也是 PHP 编程新手频繁地因为丑陋、过时、或不安全的代码而遭到责备的原因之一。 99 | 如果 Google 搜索的第一个结果是一篇 4 年前的文章,讲述一种 5 年前的方法,那么 PHP 新手们也就很难改变经常遭受责备的现状。

100 | 101 |

本文档通过为 PHP 中常见的令人困惑的问题和任务编辑组织一系列被认为最佳实践的基本做法, 102 | 来尝试解决上述问题。 103 | 若一个低层次的任务在PHP中有多种令人困惑的实现方式,本文也会涵盖。

104 | 105 |

是什么

106 |

这是一份指南,在 PHP 程序员遇到一些常见低层次任务但不明确最佳做法(由于 PHP 可能提供了多种解决方案)之时,为其建议最佳实践。 107 | 例如:连接数据库是一个常见任务,PHP 中提供了大量可行的方案,但并不是所有的都是好的做法,因此,本文也会包含该问题。

108 |

本文包含的是一系列简短的、入门性质的方案。 109 | 涉及的示例在基本设定下就能够运行起来,你研究一下应该就能把它们变为对你有用的东西。

110 | 111 |

本文将指出一些我们认为是 PHP 中最新最好的东西。然而,这意味如果你在使用老版本的 PHP, 112 | 一些用来实现这些解决方案的特性对你并不可用。

113 | 114 |

这份文档会一直更新,我会尽我最大努力保持该文档与 PHP 的发展同步。

115 | 116 |

是什么

117 |

本文档不是一份 PHP 教程。你应该在别处学习语言基础和语法。

118 |

它也不是一份针对 web 应用常见问题,如 cookie 存储、缓存、编程风格、文档等的指南。

119 |

它也不是一个安全指南。当本文档触碰到一些安全相关的问题时,也是希望你自己做些研究来确保你的 PHP 应用的安全问题。 120 | 你的代码造成的问题应该都是自己的过错。

121 |

该文档也并不是在主张一种特定的编程风格、模式或者框架。

122 |

也不是在主张一种特定的方式来完成高层次任务如用户注册、登录系统等。 123 | 本文档只限于 PHP 的悠久历史所造成的一些易混淆或不明确的低层次任务。

124 |

它不是一个一劳永逸的解决方案,也不是一个唯一的方案。 125 | 下面要讲述的一些方法对于你的特定场景来说也许并不是最好的,存在很多不同的方式来达到同样的目的。 126 | 特别是,高负载 web 应用也许能从更加难懂的方案中获益更多。

127 |
128 |
129 |

我们在使用哪个版本的 PHP?

130 |

带 Suhosin-Patch 的 PHP 5.3.10-1ubuntu3.6,安装在 Ubuntu 12.04 LTS 上。

131 |

PHP 是 Web 世界里的百年老龟,它的壳上铭刻着一段丰富、复杂、而粗糙的历史。 132 | 在一个共享主机的环境里,它的配置可能会限制你能做的事情。

133 |

为了保持清晰地叙述,我们将仅针对一个版本的 PHP 进行讲述。 134 | 在 2013 年 4 月 30 日时,该版本为 PHP 5.3.10-1ubuntu3.6 with Suhosin-Patch。 135 | 若你在 Ubuntu 12.04 LTS 服务器上使用 apt-get 进行安装的就是该版本的 PHP。

136 |

你也许发现这些方案中的一些在其他或者更老版本的 PHP 上也能工作。 137 | 如果是这样的话,就 由你来研究在这些更老版本上潜在的难以捉摸的 bug 或安全问题

138 |
139 |
140 |

存储密码

141 |

使用 phpass 库来哈希和比较密码

142 |

经 phpass 0.3 测试,在存入数据库之前进行哈希保护用户密码的标准方式。 143 | 许多常用的哈希算法如 md5,甚至是 sha1 对于密码存储都是不安全的, 144 | 因为骇客能够使用那些算法轻而易举地破解密码

145 |

对密码进行哈希最安全的方法是使用 bcrypt 算法。开源的 phpass 库以一个易于使用的类来提供该功能。

146 |

示例

147 |
148 |
<?php
149 | // Include phpass 库
150 | require_once('phpass-03/PasswordHash.php')
151 | 
152 | // 初始化散列器为不可移植(这样更安全)
153 | $hasher = new PasswordHash(8, false);
154 | 
155 | // 计算密码的哈希值。$hashedPassword 是一个长度为 60 个字符的字符串.
156 | $hashedPassword = $hasher->HashPassword('my super cool password');
157 | 
158 | // 你现在可以安全地将 $hashedPassword 保存到数据库中!
159 | 
160 | // 通过比较用户输入内容(产生的哈希值)和我们之前计算出的哈希值,来判断用户是否输入了正确的密码
161 | $hasher->CheckPassword('the wrong password', $hashedPassword);  // false
162 | 
163 | $hasher->CheckPassword('my super cool password', $hashedPassword);  // true
164 | ?>
165 | 
166 |
167 |

陷阱

168 | 171 |

进一步阅读

172 | 177 |
178 |
179 |

PHP 与 MySQL

180 |

使用 PDO 及其预处理语句功能。

181 |

在 PHP 中,有很多方式来连接到一个 MySQL 数据库。PDO(PHP 数据对象)是其中最新且最健壮的一种。 182 | PDO 跨多种不同类型数据库有一个一致的接口,使用面向对象的方式,支持更多的新数据库支持的特性。

183 |

你应该使用 PDO 的预处理语句函数来帮助防范 SQL 注入攻击。 184 | 使用函数 bindValue 来确保你的 SQL 免于一级 SQL 注入攻击。 185 | (虽然并不是 100% 安全的,查看进一步阅读获取更多细节。) 186 | 在以前,这必须使用一些「魔术引号(magic quotes)」函数的组合来实现。PDO 使得那堆东西不再需要。

187 |

示例

188 |
189 |
<?php
190 | try{
191 |     // 新建一个数据库连接
192 |     // You'll probably want to replace hostname with localhost in the first parameter.
193 |     // The PDO options we pass do the following:
194 |     // \PDO::ATTR_ERRMODE enables exceptions for errors.  This is optional but can be handy.
195 |     // \PDO::ATTR_PERSISTENT disables persistent connections, which can cause concurrency issues in certain cases.  See "Gotchas".
196 |     // \PDO::MYSQL_ATTR_INIT_COMMAND alerts the connection that we'll be passing UTF-8 data.
197 |     // This may not be required depending on your configuration, but it'll save you headaches down the road
198 |     // if you're trying to store Unicode strings in your database.  See "Gotchas".
199 |     $link = new \PDO(   'mysql:host=your-hostname;dbname=your-db', 
200 |                         'your-username', 
201 |                         'your-password', 
202 |                         array(
203 |                             \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, 
204 |                             \PDO::ATTR_PERSISTENT => false, 
205 |                             \PDO::MYSQL_ATTR_INIT_COMMAND => 'set names utf8mb4'
206 |                         )
207 |                     );
208 | 
209 |     $handle = $link->prepare('select Username from Users where UserId = ? or Username = ? limit ?');
210 | 
211 |     // PHP bug: if you don't specify PDO::PARAM_INT, PDO may enclose the argument in quotes.
212 |     // This can mess up some MySQL queries that don't expect integers to be quoted.
213 |     // See: https://bugs.php.net/bug.php?id=44639
214 |     // If you're not sure whether the value you're passing is an integer, use the is_int() function.
215 |     $handle->bindValue(1, 100, PDO::PARAM_INT);
216 |     $handle->bindValue(2, 'Bilbo Baggins');
217 |     $handle->bindValue(3, 5, PDO::PARAM_INT);
218 | 
219 |     $handle->execute();
220 | 
221 |     // Using the fetchAll() method might be too resource-heavy if you're selecting a truly massive amount of rows.
222 |     // If that's the case, you can use the fetch() method and loop through each result row one by one.
223 |     // You can also return arrays and other things instead of objects.  See the PDO documentation for details.
224 |     $result = $handle->fetchAll(\PDO::FETCH_OBJ);
225 | 
226 |     foreach($result as $row){
227 |         print($row->Username);
228 |     }
229 | }
230 | catch(\PDOException $ex){
231 |     print($ex->getMessage());
232 | }
233 | ?>
234 | 
235 |
236 |

陷阱

237 | 257 |

进一步阅读

258 | 265 |
266 |
267 |

PHP 标签

268 |

使用 <?php ?>

269 |

有几种不同的方式用来区分 PHP 程序块:<?php ?>, <?= ?>, <? ?>, 以及<% %>。 270 | 对于打字来说,更短的标签更方便些,但唯一一种在所有 PHP 服务器上都一定能工作的标签是<?php ?>。 271 | 若你计划将你的 PHP 应用部署到一台上面的 PHP 配置你无法控制的服务器上,那么你应始终使用 <?php ?>

272 | 273 |

若你仅仅是为自己编码,也能控制你将使用的 PHP 配置,你可能觉得短标签更方便些。 274 | 但记住 <? ?>可能会和 XML 声明冲突,并且<? ?>实际上是 ASP 的风格。

275 |

无论你选择哪一种,确保一致。

276 |

陷阱

277 | 283 |

进一步阅读

284 | 287 |
288 |
289 |

自动加载类

290 |

使用 spl_autoload_register() 来注册你的自动加载函数。

291 |

PHP 提供了若干方式来自动加载包含还未加载的类的文件。 292 | 老的方法是使用名为 __autoload() 魔术全局函数。 293 | 然而你一次仅能定义一个 __autoload() 函数,因此如果你的程序包含一个也使用了 __autoload() 函数的库,就会发生冲突。

294 |

处理这个问题的正确方法是唯一地命名你的自动加载函数,然后使用 spl_autoload_register() 函数来注册它。 295 | 该函数允许定义多个 __autoload() 这样的函数,因此你不必担心其他代码的 __autoload() 函数。

296 |

示例

297 |
298 |
<?php
299 | // 首先,定义你的自动载入的函数
300 | function MyAutoload($className){
301 |     include_once($className . '.php');
302 | }
303 | 
304 | // 然后注册它。
305 | spl_autoload_register('MyAutoload');
306 | 
307 | // Try it out!
308 | // 因为我们没包含一个定义有 MyClass 的文件,所以自动加载器会介入并包含 MyClass.php。
309 | // 在本例中,假定在 MyClass.php 文件中定义了 MyClass 类。
310 | $var = new MyClass();
311 | ?>
312 | 
313 |
314 |

进一步阅读

315 | 319 |
320 |
321 |

从性能角度来看单引号和双引号

322 |

其实并不重要。

323 |

已有很多人花费很多笔墨来讨论是使用单引号(')还是双引号(")来定义字符串。 324 | 单引号字符串不会被解析,因此放入字符串的任何东西都会以原样显示。 325 | 双引号字符串会被解析,字符串中的任何 PHP 变量都会被求值。 326 | 另外,转义字符如换行符 \n 和制表符 \t 在单引号字符串中不会被求值,但在双引号字符串中会被求值。

327 |

由于双引号字符串在程序运行时要求值,从而理论上使用单引号字符串能提高性能,因为 PHP 不会对单引号字符串求值。 328 | 这对于一定规模的应用来说也许确实如此,但对于现实中一般的应用来说, 329 | 区别非常小以至于根本不用在意。因此对于普通应用,你选择哪种字符串并不重要。 330 | 对于负载极其高的应用来说,是有点作用的。 331 | 根据你的应用的需要来做选择,但无论你选择什么,请保持一致。

332 |

进一步阅读

333 | 339 |
340 |
341 |

define() vs. const

342 |

使用 define(),除非考虑到可读性、类常量、或关注微优化

343 |

习惯上,在 PHP 中是使用 define() 函数来定义常量。 344 | 但从某个时候开始,PHP 中也能够使用 const 关键字来声明常量了。 345 | 那么当定义常量时,该使用哪种方式呢?

346 |

答案在于这两种方法之间的区别。

347 |
    348 |
  1. define() 在执行期定义常量,而 const 在编译期定义常量。这样 const 就有轻微的速度优势, 349 | 但不值得考虑这个问题,除非你在构建大规模的软件。
  2. 350 |
  3. define() 将常量放入全局作用域,虽然你可以在常量名中包含命名空间。 351 | 这意味着你不能使用 define() 定义类常量。
  4. 352 |
  5. define() 允许你在常量名和常量值中使用表达式,而 const 则都不允许。 353 | 这使得 define() 更加灵活。
  6. 354 |
  7. define() 可以在 if() 代码块中调用,但 const 不行。
  8. 355 |
356 |

示例

357 |
358 |
<?php
359 | // 来看看这两种方法如何处理 namespaces
360 | namespace MiddleEarth\Creatures\Dwarves;
361 | const GIMLI_ID = 1;
362 | define('MiddleEarth\Creatures\Elves\LEGOLAS_ID', 2);
363 | 
364 | echo(\MiddleEarth\Creatures\Dwarves\GIMLI_ID);  // 1
365 | echo(\MiddleEarth\Creatures\Elves\LEGOLAS_ID);  // 2; 注意:我们使用了 define()
366 | 
367 | // Now let's declare some bit-shifted constants representing ways to enter Mordor.
368 | define('TRANSPORT_METHOD_SNEAKING', 1 << 0); // OK!
369 | const TRANSPORT_METHOD_WALKING = 1 << 1; //Compile error! const can't use expressions as values
370 | 
371 | // 接下来, 条件常量。
372 | define('HOBBITS_FRODO_ID', 1);
373 | 
374 | if($isGoingToMordor){
375 |     define('TRANSPORT_METHOD', TRANSPORT_METHOD_SNEAKING); // OK!
376 |     const PARTY_LEADER_ID = HOBBITS_FRODO_ID // 编译错误: const 不能用于 if 块中
377 | }
378 | 
379 | // 最后, 类常量
380 | class OneRing{
381 |     const MELTING_POINT_DEGREES = 1000000; // OK!
382 |     define('SHOW_ELVISH_DEGREES', 200); // 编译错误: 在类内不能使用 define()
383 | }
384 | ?>
385 | 
386 |
387 |

小插曲:当我看到第一行的 MiddleEarth 还没有感觉到什么,再往下看到 Mordor 时,震惊了。OneRingOneRingOneRingggggg

388 |

因为 define() 更加灵活,你应该使用它以避免一些令人头疼的事情,除非你明确地需要类常量。 389 | 使用 const 通常会产生更加可读的代码,但是以牺牲灵活性为代价的。

390 |

无论你选择哪一种,请保持一致。

391 |

进一步阅读

392 | 397 |
398 |
399 |

缓存 PHP opcode

400 |

使用 APC

401 |

在一个标准的 PHP 环境中,每次访问PHP脚本时,脚本都会被编译然后执行。 402 | 一次又一次地花费时间编译相同的脚本对于大型站点会造成性能问题。

403 |

解决方案是采用一个 opcode 缓存。 404 | opcode 缓存是一个能够记下每个脚本经过编译的版本,这样服务器就不需要浪费时间一次又一次地编译了。 405 | 通常这些 opcode 缓存系统也能智能地检测到一个脚本是否发生改变,因此当你升级 PHP 源码时,并不需要手动清空缓存。

406 |

PHP 5.5 内建了一个缓存 OPcache。PHP 5.2 - 5.4 下可以作为PECL扩展安装。

407 |

此外还有几个PHP opcode 缓存值得关注 eacceleratorxcache,以及APC。 408 | APC 是 PHP 项目官方支持的,最为活跃,也最容易安装。 409 | 它也提供一个可选的类 memcached 的持久化键-值对存储,因此你应使用它。

410 |

安装 APC

411 |

在 Ubuntu 12.04 上你可以通过在终端中执行以下命令来安装 APC:

412 |
413 |
user@localhost: sudo apt-get install php-apc
414 |
415 |

除此之外,不需要进一步的配置。

416 |

将 APC 作为一个持久化键-值存储系统来使用

417 |

APC 也提供了对于你的脚本透明的类似于 memcached 的功能。 418 | 与使用 memcached 相比一个大的优势是 APC 是集成到 PHP 核心的,因此你不需要在服务器上维护另一个运行的部件, 419 | 并且 PHP 开发者在 APC 上的工作很活跃。 420 | 但从另一方面来说,APC 并不是一个分布式缓存,如果你需要这个特性,你就必须使用 memcached 了。

421 |

示例

422 |
423 |
<?php
424 | // Store some values in the APC cache.  We can optionally pass a time-to-live, 
425 | // but in this example the values will live forever until they're garbage-collected by APC.
426 | apc_store('username-1532', 'Frodo Baggins');
427 | apc_store('username-958', 'Aragorn');
428 | apc_store('username-6389', 'Gandalf');
429 | 
430 | // After storing these values, any PHP script can access them, no matter when it's run!
431 | $value = apc_fetch('username-958', $success);
432 | if($success === true)
433 |     print($value); // Aragorn
434 | 
435 | $value = apc_fetch('username-1', $success); // $success will be set to boolean false, because this key doesn't exist.
436 | if($success !== true) // Note the !==, this checks for true boolean false, not "falsey" values like 0 or empty string.
437 |     print('Key not found');
438 | 
439 | apc_delete('username-958'); // This key will no longer be available.
440 | ?>
441 | 
442 |
443 |

陷阱

444 | 449 |

进一步阅读

450 | 454 |
455 |
456 |

PHP 与 Memcached

457 |

若你需要一个分布式缓存,那就使用 Memcached 客户端库。否则,使用 APC。

458 |

缓存系统通常能够提升应用的性能。Memcached 是一个受欢迎的选择,它能配合许多语言使用,包括 PHP。

459 |

然而,从一个 PHP 脚本中访问一个 Memcached 服务器,你有两个不同且命名很愚蠢的客户端库选择项: MemcacheMemcached。 460 | 它们是两个名字几乎相同的不同库,两者都可用于访问一个 Memcached 实例。

461 |

事实证明,Memcached 库对于 Memcached 协议的实现最好,包含了一些 Mmecache 库没有的有用的特性, 462 | 并且看起来 Memcached 库的开发也最为活跃。

463 |

然而,如果不需要访问来自一组分布式服务器的一个 Memcached 实例,那就使用 APC。 464 | APC 得到 PHP 项目的支持,具备很多和 Memcached 相同的功能,并且能够用作 opcode 缓存,这能提高 PHP 脚本的性能。

465 |

安装M emcached 客户端库

466 |

在安装 Memcached 服务器之后,需要安装 Memcached 客户端库。没有该库,PHP 脚本就没法与 Memcached 服务器通信。

467 |

在 Ubuntu 12.04 上,你可以使用如下命令来安装 Memcached 客户端库:

468 |
user@localhost: sudo apt-get install php5-memcached
469 | 
470 |

使用 APC 作为替代

471 |

查看 opcode 缓存一节阅读更多与使用 APC 作为 472 | Memcached 替代方案相关的信息。

473 |

进一步阅读

474 | 480 |
481 |
482 |

PHP 与正则表达式

483 |

使用 PCRE(preg_*)家族函数

484 |

PHP有两种使用不同的方式来使用正则表达式:PCRE(Perl兼容表示法,preg_*)函数 485 | 和 POSIX(POSIX 扩展表示法,ereg_*) 486 | 函数。

487 |

每个函数家族各自使用一种风格稍微不同的正则表达式。幸运的是,POSIX 家族函数从 PHP 488 | 5.3.0 开始就被弃用了。因此,你绝不应该使用 POSIX 家族函数编写新的代码。 489 | 始终使用 PRCE 家族函数,即 preg_* 函数。

490 |

进一步阅读

491 | 496 |
497 |
498 |

配置 Web 服务器提供 PHP 服务

499 |

使用 PHP-FPM

500 |

有多种方式来配置一个 web 服务器以提供 PHP 服务。传统(并且糟糕的)的方式是使用 Apache 的 mod_php。Mod_php将PHP 501 | 绑定到 Apache 自身,但是 Apache 对于该模块功能的管理工作非常糟糕。一旦遇到较大的流量, 502 | 就会遭受严重的内存问题。

503 |

后来两个新的可选项很快流行起来:mod_fastcgimod_fcgid。 504 | 两者均保持一定数量的 PHP 执行进程, 505 | Apache 将请求发送到这些端口来处理 PHP 的执行。由于这些库限制了存活的 PHP 进程的数量, 506 | 从而大大减少了内存使用而没有影响性能。

507 |

一些聪明的人创建一个 fastcgi 的实现,专门为真正与 PHP 工作良好而设计,他们称之为 PHP-FPM。PHP 5.3.0 之前,为安装它, 508 | 你得跨越许多障碍,但幸运的是,PHP 5.3.3 的核心包含了 PHP-FPM,因此在 Ubuntu 12.04 上安装它非常方便。

509 |

如下示例是针对 Apache 2.2.22 的,但 PHP-FPM 也能用于其他 web 服务器如 Nginx。

510 |

安装 PHP-FPM 和 Apache

511 |

在 Ubuntu 12.04 上你可以使用如下命令安装 PHP-FPM 和 Apache:

512 |
user@localhost: sudo apt-get install apache2-mpm-worker
513 | libapache2-mod-fastcgi php5-fpm
514 | user@localhost: sudo a2enmod actions alias fastcgi
515 | 
516 |

注意我们 必须 使用 apache2-mpm-worker,而不是 apache2-mpm-prefork 或 apache2-mpm-threaded。

517 |

接下来配置 Aapache 虚拟主机将 PHP 请求路由到 PHP-FPM 进程。将如下配置语句放入 Apache 518 | 配置文件(在 Ubuntu 12.04 上默认配置文件是 /etc/apache2/sites-available/default)。

519 |
<VirtualHost *:80>
520 |     AddHandler php5-fcgi .php
521 |     Action php5-fcgi /php5-fcgi
522 |     Alias /php5-fcgi /usr/lib/cgi-bin/php5-fcgi
523 |     FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -host 127.0.0.1:9000 -idle-timeout 120 -pass-header Authorization
524 | </VirtualHost>
525 | 
526 |

最后,重启 Apache 和 FPM 进程:

527 |
user@localhost: sudo service apache2 restart && sudo service php5-fpm
528 | restart
529 | 
530 |

进一步阅读

531 | 537 |
538 |
539 |

发送邮件

540 |

使用PHPMailer

541 |

经 PHPMailer 5.1 测试

542 |

PHP 提供了一个 mail() 函数,看起来很简单易用。 543 | 不幸的是,与 PHP 中的很多东西一样,它的简单性是个幻象,因其虚假的表面使用它会导致严重的安全问题。

544 |

Email 是一组网络协议,比 PHP 的历史还曲折。完全可以说发送邮件中的陷阱与 PHP 的 mail() 函数一样多,这个可能会令你有点「不寒而栗」吧。

545 |

PHPMailer 是一个流行而成熟的开源库,为安全地发送邮件提供一个易用的接口。 546 | 它关注可能陷阱,这样你可以专注于更重要的事情。

547 |

示例

548 |
549 |
<?php
550 | // Include the PHPMailer library
551 | require_once('phpmailer-5.1/class.phpmailer.php');
552 | 
553 | // Passing 'true' enables exceptions.  This is optional and defaults to false.
554 | $mailer = new PHPMailer(true);
555 | 
556 | // Send a mail from Bilbo Baggins to Gandalf the Grey
557 | 
558 | // Set up to, from, and the message body.  The body doesn't have to be HTML;
559 | // check the PHPMailer documentation for details.
560 | $mailer->Sender = 'bbaggins@example.com';
561 | $mailer->AddReplyTo('bbaggins@example.com', 'Bilbo Baggins');
562 | $mailer->SetFrom('bbaggins@example.com', 'Bilbo Baggins');
563 | $mailer->AddAddress('gandalf@example.com');
564 | $mailer->Subject = 'The finest weed in the South Farthing';
565 | $mailer->MsgHTML('<p>You really must try it, Gandalf!</p><p>-Bilbo</p>');
566 | 
567 | // Set up our connection information.
568 | $mailer->IsSMTP();
569 | $mailer->SMTPAuth = true;
570 | $mailer->SMTPSecure = 'ssl';
571 | $mailer->Port = 465;
572 | $mailer->Host = 'my smpt host';
573 | $mailer->Username = 'my smtp username';
574 | $mailer->Password = 'my smtp password';
575 | 
576 | // All done!
577 | $mailer->Send();
578 | ?>
579 | 
580 |
581 |
582 |
583 |

验证邮件地址

584 |

使用 filter_var() 函数

585 |

Web 应用可能需要做的一件常见任务是检测用户是否输入了一个有效的邮件地址。毫无疑问你可以在网上找到一些声称可以解决该问题的复杂的正则表达式,但是最简单的方法是使用 586 | PHP 的内建 filter_val() 函数。

587 |

示例

588 |
589 |
<?php
590 | filter_var('sgamgee@example.com', FILTER_VALIDATE_EMAIL);
591 | //Returns "sgamgee@example.com". This is a valid email address.
592 | 
593 | filter_var('sauron@mordor', FILTER_VALIDATE_EMAIL);
594 | // Returns boolean false! This is *not* a valid email address.
595 | ?>
596 | 
597 |
598 |

进一步阅读

599 | 603 |

注意

604 |

邮件地址验证也可以交给前端解决。HTML 5 的 表单即支持验证邮箱地址。只需将input元素的type设为email,就会自动验证用户输入的是否是合法的邮件地址。

605 |
<input type="email" name="email"></pre>
606 | 607 |

608 |
609 |
610 |

净化 HTML 输入和输出

611 |

对于简单的数据净化,使用 htmlentities() 函数, 612 | 复杂的数据净化则使用 HTML Purifier

613 |

经 HTML Purifier 4.4.0 测试

614 |

在任何 wbe 应用中展示用户输出时,首先对其进行“净化”去除任何潜在危险的 HTML 是非常必要的。 615 | 一个恶意的用户可以制作某些 HTML,若被你的 web 应用直接输出,对查看它的人来说会很危险。

616 |

虽然可以尝试使用正则表达式来净化 HTML,但不要这样做。HTML是一种复杂的语言,试图使用正则表达式来净化 HTML 几乎总是失败的。

617 |

你可能会找到建议你使用 strip_tags() 函数的观点。 618 | 虽然 strip_tags() 从技术上来说是安全的,但如果输入的不合法的 HTML(比如, 619 | 没有结束标签),它就成了一个「愚蠢」的函数,可能会去除比你期望的更多的内容。 620 | 由于非技术用户在通信中经常使用 <> 字符,strip_tags() 也就不是一个好的选择了。

621 |

如果阅读了验证邮件地址一节, 622 | 你也许也会考虑使用 filter_var() 函数。 623 | 然而 filter_var() 函数在遇到断行时会出现问题, 624 | 并且需要不直观的配置以接近 htmlentities() 函数的效果, 625 | 因此也不是一个好的选择。

626 |

对于简单需求的净化

627 |

如果你的 web 应用仅需要完全地转义(因此可以无害地呈现,但不是完全去除) HTML, 628 | 则使用 PHP 的内建 htmlentities() 函数。 629 | 这个函数要比 HTML Purifier 快得多,因此它不对 HTML 做任何验证---仅转义所有东西。

630 |

htmlentities() 不同于类似功能的函数htmlspecialchars(), 631 | 它会编码所有适用的 HTML 实体,而不仅仅是一个小的子集。

632 |

示例

633 |
634 |
<?php
635 | // Oh no!  The user has submitted malicious HTML, and we have to display it in our web app!
636 | $evilHtml = '<div onclick="xss();">Mua-ha-ha!  Twiddling my evil mustache...</div>';
637 | 
638 | // Use the ENT_QUOTES flag to make sure both single and double quotes are escaped.
639 | // Use the UTF-8 character encoding if you've stored the text as UTF-8 (as you should have).
640 | // See the UTF-8 section in this document for more details.
641 | $safeHtml = htmlentities($evilHtml, ENT_QUOTES, 'UTF-8');
642 | // $safeHtml is now fully escaped HTML.  You can output $safeHtml to your users without fear!
643 | ?>
644 | 
645 |
646 |

对于复杂需求的净化

647 |

对于很多 web 应用来说,简单地转义 HTML 是不够的。 648 | 你可能想完全去除任何HTML,或者允许一小部分子集的 HTML 存在。 649 | 若是如此,则使用 HTML Purifier 库。

650 |

HTML Purifier 是一个经过充分测试但效率比较低的库。 651 | 这就是为什么如果你的需求并不复杂就应使用 htmlentities(), 652 | 因为它的效率要快得多。

653 |

HTML Purifier 相比 strip_tags() 是有优势的, 654 | 因为它在净化 HTML 之前会对其校验。 655 | 这意味着如果用户输入无效 HTML,HTML Purifier 相比 strip_tags() 更能保留 HTML 的原意。 656 | HTML Purifier 高度可定制,允许你为 HTML 的一个子集建立白名单来允许这个 HTML 子集的实体存在输出中。

657 |

但其缺点就是相当的慢,它要求一些设置,在一个共享主机的环境里可能是不可行的。 658 | 其文档通常也复杂而不易理解。 659 | 以下示例是一个基本的使用配置。 660 | 查看文档阅读 HTML Purifier 提供的更多更高级的特性。

661 |

示例

662 |
663 |
<?php
664 | // Include the HTML Purifier library
665 | require_once('htmlpurifier-4.4.0/HTMLPurifier.auto.php');
666 | 
667 | // Oh no!  The user has submitted malicious HTML, and we have to display it in our web app!
668 | $evilHtml = '<div onclick="xss();">Mua-ha-ha!  Twiddling my evil mustache...</div>';
669 | 
670 | // Set up the HTML Purifier object with the default configuration.
671 | $purifier = new HTMLPurifier(HTMLPurifier_Config::createDefault());
672 | 
673 | $safeHtml = $purifier->purify($evilHtml);
674 | // $safeHtml is now sanitized.  You can output $safeHtml to your users without fear!
675 | ?>
676 | 
677 |
678 |

陷阱

679 | 687 |

进一步阅读

688 | 695 |
696 |
697 |

PHP 与 UTF-8

698 |

没有一行式解决方案。小心、注意细节,以及一致性。

699 |

PHP 中的 UTF-8 糟透了。原谅我的用词。

700 |

目前 PHP 在低层次上还不支持 Unicode。有几种方式可以确保 UTF-8 字符串能够被正确处理, 701 | 但并不容易,需要深入到 web 应用的所有层面,从 HTML,到 SQL,到 PHP。我们旨在提供一个简洁、 702 | 实用的概述。

703 |

PHP 层面的 UTF-8

704 |

基本的字符串操作,如串接 705 | 两个字符串、将字符串赋给变量,并不需要任何针对 UTF-8 的特殊东西。 706 | 然而,多数 字符串函数,如 strpos()strlen,就需要特殊的考虑。 707 | 这些函数都有一个对应的 mb_* 函数:例如,mb_strpos()mb_strlen()。 708 | 这些对应的函数统称为多字节字符串函数。 709 | 这些多字节字符串函数是专门为操作 Unicode 字符串而设计的。

710 |

当你操作 Unicode 字符串时,必须使用 mb_* 函数。 711 | 例如,如果你使用 substr() 操作一个 UTF-8 字符串,其结果就很可能包含一些乱码。 712 | 正确的函数应该是对应的多字节函数, mb_substr()

713 |

难的是始终记得使用 mb_* 函数。即使你仅一次忘了,你的 Unicode 字符串在接下来的处理中就可能产生乱码。

714 |

并不是所有的字符串函数都有一个对应的 mb_*。如果不存在你想要的那一个,那你就只能自认倒霉了。

715 |

此外,在每个 PHP 脚本的顶部(或者在全局包含脚本的顶部)你都应使用 mb_internal_encoding 函数,如果你的脚本会输出到浏览器,那么还得紧跟其后加个mb_http_output() 函数。在每个脚本中显式地定义字符串的编码在以后能为你减少很多令人头疼的事情。

716 |

最后,许多操作字符串的 PHP 函数都有一个可选参数让你指定字符编码。 717 | 若有该选项, 你应始终显式地指明 UTF-8 编码。 718 | 例如,htmlentities() 就有一个字符编码方式选项,在处理这样的字符串时应始终指定 UTF-8。

719 |

MySQL 层面的 UTF-8

720 |

如果你的 PHP 脚本会访问 MySQL,即使你遵从了前述的注意事项,你的字符串也有可能在数据库中存储为非 UTF-8 字符串。

721 |

确保从 PHP 到 MySQL 的字符串为 UTF-8 编码的,确保你的数据库以及数据表均设置为 utf8mb4 字符集, 722 | 并且在你的数据库中执行任何其他查询之前先执行 MySQL 查询 `set names utf8mb4`。这是至关重要的。 723 | 示例请查看连接并查询 MySQL 数据库一节内容。

724 |

注意你必须使用 `utf8mb4` 字符集来获得完整的 UTF-8 支持,而不是 `utf8` 字符集!原因请查看进一步阅读

725 |

浏览器层面的 UTF-8

726 |

使用 mb_http_output() 函数 727 | 来确保你的 PHP 脚本输出 UTF-8 字符串到浏览器。 728 | 并且在 HTML 页面的 <head> 标签块中包含 字符集 <meta> 标签块

729 |

示例

730 |
731 |
<?php
732 | // Tell PHP that we're using UTF-8 strings until the end of the script
733 | mb_internal_encoding('UTF-8');
734 | 
735 | // Tell PHP that we'll be outputting UTF-8 to the browser
736 | mb_http_output('UTF-8');
737 | 
738 | // Our UTF-8 test string
739 | $string = 'Aš galiu valgyti stiklą ir jis manęs nežeidžia';
740 | 
741 | // Transform the string in some way with a multibyte function
742 | $string = mb_substr($string, 0, 10);
743 | 
744 | // Connect to a database to store the transformed string
745 | // See the PDO example in this document for more information
746 | // Note the `set names utf8mb4` commmand!
747 | $link = new \PDO(   'mysql:host=your-hostname;dbname=your-db',
748 |                     'your-username',
749 |                     'your-password',
750 |                     array(
751 |                         \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
752 |                         \PDO::ATTR_PERSISTENT => false,
753 |                         \PDO::MYSQL_ATTR_INIT_COMMAND => 'set names utf8mb4'
754 |                     )
755 |                 );
756 | 
757 | // Store our transformed string as UTF-8 in our database
758 | // Assume our DB and tables are in the utf8mb4 character set and collation
759 | $handle = $link->prepare('insert into Sentences (Id, Body) values (?, ?)');
760 | $handle->bindValue(1, 1, PDO::PARAM_INT);
761 | $handle->bindValue(2, $string);
762 | $handle->execute();
763 | 
764 | // Retrieve the string we just stored to prove it was stored correctly
765 | $handle = $link->prepare('select * from Sentences where Id = ?');
766 | $handle->bindValue(1, 1, PDO::PARAM_INT);
767 | $handle->execute();
768 | 
769 | // Store the result into an object that we'll output later in our HTML
770 | $result = $handle->fetchAll(\PDO::FETCH_OBJ);
771 | ?><!doctype html>
772 | <html>
773 |     <head>
774 |         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
775 |         <title>UTF-8 test page</title>
776 |     </head>
777 |     <body>
778 |         <?php
779 |         foreach($result as $row){
780 |             print($row->Body);  // This should correctly output our transformed UTF-8 string to the browser
781 |         }
782 |         ?>
783 |     </body>
784 | </html>
785 | 
786 |
787 |

进一步阅读

788 | 795 |
796 |
797 |

处理日期和时间

798 |

使用DateTime 类

799 |

在 PHP 糟糕的老时光里,我们必须使用 date()gmdate()date_timezone_set()strtotime()等等令人迷惑的 800 | 组合来处理日期和时间。悲哀的是现在你仍旧会找到很多在线教程在讲述这些不易使用的老式函数。

801 |

幸运的是,我们正在讨论的 PHP 版本包含友好得多的 DateTime 类。 802 | 该类封装了老式日期函数所有功能,甚至更多,在一个易于使用的类中,并且使得时区转换更加容易。 803 | 在PHP中始终使用 DateTime 类来创建,比较,改变以及展示日期。

804 |

示例

805 |
806 |
<?php
807 | // Construct a new UTC date.  Always specify UTC unless you really know what you're doing!
808 | $date = new DateTime('2011-05-04 05:00:00', new DateTimeZone('UTC'));
809 | 
810 | // Add ten days to our initial date
811 | $date->add(new DateInterval('P10D'));
812 | 
813 | echo($date->format('Y-m-d h:i:s')); // 2011-05-14 05:00:00
814 | 
815 | // Sadly we don't have a Middle Earth timezone
816 | // Convert our UTC date to the PST (or PDT, depending) time zone
817 | $date->setTimezone(new DateTimeZone('America/Los_Angeles'));
818 | 
819 | // Note that if you run this line yourself, it might differ by an hour depending on daylight savings
820 | echo($date->format('Y-m-d h:i:s')); // 2011-05-13 10:00:00
821 | 
822 | $later = new DateTime('2012-05-20', new DateTimeZone('UTC'));
823 | 
824 | // Compare two dates
825 | if($date < $later)
826 |     echo('Yup, you can compare dates using these easy operators!');
827 | 
828 | // Find the difference between two dates
829 | $difference = $date->diff($later);
830 | 
831 | echo('The 2nd date is ' . $difference['days'] . ' later than 1st date.');
832 | ?>
833 | 
834 |
835 |

陷阱

836 | 843 |

进一步阅读

844 | 848 |
849 |
850 |

检测一个值是否为 null 或 false

851 |

使用 === 操作符来检测 null 和布尔 false 值。

852 |

PHP 宽松的类型系统提供了许多不同的方法来检测一个变量的值。 853 | 然而这也造成了很多问题。 854 | 使用 == 来检测一个值是否为 null 或 false,如果该值实际上是一个空字符串或 0,也会误报为 false。 855 | isset 是检测一个变量是否有值, 856 | 而不是检测该值是否为 null 或 false,因此在这里使用是不恰当的。

857 |

is_null() 函数能准确地检测一个值是否为 null, 858 | is_bool 可以检测一个值是否是布尔值(比如 false), 859 | 但存在一个更好的选择:=== 操作符。=== 检测两个值是否同一, 860 | 这不同于 PHP 宽松类型世界里的 相等。它也比 is_null() 和 is_bool() 要快一些,并且有些人认为这比使用函数来做比较更干净些。

861 |

示例

862 |
863 |
<?php
864 | $x = 0;
865 | $y = null;
866 | 
867 | // Is $x null?
868 | if($x == null)
869 |     print('Oops! $x is 0, not null!');
870 | 
871 | // Is $y null?
872 | if(is_null($y))
873 |     print('Great, but could be faster.');
874 | 
875 | if($y === null)
876 |     print('Perfect!');
877 | 
878 | // Does the string abc contain the character a?
879 | if(strpos('abc', 'a'))
880 |     // GOTCHA!  strpos returns 0, indicating it wishes to return the position of the first character.
881 |     // But PHP interpretes 0 as false, so we never reach this print statement!
882 |     print('Found it!'); 
883 | 
884 | //Solution: use !== (the opposite of ===) to see if strpos() returns 0, or boolean false.   
885 | if(strpos('abc', 'a') !== false)
886 |     print('Found it for real this time!');
887 | ?>
888 | 
889 |
890 |

陷阱

891 | 894 |

进一步阅读

895 | 900 |
901 |
902 |

建议与指正

903 |

感谢阅读!如果你有些地方还不太理解,很正常,PHP 是复杂的,并且充斥着陷阱。 904 | 因为我也只是一个人,所以本文档中难免存在错误。

905 |

如果你想为本文档贡献建议或纠正错误之处, 906 | 请使用最后修订日期&维护者 一节中的信息联系我。

907 |
908 |
909 | 910 | Fork me on GitHub 911 | 912 | 913 | 914 | 923 | 924 | 925 | 926 | -------------------------------------------------------------------------------- /js/jquery/jquery-1.7.2.min.js: -------------------------------------------------------------------------------- 1 | /*! jQuery v1.7.2 jquery.com | jquery.org/license */ 2 | (function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cu(a){if(!cj[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){ck||(ck=c.createElement("iframe"),ck.frameBorder=ck.width=ck.height=0),b.appendChild(ck);if(!cl||!ck.createElement)cl=(ck.contentWindow||ck.contentDocument).document,cl.write((f.support.boxModel?"":"")+""),cl.close();d=cl.createElement(a),cl.body.appendChild(d),e=f.css(d,"display"),b.removeChild(ck)}cj[a]=e}return cj[a]}function ct(a,b){var c={};f.each(cp.concat.apply([],cp.slice(0,b)),function(){c[this]=a});return c}function cs(){cq=b}function cr(){setTimeout(cs,0);return cq=f.now()}function ci(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ch(){try{return new a.XMLHttpRequest}catch(b){}}function cb(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g0){if(c!=="border")for(;e=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?+d:j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.2",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){if(typeof c!="string"||!c)return null;var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c
a",d=p.getElementsByTagName("*"),e=p.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=p.getElementsByTagName("input")[0],b={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:p.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,pixelMargin:!0},f.boxModel=b.boxModel=c.compatMode==="CSS1Compat",i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete p.test}catch(r){b.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",function(){b.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),i.setAttribute("name","t"),p.appendChild(i),j=c.createDocumentFragment(),j.appendChild(p.lastChild),b.checkClone=j.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,j.removeChild(i),j.appendChild(p);if(p.attachEvent)for(n in{submit:1,change:1,focusin:1})m="on"+n,o=m in p,o||(p.setAttribute(m,"return;"),o=typeof p[m]=="function"),b[n+"Bubbles"]=o;j.removeChild(p),j=g=h=p=i=null,f(function(){var d,e,g,h,i,j,l,m,n,q,r,s,t,u=c.getElementsByTagName("body")[0];!u||(m=1,t="padding:0;margin:0;border:",r="position:absolute;top:0;left:0;width:1px;height:1px;",s=t+"0;visibility:hidden;",n="style='"+r+t+"5px solid #000;",q="
"+""+"
",d=c.createElement("div"),d.style.cssText=s+"width:0;height:0;position:static;top:0;margin-top:"+m+"px",u.insertBefore(d,u.firstChild),p=c.createElement("div"),d.appendChild(p),p.innerHTML="
t
",k=p.getElementsByTagName("td"),o=k[0].offsetHeight===0,k[0].style.display="",k[1].style.display="none",b.reliableHiddenOffsets=o&&k[0].offsetHeight===0,a.getComputedStyle&&(p.innerHTML="",l=c.createElement("div"),l.style.width="0",l.style.marginRight="0",p.style.width="2px",p.appendChild(l),b.reliableMarginRight=(parseInt((a.getComputedStyle(l,null)||{marginRight:0}).marginRight,10)||0)===0),typeof p.style.zoom!="undefined"&&(p.innerHTML="",p.style.width=p.style.padding="1px",p.style.border=0,p.style.overflow="hidden",p.style.display="inline",p.style.zoom=1,b.inlineBlockNeedsLayout=p.offsetWidth===3,p.style.display="block",p.style.overflow="visible",p.innerHTML="
",b.shrinkWrapBlocks=p.offsetWidth!==3),p.style.cssText=r+s,p.innerHTML=q,e=p.firstChild,g=e.firstChild,i=e.nextSibling.firstChild.firstChild,j={doesNotAddBorder:g.offsetTop!==5,doesAddBorderForTableAndCells:i.offsetTop===5},g.style.position="fixed",g.style.top="20px",j.fixedPosition=g.offsetTop===20||g.offsetTop===15,g.style.position=g.style.top="",e.style.overflow="hidden",e.style.position="relative",j.subtractsBorderForOverflowNotVisible=g.offsetTop===-5,j.doesNotIncludeMarginInBodyOffset=u.offsetTop!==m,a.getComputedStyle&&(p.style.marginTop="1%",b.pixelMargin=(a.getComputedStyle(p,null)||{marginTop:0}).marginTop!=="1%"),typeof d.style.zoom!="undefined"&&(d.style.zoom=1),u.removeChild(d),l=p=d=null,f.extend(b,j))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e1,null,!1)},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){var d=2;typeof a!="string"&&(c=a,a="fx",d--);if(arguments.length1)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,f.prop,a,b,arguments.length>1)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.type]||f.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.type]||f.valHooks[g.nodeName.toLowerCase()];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h,i=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;i=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/(?:^|\s)hover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function( 3 | a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")};f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler,g=p.selector),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;le&&j.push({elem:this,matches:d.slice(e)});for(k=0;k0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return bc[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));o.match.globalPOS=p;var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="

";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="
";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h0)for(h=g;h=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/]","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*",""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div
","
"]),f.fn.extend({text:function(a){return f.access(this,function(a){return a===b?f.text(this):this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f 4 | .clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){return f.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1>");try{for(;d1&&l0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||f.isXMLDoc(a)||!bc.test("<"+a.nodeName+">")?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g,h,i,j=[];b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);for(var k=0,l;(l=a[k])!=null;k++){typeof l=="number"&&(l+="");if(!l)continue;if(typeof l=="string")if(!_.test(l))l=b.createTextNode(l);else{l=l.replace(Y,"<$1>");var m=(Z.exec(l)||["",""])[1].toLowerCase(),n=bg[m]||bg._default,o=n[0],p=b.createElement("div"),q=bh.childNodes,r;b===c?bh.appendChild(p):U(b).appendChild(p),p.innerHTML=n[1]+l+n[2];while(o--)p=p.lastChild;if(!f.support.tbody){var s=$.test(l),t=m==="table"&&!s?p.firstChild&&p.firstChild.childNodes:n[1]===""&&!s?p.childNodes:[];for(i=t.length-1;i>=0;--i)f.nodeName(t[i],"tbody")&&!t[i].childNodes.length&&t[i].parentNode.removeChild(t[i])}!f.support.leadingWhitespace&&X.test(l)&&p.insertBefore(b.createTextNode(X.exec(l)[0]),p.firstChild),l=p.childNodes,p&&(p.parentNode.removeChild(p),q.length>0&&(r=q[q.length-1],r&&r.parentNode&&r.parentNode.removeChild(r)))}var u;if(!f.support.appendChecked)if(l[0]&&typeof (u=l.length)=="number")for(i=0;i1)},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=by(a,"opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bu.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(by)return by(a,c)},swap:function(a,b,c){var d={},e,f;for(f in b)d[f]=a.style[f],a.style[f]=b[f];e=c.call(a);for(f in b)a.style[f]=d[f];return e}}),f.curCSS=f.css,c.defaultView&&c.defaultView.getComputedStyle&&(bz=function(a,b){var c,d,e,g,h=a.style;b=b.replace(br,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b))),!f.support.pixelMargin&&e&&bv.test(b)&&bt.test(c)&&(g=h.width,h.width=c,c=e.width,h.width=g);return c}),c.documentElement.currentStyle&&(bA=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f==null&&g&&(e=g[b])&&(f=e),bt.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),by=bz||bA,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0?bB(a,b,d):f.swap(a,bw,function(){return bB(a,b,d)})},set:function(a,b){return bs.test(b)?b+"px":b}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bq.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bp,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bp.test(g)?g.replace(bp,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){return f.swap(a,{display:"inline-block"},function(){return b?by(a,"margin-right"):a.style.marginRight})}})}),f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)}),f.each({margin:"",padding:"",border:"Width"},function(a,b){f.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bx[d]+b]=e[d]||e[d-2]||e[0];return f}}});var bC=/%20/g,bD=/\[\]$/,bE=/\r?\n/g,bF=/#.*$/,bG=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bH=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bI=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bJ=/^(?:GET|HEAD)$/,bK=/^\/\//,bL=/\?/,bM=/)<[^<]*)*<\/script>/gi,bN=/^(?:select|textarea)/i,bO=/\s+/,bP=/([?&])_=[^&]*/,bQ=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bR=f.fn.load,bS={},bT={},bU,bV,bW=["*/"]+["*"];try{bU=e.href}catch(bX){bU=c.createElement("a"),bU.href="",bU=bU.href}bV=bQ.exec(bU.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bR)return bR.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("
").append(c.replace(bM,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bN.test(this.nodeName)||bH.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bE,"\r\n")}}):{name:b.name,value:c.replace(bE,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b$(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b$(a,b);return a},ajaxSettings:{url:bU,isLocal:bI.test(bV[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bW},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bY(bS),ajaxTransport:bY(bT),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?ca(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cb(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bG.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bF,"").replace(bK,bV[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bO),d.crossDomain==null&&(r=bQ.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bV[1]&&r[2]==bV[2]&&(r[3]||(r[1]==="http:"?80:443))==(bV[3]||(bV[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),bZ(bS,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bJ.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bL.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bP,"$1_="+x);d.url=y+(y===d.url?(bL.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bW+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=bZ(bT,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)b_(g,a[g],c,e);return d.join("&").replace(bC,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cc=f.now(),cd=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cc++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=typeof b.data=="string"&&/^application\/x\-www\-form\-urlencoded/.test(b.contentType);if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(cd.test(b.url)||e&&cd.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(cd,l),b.url===j&&(e&&(k=k.replace(cd,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var ce=a.ActiveXObject?function(){for(var a in cg)cg[a](0,1)}:!1,cf=0,cg;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ch()||ci()}:ch,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,ce&&delete cg[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n);try{m.text=h.responseText}catch(a){}try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cf,ce&&(cg||(cg={},f(a).unload(ce)),cg[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cj={},ck,cl,cm=/^(?:toggle|show|hide)$/,cn=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,co,cp=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cq;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(ct("show",3),a,b,c);for(var g=0,h=this.length;g=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);f.fn[a]=function(e){return f.access(this,function(a,e,g){var h=cy(a);if(g===b)return h?c in h?h[c]:f.support.boxModel&&h.document.documentElement[e]||h.document.body[e]:a[e];h?h.scrollTo(d?f(h).scrollLeft():g,d?g:f(h).scrollTop()):a[e]=g},a,e,arguments.length,null)}}),f.each({Height:"height",Width:"width"},function(a,c){var d="client"+a,e="scroll"+a,g="offset"+a;f.fn["inner"+a]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,c,"padding")):this[c]():null},f.fn["outer"+a]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,c,a?"margin":"border")):this[c]():null},f.fn[c]=function(a){return f.access(this,function(a,c,h){var i,j,k,l;if(f.isWindow(a)){i=a.document,j=i.documentElement[d];return f.support.boxModel&&j||i.body&&i.body[d]||j}if(a.nodeType===9){i=a.documentElement;if(i[d]>=i[e])return i[d];return Math.max(a.body[e],i[e],a.body[g],i[g])}if(h===b){k=f.css(a,c),l=parseFloat(k);return f.isNumeric(l)?l:k}f(a).css(c,h)},c,a,arguments.length,null)}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window); -------------------------------------------------------------------------------- /js/jquery/jquery.smooth-scroll-1.4.5.min.js: -------------------------------------------------------------------------------- 1 | /*! Smooth Scroll - v1.4.5 - 2012-07-22 2 | * Copyright (c) 2012 Karl Swedberg; Licensed MIT, GPL */ 3 | (function(a){function f(a){return a.replace(/(:|\.)/g,"\\$1")}var b="1.4.5",c={exclude:[],excludeWithin:[],offset:0,direction:"top",scrollElement:null,scrollTarget:null,beforeScroll:function(){},afterScroll:function(){},easing:"swing",speed:400,autoCoefficent:2},d=function(b){var c=[],d=!1,e=b.dir&&b.dir=="left"?"scrollLeft":"scrollTop";return this.each(function(){if(this==document||this==window)return;var b=a(this);b[e]()>0?c.push(this):(b[e](1),d=b[e]()>0,b[e](0),d&&c.push(this))}),b.el==="first"&&c.length&&(c=[c[0]]),c},e="ontouchend"in document;a.fn.extend({scrollable:function(a){var b=d.call(this,{dir:a});return this.pushStack(b)},firstScrollable:function(a){var b=d.call(this,{el:"first",dir:a});return this.pushStack(b)},smoothScroll:function(b){b=b||{};var c=a.extend({},a.fn.smoothScroll.defaults,b),d=a.smoothScroll.filterPath(location.pathname);return this.unbind("click.smoothscroll").bind("click.smoothscroll",function(b){var e=this,g=a(this),h=c.exclude,i=c.excludeWithin,j=0,k=0,l=!0,m={},n=location.hostname===e.hostname||!e.hostname,o=c.scrollTarget||(a.smoothScroll.filterPath(e.pathname)||d)===d,p=f(e.hash);if(!c.scrollTarget&&(!n||!o||!p))l=!1;else{while(l&&jHashPassword('my super cool password'); 110 | 111 | // You can now safely store the contents of $hashedPassword in your database! 112 | 113 | // Check if a user has provided the correct password by comparing what they 114 | // typed with our hash 115 | $hasher->CheckPassword('the wrong password', $hashedPassword); // false 116 | 117 | $hasher->CheckPassword('my super cool password', $hashedPassword); // true 118 | ?> 119 | ``` 120 | 121 | **陷阱** 122 | 123 | - 许多资源可能推荐你在哈希之前对你的密码“加盐”。想法很好,但phpass在HashPassword()函数中已经对你的密码“加盐”了,这意味着你不需要自己“加盐”。 124 | 125 | **进一步阅读** 126 | 127 | - [phpass](http://www.openwall.com/phpass/) 128 | - [为什么使用md5或sha哈希密码是不安全的](http://blogs.msdn.com/b/lixiong/archive/2011/12/25/md5-sha1-salt-and-bcrypt.aspx) 129 | - [怎样安全地存储密码](http://codahale.com/how-to-safely-store-a-password/) 130 | 131 | 132 | ## 连接并查询MySQL数据库 133 | 134 | ### 使用[PDO](http://php.net/manual/en/book.pdo.php)及其预处理语句功能。 135 | 136 | 在PHP中,有很多方式来连接到一个MySQL数据库。PDO(PHP数据对象)是其中最新且最健壮的一种。PDO跨多种不同类型数据库有一个一致的接口,使用面向对象的方式,支持更多的新数据库支持的特性。 137 | 138 | 你应该使用PDO的预处理语句函数来帮助防范SQL注入攻击。使用函数[bindValue](http://php.net/manual/en/pdostatement.bindvalue.php)来确保你的SQL免于一级SQL注入攻击。(虽然并不是100%安全的,查看进一步阅读获取更多细节。)在以前,这必须使用一些“魔术引号(magic 139 | quotes)”函数的组合来实现。PDO使得那堆东西不再需要。 140 | 141 | **示例** 142 | 143 | ```php 144 | \PDO::ERRMODE_EXCEPTION, 159 | \PDO::ATTR_PERSISTENT => false, 160 | \PDO::MYSQL_ATTR_INIT_COMMAND => 'set names utf8mb4' 161 | ) 162 | ); 163 | 164 | $handle = $link->prepare('select Username from Users where UserId = ? or Username = ? limit ?'); 165 | 166 | // PHP bug: if you don't specify PDO::PARAM_INT, PDO may enclose the argument in quotes. 167 | // This can mess up some MySQL queries that don't expect integers to be quoted. 168 | // See: https://bugs.php.net/bug.php?id=44639 169 | // If you're not sure whether the value you're passing is an integer, use the is_int() function. 170 | $handle->bindValue(1, 100, PDO::PARAM_INT); 171 | $handle->bindValue(2, 'Bilbo Baggins'); 172 | $handle->bindValue(3, 5, PDO::PARAM_INT); 173 | 174 | $handle->execute(); 175 | 176 | // Using the fetchAll() method might be too resource-heavy if you're selecting a truly massive amount of rows. 177 | // If that's the case, you can use the fetch() method and loop through each result row one by one. 178 | // You can also return arrays and other things instead of objects. See the PDO documentation for details. 179 | $result = $handle->fetchAll(\PDO::FETCH_OBJ); 180 | 181 | foreach($result as $row){ 182 | print($row->Username); 183 | } 184 | } 185 | catch(\PDOException $ex){ 186 | print($ex->getMessage()); 187 | } 188 | ?> 189 | ``` 190 | 191 | **陷阱** 192 | 193 | - 当绑定整型变量时,如果不传递PDO::PARAM_INT参数有事可能会导致PDO对数据加引号。这会 194 | 搞坏特定的MySQL查询。查看[该bug报告](https://bugs.php.net/bug.php?id=44639)。 195 | - 未使用 \`set names utf8mb4\` 196 | 作为首个查询,可能会导致Unicode数据错误地存储进数据库,这依赖于你的配置。如果你 197 | 绝对有把握你的Unicode编码数据不会出问题,那你可以不管这个。 198 | - 启用持久连接可能会导致怪异的并发相关的问题。这不是一个PHP的问题,而是一个应用层面 199 | 的问题。只要你仔细考虑了后果,持久连接一般会是安全的。查看[Stack 200 | Overfilow这个问题](http://stackoverflow.com/questions/3332074/what-are-the-disadvantages-of-using-persistent-connection-in-pdo)。 201 | - 即使你使用了 \`set names utf8mb4\` 202 | ,你也得确认实际的数据库表使用的是utf8mb4字符集! 203 | 204 | - 可以在单个execute()调用中执行多条SQL语句。只需使用分号分隔语句,但注意[这个bug](https://bugs.php.net/bug.php?id=61207),在该文档所针对的PHP版本中还没修复。 205 | 206 | **进一步阅读** 207 | 208 | - [PHP手册:PDO](http://php.net/manual/en/book.pdo.php) 209 | - [为什么你应该使用PHP的PDO访问数据库](http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/) 210 | - [Stack Overflow: PHP PDO vs 普通的mysql_connect](http://stackoverflow.com/questions/1402017/php-pdo-vs-normal-mysql-connect) 211 | - [Stack Overflow: PDO预处理语句足以防范SQL注入吗?](http://stackoverflow.com/questions/134099/are-pdo-prepared-statements-sufficient-to-prevent-sql-injection) 212 | - [Stack Overflow: 在MySQL中使用SET NAMES utf8?](http://stackoverflow.com/questions/2159434/set-names-utf8-in-mysql) 213 | 214 | 215 | ## PHP标签 216 | 217 | ### 使用 `` 。 218 | 219 | 有几种不同的方式用来区分PHP程序块:``, ``, ``, 以及`<% 220 | %>`。对于打字来说,更短的标签更方便些,但唯一一种在所有PHP服务器上都一定能工作的标签 221 | 是``。若你计划将你的PHP应用部署到一台上面的PHP配置你无法控制的服务器上,那么你应始终使用 223 | ``。 224 | 225 | 若你仅仅是为自己编码,也能控制你将使用的PHP配置,你可能觉得短标签更方便些。但记住 226 | ``可能会和XML声明冲突,并且``实际上是ASP的风格。 227 | 228 | 无论你选择哪一种,确保一致。 229 | 230 | **陷阱** 231 | 232 | - 在一个纯PHP文件(例如,仅包含一个类定义的文件)中包含一个关闭`?>`标签时,确保其后 233 | 不会跟着任何换行。当PHP解析器安全地吃进跟在关闭标签之后的单个换行符时,任何其他的换行 234 | 都可能被输出到浏览器,如果之后要输出某些HTTP头,那么可能会造成混淆。 235 | - 编写Web应用时,确保在关闭`?>`标签与html的``标签之间不会留下换行。正确的HTML 236 | 文件中,``标签必须是文件中的第一样东西---在其之前的任何空格或换行都会使其 237 | 无效。 238 | 239 | **进一步阅读** 240 | 241 | - [Stack Overflow: 可以使用PHP短标签吗?](http://stackoverflow.com/questions/200640/are-php-short-tags-acceptable-to-use) 242 | 243 | 244 | ## 自动加载类 245 | 246 | ### 使用[spl_autoload_register()](http://php.net/manual/en/function.spl-autoload-register.php)来注册你的自动加载函数。 247 | 248 | PHP提供了若干方式来自动加载包含还未加载的类的文件。老的方法是使用名为[`__autoload()`](http://php.net/manual/en/function.autoload.php)魔术全局函数。然而你一次仅能定义一个`__autoload()`函数,因此如果你的程序 249 | 包含一个也使用了`__autoload()`函数的库,就会发生冲突。 250 | 251 | 处理这个问题的正确方法是唯一地命名你的自动加载函数,然后使用`spl_autoload_register()`函数 252 | 来注册它。该函数允许定义多个`__autoload()`这样的函数,因此你不必担心其他代码的`__autoload()`函数。 253 | 254 | **示例** 255 | 256 | ```php 257 | 273 | ``` 274 | 275 | **进一步阅读** 276 | 277 | - [PHP手册:spl_autoload_register()](http://php.net/manual/en/function.spl-autoload-register.php) 278 | - [Stack Overflow: 高效的PHP自动加载和命名策略](http://stackoverflow.com/questions/791899/efficient-php-auto-loading-and-naming-strategies) 279 | 280 | 281 | ## 从性能角度来看单引号和双引号 282 | 283 | ### 其实并不重要。 284 | 285 | 已有很多人花费很多笔墨来讨论是使用单引号(`'`)还是双引号(`"`)来定义字符串。 286 | 单引号字符串不会被解析,因此放入字符串的任何东西都会以原样显示。双引号字符串会被解析, 287 | 字符串中的任何PHP变量都会被求值。另外,转义字符如换行符`\n`和制表符`\t`在单引号字符串中 288 | 不会被求值,但在双引号字符串中会被求值。 289 | 290 | 由于双引号字符串在程序运行时要求值,从而理论上使用单引号字符串能提高性能,因为PHP 291 | 不会对单引号字符串求值。这对于一定规模的应用来说也许确实如此,但对于现实中一般的应用来说, 292 | 区别非常小以至于根本不用在意。因此对于普通应用,你选择哪种字符串并不重要。对于负载 293 | 极其高的应用来说,是有点作用的。根据你的应用的需要来做选择,但无论你选择什么,请保持一致。 294 | 295 | **进一步阅读** 296 | 297 | - [PHP手册:字符串](http://php.net/manual/en/language.types.string.php) 298 | - [PHP基准](http://phpbench.com/)(向下滚动到引号类型(Quote Types)) 299 | - [Stack Overflow: PHP中单引号字符串相比双引号字符串有性能优势么?](http://stackoverflow.com/questions/13620/speed-difference-in-using-inline-strings-vs-concatenation-in-php5) 300 | 301 | 302 | ## define() vs. const 303 | 304 | ### 使用[define()](http://www.php.net/manual/en/function.define.php),除非考虑到可读性、类常量、或关注微优化 305 | 306 | 习惯上,在PHP中是使用define()函数来定义常量。但从某个时候开始,PHP中也能够使用[const](http://php.net/manual/en/language.oop5.constants.php) 307 | 关键字来声明常量了。那么当定义常量时,该使用哪种方式呢? 308 | 309 | 答案在于这两种方法之间的区别。 310 | 311 | 1. define()在执行期定义常量,而const在编译期定义常量。这样const就有轻微的速度优势, 312 | 但不值得考虑这个问题,除非你在构建大规模的软件。 313 | 2. define()将常量放入全局作用域,虽然你可以在常量名中包含命名空间。这意味着你不能 314 | 使用define()定义类常量。 315 | 3. define()允许你在常量名和常量值中使用表达式,而const则都不允许。这使得define() 316 | 更加灵活。 317 | 4. define()可以在if()代码块中调用,但const不行。 318 | 319 | **示例** 320 | 321 | ```php 322 | 349 | ``` 350 | 351 | 因为define()更加灵活,你应该使用它以避免一些令人头疼的事情,除非你明确地需要类 352 | 常量。使用const通常会产生更加可读的代码,但是以牺牲灵活性为代价的。 353 | 354 | 无论你选择哪一种,请保持一致。 355 | 356 | **进一步阅读** 357 | 358 | - [Stack Overflow: define() vs. const](http://stackoverflow.com/questions/2447791/define-vs-const) 359 | - [PHP手册:常量](http://www.php.net/manual/en/language.constants.syntax.php) 360 | - [Stack Overflow: define() vs. 变量](http://stackoverflow.com/questions/1225082/define-vs-variable-in-php) 361 | 362 | 363 | ## 缓存PHP opcode 364 | 365 | ### 使用[APC](http://php.net/manual/en/book.apc.php) 366 | 367 | 在一个标准的PHP环境中,每次访问PHP脚本时,脚本都会被编译然后执行。一次又一次地花费 368 | 时间编译相同的脚本对于大型站点会造成性能问题。 369 | 370 | 解决方案是采用一个opcode缓存。opcode缓存是一个能够记下每个脚本经过编译的版本,这样 371 | 服务器就不需要浪费时间一次又一次地编译了。通常这些opcode缓存系统也能智能地检测到 372 | 一个脚本是否发生改变,因此当你升级PHP源码时,并不需要手动清空缓存。 373 | 374 | 有几个PHP 375 | opcode缓存可用,其中值得关注的有[eaccelerator](http://sourceforge.net/projects/eaccelerator/), 376 | [xcache](http://xcache.lighttpd.net/),以及[APC](http://php.net/manual/en/book.apc.php)。 377 | APC是PHP项目官方支持的,最为活跃,也最容易安装。它也提供一个可选的类[memcached](http://memcached.org/) 378 | 的持久化键-值对存储,因此你应使用它。 379 | 380 | **安装APC** 381 | 382 | 在Ubuntu 12.04上你可以通过在终端中执行以下命令来安装APC: 383 | 384 | user@localhost: sudo apt-get install php-apc 385 | 386 | 除此之外,不需要进一步的配置。 387 | 388 | **将APC作为一个持久化键-值存储系统来使用** 389 | 390 | APC也提供了对于你的脚本透明的类似于memcached的功能。与使用memcached相比一个大的优势是 391 | APC是集成到PHP核心的,因此你不需要在服务器上维护另一个运行的部件,并且PHP开发者在APC 392 | 上的工作很活跃。但从另一方面来说,APC并不是一个分布式缓存,如果你需要这个特性,你就 393 | 必须使用memcached了。 394 | 395 | **示例** 396 | 397 | ```php 398 | 416 | ``` 417 | 418 | **陷阱** 419 | 420 | - 如果你使用的不是[PHP-FPM](https://phpbestpractices.org/#serving-php)(例如你在 421 | 使用[mod_php](http://stackoverflow.com/questions/2712825/what-is-mod-php) 422 | 或[mod_fastcgi](http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html)),那么 423 | 每个PHP进程都会有自己独有的APC实例,包括键-值存储。若你不注意,这可能会在你的应用 424 | 代码中造成同步问题。 425 | 426 | **进一步阅读** 427 | 428 | - [PHP手册:APC](http://php.net/manual/en/book.apc.php) 429 | 430 | 431 | ## PHP与Memcached 432 | 433 | ### 若你需要一个分布式缓存,那就使用[Memcached](http://php.net/manual/en/book.memcached.php)客户端库。否则,使用APC。 434 | 435 | 缓存系统通常能够提升应用的性能。Memcached是一个受欢迎的选择,它能配合许多语言使用, 436 | 包括PHP。 437 | 438 | 然而,从一个PHP脚本中访问一个Memcached服务器,你有两个不同且命名很愚蠢的客户端库选择项: 439 | [Memcache](http://php.net/manual/en/book.memcache.php)和[Memcached](http://php.net/manual/en/book.memcached.php)。 440 | 它们是两个名字几乎相同的不同库,两者都可用于访问一个Memcached实例。 441 | 442 | 事实证明,Memcached库对于Memcached协议的实现最好,包含了一些Mmecache库没有的有用的特性, 443 | 并且看起来Memcached库的开发也最为活跃。 444 | 445 | 然而,如果不需要访问来自一组分布式服务器的一个Memcached实例,那就[使用APC](https://phpbestpractices.org/#opcode-cache)。 446 | APC得到PHP项目的支持,具备很多和Memcached相同的功能,并且能够用作opcode缓存,这能提高PHP脚本的性能。 447 | 448 | **安装Memcached客户端库** 449 | 450 | 在安装Memcached服务器之后,需要安装Memcached客户端库。没有该库,PHP脚本就没法与 451 | Memcached服务器通信。 452 | 453 | 在Ubuntu 12.04上,你可以使用如下命令来安装Memcached客户端库: 454 | 455 | user@localhost: sudo apt-get install php5-memcached 456 | 457 | **使用APC作为替代** 458 | 459 | 查看[opcode缓存一节](https://phpbestpractices.org/#opcode-cache)阅读更多与使用APC作为 460 | Memcached替代方案相关的信息。 461 | 462 | **进一步阅读** 463 | 464 | - [PHP手册:Memcached](http://php.net/manual/en/book.memcached.php) 465 | - [PHP手册:APC](http://php.net/manual/en/book.apc.php) 466 | - [Stack Overflow: PHP中使用Memcache vs. Memcached](http://stackoverflow.com/questions/1442411/using-memcache-vs-memcached-with-php) 467 | - [Stack Overflow: Memcached vs APC,我该选择哪一个?](http://stackoverflow.com/questions/815041/memcached-vs-apc-which-one-should-i-choose) 468 | 469 | 470 | ## PHP与正则表达式 471 | 472 | ### 使用[PCRE](http://php.net/manual/en/book.pcre.php)(`preg_*`)家族函数 473 | 474 | PHP有两种使用不同的方式来使用正则表达式:PCRE(Perl兼容表示法,`preg_*`)函数 475 | 和[POSIX](http://php.net/manual/en/book.regex.php)(POSIX扩展表示法,`ereg_*`) 476 | 函数。 477 | 478 | 每个函数家族各自使用一种风格稍微不同的正则表达式。幸运的是,POSIX家族函数从PHP 479 | 5.3.0开始就被弃用了。因此,你绝不应该使用POSIX家族函数编写新的代码。始终使用 480 | PRCE家族函数,即`preg_*`函数。 481 | 482 | **进一步阅读** 483 | 484 | - [PHP手册:PCRE](http://php.net/manual/en/book.pcre.php) 485 | - [PHP正则表达式起步](http://www.noupe.com/php/php-regular-expressions.html) 486 | 487 | 488 | ## 配置Web服务器提供PHP服务 489 | 490 | ### 使用[PHP-FPM](http://php.net/manual/en/install.fpm.php) 491 | 492 | 有多种方式来配置一个web服务器以提供PHP服务。传统(并且糟糕的)的方式是使用Apache的 493 | [mod_php](http://stackoverflow.com/questions/2712825/what-is-mod-php)。Mod_php将PHP 494 | 绑定到Apache自身,但是Apache对于该模块功能的管理工作非常糟糕。一旦遇到较大的流量, 495 | 就会遭受严重的内存问题。 496 | 497 | 后来两个新的可选项很快流行起来:[mod_fastcgi](http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html) 498 | 和[mod_fcgid](http://httpd.apache.org/mod_fcgid/)。两者均保持一定数量的PHP执行进程, 499 | Apache将请求发送到这些端口来处理PHP的执行。由于这些库限制了存活的PHP进程的数量, 500 | 从而大大减少了内存使用而没有影响性能。 501 | 502 | 一些聪明的人创建一个fastcgi的实现,专门为真正与PHP工作良好而设计,他们称之为 503 | [PHP-FPM](http://php.net/manual/en/install.fpm.php)。PHP 5.3.0之前,为安装它, 504 | 你得跨越许多障碍,但幸运的是,PHP 5.3.3的核心包含了PHP-FPM,因此在Ubuntu 12.04上安装它非常方便。 505 | 506 | 如下示例是针对Apache 2.2.22的,但PHP-FPM也能用于其他web服务器如Nginx。 507 | 508 | **安装PHP-FPM和Apache** 509 | 510 | 在Ubuntu 12.04上你可以使用如下命令安装PHP-FPM和Apache: 511 | 512 | user@localhost: sudo apt-get install apache2-mpm-worker 513 | libapache2-mod-fastcgi php5-fpm 514 | user@localhost: sudo a2enmod actions alias fastcgi 515 | 516 | 注意我们*必须*使用apache2-mpm-worker,而不是apache2-mpm-prefork或apache2-mpm-threaded。 517 | 518 | 接下来配置Aapache虚拟主机将PHP请求路由到PHP-FPM进程。将如下配置语句放入Apache 519 | 配置文件(在Ubuntu 12.04上默认配置文件是/etc/apache2/sites-available/default)。 520 | 521 | 522 | AddHandler php5-fcgi .php 523 | Action php5-fcgi /php5-fcgi 524 | Alias /php5-fcgi /usr/lib/cgi-bin/php5-fcgi 525 | FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -host 127.0.0.1:9000 -idle-timeout 120 -pass-header Authorization 526 | 527 | 528 | 最后,重启Apache和FPM进程: 529 | 530 | user@localhost: sudo service apache2 restart && sudo service php5-fpm 531 | restart 532 | 533 | **进一步阅读** 534 | 535 | - [PHP手册:PHP-FPM](http://php.net/manual/en/install.fpm.php) 536 | - [PHP-FPM主页](http://php-fpm.org/) 537 | - [在Ubuntu服务器Maverick上安装Apache + mod_fastcgi + PHP-FPM](https://alexcabal.com/installing-apache-mod_fastcgi-php-fpm-on-ubuntu-server-maverick/) 538 | - [为什么mod_php的性能很糟糕](http://www.joomlaperformance.com/articles/webcasts/why_mod_php_is_bad_for_performance_52_58.html) 539 | 540 | 541 | ## 发送邮件 542 | 543 | ### 使用[PHPMailer](https://code.google.com/a/apache-extras.org/p/phpmailer/) 544 | 545 | *经PHPMailer 5.1测试* 546 | 547 | PHP提供了一个[mail()](http://php.net/manual/en/function.mail.php)函数,看起来很简单易用。 548 | 不幸的是,与PHP中的很多东西一样,它的简单性是个幻象,因其虚假的表面使用它会导致 549 | 严重的安全问题。 550 | 551 | Email是一组网络协议,比PHP的历史还曲折。完全可以说发送邮件中的陷阱与PHP的mail() 552 | 函数一样多,这个可能会令你有点“不寒而栗”吧。 553 | 554 | [PHPMailer](http://code.google.com/a/apache-extras.org/p/phpmailer/)是一个流行而 555 | 成熟的开源库,为安全地发送邮件提供一个易用的接口。它关注可能陷阱,这样你可以专注 556 | 于更重要的事情。 557 | 558 | **示例** 559 | 560 | ```php 561 | Sender = 'bbaggins@example.com'; 573 | $mailer->AddReplyTo('bbaggins@example.com', 'Bilbo Baggins'); 574 | $mailer->SetFrom('bbaggins@example.com', 'Bilbo Baggins'); 575 | $mailer->AddAddress('gandalf@example.com'); 576 | $mailer->Subject = 'The finest weed in the South Farthing'; 577 | $mailer->MsgHTML('

You really must try it, Gandalf!

-Bilbo

'); 578 | 579 | // Set up our connection information. 580 | $mailer->IsSMTP(); 581 | $mailer->SMTPAuth = true; 582 | $mailer->SMTPSecure = 'ssl'; 583 | $mailer->Port = 465; 584 | $mailer->Host = 'my smpt host'; 585 | $mailer->Username = 'my smtp username'; 586 | $mailer->Password = 'my smtp password'; 587 | 588 | // All done! 589 | $mailer->Send(); 590 | ?> 591 | ``` 592 | 593 | 594 | ## 验证邮件地址 595 | 596 | ### 使用[filter_var()](http://php.net/manual/en/function.filter-var.php)函数 597 | 598 | Web应用可能需要做的一件常见任务是检测用户是否输入了一个有效的邮件地址。毫无疑问 599 | 你可以在网上找到一些声称可以解决该问题的复杂的正则表达式,但是最简单的方法是使用 600 | PHP的内建`filter_val()`函数。 601 | 602 | **示例** 603 | 604 | ```php 605 | 612 | ``` 613 | 614 | **进一步阅读** 615 | 616 | - [PHP手册:filter_var()](http://php.net/manual/en/function.filter-var.php) 617 | - [PHP手册:过滤器的类型](http://php.net/manual/en/filter.filters.php) 618 | 619 | 620 | ## 净化HTML输入和输出 621 | 622 | **对于简单的数据净化,使用[htmlentities()](http://php.net/manual/en/function.htmlentities.php)函数, 623 | 复杂的数据净化则使用[HTML Purifier](http://htmlpurifier.org/)库** 624 | 625 | *经HTML Purifier 4.4.0测试* 626 | 627 | 在任何wbe应用中展示用户输出时,首先对其进行“净化”去除任何潜在危险的HTML是非常必要的。 628 | 一个恶意的用户可以制作某些HTML,若被你的web应用直接输出,对查看它的人来说会很危险。 629 | 630 | 虽然可以尝试使用正则表达式来净化HTML,但不要这样做。HTML是一种复杂的语言,试图 631 | 使用正则表达式来净化HTML几乎总是失败的。 632 | 633 | 你可能会找到建议你使用[strip_tags()](http://php.net/manual/en/function.strip-tags.php) 634 | 函数的观点。虽然strip_tags()从技术上来说是安全的,但如果输入的不合法的HTML(比如, 635 | 没有结束标签),它就成了一个“愚蠢”的函数,可能会去除比你期望的更多的内容。由于非技术用户 636 | 在通信中经常使用`<`和`>`字符,`strip_tags()`也就不是一个好的选择了。 637 | 638 | 如果阅读了[验证邮件地址](https://phpbestpractices.org/#validating-emails)一节, 639 | 你也许也会考虑使用[filter_var()](http://php.net/manual/en/function.filter-var.php) 640 | 函数。然而[filter_var()函数在遇到断行时会出现问题](http://stackoverflow.com/questions/3150413/filter-sanitize-special-chars-problem-with-line-breaks), 641 | 并且需要不直观的配置以接近[htmlentities()](http://php.net/manual/en/function.htmlentities.php)函数的效果, 642 | 因此也不是一个好的选择。 643 | 644 | **对于简单需求的净化** 645 | 646 | 如果你的web应用仅需要完全地转义(因此可以无害地呈现,但不是完全去除)HTML,则使用 647 | PHP的内建[htmlentities()](http://php.net/manual/en/function.htmlentities.php)函数。 648 | 这个函数要比HTML Purifier快得多,因此它不对HTML做任何验证---仅转义所有东西。 649 | 650 | htmlentities()不同于类似功能的函数[htmlspecialchars()](http://php.net/manual/en/function.htmlspecialchars.php), 651 | 它会编码所有适用的HTML实体,而不仅仅是一个小的子集。 652 | 653 | **示例** 654 | 655 | ```php 656 | Mua-ha-ha! Twiddling my evil mustache...
'; 659 | 660 | // Use the ENT_QUOTES flag to make sure both single and double quotes are escaped. 661 | // Use the UTF-8 character encoding if you've stored the text as UTF-8 (as you should have). 662 | // See the UTF-8 section in this document for more details. 663 | $safeHtml = htmlentities($evilHtml, ENT_QUOTES, 'UTF-8'); 664 | // $safeHtml is now fully escaped HTML. You can output $safeHtml to your users without fear! 665 | ?> 666 | ``` 667 | 668 | **对于复杂需求的净化** 669 | 670 | 对于很多web应用来说,简单地转义HTML是不够的。你可能想完全去除任何HTML,或者允许 671 | 一小部分子集的HTML存在。若是如此,则使用[HTML Purifier](http://htmlpurifier.org/) 672 | 库。 673 | 674 | HTML Purifier是一个经过充分测试但效率比较低的库。这就是为什么如果你的需求并不复杂 675 | 就应使用[htmlentities()](http://php.net/manual/en/function.htmlentities.php),因为 676 | 它的效率要快得多。 677 | 678 | HTML Purifier相比[strip_tags()](http://php.net/manual/en/function.strip-tags.php) 679 | 是有优势的,因为它在净化HTML之前会对其校验。这意味着如果用户输入无效HTML,HTML 680 | Purifier相比strip_tags()更能保留HTML的原意。HTML 681 | Purifier高度可定制,允许你为HTML的一个子集建立白名单来允许这个HTML子集的实体存在 682 | 输出中。 683 | 684 | 但其缺点就是相当的慢,它要求一些设置,在一个共享主机的环境里可能是不可行的。其文档 685 | 通常也复杂而不易理解。以下示例是一个基本的使用配置。查看[文档](http://htmlpurifier.org/docs) 686 | 阅读HTML Purifier提供的更多更高级的特性。 687 | 688 | **示例** 689 | 690 | ```php 691 | Mua-ha-ha! Twiddling my evil mustache...'; 697 | 698 | // Set up the HTML Purifier object with the default configuration. 699 | $purifier = new HTMLPurifier(HTMLPurifier_Config::createDefault()); 700 | 701 | $safeHtml = $purifier->purify($evilHtml); 702 | // $safeHtml is now sanitized. You can output $safeHtml to your users without fear! 703 | ?> 704 | ``` 705 | 706 | **陷阱** 707 | 708 | - 以错误的字符编码使用htmlentities()会造成意想不到的输出。在调用该函数时始终确认 709 | 指定了一种字符编码,并且该编码与将被净化的字符串的编码相匹配。更多细节请查看 710 | [UTF-8一节](https://phpbestpractices.org/#utf-8)。 711 | - 使用htmlentities()时,始终包含ENT_QUOTES和字符编码参数。默认情况下,htmlentities() 712 | 不会对单引号编码。多愚蠢的默认做法! 713 | - HTML 714 | Purifier对于复杂的HTML效率极其的低。可以考虑设置一个缓存方案如APC来保存经过净化的结果 715 | 以备后用。 716 | 717 | **进一步阅读** 718 | 719 | - [PHP HTML净化工具对比](http://htmlpurifier.org/comparison) 720 | - [Stack Overflow: 使用strip_tags()来防止XSS?](http://stackoverflow.com/questions/3605629/php-prevent-xss-with-strip-tags) 721 | - [Stack Overflow: PHP中净化用户输入的最佳方法是什么?](http://stackoverflow.com/questions/129677/whats-the-best-method-for-sanitizing-user-input-with-php) 722 | - [Stack Overflow: 断行时的FILTER_SANITIZE_SPECIAL_CHARS问题](http://stackoverflow.com/questions/3150413/filter-sanitize-special-chars-problem-with-line-breaks) 723 | 724 | 725 | ## PHP与UTF-8 726 | 727 | ### 没有一行式解决方案。小心、注意细节,以及一致性。 728 | 729 | PHP中的UTF-8糟透了。原谅我的用词。 730 | 731 | 目前PHP在低层次上还不支持Unicode。有几种方式可以确保UTF-8字符串能够被正确处理, 732 | 但并不容易,需要深入到web应用的所有层面,从HTML,到SQL,到PHP。我们旨在提供一个简洁、 733 | 实用的概述。 734 | 735 | **PHP层面的UTF-8** 736 | 737 | 基本的[字符串操作](http://php.net/manual/en/language.operators.string.php),如串接 738 | 两个字符串、将字符串赋给变量,并不需要任何针对UTF-8的特殊东西。然而,多数 739 | [字符串函数](http://php.net/manual/en/ref.strings.php),如[strpos()](http://php.net/manual/en/function.strpos.php) 740 | 和[strlen](http://php.net/manual/en/function.strlen.php),就需要特殊的考虑。这些 741 | 函数都有一个对应的`mb_*`函数:例如,[mb_strpos()](http://php.net/manual/en/function.mb-strpos.php) 742 | 和[mb_strlen()](http://php.net/manual/en/function.mb-strlen.php)。这些对应的函数 743 | 统称为[多字节字符串函数](http://php.net/manual/en/ref.mbstring.php)。这些多字节字符串 744 | 函数是专门为操作Unicode字符串而设计的。 745 | 746 | 当你操作Unicode字符串时,必须使用`mb_*`函数。例如,如果你使用[substr()](http://php.net/manual/en/function.substr.php) 747 | 操作一个UTF-8字符串,其结果就很可能包含一些乱码。正确的函数应该是对应的多字节函数, 748 | [mb_substr()](http://php.net/manual/en/function.mb-substr.php)。 749 | 750 | 难的是始终记得使用`mb_*`函数。即使你仅一次忘了,你的Unicode字符串在接下来的处理中 751 | 就可能产生乱码。 752 | 753 | 并不是所有的字符串函数都有一个对应的`mb_*`。如果不存在你想要的那一个,那你就只能 754 | 自认倒霉了。 755 | 756 | 此外,在每个PHP脚本的顶部(或者在全局包含脚本的顶部)你都应使用 757 | [mb_internal_encoding](http://php.net/manual/en/function.mb-internal-encoding.php) 758 | 函数,如果你的脚本会输出到浏览器,那么还得紧跟其后加个[mb_http_output()](http://php.net/manual/en/function.mb-http-output.php) 759 | 函数。在每个脚本中显式地定义字符串的编码在以后能为你减少很多令人头疼的事情。 760 | 761 | 最后,许多操作字符串的PHP函数都有一个可选参数让你指定字符编码。若有该选项, 你应 762 | 始终显式地指明UTF-8编码。例如,[htmlentities()](http://php.net/manual/en/function.htmlentities.php) 763 | 就有一个字符编码方式选项,在处理这样的字符串时应始终指定UTF-8。 764 | 765 | **MySQL层面的UTF-8** 766 | 767 | 如果你的PHP脚本会访问MySQL,即使你遵从了前述的注意事项,你的字符串也有可能在数据库 768 | 中存储为非UTF-8字符串。 769 | 770 | 确保从PHP到MySQL的字符串为UTF-8编码的,确保你的数据库以及数据表均设置为utf8mb4字符集, 771 | 并且在你的数据库中执行任何其他查询之前先执行MySQL查询\`set names 772 | utf8mb4\`。这是至关重要的。示例 773 | 请查看[连接并查询MySQL数据库](https://phpbestpractices.org/#mysql)一节内容。 774 | 775 | 注意你必须使用\`utf8mb4\`字符集来获得完整的UTF-8支持,而不是\`utf8\`字符集!原因 776 | 请查看[进一步阅读](https://phpbestpractices.org/#utf8-further-reading)。 777 | 778 | **浏览器层面的UTF-8** 779 | 780 | 使用[mb_http_output()](http://php.net/manual/en/function.mb-http-output.php)函数 781 | 来确保你的PHP脚本输出UTF-8字符串到浏览器。并且在HTML页面的``标签块中包含 782 | [字符集``标签块](http://htmlpurifier.org/docs/enduser-utf8.html)。 783 | 784 | **示例** 785 | 786 | ```php 787 | \PDO::ERRMODE_EXCEPTION, 808 | \PDO::ATTR_PERSISTENT => false, 809 | \PDO::MYSQL_ATTR_INIT_COMMAND => 'set names utf8mb4' 810 | ) 811 | ); 812 | 813 | // Store our transformed string as UTF-8 in our database 814 | // Assume our DB and tables are in the utf8mb4 character set and collation 815 | $handle = $link->prepare('insert into Sentences (Id, Body) values (?, ?)'); 816 | $handle->bindValue(1, 1, PDO::PARAM_INT); 817 | $handle->bindValue(2, $string); 818 | $handle->execute(); 819 | 820 | // Retrieve the string we just stored to prove it was stored correctly 821 | $handle = $link->prepare('select * from Sentences where Id = ?'); 822 | $handle->bindValue(1, 1, PDO::PARAM_INT); 823 | $handle->execute(); 824 | 825 | // Store the result into an object that we'll output later in our HTML 826 | $result = $handle->fetchAll(\PDO::FETCH_OBJ); 827 | ?> 828 | 829 | 830 | 831 | UTF-8 test page 832 | 833 | 834 | Body); // This should correctly output our transformed UTF-8 string to the browser 837 | } 838 | ?> 839 | 840 | 841 | ``` 842 | 843 | **进一步阅读** 844 | 845 | - [PHP手册:多字节字符串函数](http://php.net/manual/en/ref.mbstring.php) 846 | - [PHP UTF-8备忘单](http://blog.loftdigital.com/blog/php-utf-8-cheatsheet) 847 | - [Stack Overflow: 什么因素致使PHP不兼容Unicode?](http://stackoverflow.com/questions/571694/what-factors-make-php-unicode-incompatible) 848 | - [Stack Overflow: PHP与MySQL之间国际化字符串的最佳实践](http://stackoverflow.com/questions/140728/best-practices-in-php-and-mysql-with-international-strings) 849 | - [怎样在MySQL数据库中完整支持Unicode](http://mathiasbynens.be/notes/mysql-utf8mb4) 850 | 851 | 852 | ## 处理日期和时间 853 | 854 | ### 使用[DateTime类](http://www.php.net/manual/en/class.datetime.php)。 855 | 856 | 在PHP糟糕的老时光里,我们必须使用[date()](http://www.php.net/manual/en/function.date.php), 857 | [gmdate()](http://www.php.net/manual/en/function.gmdate.php), 858 | [date_timezone_set()](http://www.php.net/manual/en/function.date-timezone-set.php), 859 | [strtotime()](http://www.php.net/manual/en/function.strtotime.php)等等令人迷惑的 860 | 组合来处理日期和时间。悲哀的是现在你仍旧会找到很多在线教程在讲述这些不易使用的老式函数。 861 | 862 | 幸运的是,我们正在讨论的PHP版本包含友好得多的[DateTime类](http://www.php.net/manual/en/class.datetime.php)。 863 | 该类封装了老式日期函数所有功能,甚至更多,在一个易于使用的类中,并且使得时区转换更加容易。 864 | 在PHP中始终使用DateTime类来创建,比较,改变以及展示日期。 865 | 866 | **示例** 867 | 868 | ```php 869 | add(new DateInterval('P10D')); 875 | 876 | echo($date->format('Y-m-d h:i:s')); // 2011-05-14 05:00:00 877 | 878 | // Sadly we don't have a Middle Earth timezone 879 | // Convert our UTC date to the PST (or PDT, depending) time zone 880 | $date->setTimezone(new DateTimeZone('America/Los_Angeles')); 881 | 882 | // Note that if you run this line yourself, it might differ by an hour depending on daylight savings 883 | echo($date->format('Y-m-d h:i:s')); // 2011-05-13 10:00:00 884 | 885 | $later = new DateTime('2012-05-20', new DateTimeZone('UTC')); 886 | 887 | // Compare two dates 888 | if($date < $later) 889 | echo('Yup, you can compare dates using these easy operators!'); 890 | 891 | // Find the difference between two dates 892 | $difference = $date->diff($later); 893 | 894 | echo('The 2nd date is ' . $difference['days'] . ' later than 1st date.'); 895 | ?> 896 | ``` 897 | 898 | **陷阱** 899 | 900 | - 如果你不指定一个时区,[DateTime::__construct()](http://www.php.net/manual/en/datetime.construct.php) 901 | 就会将生成日期的时区设置为正在运行的计算机的时区。之后,这会导致大量令人头疼的事情。 902 | **在创建新日期时始终指定UTC时区,除非你确实清楚自己在做的事情。** 903 | - 如果你在DateTime::__construct()中使用Unix时间戳,那么时区将始终设置为UTC而不管 904 | 第二个参数你指定了什么。 905 | - 向DateTime::__construct()传递零值日期(如:“0000-00-00”,常见MySQL生成该值作为 906 | DateTime类型数据列的默认值)会产生一个无意义的日期,而不是“0000-00-00”。 907 | - 在32位系统上使用[DateTime::getTimestamp()](http://www.php.net/manual/en/datetime.gettimestamp.php) 908 | 不会产生代表2038年之后日期的时间戳。64位系统则没有问题。 909 | 910 | **进一步阅读** 911 | 912 | - [PHP手册:DateTime类](http://www.php.net/manual/en/book.datetime.php) 913 | - [Stack Overflow: 访问超出2038的日期](http://stackoverflow.com/questions/5319710/accessing-dates-in-php-beyond-2038) 914 | 915 | 916 | ## 检测一个值是否为null或false 917 | 918 | ### 使用[===](http://php.net/manual/en/language.operators.comparison.php)操作符来检测null和布尔false值。 919 | 920 | PHP宽松的类型系统提供了许多不同的方法来检测一个变量的值。然而这也造成了很多问题。 921 | 使用`==`来检测一个值是否为null或false,如果该值实际上是一个空字符串或0,也会误报 922 | 为false。[isset](http://php.net/manual/en/function.isset.php)是检测一个变量是否有值, 923 | 而不是检测该值是否为null或false,因此在这里使用是不恰当的。 924 | 925 | [is_null()](http://php.net/manual/en/function.is-null.php)函数能准确地检测一个值 926 | 是否为null,[is_bool](http://php.net/manual/en/function.is-bool.php)可以检测一个值 927 | 是否是布尔值(比如false),但存在一个更好的选择:`===`操作符。`===`检测两个值是否同一, 928 | 这不同于PHP宽松类型世界里的*相等*。它也比is_null()和is_bool()要快一些,并且有些人 929 | 认为这比使用函数来做比较更干净些。 930 | 931 | **示例** 932 | 933 | ```php 934 | 959 | ``` 960 | 961 | **陷阱** 962 | 963 | - 测试一个返回0或布尔false的函数的返回值时,如strpos(),始终使用`===`和`!==`,否则 964 | 你就会碰到问题。 965 | 966 | **进一步阅读** 967 | 968 | - [PHP手册:比较操作符](http://php.net/manual/en/language.operators.comparison.php) 969 | - [Stack Overflow: is_null() vs ===](http://stackoverflow.com/questions/8228837/is-nullx-vs-x-null-in-php) 970 | 971 | 972 | ## 建议与指正 973 | 974 | 感谢阅读!如果你有些地方还不太理解,很正常,PHP是复杂的,并且充斥着陷阱。因为我也 975 | 只是一个人,所以本文档中难免存在错误。 976 | 977 | 如果你想为本文档贡献建议或纠正错误之处,请使用[最后修订日期&维护者](https://phpbestpractices.org/#maintainers) 978 | 一节中的信息联系我。 979 | --------------------------------------------------------------------------------