Netkiller PHP 手札

PHP Language...

Mr. Neo Chan, 陈景峰(BG7NYT)

中国广东省深圳市龙华新区民治街道溪山美地
518131
+86 13113668890
+86 755 29812080
<netkiller@msn.com>

$Id: book.xml 642 2013-07-19 01:28:13Z netkiller $

版权 © 2008, 2009, 2010, 2011, 2012, 2013 Netkiller(Neo Chan). All rights reserved.

版权声明

转载请与作者联系，转载时请务必标明文章原始出处和作者信息及本声明。
文档出处:
http://netkiller.github.io
http://netkiller.sourceforge.net

$Date: 2013-07-19 09:28:13 +0800 (Fri, 19 Jul 2013) $

我的系列文档

Netkiller Architect 手札 | Netkiller Developer 手札 | Netkiller PHP 手札 | Netkiller Python 手札 | Netkiller Testing 手札 | Netkiller Cryptography 手札
Netkiller Linux 手札 | Netkiller CentOS 手札 | Netkiller FreeBSD 手札 | Netkiller Security 手札 | Netkiller Version 手札 | Netkiller Web 手札
Netkiller Monitoring 手札 | Netkiller Storage 手札 | Netkiller Mail 手札 | Netkiller Shell 手札 | Netkiller Network 手札 | Netkiller Database 手札
Netkiller PostgreSQL 手札 | Netkiller MySQL 手札 | Netkiller NoSQL 手札 | Netkiller LDAP 手札 | Netkiller Cisco IOS 手札 | Netkiller H3C 手札
Netkiller Multimedia 手札 | Netkiller Docbook 手札 | Netkiller 开源软件 手札 |  |  |

您可以使用iBook阅读当前文档

QQ群：128659835 请注明“读者”

目录

自述
1. 系列文档
2. 作者简介
3. 写给读者
1. install and configure
1.1. php.ini
1.1.1. Time Zone
1.1.2. open_basedir
1.1.3. disable_functions
1.1.4. disable_classes
1.1.5. 隐藏php本版信息
2. Language Reference
2.1. php://stdin & php://stdout
2.2. Exception
3. String 字符串操作
3.1. 英文大小写
3.2. str_replace
4. Array 数组
4.1. 删除数组元素
4.2. 数组与字符串操作
5. Function
5.1. 列出所有function
5.2. php.ini
5.2.1. ini_set
5.2.2. ini_get
5.3. PHP Option
5.4. 操作系统类型
5.5. 日期比较
5.6. rand()
5.7. header
6. PHP Classes 类与对象
6.1. 构造函数和析构函数 __construct() / __destruct()
6.2. Traits
7. PECL :: The PHP Extension Community Library
7.1. php-apc - APC (Alternative PHP Cache) module for PHP 5
7.1.1. 编译安装 APC Cache
7.2. PHP Memcache
7.2.1. pecl
7.2.2. apt-get
7.2.3. example
7.3. php5-gd - GD module for php5
7.4. Database Extensions
7.4.1. sqlite
7.4.2. mysqli
7.4.3. MongoDB
7.4.4. php-redis.x86_64 : Extension for communicating with the Redis key-value store
7.4.4.1. pecl 安装
7.4.4.2. yum安装
7.4.4.3. 源码编译安装
7.4.4.4. 配置 redis.ini
7.4.4.5. Session 配置
7.4.5. php5-pgsql - PostgreSQL module for php5
7.4.6. PHP connect SQL Server under unix like
7.4.7. MySQL
7.4.8. oracle
7.5. xmlrpc
7.6. openssl
7.7. mcrypt
7.8. mhash
7.9. simplexml
7.10. ionCube
7.11. ZendOptimizer
7.12. zip
7.13. pcntl
7.14. mbstring
7.15. Suhosin
7.16. freetype
7.17. XCache
7.17.1. apt-get
7.17.2. make
7.18. XHProf
7.19. Xdebug
7.19.1. Webgrind
7.19.2. WinCacheGrind
7.20. UploadProgress
7.21. msgpack
7.22. iconv
7.23. imagick
7.24. sysvmsg
8. PEAR - PHP Extension and Application Repository
8.1. PEAR 使用说明
8.1.1. php-pear 安装
8.1.2. channel-update
8.1.3. install/uninstall
8.2. Pyrus
8.3. Pirum is a simple PEAR Channel Server Manager
8.4. PHPUnit - Unit testing framework for PHP
8.5. XML_RSS
8.6. Propel - smart, easy object persistence
8.6.1. 环境配置
8.6.2. PEAR Installer
8.7. Lua for PHP extension
8.8. libuv php extension
9. Application
9.1. phpmailer
9.2. Soap
9.2.1. soapfunc.php
9.2.2. soapserver.php
9.2.3. soapclient.php
9.3. php function check
9.4. whois 域名查询
9.5. React - Event-driven, non-blocking I/O with PHP. (Node.PHP)
10. Frameworks
10.1. CodeIgniter - Open source PHP web application framework
10.1.1. Nginx
10.1.2. PHP_CodeSniffer
10.2. Fuel PHP
10.2.1. 框架安装
10.2.1.1. oil
10.2.1.2. Apache
10.2.1.3. Nginx
10.3. Kohana
10.4. Yii
10.5. Zend Framework
10.5.1. Install Zend Framework
10.5.2. Create Your Project
10.5.3. Create a virtual host
10.5.4. Database
10.5.4.1. MySQL
10.5.4.2. SQLite
10.5.5. zf.sh
10.5.5.1. controller
10.5.5.2. model
10.5.5.3. layout
10.5.5.4. form
10.5.6. Smarty
11. PHP Extension 扩展开发
11.1. Extension Example
11.2. PHP_FUNCTION
11.3. PHP_INI
11.4. PHP_MINFO_FUNCTION
12. Debug
12.1. FirePHP
13. FAQ
13.1. Error in TLS handshake, trying SSLv3...

范例清单

7.1. php apc cache
7.2. memcache.php
7.3. oracle
7.4. php openssl
7.5. mcrypt
7.6. simplexml
7.7. xhprof/sample.php
8.1. RSS.php


自述

目录

1. 系列文档
2. 作者简介
3. 写给读者

目前技术书籍的价格一路飙升，动则80，100，少则50，60. 技术书籍有时效性，随着技术的革新或淘汰，大批书记成为废纸垃圾。并且这些书技术内容雷同，相互抄袭，质量越来越差，甚至里面给出的例子错误百出，只能购买影印版，或者翻译的版本。

在这种背景下我便萌生了自己写书的想法，资料主要来源是我的笔记与例子。我并不想出版，只为分享，所有我制作了基于CC License 发行的系列电子书。

本书注重例子，少理论，只要你对这例子一步一步操作，就会成功，会让你有成就感并能坚持学下去，因为很多人遇到障碍就会放弃，其实我就是这种人，只要让他看到希望，就能坚持下去。

为什么写这篇文章

有很多想法,工作中也用不到所以未能实现，所以想写出来,和大家分享.有一点写一点,写得也不好,只要能看懂就行,就当学习笔记了.

开始零零碎碎写过一些文档，也向维基百科供过稿，但维基经常被ZF封锁，后来发现sf.net可以提供主机存放文档，便做了迁移。并开始了我的写作生涯。

这篇文档是作者10年来对工作的总结,是作者一点一滴的积累起来的，有些笔记已经丢失，所以并不完整。

因为工作太忙整理比较缓慢。目前的工作涉及面比较窄所以新文档比较少。

我现在花在技术上的时间越来越少，兴趣转向摄影，无线电。也想写写摄影方面的心得体会。

写作动力:

曾经在网上看到外国开源界对中国的评价，中国人对开源索取无度，但贡献却微乎其微.这句话一直记在我心中，发誓要为中国开源事业做我仅有的一点微薄贡献

另外写文档也是知识积累，还可以增加在圈内的影响力.

人跟动物的不同,就是人类可以把自己学习的经验教给下一代人.下一代在上一代的基础上再创新,不断积累才有今天.

所以我把自己的经验写出来,可以让经验传承

没有内容的章节:

目前我自己一人维护所有文档，写作时间有限，当我发现一个好主题就会加入到文档中，待我有时间再完善章节，所以你会发现很多章节是空无内容的.

文档目前几乎是流水帐试的写作，维护量很大，先将就着看吧.

我想到哪写到哪,你会发现文章没一个中心,今天这里写点,明天跳过本章写其它的.
文中例子绝对多,对喜欢复制然后粘贴朋友很有用,不用动手写,也省时间.
理论的东西,网上大把,我这里就不写了,需要可以去网上查.
我爱写错别字,还有一些是打错的,如果发现请指正.
文中大部分试验是在Debian/Ubuntu/Redhat AS上完成.

1. 系列文档

下面是我多年积累下来的经验总结，整理成文档供大家参考:

HTML 格式

http://netkiller.github.com/home/technology.html

http://netkiller.sourceforge.net/home/technology.html

PDF 格式

Download PDF Document 下载PDF文档1

Download PDF Document 下载PDF文档2

EPUB 格式

http://netkiller.sourceforge.net/technology.html

通过 GIT 镜像整个网站

https://github.com/netkiller/netkiller.github.com.git

$ git clone https://github.com/netkiller/netkiller.github.com.git

其他方式

获得光盘介质，RPM包，DEB包，如有特别需要，请联系我


2. 作者简介

陈景峰 (ㄔㄣ ㄐ丨ㄥ ㄈㄥ)

Nickname：netkiller | English name: Neo chen | Nippon name: ちんけいほう (音訳) | Korean name: 천징봉 | Thailand name: ภูมิภาพภูเขา

Callsign: BG7NYT | QTH: ZONE CQ24 ITU44 ShenZhen, China

程序猿，攻城狮，挨踢民工， UNIX like Evangelist, 业余无线电爱好者（呼号：BG7NYT）,户外运动，山地骑行以及摄影爱好者。

《Netkiller 系列 手札》的作者

1981年1月19日(庚申年腊月十四)出生于黑龙江省青冈县建设乡双富大队第一小队

1989年9岁随父母迁居至黑龙江省伊春市

1996年第一次接触UNIX操作系统，BSD UNIX, Microsoft Xinux(盖茨亲自写的微软Unix，知道的人不多)

1997年第自学BASIC语言，Turbo C语言，苦于没有电脑，后来学校建了微机室才第一次使用QBASIC(DOS 6.22 自带命令)，那个年代只能通过软盘拷贝转播Trubo C编译器始终没有搞到，

1997年第一次上Internet网速只有9600Bps, 当时全国兴起各种信息港域名格式是www.xxxx.info.net, 访问的第一个网站是NASA下载了很多火星探路者拍回的照片，还有“淞沪”sohu的前身

1998~2000年在哈尔宾学习计算机，充足的上机时间，但老师让我们练打字（明伦五笔/WT）打字不超过80个/每分钟还要强化训练，不过这个给我的键盘功夫打了好底。

1999年学校的电脑终于安装了光驱，在一张工具盘上终于找到了Turbo C与Quick Basic编译器，当时对VGA图形编程非常感兴趣，通过INT33中断控制鼠标，使用绘图函数模仿windows界面。还有操作 UCDOS 中文字库，绘制矢量与点阵字体。

2000年沉迷于Windows NT与Back Office各种技术，神马主域控制器，DHCP，WINS，IIS，域名服务器，Exchange邮件服务器，MS Proxy, NetMeeting...以及ASP+MS SQL开发

职业生涯

2001年来深圳进城打工,成为一名外来务工者. 在一个4人公司做PHP开发，当时PHP的版本是2。0, 开始使用Linux Redhat 6.2.当时很多门户网站都是用FreeBSD,但很难搞到安装盘，在网易社区认识了一个网友,从广州给我寄了一张光盘，FreeBSD 3.2

2002年我发现不能埋头苦干,还要学会"做人".同住辗转广州工作了半年。

2003年这年最惨,公司拖欠工资16000元,打过两次官司2005才付清.

2004年开始加入分布式计算团队,目前成绩

2004-10月开始玩户外和摄影

2005-6月成为中国无线电运动协会会员,呼号BG7NYT,进了一部Yaesu FT-60R手台。

2006年单身生活了这么多年,终于找到归宿.

2007物价上涨,金融危机，休息了4个月（其实是找不到工作）,关外很难上439.460中继，搞了一台Yaesu FT-7800.

2008终于找到英文学习方法，， 《Netkiller Developer 手札》，《Netkiller Document 手札》

2008-8-8 08:08:08 结婚,后全家迁居湖南省常德市

2009《Netkiller Database 手札》,年底拿到C1驾照

2010对电子打击乐产生兴趣，计划学习爵士鼓

2011 平凡的一年，户外运动停止，电台很少开，中继很少上，摄影主要是拍女儿与家人，年末买了一辆山地车

2012 对油笔画产生了兴趣，活动基本是骑行银湖山绿道，

2013开始学习民谣吉他，同时对电吉他也极有兴趣；最终都放弃了。这一年深圳开始推数字中继2013-7-6日入手Motorola MOTOTRBO XIR P8668

职业生涯路上继续打怪升级

联系作者

http://netkiller.github.io/

http://netkiller.sourceforge.net/

Mobile: +86 13113668890

Tel: +86 755 2981-2080

Callsign: BG7NYT QTH: Shenzhen, China

注：请不要问我安装问题！

Email: netkiller@msn.com

MSN: netkiller@msn.com

ICQ: 101888222

QQ: 13721218

Yahoo/AIM/GTalk: bg7nyt

IRC: irc://irc.freenode.net /nickname netkiller or neo

CQ CQ CQ DE BG7NYT

写给火腿:

欢迎无线电爱好者和我QSO,我的QTH在深圳宝安区龙华镇溪山美地12B7CD,设备YAESU FT-50R,FT-60R,FT-7800 144-430双段机, ,拉杆天线/GP天线 Nagoya MAG-79EL-3W/Yagi

如果这篇文章对你有所帮助,请寄给我一张QSL卡片,qrz.cn or qrz.com or hamcall.net

Personal Amateur Radiostations of P.R.China

ZONE CQ24 ITU44 ShenZhen, China

Best Regards, VY 73! OP. BG7NYT

Blogger

Twitter: http://twitter.com/bg7nyt

Digg: http://www.digg.com/netkiller

Facebook: https://www.facebook.com/bg7nyt

LinkedIn: http://cn.linkedin.com/in/netkiller

Flickr: http://www.flickr.com/photos/bg7nyt/

Disqus: http://disqus.com/netkiller/

solidot: http://solidot.org/~netkiller/

ITEYE: http://netkiller-github-com.iteye.com

51CTO: http://bg7nyt.blog.51cto.com/|http://g.51cto.com/netkiller

pengyou: http://www.pengyou.com/netkiller

weibo: http://weibo.com/bg7nyt

163 Blog: http://t.163.com/netkiller

Mailing List

http://groups.google.com/group/netkiller

Send email to this group: netkiller@googlegroups.com

RSS http://groups.google.com/group/netkiller/feed/rss_v2_0_topics.xml?num=50


3. 写给读者

写给读者

欢迎提出宝贵的建议,如有问题请到 邮件列表 讨论

至读者：
我不知道什么时候，我不再更新文档或者退出IT行业去从事其他工作，我必须给这些文档找一个归宿，让他能持续更新下去。
我想捐赠给某些基金会继续运转，或者建立一个团队维护它。
我用了10年时间坚持不停地写作，持续更新，才有今天你看到的《Netkiller 手扎》系列文档，在中国能坚持10年，同时没有任何收益的技术类文档，是非常不容易的。
有很多时候想放弃，看到外国读者的支持与国内社区的影响，我坚持了下来。
中国开源事业需要各位参与，不要成为局外人，不要让外国人说：中国对开源索取无度，贡献却微乎其微。
我们参与内核的开发还比较遥远，但是进个人能力，写一些文档还是可能的。


第 1 章 install and configure

目录

1.1. php.ini
1.1.1. Time Zone
1.1.2. open_basedir
1.1.3. disable_functions
1.1.4. disable_classes
1.1.5. 隐藏php本版信息
$ sudo apt-get install php5
$ sudo apt-get install php5 php5-cli

fastcgi

sudo apt-get install php5
sudo apt-get install php5-cli
sudo apt-get install php5-fpm

1.1. php.ini

1.1.1. Time Zone

date.timezone = "Asia/Chongqing"

date.timezone = "Asia/Shanghai"

大陆内地可用的值是：Asia/Chongqing ，Asia/Shanghai ，Asia/Urumqi （依次为重庆，上海，乌鲁木齐）
港台地区可用：Asia/Macao ，Asia/Hong_Kong ，Asia/Taipei （依次为澳门，香港，台北）
还有新加坡：Asia/Singapore
其他可用的值是：Etc/GMT-8 ，Singapore ，Hongkong ，PRC (中华人民共和国)

php 代码中加入：

date_default_timezone_set ("Asia/Chongqing");

1.1.2. open_basedir

open_basedir = "/var/www/foo.bar/:/usr/local/php/:/tmp/"

1.1.3. disable_functions

disable_functions = phpinfo,

文件目录

chdir,chroot,dir,getcwd,opendir,readdir,scandir,mkdir,rmdir,unlink,delete,copy,rename

fopen,file,file_get_contents,fputs,fwrite,

权限

chgrp,chmod,chown

Shell 安全

exec, system, shell_exec, escapeshellcmd, escapeshellarg, proc_get_status, proc_open

php.ini 安全

ini_set, ini_alter, max_execution_time

1.1.4. disable_classes

disable_classes=

1.1.5. 隐藏php本版信息

expose_php On
改成
expose_php Off


第 2 章 Language Reference

目录

2.1. php://stdin & php://stdout
2.2. Exception

2.1. php://stdin & php://stdout

$ cat test.php
#!/usr/bin/php
<?php

$handle = fopen("php://stdin", "r");

while (!feof($handle)) {
    $buffer = fgets($handle);
    print($buffer);
}
fclose($handle);

$ cat /etc/passwd | ./test.php


2.2. Exception

$ cat exception1.php
<?php

function test1(){
    throw new Exception("Test1 exception!");
}

try {
    test1();
}
catch(Exception $e){
    die( $e->__toString() );
}

$ php exception1.php
exception 'Exception' with message 'Test1 exception!' in /home/neo/workspace/example/PHP/exception.php:4
Stack trace:
#0 /home/neo/workspace/example/PHP/exception.php(8): test1()
#1 {main}

$ cat exception2.php
<?php

class MyException extends Exception {}
function test2(){
    throw new MyException('Test2 exception');
}
try {
    test2();
}
catch(Exception $e){
    die( $e->__toString() );
}

$ php exception2.php
exception 'MyException' with message 'Test2 exception' in /home/neo/workspace/example/PHP/exception2.php:5
Stack trace:
#0 /home/neo/workspace/example/PHP/exception2.php(8): test2()
#1 {main}

$ cat exception.php
<?php
class FileException extends Exception {}
class DataException extends Exception {}

function test1(){
    throw new FileException("Test1 exception!");
}

function test2(){
    throw new DataException('Test2 exception');
}
function test3(){
    throw new Exception('Test3 exception');
}

try {
    test1();
    test2();
    test3();
}
catch(FileException $e){
    print( $e->__toString() );
}
catch(DataException $e){
    print( $e->__toString() );
}
catch(Exception $e){
    print( $e->__toString() );
}


第 3 章 String 字符串操作

目录

3.1. 英文大小写
3.2. str_replace

3.1. 英文大小写

1.将字符串转换成小写

strtolower(): 该函数将传入的字符串参数所有的字符都转换成小写,并以小定形式放回这个字符串

2.将字符转成大写

strtoupper(): 该函数的作用同strtolower函数相反,是将传入的字符参数的字符全部转换成大写,并以大写的形式返回这个字符串.用法同strtolowe()一 样.

3.将字符串首字符转换成大写

ucfirst(): 该函数的作用是将字符串的第一个字符改成大写,该函数返回首字符大写的字符串.用法同strtolowe()一样.

4.将字符串每个单词的首字符转换成大写

ucwords(): 该函数将传入的字符串的每个单词的首字符变成大写.如"hello world",经过该函数处理后,将返回"Hello Word".用法同strtolowe()一样.


3.2. str_replace

$search  = array('one', 'two', 'three');
$replace = array('1',  '2', '3']);
$content =  str_replace($search, $replace, $file_tpl);


第 4 章 Array 数组

目录

4.1. 删除数组元素
4.2. 数组与字符串操作

数据相关函数

4.1. 删除数组元素

$a[]="a1";
$a[]="a2";
$a[]="a3";
print_r($a);
unset($a[1]);
print_r($a);


4.2. 数组与字符串操作

implode(separator,array)

<?php
$arr = array('Hello','World!');
echo implode(" ",$arr);
?>

explode(separator,string,limit)

<?php
$str = "Hello world!";
print_r (explode(" ",$str));
?>


第 5 章 Function

目录

5.1. 列出所有function
5.2. php.ini
5.2.1. ini_set
5.2.2. ini_get
5.3. PHP Option
5.4. 操作系统类型
5.5. 日期比较
5.6. rand()
5.7. header

5.1. 列出所有function

<?php

$extensions = get_loaded_extensions();
foreach($extensions as $each_ext)
{
    echo "\t<keyword>$each_ext, ";
    $ext_funcs = get_extension_funcs($each_ext);
    foreach($ext_funcs as $func)
    {
       echo "$func, ";
    }
    echo "</keyword>\r\n";
}
?>


5.2. php.ini

5.2.1. ini_set

@ini_set('memory_limit',          '16M');

5.2.2. ini_get

<?php
  echo ini_get('short_open_tag');
?>


5.3. PHP Option

include_path

<?php
$path = '/usr/lib/pear';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
?>


5.4. 操作系统类型

php_uname();
PHP_OS
DIRECTORY_SEPARATOR
PHP_SHLIB_SUFFIX
PATH_SEPARATOR

for example：
if(PATH_SEPARATOR==':'){
    echo 'Linux';
}else{
    else echo 'Windows';
}


5.5. 日期比较

if(strftime('%Y-%m-%d',strtotime('2009-04-19')) <= date('Y-m-d')){
    to-do ...
}


5.6. rand()

if(rand(0,99)>50){

}else{

}

生成随机IP地址

<?php
$min=1;
$min=254;
$ipaddr = rand($min,$max).'.'.rand($min,$max).'.'.rand($min,$max).'.'.rand($min,$max);
//$ipaddr = '111.'.rand($min,$max).'.'.rand($min,$max).'.'.rand($min,$max);
echo $ipaddr;


5.7. header

// See related links for more status codes

// Use this header instruction to fix 404 headers
// produced by url rewriting...
header('HTTP/1.1 200 OK');

// Page was not found:
header('HTTP/1.1 404 Not Found');

// Access forbidden:
header('HTTP/1.1 403 Forbidden');

// The page moved permanently should be used for
// all redrictions, because search engines know
// what's going on and can easily update their urls.
header('HTTP/1.1 301 Moved Permanently');

// Server error
header('HTTP/1.1 500 Internal Server Error');

// Redirect to a new location:
header('Location: http://www.example.org/');

// Redriect with a delay:
header('Refresh: 10; url=http://www.example.org/');
print 'You will be redirected in 10 seconds';

// you can also use the HTML syntax:
// <meta http-equiv="refresh" content="10;http://www.example.org/ />

// override X-Powered-By value
header('X-Powered-By: PHP/4.4.0');
header('X-Powered-By: Brain/0.6b');

// content language (en = English)
header('Content-language: en');

// last modified (good for caching)
$time = time() - 60; // or filemtime($fn), etc
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $time).' GMT');

// header for telling the browser that the content
// did not get changed
header('HTTP/1.1 304 Not Modified');

// set content length (good for caching):
header('Content-Length: 1234');

// Headers for an download:
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="example.zip"');
header('Content-Transfer-Encoding: binary');
// load the file to send:
readfile('example.zip');

// Disable caching of the current document:
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Pragma: no-cache');

// set content type:
header('Content-Type: text/html; charset=iso-8859-1');
header('Content-Type: text/html; charset=utf-8');
header('Content-Type: text/plain'); // plain text file
header('Content-Type: image/jpeg'); // JPG picture
header('Content-Type: application/zip'); // ZIP file
header('Content-Type: application/pdf'); // PDF file
header('Content-Type: audio/mpeg'); // Audio MPEG (MP3,...) file
header('Content-Type: application/x-shockwave-flash'); // Flash animation

// show sign in box
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Top Secret"');
print 'Text that will be displayed if the user hits cancel or ';
print 'enters wrong login data';


第 6 章 PHP Classes 类与对象

目录

6.1. 构造函数和析构函数 __construct() / __destruct()
6.2. Traits

6.1. 构造函数和析构函数 __construct() / __destruct()

<?php
class MyClass {
   function __construct() {
       print "In constructor\n";
       $this->name = "MyClass";
   }

   function __destruct() {
       print "Destroying " . $this->name . "\n";
   }
}

$obj = new MyClass();
?>


6.2. Traits

http://php.net/manual/en/language.oop5.traits.php

<?php
class Base {
    public function sayHello() {
        echo 'Hello ';
    }
}

trait SayWorld {
    public function sayHello() {
        parent::sayHello();
        echo 'World!';
    }
}

class MyHelloWorld extends Base {
    use SayWorld;
}

$o = new MyHelloWorld();
$o->sayHello();
?>

<?php
trait HelloWorld {
    public function sayHello() {
        echo 'Hello World!';
    }
}

class TheWorldIsNotEnough {
    use HelloWorld;
    public function sayHello() {
        echo 'Hello Universe!';
    }
}

$o = new TheWorldIsNotEnough();
$o->sayHello();
?>

Multiple Traits

<?php
trait Hello {
    public function sayHello() {
        echo 'Hello ';
    }
}

trait World {
    public function sayWorld() {
        echo 'World';
    }
}

class MyHelloWorld {
    use Hello, World;
    public function sayExclamationMark() {
        echo '!';
    }
}

$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
$o->sayExclamationMark();
?>

Conflict Resolution

<?php
trait A {
    public function smallTalk() {
        echo 'a';
    }
    public function bigTalk() {
        echo 'A';
    }
}

trait B {
    public function smallTalk() {
        echo 'b';
    }
    public function bigTalk() {
        echo 'B';
    }
}

class Talker {
    use A, B {
        B::smallTalk insteadof A;
        A::bigTalk insteadof B;
    }
}

class Aliased_Talker {
    use A, B {
        B::smallTalk insteadof A;
        A::bigTalk insteadof B;
        B::bigTalk as talk;
    }
}
?>

Changing Method Visibility

<?php
trait HelloWorld {
    public function sayHello() {
        echo 'Hello World!';
    }
}

// Change visibility of sayHello
class MyClass1 {
    use HelloWorld { sayHello as protected; }
}

// Alias method with changed visibility
// sayHello visibility not changed
class MyClass2 {
    use HelloWorld { sayHello as private myPrivateHello; }
}
?>

Traits Composed from Traits

<?php
trait Hello {
    public function sayHello() {
        echo 'Hello ';
    }
}

trait World {
    public function sayWorld() {
        echo 'World!';
    }
}

trait HelloWorld {
    use Hello, World;
}

class MyHelloWorld {
    use HelloWorld;
}

$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
?>


第 7 章 PECL :: The PHP Extension Community Library

目录

7.1. php-apc - APC (Alternative PHP Cache) module for PHP 5
7.1.1. 编译安装 APC Cache
7.2. PHP Memcache
7.2.1. pecl
7.2.2. apt-get
7.2.3. example
7.3. php5-gd - GD module for php5
7.4. Database Extensions
7.4.1. sqlite
7.4.2. mysqli
7.4.3. MongoDB
7.4.4. php-redis.x86_64 : Extension for communicating with the Redis key-value store
7.4.4.1. pecl 安装
7.4.4.2. yum安装
7.4.4.3. 源码编译安装
7.4.4.4. 配置 redis.ini
7.4.4.5. Session 配置
7.4.5. php5-pgsql - PostgreSQL module for php5
7.4.6. PHP connect SQL Server under unix like
7.4.7. MySQL
7.4.8. oracle
7.5. xmlrpc
7.6. openssl
7.7. mcrypt
7.8. mhash
7.9. simplexml
7.10. ionCube
7.11. ZendOptimizer
7.12. zip
7.13. pcntl
7.14. mbstring
7.15. Suhosin
7.16. freetype
7.17. XCache
7.17.1. apt-get
7.17.2. make
7.18. XHProf
7.19. Xdebug
7.19.1. Webgrind
7.19.2. WinCacheGrind
7.20. UploadProgress
7.21. msgpack
7.22. iconv
7.23. imagick
7.24. sysvmsg

7.1. php-apc - APC (Alternative PHP Cache) module for PHP 5

$ apt-cache search php-apc
php-apc - APC (Alternative PHP Cache) module for PHP 5

$ sudo apt-get install php-apc

echo "apc.enabled = 1
apc.shm_size = 128
apc.shm_segments=1
apc.write_lock = 1
apc.rfc1867 = On
apc.ttl=7200
apc.user_ttl=7200
apc.num_files_hint=1024
apc.mmap_file_mask=/tmp/apc.XXXXXX
apc.enable_cli=1
apc.slam_defense = Off
" >> /etc/php5/conf.d/apc.ini

# php -r 'phpinfo();' | grep apc
PHP Warning:  phpinfo(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone. in Command line code on line 1
Additional .ini files parsed => /srv/php-5.4.15/etc/conf.d/apc.ini
apc
apc.cache_by_default => On => On
apc.canonicalize => On => On
apc.coredump_unmap => Off => Off
apc.enable_cli => Off => Off
apc.enabled => On => On
apc.file_md5 => Off => Off
apc.file_update_protection => 2 => 2
apc.filters => no value => no value
apc.gc_ttl => 3600 => 3600
apc.include_once_override => Off => Off
apc.lazy_classes => Off => Off
apc.lazy_functions => Off => Off
apc.max_file_size => 1M => 1M
apc.mmap_file_mask => no value => no value
apc.num_files_hint => 1000 => 1000
apc.preload_path => no value => no value
apc.report_autofilter => Off => Off
apc.rfc1867 => Off => Off
apc.rfc1867_freq => 0 => 0
apc.rfc1867_name => APC_UPLOAD_PROGRESS => APC_UPLOAD_PROGRESS
apc.rfc1867_prefix => upload_ => upload_
apc.rfc1867_ttl => 3600 => 3600
apc.serializer => default => default
apc.shm_segments => 1 => 1
apc.shm_size => 32M => 32M
apc.shm_strings_buffer => 4M => 4M
apc.slam_defense => On => On
apc.stat => On => On
apc.stat_ctime => Off => Off
apc.ttl => 0 => 0
apc.use_request_time => On => On
apc.user_entries_hint => 4096 => 4096
apc.user_ttl => 0 => 0
apc.write_lock => On => On

7.1.1. 编译安装 APC Cache

例 7.1. php apc cache

pecl install

/usr/local/php/bin/pecl install apc

php.ini

extension_dir = "/usr/local/php-5.3.3/lib/php/extensions/"
extension = apc.so


7.2. PHP Memcache

参考PHP安装

7.2.1. pecl

进入PHP工作目录

cd /usr/local/php/

安装 memcache

pecl install

bin/pecl install memcache

php.ini

vi etc/php.ini

extension_dir = "/usr/local/php-5.3.3/lib/php/extensions/"
extension = memcache.so

php.ini memcache 参数

cat >> /usr/local/php/etc/php.ini <<EOF
[memcache]
memcache.allow_failover = 1
memcache.max_failover_attempts=20
memcache.chunk_size =8192
memcache.default_port = 11211
memcache.default_timeout_ms=30
EOF

7.2.2. apt-get

$ sudo apt-get install php5-memcache

memcache.ini 文件

$ cat /etc/php5/conf.d/memcache.ini
; uncomment the next line to enable the module
extension=memcache.so

[memcache]
memcache.dbpath="/var/lib/memcache"
memcache.maxreclevel=0
memcache.maxfiles=0
memcache.archivememlim=0
memcache.maxfilesize=0
memcache.maxratio=0

7.2.3. example

例 7.2. memcache.php

<?php
    $memcache = new Memcache;
    $memcache->connect('localhost', 11211) or die ("Could not connect");

    $memcache->set('var_key', 'some really big variable', MEMCACHE_COMPRESSED, 50);
    echo $memcache->get('var_key');
?>

运行测试脚本

php -q memcache.php


7.3. php5-gd - GD module for php5

$ apt-cache search php|grep gd
php5-gd - GD module for php5
$ sudo apt-get install php5-gd

$ apt-cache search php|grep zip
libphp-pclzip - zip archive manager class for PHP
$ sudo apt-get install libphp-pclzip

$ sudo apt-get install libapache2-modxslt php-xml-htmlsax3 php-xml-parser php-xml-rss php-xml-serializer php-xml-util


7.4. Database Extensions

7.4.1. sqlite

mkdir /srv/php-5.2.17/etc/conf.d
/srv/php-5.2.17/bin/phpize
./configure --with-php-config=/srv/php-5.2.17/bin/php-config
make && make install

cat > /srv/php-5.2.17/etc/conf.d/sqlite.ini <<EOF
extension=sqlite.so
extension=pdo_sqlite.so
EOF

7.4.2. mysqli

mkdir /srv/php-5.2.17/etc/conf.d
/srv/php-5.2.17/bin/phpize
./configure --with-php-config=/srv/php-5.2.17/bin/php-config
make && make install

cat > /srv/php-5.2.17/etc/conf.d/mysqli.ini <<EOF
extension=mysqli.so
EOF

7.4.3. MongoDB

sudo pecl install mongo

vim /srv/php/etc/conf.d/mongo.ini
extension=mongo.so

7.4.4. php-redis.x86_64 : Extension for communicating with the Redis key-value store

7.4.4.1. pecl 安装

pecl install redis

7.4.4.2. yum安装

https://github.com/nicolasff/phpredis

yum search redis

php-redis.x86_64 : Extension for communicating with the Redis key-value store
python-redis.noarch : A Python client for redis
redis.x86_64 : A persistent key-value database

7.4.4.3. 源码编译安装

安装git版本控制客户端

yum install git

从github仓库中克隆一份代码到本地

git clone git://github.com/nicolasff/phpredis.git

编译安装phpredis； 我暂时没有找到 pecl的phpredis源

cd phpredis
phpize
./configure --with-php-config=/srv/php-5.4.9/bin/php-config
make && make install

创建配置文件

7.4.4.4. 配置 redis.ini

cat > /srv/php-5.4.9/etc/conf.d/redis.ini <<EOF
extension=redis.so
EOF

查看安装情况

# php -m | grep redis
redis

7.4.4.5. Session 配置

使用 Redis 存储 Session 数据

session.save_handler = redis
session.save_path = "tcp://127.0.0.1:6379"
或者使用多个redis
session.save_path = "tcp://host1:6379?weight=1, tcp://host2:6379?weight=2&timeout=2.5, tcp://host3:6379?weight=2"

7.4.5. php5-pgsql - PostgreSQL module for php5

$ sudo apt-get install php5-pgsql

7.4.6. PHP connect SQL Server under unix like

Sql Server 支持由Freetds提供

主页：http://www.freetds.org/

cd /usr/local/src/
wget ftp://ftp.ibiblio.org/pub/Linux/ALPHA/freetds/stable/freetds-stable.tgz
tar zxvf freetds-stable.tgz
cd freetds-0.64/

./configure --prefix=/usr/local/freetds-0.64
make
make install

ln -s /usr/local/freetds-0.64 /usr/local/freetds

configure

./configure --prefix=/usr/local/php-5.2.3 \
--with-config-file-path=/usr/local/php-5.2.3/etc \
--enable-fastcgi \
--enable-force-cgi-redirect \
--with-curl \
--with-gd \
--with-ldap \
--enable-zip \
--enable-exif \
--enable-pcntl \
--with-mssql=/usr/local/freetds

make
make test
make install

MSSQL在PHP中的配置如下

/usr/local/freetds/etc/freetds.conf

[MyServer2k]
       host = 10.10.10.11
       port = 3433
       tds version = 8.0

mssql.php 测试文件

<?php
$conn = mssql_pconnect('MyServer2k', 'u_mobile', 'kEyt+_Zf.$P6');
mssql_select_db('D3_Mobile', $conn);
$query = mssql_query ('select * from dbo.MobileCommand where id=1');
$result = mssql_fetch_array ($query);
echo '<pre>';
print_r($result);
echo '</pre>';
?>

mssql_pconnect

resource mssql_connect ( [string servername [, string username [, string password [, bool new_link]]]] )

servername 指的是freetds.conf中定义服务器名

测试

php -q mssql.php

7.4.7. MySQL

$ sudo apt-get install php5-mysql

7.4.8. oracle

pdo_oci/oci8

http://www.oracle.com/technetwork/topics/linuxx86-64soft-092277.html

export ORACLE_HOME=/usr/lib/oracle/11.1/client64/
export LD_LIBRARY_PATH=/usr/lib/oracle/11.1/client64:$LD_LIBRARY_PATH
export  NLS_LANG="AMERICAN_AMERICA.AL32UTF8"

cd /usr/local/src/php-5.2.14/ext/pdo_oci
/usr/local/php-5.2.14/bin/phpize
./configure --with-php-config=/usr/local/php-5.2.14/bin/php-config --with-oci8=instantclient,/usr/lib/oracle/11.1/client64/lib
    make
    make install

   安装后生成/usr/local/php/lib/php/extensions/no-debug-non-zts-yyyymmdd/oci8.so
   把oci8.so 移动到/usr/local/php/lib/php/extensions/目录下
    mv /usr/local/php/lib/php/extensions/no-debug-non-zts-yyyymmdd/oci8.so ../

    extension_dir = /usr/local/php/lib/php/extensions/

   添加
     extension = pdo_oci.so
     extension = oci8.so

例 7.3. oracle

ln -s /usr/lib/oracle/10.2.0.3/client64 /usr/lib/oracle/10.2.0.3/client
ln -s /usr/include/oracle/10.2.0.3/client64    /usr/include/oracle/10.2.0.3/client

export ORACLE_HOME=/usr/lib/oracle/10.2.0.3/client64/
export LD_LIBRARY_PATH=/usr/lib/oracle/10.2.0.3/client64:$LD_LIBRARY_PATH
export  NLS_LANG="AMERICAN_AMERICA.AL32UTF8"
# /usr/local/php-5.2.14/bin/phpize
# ./configure --with-php-config=/usr/local/php-5.2.14/bin/php-config  --with-pdo-oci=instantclient,/usr,10.2.0.3
# make && make install

php.ini

extension=pdo_oci.so

oci.php

    <?php
    $pdo= new PDO("oci:dbname=//localhost:1521/mydbname;charset=utf-8,username,password);

    $sql="select table_name as tname from user_tables";
    $query = $pdo->prepare($sql);
    $query->execute();

    for($i=0; $row = $query->fetch(); $i++){
      #print_r($row);
      echo $i." - ".$row[0]."<br/>";
      echo $i." - ".$row['TNAME']."<br/>";
    }
    ?>


7.5. xmlrpc

单独编译php扩展模块

[root@websrv]# cd /usr/local/php-5.3.0/ext/xmlrpc
[root@websrv]# /usr/local/php-5.3.0/bin/phpize
[root@websrv]# ./configure --with-php-config=/usr/local/php-5.3.0/bin/php-config
[root@websrv]# make
[root@websrv]# make test
[root@websrv]# make install
Installing shared extensions: /usr/local/php-5.3.0/lib/php/extensions/no-debug-zts-20060613/
[root@websrv]# mv /usr/local/php-5.3.0/lib/php/extensions/no-debug-zts-20060613/* /usr/local/php-5.3.0/lib/php/extensions/

修改配置在php.ini里，配置扩展目录 并添加扩展模块引用：

extension_dir = "/usr/local/php-5.3.0/lib/php/extensions/"
extension = xmlrpc.so


7.6. openssl

例 7.4. php openssl

source install

# yum install openssl-devel
# cd /usr/local/src/php-5.2.17/ext/openssl
# cp config0.m4 config.m4
# /srv/php-5.2.17/bin/phpize

Configuring for:
PHP Api Version:         20041225
Zend Module Api No:      20060613
Zend Extension Api No:   220060519

# ./configure --with-php-config=/srv/php-5.2.17/bin/php-config
# make && make test && make install

Thank you for helping to make PHP better.
Installing shared extensions: /srv/php-5.2.17/lib/php/extensions/no-debug-non-zts-20060613/

php.ini

cat > /srv/php-5.2.17/etc/conf.d/openssl.ini <<EOF
extension=openssl.so
EOF


7.7. mcrypt

例 7.5. mcrypt

# yum install libmcrypt libmcrypt-devel

# cd /usr/local/src/php-5.2.17/ext/mcrypt
# /usr/local/php-5.2.17/bin/phpize
# ./configure --with-php-config=/usr/local/php-5.2.17/bin/php-config
# make
# make test
# make install

# cp /usr/local/php-5.2.17/lib/php/extensions/no-debug-zts-20060613/mcrypt.so /usr/local/php-5.2.17/lib/php/extensions/

# vim /usr/local/php-5.2.17/etc/php.ini
extension_dir = "/usr/local/php-5.2.17/lib/php/extensions/"
extension=mcrypt.so

cat > /srv/php-5.2.17/etc/conf.d/mcrypt.ini <<EOF
extension=mcrypt.so
EOF


7.8. mhash

cat > /srv/php-5.2.17/etc/conf.d/mhash.ini <<EOF
extension=mhash.so
EOF


7.9. simplexml

例 7.6. simplexml

# cd /usr/local/src/php-5.2.17/ext/simplexml
# /usr/local/php-5.2.17/bin/phpize
# ./configure --with-php-config=/usr/local/php-5.2.17/bin/php-config
# make
# make test
# make install
# cp /usr/local/php-5.2.17/lib/php/extensions/no-debug-zts-20060613/simplexml.so /usr/local/php-5.2.17/lib/php/extensions/
extension_dir = "/usr/local/php-5.2.17/lib/php/extensions/"
extension=simplexml.so


7.10. ionCube

http://www.ioncube.com/

# cd /usr/local/src/
# wget http://downloads2.ioncube.com/loader_downloads/ioncube_loaders_lin_x86-64.tar.gz

# tar zxvf ioncube_loaders_lin_x86-64.tar.gz
ioncube/
ioncube/ioncube_loader_lin_4.3_ts.so
ioncube/ioncube_loader_lin_5.2_ts.so
ioncube/LICENSE.txt
ioncube/loader-wizard.php
ioncube/ioncube_loader_lin_4.4_ts.so
ioncube/ioncube_loader_lin_5.1_ts.so
ioncube/ioncube_loader_lin_5.0.so
ioncube/ioncube_loader_lin_5.1.so
ioncube/ioncube_loader_lin_5.3_ts.so
ioncube/ioncube_loader_lin_5.2.so
ioncube/ioncube_loader_lin_4.2.so
ioncube/README.txt
ioncube/ioncube_loader_lin_5.0_ts.so
ioncube/ioncube_loader_lin_4.3.so
ioncube/ioncube_loader_lin_4.4.so
ioncube/ioncube_loader_lin_4.1.so
ioncube/ioncube_loader_lin_5.3.so

# mv ioncube ..

php.ini

[Zend]
zend_extension_ts = /usr/local/ioncube/ioncube_loader_lin_5.2_ts.so

test

# /usr/local/php-5.2.14/bin/php -m
[PHP Modules]
ctype
curl
date
dom
filter
ftp
gd
hash
iconv
ionCube Loader
json
libxml
mbstring
memcache
mysql
mysqli
openssl
pcre
PDO
pdo_mysql
pdo_sqlite
posix
Reflection
session
SimpleXML
soap
sockets
SPL
SQLite
standard
tokenizer
xml
xmlreader
xmlrpc
xmlwriter
zip
zlib

[Zend Modules]
the ionCube PHP Loader


7.11. ZendOptimizer

# cd /usr/local/src
# tar zxvf ZendOptimizer-3.3.9-linux-glibc23-x86_64.tar.gz
ZendOptimizer-3.3.9-linux-glibc23-x86_64/
ZendOptimizer-3.3.9-linux-glibc23-x86_64/md5
ZendOptimizer-3.3.9-linux-glibc23-x86_64/Inventory.xml
ZendOptimizer-3.3.9-linux-glibc23-x86_64/EULA-ZendOptimizer
ZendOptimizer-3.3.9-linux-glibc23-x86_64/README-ZendOptimizer
ZendOptimizer-3.3.9-linux-glibc23-x86_64/LICENSE
ZendOptimizer-3.3.9-linux-glibc23-x86_64/data/
ZendOptimizer-3.3.9-linux-glibc23-x86_64/data/4_3_x_comp/
ZendOptimizer-3.3.9-linux-glibc23-x86_64/data/4_3_x_comp/ZendOptimizer.so
ZendOptimizer-3.3.9-linux-glibc23-x86_64/data/5_1_x_comp/
ZendOptimizer-3.3.9-linux-glibc23-x86_64/data/5_1_x_comp/ZendOptimizer.so
ZendOptimizer-3.3.9-linux-glibc23-x86_64/data/4_2_x_comp/
ZendOptimizer-3.3.9-linux-glibc23-x86_64/data/4_2_x_comp/ZendOptimizer.so
ZendOptimizer-3.3.9-linux-glibc23-x86_64/data/5_0_x_comp/
ZendOptimizer-3.3.9-linux-glibc23-x86_64/data/5_0_x_comp/ZendOptimizer.so
ZendOptimizer-3.3.9-linux-glibc23-x86_64/data/4_4_x_comp/
ZendOptimizer-3.3.9-linux-glibc23-x86_64/data/4_4_x_comp/ZendOptimizer.so
ZendOptimizer-3.3.9-linux-glibc23-x86_64/data/poweredbyoptimizer.gif
ZendOptimizer-3.3.9-linux-glibc23-x86_64/data/4_2_0_comp/
ZendOptimizer-3.3.9-linux-glibc23-x86_64/data/4_2_0_comp/ZendOptimizer.so
ZendOptimizer-3.3.9-linux-glibc23-x86_64/data/5_2_x_comp/
ZendOptimizer-3.3.9-linux-glibc23-x86_64/data/5_2_x_comp/ZendOptimizer.so

# mv ZendOptimizer-3.3.9-linux-glibc23-x86_64 ..
# cd ..
# ln -s ZendOptimizer-3.3.9-linux-glibc23-x86_64 ZendOptimizer

php.ini

zend_optimizer.optimization_level=15
zend_extension="/usr/local/ZendOptimizer/data/5_2_x_comp/ZendOptimizer.so"

tar zxf ZendOptimizer-3.3.9-linux-glibc23-x86_64.tar.gz
mv ZendOptimizer-3.3.9-linux-glibc23-x86_64 ..

ln -s /usr/local/ZendOptimizer-3.3.9-linux-glibc23-x86_64 /usr/local/ZendOptimizer

cat >> /usr/local/php/etc/php.ini <<EOF
[Zend]
zend_optimizer.optimization_level=15
zend_extension="/usr/local/ZendOptimizer/data/5_2_x_comp/ZendOptimizer.so"
EOF


7.12. zip

cd /usr/src/php-5.2.14/ext/zip/

/usr/local/php-5.2.14/bin/phpize
./configure --with-php-config=/usr/local/php-5.2.14/bin/php-config
make
make install
mv /usr/local/php-5.2.14/lib/php/extensions/no-debug-non-zts-20060613/zip.so /usr/local/php-5.2.14/lib/php/extensions/

vim /usr/local/php-5.2.14/etc/php.ini
extension_dir = "/usr/local/php-5.2.14/lib/php/extensions/"
extension=zip.so

/usr/local/php-5.2.14/bin/php -m | grep zip


7.13. pcntl

编译的时候没有带--enable-pcntl参数的补救办法

cd php-5.2.17/ext/pcntl

/srv/php-5.2.17/bin/phpsize
./configure --with-php-config=/srv/php-5.2.17/bin/php-config
make && make install

加入到php.ini

cat > /srv/php-5.2.17/etc/conf.d/pcntl.ini <<EOF
extension=pcntl.so
EOF

php -m | grep pcntl


7.14. mbstring

cd /usr/local/src/php-5.2.17/ext/mbstring

phpsize
./configure --with-php-config=/srv/php-5.2.17/bin/php-config
make && make install

extension=mbstring.so

# vi php.ini

把输出处理程序设为mbstring对应。
;output_handler =
output_handler = "mb_output_handler"

设定文字集为UTF-8。
;default_charset = "iso-8859-1"
default_charset = "UTF-8"

设置mbstring的语言为Chinese
;mbstring.language = Japanese
mbstring.language = Chinese

设置mbstring的内部编码为UTF-8。
;mbstring.internal_encoding = EUC-JP
mbstring.internal_encoding = UTF-8

设置mbstring的输入文字编码为自动判别方式。
;mbstring.http_input = auto
mbstring.http_input = auto

把mbstring输出文字编码设为UTF-8。
;mbstring.http_output = SJIS
mbstring.http_output = UTF-8

激活mbstring的文字编码自动变换方式。
;mbstring.encoding_translation = Off
mbstring.encoding_translation = On


7.15. Suhosin

Step of installation for Suhosin:
1. Download suhosin and install it
#cd /usr/local/
#wget http://www.hardened-php.net/suhosin/_media/suhosin-0.9.18.tgz
#tar -zxvf suhosin-0.9.18.tgz
#cd suhosin-0.9.18
#phpize
#./configure
#make && make install
2. Adding a load directive to php.ini
extension=suhosin.so
[suhosin]
suhosin.get.max_value_length = 5120
3. Restart apache service
#/etc/init.d/httpd restart

Configuration

Logging Configuration
suhosin.log.syslog
suhosin.log.syslog.facility
suhosin.log.syslog.priority
suhosin.log.sapi
suhosin.log.script
suhosin.log.phpscript
suhosin.log.script.name
suhosin.log.phpscript.name
suhosin.log.use-x-forwarded-for
Executor Options
suhosin.executor.max_depth
suhosin.executor.include.max_traversal
suhosin.executor.include.whitelist
suhosin.executor.include.blacklist
suhosin.executor.func.whitelist
suhosin.executor.func.blacklist
suhosin.executor.eval.whitelist
suhosin.executor.eval.blacklist
suhosin.executor.disable_eval
suhosin.executor.disable_emodifier
suhosin.executor.allow_symlink
Misc Options
suhosin.simulation
suhosin.apc_bug_workaround
suhosin.sql.bailout_on_error
suhosin.sql.user_prefix
suhosin.sql.user_postfix
suhosin.multiheader
suhosin.mail.protect
suhosin.memory_limit
Transparent Encryption Options
suhosin.session.encrypt
suhosin.session.cryptkey
suhosin.session.cryptua
suhosin.session.cryptdocroot
suhosin.session.cryptraddr
suhosin.session.checkraddr
suhosin.cookie.encrypt
suhosin.cookie.cryptkey
suhosin.cookie.cryptua
suhosin.cookie.cryptdocroot
suhosin.cookie.cryptraddr
suhosin.cookie.checkraddr
suhosin.cookie.cryptlist
suhosin.cookie.plainlist
Filtering Options
suhosin.filter.action
suhosin.cookie.max_array_depth
suhosin.cookie.max_array_index_length
suhosin.cookie.max_name_length
suhosin.cookie.max_totalname_length
suhosin.cookie.max_value_length
suhosin.cookie.max_vars
suhosin.cookie.disallow_nul
suhosin.get.max_array_depth
suhosin.get.max_array_index_length
suhosin.get.max_name_length
suhosin.get.max_totalname_length
suhosin.get.max_value_length
suhosin.get.max_vars
suhosin.get.disallow_nul
suhosin.post.max_array_depth
suhosin.post.max_array_index_length
suhosin.post.max_name_length
suhosin.post.max_totalname_length
suhosin.post.max_value_length
suhosin.post.max_vars
suhosin.post.disallow_nul
suhosin.request.max_array_depth
suhosin.request.max_array_index_length
suhosin.request.max_totalname_length
suhosin.request.max_value_length
suhosin.request.max_vars
suhosin.request.max_varname_length
suhosin.request.disallow_nul
suhosin.upload.max_uploads
suhosin.upload.disallow_elf
suhosin.upload.disallow_binary
suhosin.upload.remove_binary
suhosin.upload.verification_script
suhosin.session.max_id_length

suhosin有三个选项控制eval

suhosin.executor.eval.whitelist        白名单
suhosin.executor.eval.blacklist        黑名单
suhosin.executor.disable_eval        禁用eval
很多程序需要eval，所以我们不能禁用，使用黑名单禁止一些危险的函数
编辑php.ini
[Suhosin]
suhosin.executor.eval.blacklist=phpinfo,fputs,fopen,fwrite
根据实际情况自行设定

包含漏洞

suhosin.executor.include.max_traversal        包含的最大目录深度，在包含的文件名中有多少个../就禁止，例如值为2时，../../etc/passwd会禁止，值为3则允许，对于大多数程序，这个值设为4或5比较合适
suhosin.executor.include.whitelist        允许包含的URL，用逗号分隔
suhosin.executor.include.blacklist        禁止包含的URL，用逗号分隔

上传漏洞

suhosin.upload.max_uploads
suhosin.upload.disallow_elf
suhosin.upload.disallow_binary
suhosin.upload.remove_binary
suhosin.upload.verification_script        上传文件检查脚本
可以自己写一个脚本检查上传文件是否有webshell特征，然后suhosin.upload.verification_script 的值是这个脚本的绝对路径

其他更深入的防护措施，还有待研究，参考suhosin选项 http://www.hardened-php.net/suhosin/configuration.html


7.16. freetype


7.17. XCache

7.17.1. apt-get

sudo apt-get install php5-xcache

7.17.2. make

# wget http://xcache.lighttpd.net/pub/Releases/1.3.2/xcache-1.3.2.tar.gz
# tar zxvf xcache-1.3.2.tar.gz
# cd xcache-1.3.2
# /srv/php/bin/phpize
# ./configure --enable-xcache
# ./configure --enable-xcache --with-php-config=/srv/php/bin/php-config
# make
# make install

# mv /srv/php-5.3.5/lib/php/extensions/no-debug-non-zts-20090626/xcache.so  /srv/php-5.3.5/lib/php/extensions/
# mkdir -p /srv/php/etc/conf.d/

xcache.ini

cat > /srv/php/etc/conf.d/xcache.ini <<EOF
[xcache-common]
zend_extension=/srv/php-5.3.5/lib/php/extensions/xcache.so

[xcache.admin]
xcache.admin.user = "xcache"
xcache.admin.pass = "bed128365216c019988915ed3add75fb"

[xcache]
xcache.size  = 64M
xcache.count = 24
xcache.gc_interval = 300
xcache.var_size  = 16M
xcache.var_count = 24
xcache.var_gc_interval = 300
xcache.readonly_protection = On
xcache.coredump_directory =   ""
xcache.optimizer = On

[xcache.coverager]
xcache.coverager = On
xcache.coveragedump_directory = ""
EOF

# /srv/php/bin/php -m
[PHP Modules]
bcmath
calendar
Core
ctype
curl
date
dba
dom
ereg
exif
fileinfo
filter
ftp
gd
hash
iconv
json
libxml
mbstring
mcrypt
mhash
mysql
mysqli
openssl
pcre
PDO
pdo_mysql
Phar
posix
Reflection
session
shmop
SimpleXML
soap
sockets
SPL
sqlite3
standard
sysvmsg
sysvsem
sysvshm
tokenizer
wddx
XCache
xml
xmlreader
xmlrpc
xmlwriter
xsl
zip
zlib

[Zend Modules]
XCache


7.18. XHProf

XHProf是facebook开源出来的一个php轻量级的性能分析工具，跟Xdebug类似，但性能开销更低，还可以用在生产环境中，也可以由程序开 关来控制是否进行profile。

https://github.com/facebook/xhprof

安装依赖工具

$ sudo apt-get install graphviz

or

wget http://www.graphviz.org/pub/graphviz/stable/SOURCES/graphviz-2.24.0.tar.gz
tar zxf graphviz-2.24.0.tar.gz
cd graphviz-2.24.0
./configure
make && make install

安装xhprof

pecl install xhprof
mv /srv/php-5.3.8/lib/php/extensions/no-debug-non-zts-20090626/xhprof.so /srv/php-5.3.8/lib/php/extensions/

or

wget http://pecl.php.net/get/xhprof

tar zxf xhprof-0.9.2.tgz
cd xhprof-0.9.2
cp -r xhprof_html xhprof_lib /www/www.example.com/xhprof/
cd extension/
/usr/local/webserver/php/bin/phpize
./configure  –with-php-config=/srv/php/bin/php-config
make && make install

安装完提示：

Installing shared extensions:     /srv/php/lib/php/extensions/no-debug-non-zts-20060613/

cp /srv/php/lib/php/extensions/no-debug-non-zts-20060613/* /srv/php/lib/php/extensions/

增加xhprof.ini

cat >> /srv/php/etc/conf.d/xhprof.ini <<EOF
extension=xhprof.so
xhprof.output_dir=/www/logs/xhprof
EOF

分析日志输出在/www/logs/xhprof目录

检查安装是否成功

# /srv/php/bin/php -m | grep xhprof
xhprof

例 7.7. xhprof/sample.php

<?php

function bar($x) {
  if ($x > 0) {
    bar($x - 1);
  }
}

function foo() {
  for ($idx = 0; $idx < 5; $idx++) {
    bar($idx);
    $x = strlen("abc");
  }
}

// start profiling
xhprof_enable();

// run program
foo();

// stop profiler
$xhprof_data = xhprof_disable();

// display raw xhprof data for the profiler run
print_r($xhprof_data);

$XHPROF_ROOT = realpath(dirname(__FILE__) .'/..');
include_once $XHPROF_ROOT . "/xhprof_lib/utils/xhprof_lib.php";
include_once $XHPROF_ROOT . "/xhprof_lib/utils/xhprof_runs.php";

// save raw data for this profiler run using default
// implementation of iXHProfRuns.
$xhprof_runs = new XHProfRuns_Default();

// save the run under a namespace "xhprof_foo"
$run_id = $xhprof_runs->save_run($xhprof_data, "xhprof_foo");

echo "---------------\n".
     "Assuming you have set up the http based UI for \n".
     "XHProf at some address, you can view run at \n".
     "http://<xhprof-ui-address>/index.php?run=$run_id&source=xhprof_foo\n".
     "---------------\n";


7.19. Xdebug

Xdebug是一个开放源代码的PHP程序调试器(即一个Debug工具)，可以用来跟踪，调试和分析PHP程序的运行状况。

# /srv/php/bin/pecl list-all | grep xdebug
pecl/xdebug          2.1.2            Provides functions for function traces and profiling

# /srv/php/bin/pecl install xdebug

# mv /srv/php/lib/php/extensions/no-debug-non-zts-*/xdebug.so /srv/php/lib/php/extensions/

cat > /srv/php/etc/conf.d/xdebug.ini <<EOF
[Zend Modules]
zend_extension="/srv/php/lib/php/extensions/xdebug.so"

[Xdebug]
xdebug.profiler_enable = on
xdebug.trace_output_dir = "/tmp/xdebug"
xdebug.profiler_output_dir = "/tmp/xdebug"
EOF

# /srv/php/bin/php -m | grep xdebug
xdebug

参数说明

xdebug.default_enable
类型：布尔型 默认值：On
如果这项设置为On，堆栈跟踪将被默认的显示在错误事件中。你可以通过在代码中使用xdebug_disable()来禁止堆叠跟踪的显示。因为这是xdebug基本功能之一，将这项参数设置为On是比较明智的。
xdebug.max_nesting_level
类型：整型 默认值：100
The value of this setting is the maximum level of nested functions that are allowed before the script will be aborted.
限制无限递归的访问深度。这项参数设置的值是脚本失败前所允许的嵌套程序的最大访问深度。
堆栈跟踪
相关参数设置
xdebug.dump_globals
类型：布尔型 默认值：1
限制是否显示被xdebug.dump.*设置定义的超全局变量的值
例如，xdebug.dump.SERVER = REQUEST_METHOD,REQUEST_URI,HTTP_USER_AGENT 将打印 PHP 超全局变量 $_SERVER['REQUEST_METHOD']、$_SERVER['REQUEST_URI'] 和 $_SERVER['HTTP_USER_AGENT']。
xdebug.dump_once
类型：布尔型 默认值：1
限制是否超全局变量的值应该转储在所有出错环境(设置为Off时)或仅仅在开始的地方(设置为On时)
xdebug.dump_undefined
类型：布尔型 默认值：0
如果你想从超全局变量中转储未定义的值，你应该把这个参数设置成On，否则就设置成Off
xdebug.show_exception_trace
类型：整型 默认值：0
当这个参数被设置为1时，即使捕捉到异常，xdebug仍将强制执行异常跟踪当一个异常出现时。
xdebug.show_local_vars
类型：整型 默认值：0
当这个参数被设置为不等于0时，xdebug在错环境中所产生的堆栈转储还将显示所有局部变量，包括尚未初始化的变量在最上面。要注意的是这将产生大量的信息，也因此默认情况下是关闭的。
分析PHP脚本
相关参数设置
xdebug.profiler_append
类型：整型 默认值：0
当这个参数被设置为1时，文件将不会被追加当一个新的需求到一个相同的文件时(依靠xdebug.profiler_output_name的设置)。相反的设置的话，文件将被附加成一个新文件。
xdebug.profiler_enable
类型：整型 默认值：0
开放xdebug文件的权限，就是在文件输出目录中创建文件。那些文件可以通过KCacheGrind来阅读来展现你的数据。这个设置不能通过在你的脚本中调用ini_set()来设置。
xdebug.profiler_output_dir
类型：字符串 默认值：/tmp
这个文件是profiler文件输出写入的，确信PHP用户对这个目录有写入的权限。这个设置不能通过在你的脚本中调用ini_set()来设置。
xdebug.profiler_output_name
类型：字符串 默认值：cachegrind.out%p
这个设置决定了转储跟踪写入的文件的名称。
远程Debug
相关参数设置
xdebug.remote_autostart
类型：布尔型 默认值：0
一般来说，你需要使用明确的HTTP GET/POST变量来开启远程debug。而当这个参数设置为On，xdebug将经常试图去开启一个远程debug session并试图去连接客户端，即使GET/POST/COOKIE变量不是当前的。
xdebug.remote_enable
类型：布尔型 默认值：0
这个开关控制xdebug是否应该试着去连接一个按照xdebug.remote_host和xdebug.remote_port来设置监听主机和端口的debug客户端。
xdebug.remote_host
类型：字符串 默认值：localhost
选择debug客户端正在运行的主机，你不仅可以使用主机名还可以使用IP地址
xdebug.remote_port
类型：整型 默认值：9000
这个端口是xdebug试着去连接远程主机的。9000是一般客户端和被绑定的debug客户端默认的端口。许多客户端都使用这个端口数字，最好不要去修改这个设置。

7.19.1. Webgrind

Webgrind是一款可以通过浏览器图形化查看Xdebug输出的日志分析文件的软件

7.19.2. WinCacheGrind

WinCacheGrind是一款Windows下的可以图形化查看Xdebug输出的日志分析文件的软件


7.20. UploadProgress

UploadProgress是一个用于提供用户文件上传进度查看功能的PHP扩展，以便提高应用的用户体验.

# /srv/php/bin/pecl list-all | grep uploadprogress
pecl/uploadprogress  1.0.3.1          An extension to track progress of a file upload.

# /srv/php/bin/pecl install uploadprogress
# mv /srv/php-5.3.8/lib/php/extensions/no-debug-non-zts-20090626/uploadprogress.so /srv/php-5.3.8/lib/php/extensions/

cat >> /srv/php/etc/conf.d/uploadprogress.ini <<EOF
extension=uploadprogress.so
EOF

# /srv/php/bin/php -m | grep uploadprogress
uploadprogress


7.21. msgpack

git clone https://github.com/msgpack/msgpack-php.git
cd msgpack-php
phpize
./configure && make && make install
$data = array(0=>1,1=>2,2=>3);
$msg = msgpack_pack($data);
$data = msgpack_unpack($msg);


7.22. iconv

cd /usr/local/src/
cd php-5.2.17/ext/iconv/
/srv/php-5.2.17/bin/phpize
./configure --with-php-config=/srv/php-5.2.17/bin/php-config
make
make install

cat > /srv/php-5.2.17/etc/conf.d/iconv.ini <<EOF
extension=iconv.so
EOF

/srv/php-5.2.17/bin/php -m | grep iconv
iconv

/srv/php-5.2.17/sbin/php-fpm restart


7.23. imagick

# yum install -y ImageMagick-devel
# pecl install imagick

cat > /srv/php/etc/conf.d/imagick.ini <<EOF
extension=imagick.so
EOF


7.24. sysvmsg

忘记加入--enable-sysvmsg参数的补救方案。

cd /php-5.2.14/ext/sysvmsg
/srv/php-5.2.17/bin/phpize
./configure --with-php-config=/srv/php-5.2.17/bin/php-config
make
make install

cat > /srv/php/etc/conf.d/sysvmsg.ini <<EOF
extension=sysvmsg.so
EOF


第 8 章 PEAR - PHP Extension and Application Repository

目录

8.1. PEAR 使用说明
8.1.1. php-pear 安装
8.1.2. channel-update
8.1.3. install/uninstall
8.2. Pyrus
8.3. Pirum is a simple PEAR Channel Server Manager
8.4. PHPUnit - Unit testing framework for PHP
8.5. XML_RSS
8.6. Propel - smart, easy object persistence
8.6.1. 环境配置
8.6.2. PEAR Installer
8.7. Lua for PHP extension
8.8. libuv php extension

8.1. PEAR 使用说明

8.1.1. php-pear 安装

$ sudo apt-get install php-pear

8.1.2. channel-update

channel-update

pear channel-update pear.php.net

list-all

pear list-all

8.1.3. install/uninstall

install

pear install Packages

uninstall

pear uninstall Packages


8.2. Pyrus

wget http://pear2.php.net/pyrus.phar

# Set where to install packages:
$ php pyrus.phar mypear ~/src/my-project/vendor
# Install a package:
$ php pyrus.phar install PEAR2_HTTP_Request
# List installed packages:
$ php pyrus.phar list-packages


8.3. Pirum is a simple PEAR Channel Server Manager

http://pirum.sensiolabs.org/
$ pear channel-discover pear.pirum-project.org
$ pear install pirum/Pirum

$ php pirum


8.4. PHPUnit - Unit testing framework for PHP

过程 8.1. PHPUnit2

  1. install

    pear install PHPUnit2

  2. phpunit your.php


8.5. XML_RSS

http://pear.php.net/package/XML_RSS

$ sudo apt-get install php-xml-rss

例 8.1. RSS.php

 <?php
require_once "XML/RSS.php";

$rss = new XML_RSS("http://rss.slashdot.org/Slashdot/slashdot");
$rss->parse();

echo "<h1>Headlines from <a href=\"http://slashdot.org\">Slashdot</a></h1>\n";
echo "<ul>\n";

foreach ($rss->getItems() as $item) {
    echo "<li><a href=\"" . $item['link'] . "\">" . $item['title'] . "</a></li>\n";
}

echo "</ul>\n";
?>


8.6. Propel - smart, easy object persistence

ORM （ object relation mapping ）

即将数据库表映射成对像，实现通过实例化对像来访问数据库

本文主要介绍Propel - smart, easy object persistence

8.6.1. 环境配置

配置php.ini

在php.ini文件中加入：

extension=php_pdo.dll

8.6.2. PEAR Installer

$> pear channel-discover pear.phpdb.org
$> pear install phpdb/propel_generator
$> pear install phpdb/propel_runtime

Adding Channel

D:\>pear channel-discover pear.phpdb.org
Adding Channel "pear.phpdb.org" succeeded
Discovery of channel "pear.phpdb.org" succeeded

propel_generator 安装日志

D:\php-5.1.4-Win32>pear install phpdb/propel_generator
phpdb/propel_generator requires package "channel://pear.phing.info/phing" (versi
on >= 2.2.0)
downloading creole-1.1.0.tgz ...
Starting to download creole-1.1.0.tgz (92,633 bytes)
.....................done: 92,633 bytes
install ok: channel://pear.phpdb.org/creole-1.1.0

propel_runtime 安装日志

D:\php-5.1.4-Win32>pear install phpdb/propel_runtime
downloading propel_runtime-1.2.0.tgz ...
Starting to download propel_runtime-1.2.0.tgz (45,959 bytes)
.............done: 45,959 bytes
install ok: channel://pear.phpdb.org/propel_runtime-1.2.0

D:\php-5.1.4-Win32>


8.7. Lua for PHP extension

http://code.google.com/p/plua/


8.8. libuv php extension

https://github.com/chobie/php-uv


第 9 章 Application

目录

9.1. phpmailer
9.2. Soap
9.2.1. soapfunc.php
9.2.2. soapserver.php
9.2.3. soapclient.php
9.3. php function check
9.4. whois 域名查询
9.5. React - Event-driven, non-blocking I/O with PHP. (Node.PHP)

9.1. phpmailer

<?php
/**
* Simple example script using PHPMailer with exceptions enabled
* @package phpmailer
* @version $Id: chapter.application.xml 662 2013-08-14 02:46:24Z netkiller $
*/

require '../class.phpmailer.php';

try {
        $mail = new PHPMailer(true); //New instance, with exceptions enabled

        $body             = file_get_contents('contents.html');
        $body             = preg_replace('/\\\\/','', $body); //Strip backslashes

        $mail->IsSMTP();                           // tell the class to use SMTP
        $mail->SMTPAuth   = true;                  // enable SMTP authentication
        $mail->Port       = 25;                    // set the SMTP server port
        $mail->Host       = "mail.yourdomain.com"; // SMTP server
        $mail->Username   = "name@domain.com";     // SMTP server username
        $mail->Password   = "password";            // SMTP server password

        $mail->IsSendmail();  // tell the class to use Sendmail

        $mail->AddReplyTo("name@domain.com","First Last");

        $mail->From       = "name@domain.com";
        $mail->FromName   = "First Last";

        $to = "someone@example...com";

        $mail->AddAddress($to);

        $mail->Subject  = "First PHPMailer Message";

        $mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
        $mail->WordWrap   = 80; // set word wrap

        $mail->MsgHTML($body);

        $mail->IsHTML(true); // send as HTML

        $mail->Send();
        echo 'Message has been sent.';
} catch (phpmailerException $e) {
        echo $e->errorMessage();
}


9.2. Soap

9.2.1. soapfunc.php

$ cat soapfunc.php
<?php

function reverse($str){

        $retval = '';

        if(strlen($str) < 1) {

                return new SoapFault('Client','','Invalid string');

        }

        for ($i = 1; $i <= strlen($str); $i++) {

                $retval .= $str[(strlen($str) - $i)];

        }

        return $retval;

}

function sum($num1, $num2) {

        if (trim($num1) != intval($num1)) {

                return new SoapFault('Client','','The first number is invalid');

        }

        if (trim($num2) != intval($num2)) {

                return new SoapFault('Client','','The second number is invalid');

        }

        return ($num1 + $num2);

}

function gettime(){

        $time=strftime("%Y-%m-%d %H:%M:%S");

        return $time;

}

?>

9.2.2. soapserver.php

$ cat soapserver.php
<?php
include_once('soapfunc.php');

$soap = new SoapServer(null,array('uri'=>"http://netkiller.6600.org/"));

$soap->addFunction('reverse');

$soap->addFunction('sum');

$soap->addFunction('gettime');

$soap->addFunction(SOAP_FUNCTIONS_ALL);

$soap->handle();

?>

9.2.3. soapclient.php

$ cat soapclient.php
<?php

try {

        $client = new SoapClient(null, array('location' =>"http://netkiller.6600.org/soapserver.php",'uri' => "http://netkiller.6600.org/"));

        $str = "This string will be reversed";

        $reversed = $client->reverse($str);

        echo "If you reverse '",$str,"', you get '",$reversed,"' </br>";

        $n1=50;

        $n2=130;

        $sum = $client->sum($n1,$n2);

        echo "If you try ",$n1,"+",$n2,", you will get ",$sum,"</br>";

        echo "The system time is: ",$client->gettime();

} catch (SoapFault $fault){

        echo "Fault! code:",$fault->faultcode,", string: ",$fault->faultstring;

}

?>


9.3. php function check

#!/bin/bash
LOGFILE=/tmp/my.log
echo > $LOGFILE
for helper in `ls -1 class/helper/`
do
    echo ========================== $helper ============================ >> $LOGFILE
    class=`grep '^class' class/helper/$helper | awk -F ' ' '{print $2}'`
    for fun in `grep 'public function [a-zA-Z]' class/helper/$helper | awk -F ' ' '{print $3}' | awk -F '(' '{print $1}'`
    do
        count=`grep -r "$class->$fun(" *|wc -w`
        if [ $count == 0 ]; then
               echo "[ unused ] $class->$fun" >> $LOGFILE
        else

               echo "[  used  ] $class->$fun" >> $LOGFILE
        fi
        echo "[`date`] [$helper] $class->$fun (checked: $count)"
    done
done


9.4. whois 域名查询

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>whois</title>
</head>
<body>
<fieldset>
<legend>whois</legend>
<form name="form1" method="post" action="<? $PHP_SELF ?>">
<input type="text" name="domainname">
.cn
<input type="submit" name="Submit" value="查询">
</form>
</fieldset>

查询域名：
<?echo $domainname;?>
.cn
<?php
$fp = fsockopen ("whois.cnnic.cn", 43 , $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br>\n";
} else {
fputs ($fp, "$domainname".".cn"."\r\n");
echo "<pre>";
while (!feof($fp)) {

$data = fgets ($fp,1024);
$data = str_replace("no matching record", "该域名没有被注册\n<a href='http://www.cnwwwcn.com'>我想注册该域名</a>", $data);
/*
$data = fgetc ($fp);

if($data == "\n"){
echo "<br>";
}
*/
echo $data;
//no matching record
}
echo "</pre>";
fclose ($fp);
}
?>
</body>
</html>


9.5. React - Event-driven, non-blocking I/O with PHP. (Node.PHP)

http://reactphp.org/

AN EXAMPLE: WEBSERVER

This simple web server written in React responds with "Hello World" for every request.

require 'vendor/autoload.php';

$app = function ($request, $response) {
    $response->writeHead(200, array('Content-Type' => 'text/plain'));
    $response->end("Hello World\n");
};

$loop = React\EventLoop\Factory::create();
$socket = new React\Socket\Server($loop);
$http = new React\Http\Server($socket, $loop);

$http->on('request', $app);
echo "Server running at http://127.0.0.1:1337\n";

$socket->listen(1337);
$loop->run();
To install, just run this command:

% composer init --require=react/http:0.3.* -n
% composer install
To run the server, put the code into a file example.php and execute it with the php program:

% php example.php
Server running at http://127.0.0.1:1337


第 10 章 Frameworks

目录

10.1. CodeIgniter - Open source PHP web application framework
10.1.1. Nginx
10.1.2. PHP_CodeSniffer
10.2. Fuel PHP
10.2.1. 框架安装
10.2.1.1. oil
10.2.1.2. Apache
10.2.1.3. Nginx
10.3. Kohana
10.4. Yii
10.5. Zend Framework
10.5.1. Install Zend Framework
10.5.2. Create Your Project
10.5.3. Create a virtual host
10.5.4. Database
10.5.4.1. MySQL
10.5.4.2. SQLite
10.5.5. zf.sh
10.5.5.1. controller
10.5.5.2. model
10.5.5.3. layout
10.5.5.4. form
10.5.6. Smarty

PHP Frameworks 比较

10.1. CodeIgniter - Open source PHP web application framework

homepage: http://www.codeigniter.com/

下载解压后复制到 /usr/share/php/

$ chmod 755 -R /usr/share/php/CodeIgniter_2.0.0
$ ln -s /usr/share/php/CodeIgniter_2.0.0 /usr/share/php/CodeIgniter
$ ls /usr/share/php
CodeIgniter Smarty

rewrite

lighttpd 为例

url.rewrite = ( "^/(.+)" => "/index.php/$1"

10.1.1. Nginx

    location / {
        root   /www/mydomain.com/report.mydomain.com/htdocs;
        index  index.php index.html;

        if ($request_filename !~ (js|css|images|robots/.txt|index/.php) ) {
                rewrite ^/(.*)$ /index.php/$1 last;
                break;
        }

    }

    location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico|xml)$ {
        access_log        off;
        expires           7d;
    }

    location ~ \.php$ {
        if ($request_filename !~ (index/.php) ) {
                return 404;
        }
    }

    location ~ /index.php/ {
        root           html;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /www/mydomain.com/report.mydomain.com/htdocs/index.php;
        include        fastcgi_params;
    }

    location / {

        root  /www/www.example.com/public;
        index  index.php;

        # this serves static files that exist without running other rewrite tests
        if (-f $request_filename) {
            expires 30d;
            break;
        }

        # this sends all non-existing file or directory requests to index.php
        if (!-e $request_filename) {
                rewrite ^(.+)$ /index.php?$1 last;
        }
    }

    location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico|xml)$ {
        access_log        off;
        expires           30d;
        root /www/www.example.com/public;
    }

    # pass the *.php scripts to php5-fpm listening on tcp port 9000 #
    location ~ \.php$ {
        root  /www/www.example.com/public;
        index  index.php;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;

        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param SERVER_NAME $http_host;
        fastcgi_param PATH_INFO $fastcgi_script_name;
        fastcgi_ignore_client_abort on;
    }

    ## Disable viewing .htaccess & .htpassword
    location ~ /\.ht {
        deny  all;
    }

10.1.2. PHP_CodeSniffer

http://pear.php.net/manual/zh/package.php.php-codesniffer.intro.php
Easy Install
Not sure? Get more info.
pear install PHP_CodeSniffer-1.3.5

Pyrus Install
Try PEAR2's installer, Pyrus.

php pyrus.phar install pear/PHP_CodeSniffer-1.3.5


10.2. Fuel PHP

Fuel PHP 源自 CodeIgniter

10.2.1. 框架安装

http://fuelphp.com/

10.2.1.1. oil

$ curl get.fuelphp.com/oil | sh

$ oil create <project_name>

zip包安装

$ unzip fuelphp-v1.1.zip

$ ls /www/fuelphp
CHANGELOG.md  docs  fuel  oil  public  README.md

10.2.1.2. Apache

<IfModule mod_rewrite.c>
    RewriteEngine on

    RewriteBase /public

    RewriteRule ^(/)?$ index.php/$1 [L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

10.2.1.3. Nginx

$ cat /etc/nginx/sites-available/fuel

server {
        #listen   80; ## listen for ipv4; this line is default and implied
        #listen   [::]:80 default ipv6only=on; ## listen for ipv6

        root /www/fuelphp/public;
        index index.html index.php;

        # Make site accessible from http://localhost/
        server_name localhost;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to index.html
                try_files $uri $uri/ /index.html;
        }

        #location /doc {
        #       root /usr/share;
        #       autoindex on;
        #       allow 127.0.0.1;
        #       deny all;
        #}

        #location /images {
        #       root /usr/share;
        #       autoindex off;
        #}

        #error_page 404 /404.html;

        # redirect server error pages to the static page /50x.html
        #
        #error_page 500 502 503 504 /50x.html;
        #location = /50x.html {
        #       root /usr/share/nginx/www;
        #}

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #       proxy_pass http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ \.php$ {
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                include fastcgi_params;
        }

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #       deny all;
        #}
}


10.3. Kohana

Kohana 源自 CodeIgniter

http://kohanaframework.org/


10.4. Yii


10.5. Zend Framework

10.5.1. Install Zend Framework

sudo mv ZendFramework-1.10.2 /usr/local/share/
sudo ln -s
/usr/local/share/ZendFramework-1.10.2 /usr/local/share/zend

~/.bashrc

alias zf.sh=path/to/ZendFramework/bin/zf.sh

alias zf.sh=/usr/local/share/zend/bin/zf.sh

10.5.2. Create Your Project

$ zf.sh create project quickstart

$ cd quickstart/library; ln -s
/usr/local/share/zend/library/Zend .

Rewrite

.htaccess内容如下：

RewriteEngine on
RewriteRule !".(js|ico|gif|jpg|png|css)$ index.php

10.5.3. Create a virtual host

<VirtualHost *:80>
    ServerName quickstart.local
    DocumentRoot /path/to/quickstart/public

    SetEnv APPLICATION_ENV "development"

    <Directory /path/to/quickstart/public>
        DirectoryIndex index.php
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

/etc/hosts

127.0.0.1 quickstart.local

10.5.4. Database

10.5.4.1. MySQL

zf configure dbadapter "adapter=Pdo_Mysql&username=test&password=test&dbname=test"

10.5.4.2. SQLite

$ sudo apt-get install php5-sqlite
mkdir -p data/db; chmod -R a+rwX data

zf.sh configure db-adapter \
'adapter=PDO_SQLITE&dbname=APPLICATION_PATH "/../data/db/guestbook.db"' \
production

zf.sh configure db-adapter \
'adapter=PDO_SQLITE&dbname=APPLICATION_PATH "/../data/db/guestbook-testing.db"' \
testing

zf.sh configure db-adapter \
'adapter=PDO_SQLITE&dbname=APPLICATION_PATH "/../data/db/guestbook-dev.db"' \
development

10.5.5. zf.sh

10.5.5.1. controller

zf create controller Guestbook
10.5.5.1.1. action

    zf create action sign Guestbook

10.5.5.2. model

zf create model Guestbook
10.5.5.2.1. db-table

zf create db-table Guestbook guestbook

10.5.5.3. layout

zf enable layout

10.5.5.4. form

zf create form Guestbook

10.5.6. Smarty

<?php

//打开错误提示

error_reporting(E_ALL|E_STRICT);

//设定时区

date_default_timezone_set("Asia/Shanghai");

//指明引用文件的路径

set_include_path('.'.PATH_SEPARATOR.'./library'.PATH_SEPARATOR.'./app/model/'.PATH_SEPARATOR.get_include_path());

//必须手动加载Loader.php

include "Zend/Loader.php";

//自动加载类，使用时，直接实例化使用

function __autoload($class){

    Zend_Loader::loadClass($class);

}

   //getInstance()方法用来获取前端控制器实例

   $frontController = Zend_Controller_Front::getInstance();

   //设定前端路由器的工作目录，即cotroller

   $frontController->setControllerDirectory(array("default"=>"app/controller"));

   //抛出异常

   $frontController->throwExceptions(true);

   //设置基地址,方便以后url的跳转用户,注意，区分大小写！

   $frontController->setBaseUrl("/phpzend");

//使用smarty模版需关闭本身的视图助手.

$frontController->setParam("noViewRenderer", true);

       // 关闭错误提示，发生请求错误时候，转到ErrorController的errorAction控制器

//$frontController->throwExceptions(false);

//对。。进行注册

Zend_Registry::set("font", $frontController);

//------------配置Smarty模版 ----------------

include "smarty/Smarty.class.php";

/**

* 对smarty模版进行初始化

**/

$views = new Smarty();

//$views->left_delimiter = "{{";

//$views->right_delimiter = "}}";

$views->compile_dir = "app/template_c";
$views->cache_dir = "app/template_c/cache_c";
$views->template_dir = "app/template";
function smarty_block_dynamic($param,$content,&$views)
{
      return $content;
}

$views->register_block("dynamic","smarty_block_dynamic",false);

Zend_Registry::set("views", $views);

//开始运行程序

$frontController->dispatch();

<?php

   //控制器层

   class IndexController extends Zend_Controller_Action{

     var $views;   /*模板对象*/

     var $data;    /*传递模版变量的对象*/

      function init()

      {

             //拿回注册过的对象

             $this->views = Zend_Registry::get("views");

    }

      function indexAction()

      {

             //定义模版显示的变量

             $data['title']="hello world";

             //传递变量到模版

             $this->views->assign($data);

             //显示模版

             $this->views->display("index/index.tpl");

                       echo "<p>in IndexController::indexAction()</p>";

    }

      function addAction()

      {

      }

}


第 11 章 PHP Extension 扩展开发

目录

11.1. Extension Example
11.2. PHP_FUNCTION
11.3. PHP_INI
11.4. PHP_MINFO_FUNCTION

创建一个扩展只需要下面几个步骤

# cd php-5.4.14/ext/
# ./ext_skel --extname=netkiller
# cd netkiller
# /srv/php-5.4.8/bin/phpize
# ./configure --enable-netkiller --with-php-config=/srv/php-5.4.8/bin/php-config
# make
# make install

11.1. Extension Example

下面我们开始分部讲解，首先创建一个扩展。

./ext_skel --extname=netkiller
Creating directory netkiller
Creating basic files: config.m4 config.w32 .cvsignore netkiller.c php_netkiller.h CREDITS EXPERIMENTAL tests/001.phpt netkiller.php [done].

To use your new extension, you will have to execute the following steps:

1.  $ cd ..
2.  $ vi ext/netkiller/config.m4
3.  $ ./buildconf
4.  $ ./configure --[with|enable]-netkiller
5.  $ make
6.  $ ./php -f ext/netkiller/netkiller.php
7.  $ vi ext/netkiller/netkiller.c
8.  $ make

Repeat steps 3-6 until you are satisfied with ext/netkiller/config.m4 and
step 6 confirms that your module is compiled into PHP. Then, start writing
code and repeat the last two steps as often as necessary.

编辑config.m4

# vim netkiller/config.m4
PHP_ARG_ENABLE(netkiller, whether to enable netkiller support,
Make sure that the comment is aligned:
[  --enable-netkiller           Enable netkiller support])

去掉上面三行前的dnl， dnl 表示注释

# cat config.m4 | grep -v 'dnl'

PHP_ARG_ENABLE(netkiller, whether to enable netkiller support,
Make sure that the comment is aligned:
[  --enable-netkiller           Enable netkiller support])

if test "$PHP_netkiller" != "no"; then

  PHP_NEW_EXTENSION(netkiller, netkiller.c, $ext_shared)
fi

执行 phpize

# cd netkiller
# /srv/php-5.4.8/bin/phpize
Configuring for:
PHP Api Version:         20100412
Zend Module Api No:      20100525
Zend Extension Api No:   220100525

# ./configure --enable-netkiller --with-php-config=/srv/php-5.4.8/bin/php-config
# make
# make install

# ls modules/
netkiller.la  netkiller.so

创建 ini 文件

cat >> /srv/php/etc/conf.d/netkiller.ini <<PHP
extension=netkiller.so
PHP

确认扩展看装成功

# /srv/php/bin/php -f netkiller.php
Functions available in the test extension:
confirm_netkiller_compiled

Congratulations! You have successfully modified ext/netkiller/config.m4. Module netkiller is now compiled into PHP.

# /srv/php-5.4.8/bin/php -m | grep netkiller
netkiller

创建 php 测试程序

vim test.php

<?php
echo confirm_netkiller_compiled('netkiller');
phpinfo();

输出结果

Congratulations! You have successfully modified ext/netkiller/config.m4. Module netkiller is now compiled into PHP.

netkiller
---------------------------
netkiller support	enabled


11.2. PHP_FUNCTION

编辑 php_<extname>.h 文件，在 PHP_FUNCTION(confirm_netkiller_compiled); 下面增加一个新函数

# cat php_netkiller.h
/*
  +----------------------------------------------------------------------+
  | PHP Version 5                                                        |
  +----------------------------------------------------------------------+
  | Copyright (c) 1997-2010 The PHP Group                                |
  +----------------------------------------------------------------------+
  | This source file is subject to version 3.01 of the PHP license,      |
  | that is bundled with this package in the file LICENSE, and is        |
  | available through the world-wide-web at the following url:           |
  | http://www.php.net/license/3_01.txt                                  |
  | If you did not receive a copy of the PHP license and are unable to   |
  | obtain it through the world-wide-web, please send a note to          |
  | license@php.net so we can mail you a copy immediately.               |
  +----------------------------------------------------------------------+
  | Author:                                                              |
  +----------------------------------------------------------------------+
*/

/* $Id: chapter.ext.xml 579 2013-05-03 03:39:33Z netkiller $ */

#ifndef PHP_NETKILLER_H
#define PHP_NETKILLER_H

extern zend_module_entry netkiller_module_entry;
#define phpext_netkiller_ptr &netkiller_module_entry

#ifdef PHP_WIN32
#define PHP_NETKILLER_API __declspec(dllexport)
#else
#define PHP_NETKILLER_API
#endif

#ifdef ZTS
#include "TSRM.h"
#endif

PHP_MINIT_FUNCTION(netkiller);
PHP_MSHUTDOWN_FUNCTION(netkiller);
PHP_RINIT_FUNCTION(netkiller);
PHP_RSHUTDOWN_FUNCTION(netkiller);
PHP_MINFO_FUNCTION(netkiller);

PHP_FUNCTION(confirm_netkiller_compiled);	/* For testing, remove later. */
PHP_FUNCTION(netkiller_test);	/* For testing, remove later. */

/*
      Declare any global variables you may need between the BEGIN
    and END macros here:

ZEND_BEGIN_MODULE_GLOBALS(netkiller)
    long  global_value;
    char *global_string;
ZEND_END_MODULE_GLOBALS(netkiller)
*/

/* In every utility function you add that needs to use variables
   in php_netkiller_globals, call TSRMLS_FETCH(); after declaring other
   variables used by that function, or better yet, pass in TSRMLS_CC
   after the last function argument and declare your utility function
   with TSRMLS_DC after the last declared argument.  Always refer to
   the globals in your function as NETKILLER_G(variable).  You are
   encouraged to rename these macros something shorter, see
   examples in any other php module directory.
*/

#ifdef ZTS
#define NETKILLER_G(v) TSRMG(netkiller_globals_id, zend_netkiller_globals *, v)
#else
#define NETKILLER_G(v) (netkiller_globals.v)
#endif

#endif	/* PHP_NETKILLER_H */

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */

# cat netkiller.c
/*
  +----------------------------------------------------------------------+
  | PHP Version 5                                                        |
  +----------------------------------------------------------------------+
  | Copyright (c) 1997-2010 The PHP Group                                |
  +----------------------------------------------------------------------+
  | This source file is subject to version 3.01 of the PHP license,      |
  | that is bundled with this package in the file LICENSE, and is        |
  | available through the world-wide-web at the following url:           |
  | http://www.php.net/license/3_01.txt                                  |
  | If you did not receive a copy of the PHP license and are unable to   |
  | obtain it through the world-wide-web, please send a note to          |
  | license@php.net so we can mail you a copy immediately.               |
  +----------------------------------------------------------------------+
  | Author:                                                              |
  +----------------------------------------------------------------------+
*/

/* $Id: chapter.ext.xml 579 2013-05-03 03:39:33Z netkiller $ */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_netkiller.h"

/* If you declare any globals in php_netkiller.h uncomment this:
ZEND_DECLARE_MODULE_GLOBALS(netkiller)
*/

/* True global resources - no need for thread safety here */
static int le_netkiller;

/* {{{ netkiller_functions[]
 *
 * Every user visible function must have an entry in netkiller_functions[].
 */
zend_function_entry netkiller_functions[] = {
    PHP_FE(confirm_netkiller_compiled,	NULL)		/* For testing, remove later. */
    PHP_FE(netkiller_test,	NULL)		/* For testing, remove later. */
    {NULL, NULL, NULL}	/* Must be the last line in netkiller_functions[] */
};
/* }}} */

/* {{{ netkiller_module_entry
 */
zend_module_entry netkiller_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
    STANDARD_MODULE_HEADER,
#endif
    "netkiller",
    netkiller_functions,
    PHP_MINIT(netkiller),
    PHP_MSHUTDOWN(netkiller),
    PHP_RINIT(netkiller),		/* Replace with NULL if there's nothing to do at request start */
    PHP_RSHUTDOWN(netkiller),	/* Replace with NULL if there's nothing to do at request end */
    PHP_MINFO(netkiller),
#if ZEND_MODULE_API_NO >= 20010901
    "0.1", /* Replace with version number for your extension */
#endif
    STANDARD_MODULE_PROPERTIES
};
/* }}} */

#ifdef COMPILE_DL_NETKILLER
ZEND_GET_MODULE(netkiller)
#endif

/* {{{ PHP_INI
 */
/* Remove comments and fill if you need to have entries in php.ini
PHP_INI_BEGIN()
    STD_PHP_INI_ENTRY("netkiller.global_value",      "42", PHP_INI_ALL, OnUpdateLong, global_value, zend_netkiller_globals, netkiller_globals)
    STD_PHP_INI_ENTRY("netkiller.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_netkiller_globals, netkiller_globals)
PHP_INI_END()
*/
/* }}} */

/* {{{ php_netkiller_init_globals
 */
/* Uncomment this function if you have INI entries
static void php_netkiller_init_globals(zend_netkiller_globals *netkiller_globals)
{
    netkiller_globals->global_value = 0;
    netkiller_globals->global_string = NULL;
}
*/
/* }}} */

/* {{{ PHP_MINIT_FUNCTION
 */
PHP_MINIT_FUNCTION(netkiller)
{
    /* If you have INI entries, uncomment these lines
    REGISTER_INI_ENTRIES();
    */
    return SUCCESS;
}
/* }}} */

/* {{{ PHP_MSHUTDOWN_FUNCTION
 */
PHP_MSHUTDOWN_FUNCTION(netkiller)
{
    /* uncomment this line if you have INI entries
    UNREGISTER_INI_ENTRIES();
    */
    return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
 */
PHP_RINIT_FUNCTION(netkiller)
{
    return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
 */
PHP_RSHUTDOWN_FUNCTION(netkiller)
{
    return SUCCESS;
}
/* }}} */

/* {{{ PHP_MINFO_FUNCTION
 */
PHP_MINFO_FUNCTION(netkiller)
{
    php_info_print_table_start();
    php_info_print_table_header(2, "netkiller support", "enabled");
    php_info_print_table_end();

    /* Remove comments if you have entries in php.ini
    DISPLAY_INI_ENTRIES();
    */
}
/* }}} */

/* Remove the following function when you have succesfully modified config.m4
   so that your module can be compiled into PHP, it exists only for testing
   purposes. */

/* Every user-visible function in PHP should document itself in the source */
/* {{{ proto string confirm_netkiller_compiled(string arg)
   Return a string to confirm that the module is compiled in */
PHP_FUNCTION(confirm_netkiller_compiled)
{
    char *arg = NULL;
    int arg_len, len;
    char *strg;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) {
        return;
    }

    len = spprintf(&strg, 0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "netkiller", arg);
    RETURN_STRINGL(strg, len, 0);
}
/* }}} */
/* The previous line is meant for vim and emacs, so it can correctly fold and
   unfold functions in source code. See the corresponding marks just before
   function definition, where the functions purpose is also documented. Please
   follow this convention for the convenience of others editing your code.
*/

PHP_FUNCTION(netkiller_test)
{
char *arg = NULL;
int arg_len, len;
char *strg;

if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) {
return;
}

len = spprintf(&strg, 0, "Your input string: %s\n", arg);
RETURN_STRINGL(strg, len, 0);
}

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */


11.3. PHP_INI

读取INI文件

INI_STR(name)
INI_INT(name)

/* {{{ PHP_INI
 */

PHP_INI_BEGIN()
    PHP_INI_ENTRY("safenet.url", "http://localhost/", PHP_INI_ALL, NULL)
    PHP_INI_ENTRY("safenet.key", "key01", PHP_INI_ALL, NULL)
PHP_INI_END()

/* }}} */

/* {{{ PHP_MINIT_FUNCTION
 */
PHP_MINIT_FUNCTION(safenet)
{

    REGISTER_INI_ENTRIES();

    return SUCCESS;
}
/* }}} */

/* {{{ PHP_MSHUTDOWN_FUNCTION
 */
PHP_MSHUTDOWN_FUNCTION(safenet)
{

    UNREGISTER_INI_ENTRIES();

    return SUCCESS;
}
/* }}} */

/* {{{ PHP_MINFO_FUNCTION
 */
PHP_MINFO_FUNCTION(safenet)
{
    php_info_print_table_start();
    php_info_print_table_header(2, "safenet support", "enabled");
    php_info_print_table_row(2, "author", "Neo Chan<netkiller@msn.com>");
    php_info_print_table_row(2, "safenet.url", INI_STR("safenet.url"));
    php_info_print_table_row(2, "safenet.key", INI_STR("safenet.key"));
    php_info_print_table_end();

    /* Remove comments if you have entries in php.ini
    DISPLAY_INI_ENTRIES();
    */
}
/* }}} */


11.4. PHP_MINFO_FUNCTION

/* {{{ PHP_MINFO_FUNCTION
 */
PHP_MINFO_FUNCTION(netkiller)
{
        php_info_print_table_start();
        php_info_print_table_header(2, "netkiller support", "enabled");
        php_info_print_table_end();

        /* Remove comments if you have entries in php.ini
        DISPLAY_INI_ENTRIES();
        */
}
/* }}} */

表格增加一行

        php_info_print_table_start();
        php_info_print_table_header(2, "netkiller support", "enabled");
        php_info_print_table_row(2, "author", "Neo Chan");
        php_info_print_table_end();


第 12 章 Debug

目录

12.1. FirePHP

12.1. FirePHP

http://www.firephp.org/


第 13 章 FAQ

目录

13.1. Error in TLS handshake, trying SSLv3...

13.1. Error in TLS handshake, trying SSLv3...

* Initializing NSS with certpath: sql:/etc/pki/nssdb
* NSS error -12286
* Error in TLS handshake, trying SSLv3...

重新编译curl，同时禁用NSS

wget http://curl.haxx.se/download/curl-7.28.1.tar.gz
tar zxvf curl-7.28.1.tar.gz
cd curl-7.28.1
./configure --prefix=/srv/curl-7.28.1/ --without-nss --with-ssl && make &&make install

编译PHP，同时指定curl目录

./configure --prefix=/srv/php-5.2.17 \
--with-config-file-path=/srv/php-5.2.17/etc \
--with-config-file-scan-dir=/srv/php-5.2.17/etc/conf.d \
--with-libdir=lib64 \
--enable-fastcgi \
--enable-fpm \
--with-pear \
--with-curl=/srv/curl-7.28.1 \
--with-gd=shared \
--with-jpeg-dir=shared \
--with-png-dir=shared \
--with-freetype-dir=shared \
--with-zlib-dir \
--with-iconv=shared \
--with-mcrypt \
--with-mysql \
--with-pdo-mysql \
--with-mysql-sock=/var/lib/mysql/mysql.sock \
--with-openssl=shared \
--with-mhash=shared \
--with-sqlite=shared \
--with-pdo-sqlite=shared \
--with-xsl=shared \
--with-pear \
--enable-sockets \
--enable-soap \
--enable-mbstring \
--enable-magic-quotes \
--enable-inline-optimization \
--enable-gd-native-ttf \
--enable-zip \
--enable-xml \
--enable-ftp \
--enable-bcmath \
--enable-calendar \
--enable-sqlite-utf8 \
--enable-shmop \
--enable-dba \
--enable-wddx \
--enable-sysvsem \
--enable-sysvshm \
--enable-sysvmsg \
--disable-debug

解决后

* successfully set certificate verify locations:
*   CAfile: /etc/pki/tls/certs/ca-bundle.crt
  CApath: none
* SSL connection using DHE-RSA-AES256-SHA