PHP 手册

Mehdi Achour
Friedhelm Betz
Antony Dovgal
Nuno Lopes
Philip Olson
Georg Richter
Damien Seguy
Jakub Vrana
其他贡献者

编辑

Gabor Hojtsy
王远之
肖理达
肖盛文
黄啸宇
宋琪
陈伯乐
刘铭
崔岩

2005-09-12

版权信息

© Copyright 1997 - 2005 PHP 文档组版权所有。发布本资料须遵守开放出版许可协议 1.0 或者更新版本。一份开放出版许可协议的拷贝已随本手册发布,其最新版本位于 http://www.opencontent.org/openpub/

未经版权所有者明确授权,禁止发行本文档被实质上修改的版本。

未经版权所有者事先授权,禁止将此作品及其衍生作品以标准(纸质)书籍形式发行。

如果有兴趣再发行或再版本手册的全部或部分内容,不论修改过与否,或者有任何问题,请联系版权所有者 doc-license@lists.php.net。注意本地址映射到一个公开归档的邮件列表。

本手册中 Zend API 一章是根据 Zend Technologies 提供的内容而来。


目录
前言
作者和贡献者
I. 入门指引
1. 简介
2. 简明教程
II. 安装与配置
3. 安装前需要考虑的事项
4. Unix 系统下的安装
5. Mac OS X 系统下的安装
6. Windows 系统下的安装
7. PECL 扩展库安装
8. 还有问题?
9. 运行时配置
III. 语言参考
10. 基本语法
11. 类型
12. 变量
13. 常量
14. 表达式
15. 运算符
16. 流程控制
17. 函数
18. 类与对象(PHP 4)
19. 类与对象(PHP 5)
20. 异常处理
21. 引用的解释
IV. 安全
22. 简介
23. 总则
24. 以 CGI 模式安装时
25. 以 Apache 模块安装时
26. 文件系统安全
27. 数据库安全
28. 错误报告
29. 使用 Register Globals
30. 用户提交的数据
31. 魔术引号
32. 隐藏 PHP
33. 保持更新
V. 特点
34. 用 PHP 进行 HTTP 认证
35. cookies
36. 会话
37. 处理 XForms
38. 文件上传处理
39. 使用远程文件
40. 连接处理
41. 数据库永久连接
42. 安全模式
43. PHP 的命令行模式
VI. 函数参考
I. .NET 函数
II. Advanced PHP debugger
III. Alternative PHP Cache
IV. Apache 特有函数
V. Array 数组函数
VI. Aspell 函数(已废弃)
VII. BC math 高精度数学函数
VIII. Bzip2 压缩函数
IX. Calendar 日历函数
X. CCVS API Functions [deprecated]
XI. Character Type Functions
XII. Classes/Objects 类/对象函数
XIII. Classkit Functions
XIV. ClibPDF Functions
XV. COM 和 .Net(Windows)函数
XVI. Crack Functions
XVII. Credit Mutuel CyberMUT functions
XVIII. CURL, Client URL Library Functions
XIX. Cybercash Payment Functions
XX. Cyrus IMAP administration Functions
XXI. Database (dbm-style) Abstraction Layer Functions
XXII. Date/Time 日期/时间函数
XXIII. DB++ Functions
XXIV. dBase Functions
XXV. DBM Functions [deprecated]
XXVI. dbx Functions
XXVII. Direct IO Functions
XXVIII. Directory 目录函数
XXIX. DOM Functions
XXX. DOM XML Functions
XXXI. Error Handling and Logging Functions
XXXII. Exif Functions
XXXIII. File Alteration Monitor Functions
XXXIV. filePro Functions
XXXV. Filesystem 文件系统函数
XXXVI. Firebird/InterBase Functions
XXXVII. Firebird/Interbase Functions (PDO_FIREBIRD)
XXXVIII. Forms Data Format Functions
XXXIX. FriBiDi Functions
XL. FrontBase Functions
XLI. FTP 函数
XLII. Function Handling Functions
XLIII. Gettext
XLIV. GMP Functions
XLV. GNU Readline
XLVI. GNU Recode Functions
XLVII. HTTP 函数
XLVIII. Hyperwave API Functions
XLIX. Hyperwave Functions
L. IBM DB2, Cloudscape and Apache Derby Functions
LI. ICAP Functions [deprecated]
LII. iconv Functions
LIII. ID3 Functions
LIV. IIS Administration Functions
LV. Image 图像函数
LVI. IMAP, POP3 and NNTP Functions
LVII. Informix Functions
LVIII. Ingres II Functions
LIX. IRC Gateway Functions
LX. KADM5
LXI. LDAP Functions
LXII. libxml Functions
LXIII. Lotus Notes Functions
LXIV. LZF Functions
LXV. Mail Functions
LXVI. mailparse Functions
LXVII. Math 数学函数
LXVIII. MaxDB PHP Extension
LXIX. MCAL Functions
LXX. Mcrypt Encryption Functions
LXXI. MCVE Payment Functions
LXXII. Memcache Functions
LXXIII. Mhash Functions
LXXIV. Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
LXXV. Microsoft SQL Server Functions
LXXVI. Mimetype Functions
LXXVII. Ming functions for Flash
LXXVIII. Miscellaneous Functions
LXXIX. mnoGoSearch Functions
LXXX. Mohawk Software Session Handler Functions
LXXXI. mSQL Functions
LXXXII. Multibyte String Functions
LXXXIII. muscat Functions
LXXXIV. MySQL 函数
LXXXV. MySQL Functions (PDO_MYSQL)
LXXXVI. MySQL Improved Extension
LXXXVII. Ncurses Terminal Screen Control Functions
LXXXVIII. Network Functions
LXXXIX. Net_Gopher
XC. NSAPI-specific Functions
XCI. Object Aggregation/Composition Functions
XCII. Object property and method call overloading
XCIII. ODBC and DB2 functions (PDO_ODBC)
XCIV. ODBC Functions (Unified)
XCV. oggvorbis
XCVI. OpenAL Audio Bindings
XCVII. OpenSSL Functions
XCVIII. Oracle 函数
XCIX. Oracle Functions (PDO_OCI)
C. Oracle 函数(已废弃)
CI. Output Control 输出控制函数
CII. Ovrimos SQL Functions
CIII. Paradox File Access
CIV. Parsekit Functions
CV. PDF functions
CVI. PDO Functions
CVII. PHP / Java Integration
CVIII. PHP bytecode Compiler
CIX. PHP Options&Information
CX. POSIX Functions
CXI. PostgreSQL 数据库函数
CXII. PostgreSQL Functions (PDO_PGSQL)
CXIII. PostgreSQL Session Save Handler
CXIV. PostScript document creation
CXV. Printer Functions
CXVI. Process Control Functions
CXVII. Program Execution Functions
CXVIII. Pspell Functions
CXIX. qtdom Functions
CXX. Radius
CXXI. Rar Functions
CXXII. Perl 兼容正则表达式函数
CXXIII. POSIX 扩展正则表达式函数
CXXIV. runkit Functions
CXXV. SDO Functions
CXXVI. SDO Relational Data Access Service Functions
CXXVII. SDO XML Data Access Service Functions
CXXVIII. Secure Shell2 Functions
CXXIX. Semaphore, Shared Memory and IPC Functions
CXXX. SESAM Database Functions
CXXXI. Session Handling Functions
CXXXII. Shared Memory Functions
CXXXIII. Shockwave Flash Functions
CXXXIV. SimpleXML functions
CXXXV. SNMP 函数
CXXXVI. SOAP Functions
CXXXVII. Socket Functions
CXXXVIII. SQLite Functions
CXXXIX. SQLite Functions (PDO_SQLITE)
CXL. Standard PHP Library (SPL) Functions
CXLI. Stream Functions
CXLII. String 字符串处理函数
CXLIII. Sybase Functions
CXLIV. TCP Wrappers Functions
CXLV. Tidy Functions
CXLVI. Tokenizer Functions
CXLVII. Unicode Functions
CXLVIII. URL 函数
CXLIX. Variable 变量函数
CL. Verisign Payflow Pro Functions
CLI. vpopmail Functions
CLII. W32api 函数
CLIII. WDDX Functions
CLIV. xattr Functions
CLV. xdiff Functions
CLVI. XML 语法解析函数
CLVII. XML-RPC 函数
CLVIII. XMLReader functions
CLIX. XSL functions
CLX. XSLT Functions
CLXI. YAZ Functions
CLXII. YP/NIS Functions
CLXIII. Zip File Functions (Read Only Access)
CLXIV. Zlib Compression Functions
VII. PHP 和 Zend 引擎内部资料
44. PHP 扩展库编程 API 指南
45. Zend API:深入 PHP 内核
46. 扩展 PHP 3
VIII. FAQ:常见问题
47. 一般信息
48. 邮件列表
49. 获取 PHP
50. 数据库问题
51. 安装常见问题
52. 编译问题
53. 使用 PHP
54. PHP 和 HTML
55. PHP 和 COM
56. PHP 和其它语言
57. 从 PHP/FI 2 移植到 PHP 3
58. 从 PHP 3 移植到 PHP 4
59. 从 PHP 4 移植到 PHP 5
60. 杂类问题
IX. 附录
A. PHP 及其相关工程的历史
B. 从 PHP 4 移植到 PHP 5
C. 从 PHP 3 移植到 PHP 4
D. 从 PHP/FI 2 移植到 PHP 3
E. PHP 的调试
F. 配置选项
G. php.ini 配置选项
H. 扩展库分类
I. 函数别名列表
J. 保留字列表
K. 资源类型列表
L. 支持的协议/封装协议列表
M. 可用过滤器列表
N. 所支持的套接字传输器(Socket Transports)列表
O. PHP 类型比较表
P. 解析器代号列表
Q. 关于本手册
R. 开放出版许可协议
S. 函数索引

前言

PHP,即“PHP: Hypertext Preprocessor”,是一种被广泛使用的开放源代码多用途脚本语言,尤其适用于 web 开发并可以嵌入到 HTML 中去。其语法利用了 C,Java 和 Perl,非常容易学习。该语言的主要目标是让 web 开发人员可以很快写出动态生成的网页,但 PHP 的功能远不止如此。

本手册主要由函数参考组成,但也包括语言参考,PHP 一些主要特点的说明以及其它补充信息

可以在 http://www.php.net/download-docs.php 下载本手册的数种格式。关于本手册如何被开发的更多信息,请参阅附录:“关于本手册”。如果对 PHP 的历史感兴趣,请访问相关附录。

欢迎加入 PHP 简体中文翻译小组!具体加入方法请访问此页面,点击该页面右上角的“下载”以取得该 howto 文档的最新版本并仔细阅读。


作者和贡献者

手册首页仅突出了目前最活跃的人员,但是还有更多的贡献者在现在或者过去对本项目提供了大量的帮助。很多不留名的人也帮忙在手册中写下了笔记,并不断被包括在手册中,也很感谢他们的工作。下面的姓名列表按照字母顺序排列。


作者与编辑

下列人员曾经或者目前正在为本手册添砖加瓦: Jouni Ahto, Alexander Aulbach, Daniel Beckham, Stig Bakken, Jesus M. Castagnetto, Ron Chmara, Sean Coates, John Coggeshall, Simone Cortesi, Markus Fischer, Wez Furlong, Sara Golemon, Rui Hirokawa, Brad House, Moriyoshi Koizumi, Rasmus Lerdorf, Andrew Lindeman, Stanislav Malyshev, Rafael Martinez, Yasuo Ohgaki, Derick Rethans, Sander Roobol, Egon Schmid, Thomas Schoefbeck, Sascha Schumann, Dan Scott, Lars Torben Wilson, Jim Winstead, Jeroen van Wolffelaar 和 Andrei Zmievski.

下列人员对本手册做出了重大的编辑工作: Stig Bakken, Hartmut Holzgraefe 和 Egon Schmid.


用户注释维护者

目前最活跃的维护者是: Mehdi Achour, Friedhelm Betz, Vincent Gevers, Aidan Lister, Nuno Lopes 和 Tom Sommer.

下列人员为维护用户评论作出了巨大的努力: Daniel Beckham, Victor Boivie, Jesus M. Castagnetto, Nicolas Chaillan, Ron Chmara, James Cox, Sara Golemon, Zak Greant, Szabolcs Heilig, Oliver Hinckel, Hartmut Holzgraefe, Rasmus Lerdorf, Andrew Lindeman, Maxim Maletsky, James Moore, Sebastian Picklum, Derick Rethans, Sander Roobol, Damien Seguy, Jason Sheets, Jani Taskinen, Yasuo Ohgaki, Philip Olson, Lars Torben Wilson, Jim Winstead, Jared Wyles 和 Jeroen van Wolffelaar.

I. 入门指引

目录
1. 简介
2. 简明教程

章 1. 简介

PHP 是什么?

PHP(“PHP: Hypertext Preprocessor”,超文本预处理器的字母缩写)是一种被广泛应用的开放源代码的多用途脚本语言,它可嵌入到 HTML中,尤其适合 web 开发。

以上是一个简单的回答,不过这是什么意思呢?请看如下例子:

例子 1-1. 一个介绍性的范例

<html>
    <head>
        <title>Example</title>
    </head>
    <body>

        <?php
        echo "Hi, I'm a PHP script!";
        ?>

    </body>
</html>

请注意这个范例和其它用 C 或 Perl 语言写的脚本之间的区别――与用大量的命令来编写程序以输出 HTML 不同的是,我们用 PHP 编写了一个 HTML 脚本,其中嵌入了一些代码来做一些事情(例如,在本例中输出了一些文本)。PHP 代码被包含在特殊的起始符和结束符中,使得可以进出“PHP 模式”。

和客户端的 JavaScript 不同的是,PHP 代码是运行在服务端的。如果在服务器上建立了如上例类似的代码,则在运行该脚本后,客户端就能接收到其结果,但他们无法得知其背后的代码是如何运作的。甚至可以将 web 服务器设置成让 PHP 来处理所有的 HTML 文件,这么一来,用户就无法得知服务端到底做了什么。

使用 PHP 的一大好处是它对于初学者来说极其简单,同时也给专业的程序员提供了各种高级的特性。当看到 PHP 长长的特性列表时,请不要害怕。可以很快的入门,只需几个小时就可以自己写一些简单的脚本。

尽管 PHP 的开发是以服务端脚本为目的,但事实上其功能远不局限与此。请继续读后面的章节,在“PHP 能做什么”一节中将获得更多的信息。如果对 web 编程感兴趣,也可以阅读简明教程


PHP 能做什么?

PHP 能做任何事。PHP 主要是用于服务端的脚本程序,因此可以用 PHP 来完成任何其它的 CGI 程序能够完成的工作,例如收集表单数据,生成动态网页,或者发送/接收 Cookies。但 PHP 的功能远不局限于此。

PHP 脚本主要用于以下三个领域:

  • 服务端脚本。这是 PHP 最传统,也是最主要的目标领域。开展这项工作需要具备以下三点:PHP 解析器(CGI 或者服务器模块)、web 服务器和 web 浏览器。需要在运行 web 服务器时,安装并配置 PHP,然后,可以用 web 浏览器来访问 PHP 程序的输出,即浏览服务端的 PHP 页面。如果只是实验 PHP 编程,所有的这些都可以运行在自己家里的电脑中。请查阅安装一章以获取更多信息。

  • 命令行脚本。可以编写一段 PHP 脚本,并且不需要任何服务器或者浏览器来运行它。通过这种方式,仅仅只需要 PHP 解析器来执行。这种用法对于依赖 cron(Unix 或者 Linux 环境)或者 Task Scheduler(Windows 环境)的日常运行的脚本来说是理想的选择。这些脚本也可以用来处理简单的文本。请参阅 PHP 的命令行模式以获取更多信息。

  • 编写桌面应用程序。对于有着图形界面的桌面应用程序来说,PHP 或许不是一种最好的语言,但是如果用户非常精通 PHP,并且希望在客户端应用程序中使用 PHP 的一些高级特性,可以利用 PHP-GTK 来编写这些程序。用这种方法,还可以编写跨平台的应用程序。PHP-GTK 是 PHP 的一个扩展,在通常发布的 PHP 包中并不包含它。如果对 PHP-GTK 感兴趣,请访问其网站以获取更多信息。

PHP 能够用在所有的主流操作系统上,包括 Linux、Unix 的各种变种(包括 HP-UX、Solaris 和 OpenBSD)、Microsoft Windows、Mac OS X、RISC OS 等。今天,PHP已经支持了大多数的 web 服务器,包括 Apache、Microsoft Internet Information Server(IIS)、Personal web Server(PWS)、Netscape 以及 iPlant server、Oreilly Website Pro Server、Caudium、Xitami、OmniHTTPd 等。对于大多数的服务器,PHP 提供了一个模块;还有一些 PHP 支持 CGI 标准,使得 PHP 能够作为 CGI 处理器来工作。

综上所述,使用 PHP,可以自由地选择操作系统和 web 服务器。同时,还可以在开发时选择使用面对过程和面对对象,或者两者混和的方式来开发。尽管 PHP 4 不支持 OOP 所有的标准,但很多代码仓库和大型的应用程序(包括 PEAR 库)仅使用 OOP 代码来开发。PHP 5 弥补了 PHP 4 的这一弱点,引入了完全的对象模型。

使用 PHP,并不局限于输出 HTML。PHP 还能被用来动态输出图像、PDF 文件甚至 Flash 动画(使用 libswf 和 Ming)。还能够非常简便的输出文本,例如 XHTML 以及任何其它形式的 XML 文件。PHP 能够自动生成这些文件,在服务端开辟出一块动态内容的缓存,可以直接把它们打印出来,或者将它们存储到文件系统中。

PHP 最强大最显著的特性之一,是它支持很大范围的数据库。用户会发现利用 PHP 编写数据库支持的网页简单得难以置信。目前,PHP 支持如下数据库:

Adabas DInterBasePostgreSQL
dBaseFrontBaseSQLite
EmpressmSQLSolid
FilePro(只读)Direct MS-SQLSybase
HyperwaveMySQLVelocis
IBM DB2ODBCUnix dbm
InformixOracle(OCI7 和 OCI8) 
IngresOvrimos 

同时还有一个 DBX 扩展库使得可以自由地使用该扩展库支持的任何数据库。另外,PHP 还支持 ODBC,即 Open Database Connection Standard(开放数据库连接标准),因此可以连接任何其它支持该世界标准的数据库。

PHP 还支持利用诸如 LDAP、IMAP、SNMP、NNTP、POP3、HTTP、COM(Windows 环境)等不计其数的协议的服务。还可以开放原始网络端口,使得任何其它的协议能够协同工作。PHP 支持和所有 web 开发语言之间的 WDDX 复杂数据交换。关于相互连接,PHP 已经支持了对 Java 对象的即时连接,并且可以将他们自由的用作 PHP 对象。甚至可以用我们的 CORBA 扩展库来访问远程对象。

PHP 具有极其有效的文本处理特性,支持从 POSIX 扩展或者 Perl 正则表达式到 XML 文档解析。为了解析和访问 XML 文档,PHP 4 支持 SAX 和 DOM 标准,也可以使用 XSLT 扩展库来转换 XML 文档。PHP 5 基于强健的 libxm2 标准化了所有的 XML 扩展,并添加了 SimpleXML 和 XMLReader 支持,扩展了其在 XML 方面的功能。

如果将 PHP 用于电子商务领域,会发现其 Cybercash 支付、CyberMUT、VeriSign Payflow Pro 以及 MCVE 函数对于在线交易程序来说是非常有用的。

另外,还有很多其它有趣的扩展库。例如 mnoGoSearch 搜索引擎函数、IRC 网关函数、多种压缩工具(gzip、bz2)、日历转换、翻译……

由于在这里无法列出 PHP 所有的特性和可提供的便利,请参阅安装以及函数参考有关章节以获取关于这里提到的扩展库更多的信息。


章 2. 简明教程

本章将给出关于 PHP 的简明教程。虽然 PHP 的功能并不局限于生成动态的 web 页面,但本章的内容仅涉及于此。请查阅“PHP 能做什么”一节以获取更多信息。

使用了 PHP 的 web 页面将被和通常的 HTML 页面一样处理,可以用通常建立 HTML 页面的方法来建立和编辑它们。


需要些什么?

在本教程中,假设用户的服务器已经安装并运行了 PHP,所有以 .php 结尾的文件都将由 PHP 来处理。在大部分的服务器上,这是 PHP 的默认扩展名,不过,也请询问服务器管理员以确认。如果服务器支持 PHP,则不需要做任何事情。只用建立 .php 文件,并把它们放置到 web 目录中,服务器将神奇地自动解析这些文件。不用编译任何东西,也不用安装任何其它的工具,仅仅只需把这些使用了 PHP 的文件想象成简单的 HTML 文件,其中只不过多了一种新的标识符,在这里可以做各种各样的事情。大多数的 web 主机都提供 PHP 的支持,如果你的主机不支持,可以访问 PHP 相关链接来查找支持 PHP 的 web 主机。

假设用户希望在本地机器开发以节约宝贵的带宽。在这种情况下,需要安装一个诸如 Apache 的 web 服务器,当然还有 PHP。可能还希望安装一个数据库,例如 MySQL

可以一个个的安装它们或选择一个更简单的方法。可以参考本手册中 PHP 安装说明的相关章节(假设已经配置好了某个 web 服务器)。若在自己安装 PHP 时出现了问题,建议在安装邮件列表中询问。如果想使用更简便的方法安装 PHP,那么可以考虑获取一个预先配置的安装包,用这个安装包,只用点击几下鼠标,就可以自动地安装所有这些系统。在任何操作系统下建立有 PHP 支持的 web 服务器都十分简单,包括 MacOSX、Linux 和 Windiws。在 Linux 下,会发现 rpmfindPBone 能够在获取 RPM 时提供帮助。也可以使用 apt-get 搜索 Debian 的相关软件包。


第一个 PHP 页面

在 web 服务器根目录(DOCUMENT_ROOT)下建立一个文件名为 hello.php,然后完成如下内容:

例子 2-1. 第一个 PHP 脚本:hello.php

<html>
 <head>
  <title>PHP 测试</title>
 </head>
 <body>
 <?php echo '<p>Hello World</p>'; ?>
 </body>
</html>

在浏览器的地址栏里输入 web 服务器的 URL 访问这个文件,在结尾加上“/hello.php”。如果本地开发,那么这个 URL 一般是 http://localhost/hello.php 或者 http://127.0.0.1/hello.php,当然这取决于 web 服务器的设置。如果所有的设置都正确,那么这个文件将被 PHP 解析,浏览器中将会输出如下结果:

<html>
 <head>
  <title>PHP 测试</title>
 </head>
 <body>
 <p>Hello World</p>
 </body>
</html>

该程序非常的简单,它仅仅只是利用了 PHP 的 echo() 语句显示了 Hello World。用户一定不会满足与此。请注意该文件无需被执行或以任何方式指定。服务器会找到该文件并提供给 PHP 进行解释,因为使用了“.php”的扩展名,服务器已被配置成自动传递有着“.php”扩展名的文件给 PHP。一个普通的 HTML 文件,加上了几个特别的标签,就可以做很多非常有趣的事情!

如果试过了这个例子,但是没有得到任何输出,或者浏览器弹出了下载框,或者浏览器以文本方式显示了源文件,可能的原因是服务器还没有支持 PHP,或者没有正确配置。需要请服务器的管理员根据本手册“安装”一章的内容使得服务器支持 PHP。如果本地开发,请阅读手册有关安装的章节以确保所有的设置都正确。还要确认通过浏览器访问的 URL 确实指向了服务器上的这个文件。如果只是从本地文件系统调用这个文件,它不会被 PHP 解析。如果问题仍然存在,请通过 PHP 在线支持中的各种方式获取帮助。

以上例子的目的是为了显示 PHP 特殊标识符的格式。在这个例子中,用 <?php 来表示 PHP 标识符的起始,然后放入 PHP 语句并通过加上一个终止标识符 ?> 来退出 PHP 模式。可以根据自己的需要在 HTML 文件中像这样开启或关闭 PHP 模式。请参阅手册中“PHP 基本语法”以获取更多信息。

关于文本编辑器: 有很多文本编辑器以及集成开发环境(IDE)可以被用来建立、编辑和管理 PHP 文件。这些工具中的一部分被列在 PHP 编辑器列表中。如果希望推荐其它的编辑器,请访问以上页面,并要求该页面的维护者将你推荐的编辑器加入到该列表中。使用支持语法高亮功能的编辑器会给开发带来很多帮助。

关于文字处理器: 诸如 StarOffice Writer、Microsoft Word 和 Abiword 的文字处理器不适合用来编辑 PHP 程序。如果希望用以上这些工具的某一种来处理脚本,必须保证将结果存成了纯文本格式,否则 PHP 将无法读取并运行这些脚本。

关于 Windows 记事本: 如果使用 Windows 记事本来编写 PHP 脚本,需要注意在保存文件时,文件的后缀名应该为 .php(记事本将自动在文件名后面加上 .txt 后缀,除非采取以下措施之一来避免这种情况)。当保存文件时,系统会让你指定文件的文件名,这时请将文件名加上引号(例如 "hello.php")。或者,也可以点击“保存”对话框中的“保存类型”下拉菜单,并将设置改为“所有文件”。这样在输入文件名的时候就不用加引号了。

现在已经成功建立了一个简单的 PHP 脚本。还可以建立一个最著名的 PHP 脚本。调用函数 phpinfo(),将会看到很多有关自己系统有用的信息,以及预定义变量、已经加载的 PHP 模块和配置信息。请花一些时间来查看这些重要的信息。

例子 2-2. 从 PHP 获取系统信息

<?php phpinfo(); ?>


实用的脚本

现在来编写一些更实用的脚本,比如检查浏览页面的访问者在用什么浏览器。要达到这个目的,需要检查用户的 agent 字符串,它是浏览器发送的 HTTP 请求的一部分。该信息被存储在一个变量中。在 PHP 中,变量总是以一个美元符开头。我们现在感兴趣的变量是 $_SERVER['HTTP_USER_AGENT']

注: $_SERVER 是一个特殊的 PHP 保留变量,它包含了 web 服务器提供的所有信息,被称为自动全局变量(或“超全局变量”)。请查阅本手册“超全局变量”中的有关内容以获取更多信息。这些特殊的变量是在 PHP 4.1.0 版本引入的。在这之前使用 $HTTP_*_VARS 数组,如 $HTTP_SERVER_VARS。尽管现在已经不用了,但它们在新版本中仍然存在(参见“旧代码”一节中的注解)。

要显示该变量,只需简单地进行如下操作:

例子 2-3. 打印一个变量(数组元素)

<?php echo $_SERVER['HTTP_USER_AGENT']; ?>

该脚本的输出可能是:

Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)

PHP 有很多种不同类型的变量。在以上例子中我们打印了一个数组的单元。数组是一类非常有用的变量。

$_SERVER 只是 PHP 自动全局化的变量之一。可以查阅“保留变量”一节来查看这些变量的列表,或者也可以通过上节例子中 phpinfo() 函数的输出来查看。

可以在一个 PHP 标识中加入多个 PHP 语句,也可以建立一个代码块来做比简单的 echo 更多的事情。例如,如果需要识别 Internet Explorer,可以进行如下操作:

例子 2-4. 流程控制函数的使用

<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
    echo '正在使用 Internet Explorer。<br />';
}
?>

该脚本的输出可能是:

正在使用 Internet Explorer。<br />

这里要介绍一些新的原理。上面用了一个 if 语句。如果用户对 C 语言的基本语法比较熟悉,则应该对此很熟悉,否则,可能需要拿起任何一本 PHP 介绍性的书籍并阅读前面的两三个章节,或者也可以阅读本手册的“语言参考”一章。可以在 http://www.php.net/books.php 找到有关 PHP 的书籍的列表。

需要介绍的第二个原理,是对 strpos() 函数的调用。strpos() 是 PHP 的一个内置函数,其功能是在一个字符串中搜索另外一个字符串。例如我们现在需要在 $_SERVER['HTTP_USER_AGENT'](即所谓的 haystack)变量中寻找 'MSIE'。如果在这个 haystack 中该字符串(即所谓的 needle)被找到,则函数返回 needle 在 haystack 中相对开头的位置;如果没有,则返回 FALSE。如果该函数没有返回 FALSE,则 if 会将条件判断为 TRUE 并运行其花括号 {} 内的代码;否则,则不运行这些代码。可以自己尝试利用 ifelse 以及其它的函数,例如 strtoupper()strlen(),来建立类似的脚本。在本手册中相关的页面也包含有范例。如果对如何使用函数不是很确定,可以阅读手册中有关“如何阅读函数定义”和“函数”的有关章节。

以下我们进一步显示如何进出 PHP 模式,甚至是在一个 PHP 代码块的中间:

例子 2-5. 混和 HTML 和 PHP 模式

<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
?>
<h3>strpos() 肯定没有返回假 (FALSE)</h3>
<p>正在使用 Internet Explorer</p>
<?php
} else {
?>
<h3>strpos() 肯定返回假 (FALSE)</h3>
<center><b>没有使用 Internet Explorer</b></center>
<?php
}
?>

该脚本的输出可能是:

<h3>strpos() 肯定没有返回假 (FALSE)</h3>
<p>正在使用 Internet Explorer</p>

和以上我们用一个 PHP 的 echo 语句来输出不同的是,我们跳出了 PHP 模式来直接写 HTML 代码。这里很值得注意的一点是,对于这两种情况而言,脚本的逻辑效率是相同的。在判断了 strpos() 函数的返回值是 TRUE 或是 FALSE,也就是判断了字符串 'MSIE' 是否被找到之后,最终只有一个 HTML 块被发送给浏览者。


处理表单

PHP 一个很有用的特点体现在它处理 PHP 表单的方式。需要理解的非常重要的原理,是表单的任何元素都在 PHP 脚本中自动生效。请参阅本手册中“PHP 的外部变量”以获取关于在 PHP 中使用表单的详细信息及范例。以下是 HTML 表单的范例:

例子 2-6. 一个简单的 HTML 表单

<form action="action.php" method="post">
 <p>姓名: <input type="text" name="name" /></p>
 <p>年龄: <input type="text" name="age" /></p>
 <p><input type="submit" /></p>
</form>

该表单中并没有什么特殊的地方,其中没有使用任何特殊的标识符。当用户填写了该表单并点击了提交按钮,页面 action.php 将被调用。在该文件中,可以加入如下内容:

例子 2-7. 打印来自表单的数据

你好,<?php echo $_POST['name']; ?>。
你 <?php echo $_POST['age']; ?> 岁了。

该脚本的输出可能是:

你好,Joe。你 22 岁了。

该脚本进行的工作应该已经很明显了,这儿并没有其它更复杂的内容。PHP 将自动设置 $_POST['name']$_POST['age'] 变量。在这之前我们使用了自动全局变量 $_SERVER,现在我们引入了自动全局变量 $_POST,它包含了所有的 POST 数据。请注意我们的表单提交数据的方法(method)。如果使用了 GET 方法,那么表单中的信息将被储存到自动全局变量 $_GET 中。如果并不关心请求数据的来源,也可以用自动全局变量 $_REQUEST,它包含了所有 GET、POST、COOKIE 和 FILE 的数据。请参阅 import_request_variables() 函数。

也可以在 PHP 中处理 XForms 的输入,尽管可能更喜欢使用长久以来支持良好的 HTML 表单。XForms 目前还不适合初学者使用,但是用户可能对它感兴趣。手册中在“特点”一章有一节对如何处理从 XForum 接收到的数据进行了简短的介绍。


在新版本的 PHP 中使用旧的 PHP 代码

现在,PHP 已经发展成为一种流行的脚本语言,可以在很多公共的资源里找到可以在自己的脚本中重新利用的代码。PHP 语言的开发者为向下兼容性下了很多功夫,因此在新版本的 PHP 下,老版本的代码应该可以在不作任何改动的情况下(理想地)运行。不过实际上,还是必须对老的代码做一些改动。

有可能影响到老版本的代码的最重要的两点改动分别是:

  • 取消了旧的 $HTTP_*_VARS 数组(在函数或者方法中原本是全局变量)。PHP 4.1.0 版本引入了如下自动全局数组变量$_GET$_POST$_COOKIE$_SERVER$_FILE$_ENV$_REQUEST 以及 $_SESSION。老的 $HTTP_*_VARS 数组,诸如 $HTTP_POST_VARS 等,从 PHP 3 就已经开始使用,它们仍然存在。自 PHP 5.0.0 起,长格式的 PHP 预定义变量可以通过设置 register_long_arrays 来屏蔽。

  • 外部变量不再被默认注册为全局变量。也就是说,从 PHP 4.2.0 版开始,php.ini 中的设置选项 register_globals 默认值变成了 off。建议用以上提到的自动全局数组变量来访问这些值。但可能老的脚本、书籍以及教程都可能建立在该设置为 on 的基础上。如果该选项被设置为 on,则可以在 URL http://www.example.com/foo.php?id=42 中直接使用变量 $id。但不管被设置为 on 还是 off,$_GET['id'] 一直有效。

如果希望了解关于这些改动的细节,请参阅“预定义变量”一章以及其中的连接。


下一步做什么?

用现在掌握的知识,应该能够理解本手册中的大部分内容以及其中各式各样的脚本范例。在 php.net 网站的连接区 http://www.php.net/links.php 能购获得其它更多的范例。

请查阅 PHP Conference 资料网站 http://conf.php.net/http://talks.php.net/ 以观看更多幻灯片,这些幻灯片展示了许多 PHP 其它的功能。


章 3. 安装前需要考虑的事项

安装前,首先需要知道想用 PHP 来做什么。PHP 主要用在三个领域,分别在“PHP 能做什么”一节中进行了描述:

  • 服务端脚本

  • 命令行脚本

  • 编写桌面应用程序

在通常情况下,需要三样东西:PHP 自身、一个 web 服务器和一个 web 浏览器。可能已经有了一个 web 浏览器,并且根据操作系统的配置,也很可能已经有了一个 web 服务器(例如 Linux 和 MacOS 下的 Apache;Windows 下的 IIS)。也许在某个公司租用了 web 空间,这样,自己无需设置任何东西,仅需要编写 PHP 脚本,并上传到租用的空间中,然后在浏览器中查看结果。

若要自己配置服务器和 PHP,有两个方法将 PHP 连接到服务器上。对于很多服务器,PHP 均有一个直接的模块接口(也叫做 SAPI)。这些服务器包括 Apache、Microsoft Internet Information Server、Netscape 和 iPlanet 等服务器。其它很多服务器支持 ISAPI,即微软的模块接口(OmniHTTPd 就是个例子)。如果 PHP 不能作为模块支持 web 服务器,总是可以将其作为 CGI 或 FastCGI 处理器来使用。这意味着可以使用 PHP 的 CGI 可执行程序来处理所有服务器上的 PHP 文件请求。

如果对 PHP 命令行脚本感兴趣(例如在离线状态下,根据传递给脚本的参数,自动生成一些图片,或处理一些文本文件),总是需要命令行可执行程序。更多信息可以参考 PHP 的命令行模式。如果是这种情况,不需要服务器和浏览器。

还可以用 PHP 的 PHP-GTK 扩展来编写桌面图形界面应用程序。这与编写 web 页面完全不同,因为无需输出任何 HTML,而要管理窗口和窗口中的对象。关于 PHP-GTK 的更多信息,请访问专门为该扩展建立的网站。PHP-GTK 没有包含在官方发布的 PHP 中。

现在,本节开始说明如何在 Unix 和 Windows 的 web 服务器中配置服务器模块接口和 CGI 可执行程序。也将在下面几节中了解到有关命令行可执行程序安装的信息。

PHP 源代码包和二进制包可以在 http://www.php.net/downloads.php 找到。建议选择一个最近的镜象服务器下载。


章 4. Unix 系统下的安装

本节将指导如何在 Unix 系统下安装和配置 PHP。在开始安装之前,请务必研究自己使用的系统和 web 服务器的相关章节。

安装前需要考虑的事项一节提到,在本节主要以 web 为中心介绍 PHP 的设置。不过本节也会覆盖一些 PHP 命令行用法的设置方法。

在 Unix 平台下安装 PHP 有几种方法:使用配置和编译过程,或是使用各种预编译的包。本文主要针对配置和编译 PHP 的过程。很多 Unix 类系统都有包安装系统,可以用它来设置一个有着标准配置的 PHP。但是若需要与标准配置不同的功能(例如一个安全服务器,或者不同的数据库驱动扩展模块),可能需要编译 PHP 和/或 web 服务器。如果不熟悉编译软件,可以考虑搜索一下是否有人已经编译了包含所需要功能的预编译包。

编译所需的知识和软件:

  • 基础的 Unix 技能(有能力操作“make”和一种 C 语言编译器)

  • 一个 ANSI C 语言编译器

  • flex:版本 2.5.4

  • bison:版本 1.28(推荐)、1.35 或 1.75

  • 一个 web 服务器

  • 模块特别需要的组件(例如 gd、pdf 库等)

PHP 初始的配置和安装过程被 configure 脚本中一系列命令行选项控制。可以通过 ./configure --help 命令了解 PHP 所有可用的编译选项及简短解释。本手册是分开对这些选项编写文档的。可在附录中找到核心配置选项,而扩展模块特定的配置选项分别在其函数参考页面中描述。

配置好 PHP 后,便可以开始编译模块和/或可执行文件。make 命令用来做这一工作。如果该命令执行失败而找不到原因,请参考安装问题一节。


Unix 系统下的 Apache 1.3.x

本节包括在 Unix 平台的 Apache 下安装 PHP 的说明和提示。我们在另外的页面也有 Apache 2 的安装和说明

可以从核心配置选项列表以及位于手册对应部分的特定扩展配置选项中选择参数并在安装步骤第 10 步将它们添加到 configure 命令中。版本号在这里被省略了以保证此说明的正确性。需要将这里的“xxx”替换为自己使用的文件的正确值。

例子 4-1. PHP 的 Apache 共享模块版本安装说明

1.  gunzip apache_xxx.tar.gz
2.  tar -xvf apache_xxx.tar
3.  gunzip php-xxx.tar.gz
4.  tar -xvf php-xxx.tar
5.  cd apache_xxx
6.  ./configure --prefix=/www --enable-module=so
7.  make
8.  make install
9.  cd ../php-xxx
10. 现在,配置 PHP。这是定制 PHP 的不同选项的时候,例如要加载哪些扩展库。使用
      ./configure --help
    来列出可用的选项。在下面的示例中只是简单地配置 Apache 1 和 MySQL 支持。
    用户的 apxs 的路径可能和此示例中的不同。
      ./configure --with-mysql --with-apxs=/www/bin/apxs
11. make
12. make install
    如果在安装之后决定修改配置选项,那么只需重复以上最后三步。只须重新启动
    Apache 就可以使新模块生效。不需要重新编译 Apache。注意除非特别指出,
    “make install”总是会安装 PEAR,各种 PHP 工具例如 phpize,PHP CLI 以及其它。
13. 建立 php.ini 文件。
      cp php.ini-dist /usr/local/lib/php.ini
    可以编辑 php.ini 来设置 PHP 选项。如果想把 php.ini 放在其它目录,在第
    10 步加上以下选项:
      --with-config-file-path=/path
    如果选择了 php.ini-recommended,确保阅读一下其中的变更说明,因为这些会
    影响到 PHP 的行为。
14. 编辑 httpd.conf 来加载 PHP 模块。在 LoadModule 语句右边的路径必须指向系统中
    PHP 模块所在的路径。上面的 make install 步骤可能已经添加了,但还是检查确认一下。
    对 PHP 4:
      LoadModule php4_module        libexec/libphp4.so
    对 PHP 5:
      LoadModule php5_module        libexec/libphp5.so
15. 在 httpd.conf 中加入 AddModule 部分,在 ClearModuleList 下面的某处,加上这一句:
    对 PHP 4:
      AddModule mod_php4.c
    对 PHP 5:
      AddModule mod_php5.c
16. 告诉 Apache 将哪些后缀作为 PHP 解析。例如,让 Apache 把 .php 后缀的文件解析为
    PHP。可以将任何后缀的文件解析为 PHP,只要在以下语句中加入并用空格分开。这里以
    添加一个 .phtml 来示例。
      AddType application/x-httpd-php .php .phtml
    为了将 .phps 作为 PHP 的源文件进行语法高亮显示,还可以加上:
      AddType application/x-httpd-php-source .phps
17. 用通常的过程启动 Apache(必须完全停止 Apache 再重新启动,而不是用 HUP 或者
    USR1 信号使 Apache 重新加载)。

也可以将 PHP 作为静态对象来安装:

例子 4-2. PHP 的 Apache 静态模块版本安装说明

1.  gunzip -c apache_1.3.x.tar.gz | tar xf -
2.  cd apache_1.3.x
3.  ./configure
4.  cd ..

5.  gunzip -c php-4.x.y.tar.gz | tar xf -
6.  cd php-4.x.y
7.  ./configure --with-mysql --with-apache=../apache_1.3.x
8.  make
9.  make install

10. cd ../apache_1.3.x

11. ./configure --prefix=/www --activate-module=src/modules/php4/libphp4.a
    (上面一行是正确的!是的,我们知道 libphp4.a 在目前不存在。它是不应该存在的,
    它将被创建。)

12. make
    (现在应该有一个 httpd 二进制文件,可以将它复制到 Apache bin 目录。如果这是
    第一次安装,还要“make install”。)

13. cd ../php-4.x.y
14. cp php.ini-dist /usr/local/lib/php.ini

15. 可以编辑 /usr/local/lib/php.ini 文件以设置 PHP 选项。编辑 httpd.conf 或
    srm.conf 文件,添加:
    AddType application/x-httpd-php .php

根据 Unix 系统和 Apache 安装方法的不同,有很多方法停止和重启动 Apache。以下是一些不同的 Apache/UNIX 下重启动 Apache 的典型命令。需要把 /path/to/ 替换成自己系统上的确切路径。

例子 4-3. 重启动 Apache 的示例命令

1. 在一些 Linux 和 SysV 的变种下:
/etc/rc.d/init.d/httpd restart

2. 使用 apachectl 脚本:
/path/to/apachectl stop
/path/to/apachectl start

3. httpdctl 和 httpsdctl(使用了 OpenSSL),类似 apachectl:
/path/to/httpsdctl stop
/path/to/httpsdctl start

4. 使用了 mod_ssl,或其他 SSL 服务器,可能需要手工重启动:
/path/to/apachectl stop
/path/to/apachectl startssl

apachectl 和 http(s)dctl 程序所在的路径在不同系统中通常不一样。如果系统中有 locate 或者 whereis 或者 which 命令,那么可以帮助找到这些控制程序。

编译 PHP 和 Apache 的不同例子还有:

./configure --with-apxs --with-pgsql

此配置将生成在 Apache 的 httpd.conf 文件中用 LoadModule 加载的 libphp4.so 共享库。而 PostgreSQL 支持将嵌入到 libphp4.so 库中。

./configure --with-apxs --with-pgsql=shared

此配置将生成 Apache 的 libphp4.so 共享库,并且还生成 pgsql.so 共享库,可以在 php.ini 文件中用 extension 指令加载,或者在 PHP 脚本中用 dl() 函数明确地加载。

./configure --with-apache=/path/to/apache_source --with-pgsql

此配置将生成 libmodphp4.a 库,mod_php4.c 和一些相关的文件并且拷贝到 Apache 源程序目录中的 src/modules/php4 目录下。然后用 --activate-module=src/modules/php4/libphp4.a 编译 Apache,Apache 编译系统会生成 libphp4.a 并且将其静态地连接到 httpd 程序中。PostgreSQL 支持也直接包括在这个 httpd 程序中了,因此最终结果是单一的一个包括了所有 Apache 和 PHP 支持的 httpd 可执行文件。

./configure --with-apache=/path/to/apache_source --with-pgsql=shared

此配置和上面一样――除了没有在最后的 httpd 可执行文件中包括 PostgreSQL 的支持以及生成了一个 pgsql.so 共享库以外。该共享库可以在 php.ini 文件中或者用 dl() 函数加载。

当选择不同的方法编译 PHP 时,需要考虑每种方法的优势和缺点。用共享对象方式编译 PHP 意味着可以单独编译 Apache,并且不用在添加或修改了 PHP 的时候重新编译所有程序。用内置方法编译 PHP(静态方式)意味着 PHP 可以加载和运行得更快。更多信息见 Apache 的 DSO 支持页面

注: Apache 默认的 httpd.conf 文件中目前包括类似如下的内容:

User nobody
Group "#-1"

除非把它修改成“Group nogroup”或者其它类似的(“Group daemon”也很通用),PHP 将不能打开文件。

注: 确认在使用 --with-apxs=/path/to/apxs 时指向 Apache 安装后的目录中的 apxs。绝对不能用 Apache 源程序中的 apxs 而要用安装后的 apxs。


Unix 系统下的 Apache 2.0

本节包括在 Unix 平台的 Apache 2.0 下安装 PHP 的说明和提示。

警告

不推荐将线程化 MPM 用于实际运作的 Apache 2 环境中去。用 prefork MPM 替代,或者用 Apache 1。其原因见 FAQ 中的使用线程化 MPM 的 Apache2

推荐阅读 Apache 文档,了解一下 Apache 2.0 服务器。

PHP 和 Apache 2.0.x 兼容性注意事项: 已知下列版本的 PHP 可以工作于最近版本的 Apache 2.0.x 之下:

以上版本的 PHP 与 Apache 2.0.40 或更高版本兼容。

Apache 2.0 SAPI 支持自 PHP 4.2.0 起。PHP 4.2.3 可工作于 2.0.39,不要用任何其它版本的 Apache 与 PHP 4.2.3 配合。不过推荐的设置是用 PHP 4.3.0 或更高版本与最新版的 Apache2 配合使用。

所有提及的 PHP 版本仍然能工作于 Apache 1.3.x 之下。

下载最新版本的 Apache 2.0,并且根据上文选择合适版本的 PHP 下载。本向导仅包含最基础的内容,只能让 Apache 2.0 和 PHP 能够正常工作。更多信息请阅读 Apache 文档。这里省略所有的版本号,以保证本文的正确性。需要将本文的“NN”替换为相应的版本号。

例子 4-4. 安装说明(Apache 2 共享模块版本)

1.  gzip -d httpd-2_0_NN.tar.gz
2.  tar xvf httpd-2_0_NN.tar
3.  gunzip php-NN.tar.gz
4.  tar -xvf php-NN.tar
5.  cd httpd-2_0_NN
6.  ./configure --enable-so
7.  make
8.  make install

    现在已经将 Apache 2.0.NN 安装在 /usr/local/apache。本安装支持可装载模块
    和标准的 MPM prefork。之后,可以使用如下命令启动 Apache 服务器:
    /usr/local/apache2/bin/apachectl start
    如果成功,可以停止 Apache 服务器并继续安装 PHP:
    /usr/local/apache2/bin/apachectl stop.

9.  cd ../php4-NN

10. 现在需要配置 PHP。在这里可以用各种各样的参数来自定义PHP,例如启动哪些
    扩展功能包的支持等。用 ./configure --help 命令可以列出当前可用的所有参
    数。在此例中,将给出一个在有 MySQL 支持的 Apache 2 上进行配置的范例。
    用户本地的 apxs 的路径可能会不同,事实上,在用户的系统中,它可能被命名为
    apxs2。

    ./configure --with-apxs2=/usr/local/apache2/bin/apxs

11. make
12. make install

    如果决定在安装后改变配置选项,只需重复最后的三步,然后需要重新启动 Apache
    使新模块生效。无需重新编译。

    请注意,除非明确有提示,否则“make install”命令将安装 PEAR、各种 PHP 工具
    诸如 phpize,安装 PHP CLI 等等。

13. 配置 php.ini

    cp php.ini-dist /usr/local/lib/php.ini

    可以编辑 php.ini 文件以修改 PHP 的选项。如果想要把此文件放到另外的位置,
    需要在步骤 10 添加 --with-config-file-path=/path 选项。

    如果选择 php.ini -recommended,请务必阅读其中的变更的列表,它们将影响
    PHP 的执行。

14. 编辑 httpd.conf 文件以调用 PHP 模块。LoadMolude 表达式右边的路径必须指向
    系统中的 PHP。以上的 make install 命令可能已经完成了这些,但务必要检查。

    对于 PHP 4:
       LoadModule php4_module modules/libphp4.so

    对于 PHP 5:
       LoadModule php5_module modules/libphp5.so

15. 告知 Apache 将特定的扩展名解析成 PHP,例如,让 Apache 将扩展名 .php
    解析成 PHP。可以将任何扩展名指定为 PHP,只需添加它们,每一个用空格分隔。
    例如,要添加 .phtml:

    AddType application/x-httpd-php .php .phtml

    通常还将 .phps 扩展名设置成显示高亮的 PHP 源文件,可以这样来完成:

    AddType application/x-httpd-php-source .phps

16. 启动 Apache 服务器:
   /usr/local/apache2/bin/apachectl start

按照上面的步骤便可以使 Apache 2.0 将 PHP 作为 SAPI 模块了。当然 Apache 和 PHP 都还有很多配置选项,可以在相应的源代码目录中使用 ./configure --help 获得更多信息。假如要编译一个多线程版本的 Apache 2.0,必须覆盖标准的 MPM-Module prefork,或者 worker 或者 perchild。要这样,需要在上面的第 6 步使用 --with-mpm=worker 或者 --with-mpm=perchild 选项。之前需要了解自己在做什么。更多信息请参考 Apache 文档中关于 MPM-Modules 的部分。

注: 如果要使用内容协商(content negotiation)机制,请阅读 Apache MultiViews 常见问题

注: 要编译多线程版本的 Apache,系统必须支持多线程。这也意味着需要将 PHP 编译为正处在试验阶段的 Zend Thread Safety(ZTS),因此并不是所有的扩展都可以使用了。推荐编译 Apache 使用标准的 prefork MPM-Module。


Caudium 服务器

PHP 4 可以被编译为 Caudium web 服务器的一个 Pike 模块。注意 PHP 3 中不支持。请参考下面的安装说明以将 PHP 4 安装到 Caudium 服务器中。

例子 4-5. Caudium 安装指南

1.  在安装 PHP 4 之前请确认已经正确安装了 Caudium 服务器。
    要想使 PHP 4 正确的工作,还需要 Pike 7.0.268 或更高版本。
    为了方便起见,我们假定 Caudium 安装在 /opt/caudium/server/ 中。
2.  进入目录 php-x.y.z (x.y.z 是 PHP 的版本号)。
3.  ./configure --with-caudium=/opt/caudium/server
4.  make
5.  make install
6.  如果 Caudium 正在运行请重新启动它。
7.  登录图形配置界面,进入需要 PHP 4 支持的虚拟服务器。
8.  点击 Add Module 之后点击 locate,然后添加 PHP 4 脚本支持模块。
9.  如果出现“PHP 4 interpreter isn't available”的错误提示,
    请重新启动 web 服务器。如果还是不行,请检查
    /opt/caudium/logs/debug/default.1 中是否有与
    <filename>PHP4.so</filename> 文件相关的错误。也要查看
    <filename>caudium/server/lib/[pike-version]/PHP4.so</filename>
    这个文件是否存在。
10. 如果需要,请配置 PHP 脚本支持模块。

当然可以将各种 PHP 4 的扩展模块编译到 Caudium 服务器中。请参考扩展库各自配置选项的说明。

注: 当编译 PHP 4 的 MySQL 的支持时,必须确认使用了正常的 MySQL 客户端代码。否则如果 Pike 已经支持 MySQL,就会产生冲突。应该在编译的时候使用 --with-mysql 选项指定 MySQL 的安装目录。


fhttpd 服务器

要将 PHP 作为 fhttpd 的模块来编译,在提示“Build as an fhttpd module?”时,回答“yes”(用 --with-fhttpd=DIR 来配置)并且指定 fhttpd 源代码的基本目录。默认的目录是 /usr/local/src/fhttpd。如果正在使用 fhttpd 服务器,将 PHP 编译成模块方式将提供更好的性能,更多的可控性以及远程执行能力。

注: PHP 4.3.0 以后的版本已经不再提供对 fhttpd 的支持。


Sun Solaris 上的 Sun、iPlanet 和 Netscape 服务器

本节包含了在 Sun Solaris 平台的 Sun Java System web Server、Sun ONE web Server、iPlanet 和 Netscape 下安装 PHP 的说明和提示。

从 PHP 4.3.3 起,可以使用基于 NSAPI 模块 PHP 脚本来生成自定义目录列表和错误页面。更多与 Apache 兼容的功能也可以使用。要了解如何在当前的 web 服务器中支持此功能,请阅读关于子请求(subrequests)的注释

可以在下面的链接中了解更多关于在 Netscape Enterprise Server(NES)中设置 PHP 的信息:http://benoit.noss.free.fr/php/install-php4.html

要在 Sun JSWS/Sun ONE WS/iPlanet/Netscape web 服务器中编译 PHP,请为 --with-nsapi=[DIR] 输入合适的安装目录。默认的目录通常是 /opt/netscape/suitespot/。还可以阅读 /php-xxx-version/sapi/nsapi/nsapi-readme.txt

  1. http://www.sunfreeware.com/ 或其它下载站点安装下面的软件包:

    autoconf-2.13
    automake-1.4
    bison-1_25-sol26-sparc-local
    flex-2_5_4a-sol26-sparc-local
    gcc-2_95_2-sol26-sparc-local
    gzip-1.2.4-sol26-sparc-local
    m4-1_4-sol26-sparc-local
    make-3_76_1-sol26-sparc-local
    mysql-3.23.24-beta(如果想要 mysql 支持)
    perl-5_005_03-sol26-sparc-local
    tar-1.13 (GNU tar)

  2. 请确认 PATH 变量包含适当的目录 PATH=.:/usr/local/bin:/usr/sbin:/usr/bin:/usr/ccs/bin,并使用 export PATH 命令将其导出为环境变量。

  3. gunzip php-x.x.x.tar.gz(如果使用 .gz 版本,否则跳到 4)

  4. tar xvf php-x.x.x.tar

  5. 进入 PHP 解压缩后的目录:cd ../php-x.x.x

  6. 在下面的步骤中,请确认 Netscape 服务器安装在 /opt/netscape/suitespot/ 目录中。否则,将下面命令中的该路径修改为正确的路径并运行:
    ./configure --with-mysql=/usr/local/mysql \
    --with-nsapi=/opt/netscape/suitespot/ \
    --enable-libgcc

  7. 运行 make,然后运行 make install

在执行了基础的安装并阅读相应的 Readme 文件后,还需要执行一些额外的配置步骤。

Sun/iPlanet/Netscape 的配置说明. 首先需要为 LD_LIBRARY_PATH 环境变量添加一些路径,以便服务器找到所需的共享库。可以使用 web 服务器的启动脚本很好的完成这一工作。启动脚本通常位于:/path/to/server/https-servername/start。或许需要编辑其配置文件,它位于:/path/to/server/https-servername/config/

  1. 添加下面一行到 mime.types(可以在管理服务器中添加):
    type=magnus-internal/x-httpd-php exts=php

  2. 编辑 magnus.conf( 若服务器 >= 6)或 obj.conf(若服务器 < 6)并添加下述内容。shlib 的值根据系统的配置会有所不同。它可能类似于 /opt/netscape/suitespot/bin/libphp4.so。应该在 mime types init 后添加如下两行内容:
    Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="/opt/netscape/suitespot/bin/libphp4.so"
    Init fn="php4_init" LateInit="yes" errorString="Failed to initialize PHP!" [php_ini="/path/to/php.ini"]
    (PHP >= 4.3.3)php_ini 参数是可选的。但是若使用它,便可以将 php.ini 放到 web 服务器的配置目录中去。

  3. obj.conf 中配置默认对象(对于虚拟服务器的类 [版本 6.0+] 是在 vserver.obj.conf 中):
    <Object name="default">
    .
    .
    .
    .#注意 下面一行添加在所有“ObjectType”之后,所有“AddLog”之前
    Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...]
    .
    .
    </Object>
    (PHP >= 4.3.3)作为附加的参数,可以在 php.ini 中添加一些特别的配置选项。例如可以设置 docroot="/path/to/docroot" 指向 php4_execute 被调用的上下文(context)。对于布尔 ini 键值,请使用 0/1 作为其值,而不是 "On"、"Off" 等(它们是无效的),例如,使用 zlib.output_compression=1,而不应使用 zlib.output_compression="On"

  4. 本步骤仅在需要配置一个由 PHP 脚本组成的目录时由必要执行(类似于一个 cgi-bin 目录):
    <Object name="x-httpd-php">
    ObjectType fn="force-type" type="magnus-internal/x-httpd-php"
    Service fn=php4_execute [inikey=value inikey=value ...]
    </Object>
    之后,可以在管理服务器中配置一个目录,分配给它 x-httpd-php 风格(style)。这样在该目录中的所有文件都会被当作 PHP 来执行。这样就能很方便的将 PHP 文件更名为 .html 以隐藏 PHP。

  5. 认证的设置:PHP 认证不能与其它任何类型的认证一起工作。所有认证被传递到 PHP 脚本。要为整个服务器配置 PHP 认证,在默认对象中添加下面一行:
    <Object name="default">
    AuthTrans fn=php4_auth_trans
    .
    .
    .
    </Object>

  6. 要在单一目录使用 PHP 认证,添加如下内容:
    <Object ppath="d:\path\to\authenticated\dir\*">
    AuthTrans fn=php4_auth_trans
    </Object>

注: PHP 使用的堆栈大小取决于 web 服务器的配置。如果运行很大的 PHP 脚本时程序崩溃,推荐在 Admin Server(在“MAGNUS EDITOR”一节)中增大此项。


CGI 环境和对 php.ini 推荐的修改

当编写 PHP 脚本时,应特别注意 Sun JSWS/Sun ONE WS/iPlanet/Netscape 是一个多线程 web 服务器。因此,所有请求都运行在相同的进程空间(Web 服务器自己的空间),该空间仅有一套环境变量。如果想获得 CGI 变量,例如 PATH_INFOHTTP_HOST 等,使用原有的 PHP 3.x 的方式(getenv()),或使用类似的方式(注册全局变量到环境变量, $_ENV),都是不可行的。只能获得运行中的 web 服务器的环境变量,而不能获得任何有效的 CGI 变量!

注: 为什么在环境中存在(无效的)CGI 变量?

答:这是因为从管理服务器中启动 web 服务器进程时,运行了 web 服务器的启动脚本,它事实上是一个 CGI 脚本(管理服务器中的一个 CGI 脚本!)。这便是为什么启动的 web 服务器包含一些 CGI 变量。可以尝试不从管理服务器启动 web 服务器,用 root 用户登录使用命令行手动启动它,会发现这些 CGI 形式的变量不复存在。

要在 PHP 4.x 中正确获得 CGI 变量,仅需修改脚本使用超级全局变量 $_SERVER。如果老脚本中使用了 $HTTP_HOST 等变量,应该在 php.ini 中打开 register_globals,并且要修改变量顺序(注意:从中删除 "E",因为不需要这里的环境变量):
variables_order = "GPCS"
register_globals = On


错误页面及自造目录列表的特别使用 (PHP >= 4.3.3)

可以使用 PHP 为 "404 Not Found" 或类似的错误代码生成错误页面。将下面几行添加到 obj.conf 中以覆盖默认的错误页面:
Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...]
XXX 是 HTTP 错误代码。请删除任何可能干扰 Error 设置的指令。如果想为所有可能存在的错误提供一个页面,则将 code 参数删除。脚本可以通过 $_SERVER['ERROR_TYPE'] 获得 HTTP 状态代码。

另一种可能是生成自造目录列表。只要创建一个 PHP 脚本,来显示目录列表 并在 obj.conf 中为 type="magnus-internal/directory" 将相应的默认 Service 行替换为:
Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...]
错误和目录列表页面中,原始的 URI 和翻译的 URI 均被分别储存在 $_SERVER['PATH_INFO']$_SERVER['PATH_TRANSLATED'] 变量中。


关于 nsapi_virtual() 和子请求的注意事项(PHP >= 4.3.3)

NSAPI 模块现在支持 nsapi_virtual() 函数(别名:virtual()),用来在 web 服务器上创建子请求(subrequests)和在 web 页面插入请求的结果。此函数使用了一些 NSAPI 中还没有文档说明的函数。在 Unix 下,该模块自动查找需要的函数,若它们存在则使用它们。若不存在,函数 nsapi_virtual() 被禁用。

注: 但是要注意,对 nsapi_virtual() 的支持是试验性质的!


CGI 和命令行设置

默认为将 PHP 编译为 CGI 程序。这将建立一个命令行解释器,可用于 CGI 处理或非 web 相关的 PHP 脚本。如果用户运行着一个 PHP 模块支持的 web 服务器,那通常为性能考虑应该使用模块方式。不过,CGI 版可以使 Apache 用户用不同的用户 ID 运行不同的 PHP 页面。

警告

如果使用 CGI 方式安装,则服务器对于某些可能的攻击是开放的。请阅读 CGI 安全一章以学习如何防御这些攻击。

自 PHP 4.3.0 起,PHP 有了一些重要的新增功能。又有了一个新的 SAPI 称为 CLI,和 CGI 程序同名。根据配置选项它安装在 {PREFIX}/bin/php,并在手册中 PHP 的命令行模式一章中有详细说明。更多细节请阅读该章节。


测试

如果将 PHP 编译为 CGI 程序,可以通过键入 make test 来测试你的编译。测试一下编译永远是个好主意。这样就可以在你的平台上及早捕捉到 PHP 的问题而不是以后再费力的解决。


基准测试

如果将 PHP 3 编译为 CGI 程序,可以通过键入 make bench 来进行一下性能的基准测试。注意如果默认打开了安全模式,则超过 30 秒的允许范围测试可能不能完成。这是因为 set_time_limit() 不能用于安全模式。用 max_execution_time 配置选项来为你自己的脚本控制此时间限制。make bench 会忽略配置文件

注: make bench 仅能用于 PHP 3。


使用变量

某些服务器提供的环境变量没有定义在当前的 CGI/1.1 标准中。只有下列变量定义在其中:AUTH_TYPECONTENT_LENGTHCONTENT_TYPEGATEWAY_INTERFACEPATH_INFOPATH_TRANSLATEDQUERY_STRINGREMOTE_ADDRREMOTE_HOSTREMOTE_IDENTREMOTE_USERREQUEST_METHODSCRIPT_NAMESERVER_NAMESERVER_PORTSERVER_PROTOCOLSERVER_SOFTWARE。其它的变量均作为“供应商扩展(vendor extensions)”来对待。


在 HP-UX 系统下的安装

本章节的内容和提示仅限于将 PHP 安装到 HP-UX 系统上(此文章是由 paul_mckay at clearwater-it dot co dot uk 编写的)。

注: 本文涉及的技巧适用于 PHP 4.0.4 和 Apache 1.3.9。

  1. 安装 PHP 需要一个 gzip,可以从如下地址得到该软件的二进制版本的发行包 http://hpux.connect.org.uk/ftp/hpux/Gnu/gzip-1.2.4a/gzip-1.2.4a-sd-10.20.depot.Z,下载后解压缩,并且使用 swinstall 安装。

  2. 安装 PHP 需要 gcc,可以从如下地址得到该软件的二进制版本的发行包 http://gatekeep.cs.utah.edu/ftp/hpux/Gnu/gcc-2.95.2/gcc-2.95.2-sd-10.20.depot.gz,解压缩这个文件,使用 swinstall 安装 gcc。

  3. 安装 PHP 需要 GNU binutils,可以从如下地址得到该软件的二进制版本的发行包 http://hpux.connect.org.uk/ftp/hpux/Gnu/binutils-2.9.1/binutils-2.9.1-sd-10.20.depot.gz,解压缩这个文件,使用 swinstall 安装 binutils。

  4. 安装 PHP 需要 bison,可以从如下地址得到该软件的二进制版本的发行包 http://hpux.connect.org.uk/ftp/hpux/Gnu/bison-1.28/bison-1.28-sd-10.20.depot.gz,安装方式同上。

  5. 安装 PHP 需要 flex,需要从 http://www.gnu.org 的镜像站点下载一个该软件的源代码。它被放置于一个 非 gnu 目录的 ftp 服务器上。下载这个文件,并且使用 gunzip 解压缩,然后执行 tar -xvf。进入新创建的 flex 目录并运行 ./configure,再执行 make 以及 make install

    如果这里出现了错误,很可能是由于 gcc 等工具不在路径中,应将其添加到环境变量 PATH 中。

  6. 下载 PHP 和 apache 的源代码。

  7. 下载后对他们分别执行 gunziptar -xvf。在开始编译他们之前我们需要修改一些文件。

  8. 首先 configure 文件需要被修改,因为它似乎忘记自己是在 hpux 系统下了,有更好的方法解决此问题,但最省事的是在配置脚本的第 47286 行加入 lt_target=hpux10.20

  9. 其次是修改 Apache GuessOS 文件。在文件 apache_1.3.9/src/helpers 的第 89 行,将参数 echo "hp${HPUXMACH}-hpux${HPUXVER}"; exit 0 替换为 echo "hp${HPUXMACH}-hp-hpux${HPUXVER}"; exit 0

  10. 不能把 PHP 作为共享对象方式安装到 HP-UX, 因此你必须将其编译成为一个静态方式,参照 Apache 站点的指导就可以完成。

  11. 这样就完成了 PHP 和 Apache 的 安装编译,然而 Apache 将仍然不能启动,必须为 Apache 配置一个新的用户名,例如 www 或 apache。然后修改 Apache 配置文件 conf/httpd.conf 的 252 和 253 行,由原来的

    User nobody
    Group nogroup

    替换为类似如下的内容

    User www
    Group sys

    这是因为在 hp-ux 系统下, Apache 不能作为 nobody 用户运行。按照上面的方式配置 Apache 和 PHP 就应该可以正常工作了。


在 OpenBSD 系统下的安装

本章节的内容和提示仅限于将 PHP 安装到 OpenBSD 3.6 系统上。


使用二进制包安装

使用二进制包安装 PHP 到 OpenBSD 系统上是被推荐的同时也是最简单的方法。PHP 核心包已经从其他模块中分离出来了并且每个模块可以被独立的安装/卸载而不影响其他模块。所有这些安装 PHP 需要的文件可以在 OpenBSD 光盘或者在 FTP 站点上找到。

需要安装的 PHP 核心包的文件是 php4-core-4.3.8.tgz,它包含了基本的引擎(包括 gettext 和 iconv)。其次,可能还需要安装一些模块包,如:php4-mysql-4.3.8.tgzphp4-imap-4.3.8.tgz。需要使用命令 phpxs 去激活它,并且再通过修改 php.ini 文件来屏蔽他们。

例子 4-6. 在 OpenBSD 系统下的软件包的安装示例

# pkg_add php4-core-4.3.8.tgz
# /usr/local/sbin/phpxs -s
# cp /usr/local/share/doc/php4/php.ini-recommended /var/www/conf/php.ini
  (加入 mysql 包)
# pkg_add php4-mysql-4.3.8.tgz
# /usr/local/sbin/phpxs -a mysql
  (加入 imap 包)
# pkg_add php4-imap-4.3.8.tgz
# /usr/local/sbin/phpxs -a imap
  (测试一下删除 mysql 包)
# pkg_delete php4-mysql-4.3.8
# /usr/local/sbin/phpxs -r mysql
  (安装 PEAR 库)
# pkg_add php4-pear-4.3.8.tgz

阅读用户手册中的 packages(7) 部分,可以得到更多 OpenBSD 系统下有关二进制软件包的信息.


使用软件包

同样可以使用软件包目录(ports tree)来编译 PHP 的源代码。然而,这样的安装方式仅仅是建议对 OpenBSD 非常熟悉的高级用户去做。PHP4 的软件包被分别分为了两个子目录:core 和 extensions。其中 extensions 目录产生了所有 PHP 所支持的子模块。如果不希望创建并且使用这些模块中的某些模块,请使用 FLAVOR no_* 参数。例如,如果希望跳过编译 imap 模块,设置 FLAVOR 为 no_imap 即可。


常见问题

  • 默认安装的 Apache 运行于 chroot(2) jail,将限制 PHP 脚本只能访问 /var/www 下面的文件。需要建立 /var/www/tmp 目录来存放 PHP session 文件,或使用其它的 session 后端。此外,数据库套接字需要被放入 jail 或者侦听 localhost 接口。如果使用网络函数,某些 /etc 下面的文件例如 /etc/resolv.conf/etc/services 需要被移动到 /var/www/etc 中去。OpenBSD PEAR 包会自动安装到正确的 chroot 目录中,因此不需要作特殊改动。有关 OpenBSD Apache 的更多信息见 OpenBSD FAQ

  • 对应于 gd 扩展的 OpenBSD 3.6 包需要预先安装 XFree86。如果不想使用那些需要 X11 的字体特性,则安装 php4-gd-4.3.8-no_x11.tgz 包来替代之。


早期发布版本

早期的 OpenBSD 系统使用 FLAVORS 系统把 PHP 连接为静态模式。自从使用这种方法编译就造成了问题:很难制作二进制软件包。仍然可以使用早期稳定的 ports trees,但这种方式已经不被 OpenBSD 小组所支持。如果对此有任何建议和意见,软件包当前的维护人是 Anil Madhavapeddy(avsm at openbsd dot org)。


在 Solaris 下的安装

本节包含了在 Solaris 系统上安装 PHP 的说明和提示。


需要的软件

默认安装的 Solaris 系统经常缺少 C 语言编译器和其相关工具。部分工具必须使用该工具的 GNU 版本,原因请阅读 FAQ。 下面是需要的软件:

  • gcc(推荐使用,其它 C 语言编译器也可以工作)

  • make

  • flex

  • bison

  • m4

  • autoconf

  • automake

  • perl

  • gzip

  • tar

  • GNU sed

此外,还需要安装(或编译)在配置时定义的所有额外软件,比如说 Oracle 或 MySQL。


使用软件包

可以使用 pkgadd 来安装大部分需要的软件来简化 Solaris 安装过程。


在 Gentoo 系统下的安装

本节包含了在 Gentoo Linux 系统下安装 PHP 的说明和提示。


使用 Portage (emerge)

当可以下载和自己编译 PHP 源代码时,使用 Gentoo 的包系统安装 PHP 是最简单和干净的方法。但如果不熟悉在 Linux 下编译软件,可以使用本节提到的方法。

如果目前为止已经安装好了 Gentoo 系统,可能已经习惯于使用 Portage 了。安装 Apache 和 PHP 与安装其它系统工具没有什么不同。

首先要决定是安装 Apache 1.3.x 还是 Apache 2.x。二者均可使用 PHP,下面的步骤是基于 Apache 1.3.x 的。另一件要考虑的事情是,本地的 Portage 树是否为最新的。如果最近没有更新它,需要首先运行 emerge sync。这样,便可以使用最新稳定版本的 Apache 和 PHP。

现在一切都准备好了,可以参照下面的示例安装 Apache 和 PHP:

例子 4-7. Gentoo 下 Apache 1.3 + PHP 的安装示例

# emerge \<apache-2
# USE="-*" emerge php mod_php
# ebuild /var/db/pkg/dev-php/mod_php-<your PHP version>/mod_php-<your PHP version>.ebuild config
# nano /etc/conf.d/apache
  Add "-D PHP4" to APACHE_OPTS

# rc-update add apache default
# /etc/init.d/apache start

可以在 Gentoo 网站上的 Portage 手册中获得更多关于 emerge 的信息。

如果需要使用 Apache 2,可以在上例中简单的使用 emerge apache 命令。


配置时进行更好的控制

在上一节,PHP 安装时几乎没有安装任何激活的模块。在写本文档时,唯一被激活的模块是 XML,因为 PEAR 需要它。这可能不是想要的,不久就会发现需要更多激活的模块,例如 MySQL、gettext、GD 等。

当自己从源代码编译 PHP 时,需要使用 configure 激活所需模块。而在 Gentoo 中,只需使用 USE 标记,它会被自动传递到配置脚本中。要了解 USE 标记在 emerge 中是怎么工作的,可以尝试:

例子 4-8. 获得所有可用的 USE 标记列表

# USE="-*" emerge -pv php

[ebuild  N    ] dev-php/php-4.3.6-r1  -X -berkdb -crypt -curl -debug -doc
-fdftk -firebird -flash -freetds -gd -gd-external -gdbm -gmp -hardenedphp
-imap -informix -ipv6 -java -jpeg -kerberos -ldap -mcal -memlimit -mssql
-mysql -ncurses -nls -oci8 -odbc -pam -pdflib -png -postgres -qt -readline
-snmp -spell -ssl -tiff -truetype -xml2 -yaz  3,876 kB

可以从输出中看到,PHP 可用使用很多 USE 标记。请仔细查看和选择所需要的标记。如果选择的标记所需的库没有安装,Portage 会自动编译它们。可以再次使用 emerge -pv 命令以了解 Portage 会根据 USE 标记编译哪些内容。例如,如果没有安装 X,而在 USE 标记中包括了 X,Portage 将会首先编译 X,然后再编译 PHP。这会花去好几个小时。

如果要编译 PHP 并使其支持 MySQL、cURL 和 GD,使用的命令为:

例子 4-9. 使用 USE 标记安装 PHP

# USE="-* curl mysql gd" emerge php mod_php

在上例中,不要忘记同时 emerge php 和 mod_php。php 是 PHP 的命令行版本,而 mod_php 是 PHP 的 Apache 模块版本。


常见问题

  • 如果浏览 PHP 脚本时看到是 PHP 源代码,而不是其生成的页面,原因可能是忘记编辑 /etc/conf.d/apache 文件。Apache 启动时需要添加 -D PHP4 参数。要了解是否使用了该参数,可以在 Apache 运行之后输入 ps ax | grep apache 命令。

  • 由于某些原因,可能在系统中安装了多个版本的 PHP。如果是这样的话,需要手动 unmerge 旧版本。使用 emerge unmerge mod_php-<old version> 命令。

  • 如果是因为 Java 不能 emerge PHP,尝试在 USE 标记的开始使用 -*。如上面的例子所示。

  • 如果在配置 Apache 和 PHP 的过程中遇到问题,可以使用关键字“Apache PHP”搜索 Gentoo 论坛


Debian GNU/Linux 安装说明

本节包含了在 Debian GNU/Linux 下安装 PHP 的说明和提示。


使用 APT

当然可以下载 PHP 源代码并自己编译,不过使用 Debian 的软件包系统是安装 PHP 的最简单和最干净利落的方法。如果不熟悉在 Linux 下编译软件,那最好用此方法。

首先要决定是安装 Apache 1.3.x 还是 Apache 2.x。相对应的 PHP 软件包名字为 libapache-mod-php* 和 libapache2-mod-php*。以下步骤以 Apache 1.3.x 为例。注意迄今为止,还没有 PHP 5 的正式的 Debian 软件包。以下步骤将安装 PHP 4。

PHP 在 Debian 下也有 CGI 和 CLI 两种风格,分别命名为 php4-cgi 和 php4-cli。如果需要的话,只要用正确的软件包名称重复以下步骤。另外需要安装的一个特殊软件包是 php4-pear。它包含了最小的 PEAR 安装以及 pear 命令行工具。

如果需要比 Debian 的稳定版本更新的 PHP 包或者一些不在 Debian 官方库中的 PHP 模块,那应该看看 http://www.apt-get.org/。其中可以找到一个 Dotdeb。此非官方库是由 Guillaume Plessis 负责维护,其中包含了最新版 PHP 4 和 PHP 5 的 Debian 软件包。要使用,只需将以下两行添加到 /etc/apt/sources.lists 并运行 apt-get update

例子 4-10. Dotdeb 有关的两行

deb http://packages.dotdeb.org stable all
deb-src http://packages.dotdeb.org stable all

最后要考虑的是自己的软件包列表是否是最新版。如果最近没有更新过,那需要在做任何事之前先 apt-get update。这样就可以使用最近稳定版的 Apache 和 PHP 软件包了。

所有准备做好之后,就可以按照下面的例子来安装 Apache 和 PHP:

例子 4-11. Debian 中在 Apache 1.3 下安装的例子

# apt-get install libapache-mod-php4

APT 将自动安装 Apache 1.3 的 PHP 4 模块以及所有依赖的库并激活之。如果在安装过程中没有被要求重启动 Apache,那必须手工进行:

例子 4-12. 安装完 PHP 4 后停止并启动 Apache

# /etc/init.d/apache stop
# /etc/init.d/apache start

更好地控制配置

上一节中 PHP 仅安装了核心模块。但可能不够用,用户很快就会发现需要更多的激活模块,例如 MySQL,cURL,GD 等。

当自己从源代码编译 PHP 时,需要通过 configure 命令来激活模块。用 APT 则只需安装附加的软件包。这些包都命名为“php4-*”(或“php5-*”,如果安装了第三方的 PHP 5 的话)。

例子 4-13. 取得 PHP 附加软件包的列表

# dpkg -l 'php4-*'

从上面的输出中可以看到,还有很多 PHP 模块可安装(除了 php4-cgi,php4-cli 或 php4-pear 这些特殊软件包)。仔细察看并安装自己所需要的。如果选择了一个模块而没有相应的库,APT 会自动安装所有依赖的库。

如果选择将 MySQL,cURL 和 GD 支持添加到 PHP 中,则其命令类似于:

例子 4-14. 安装 PHP 的 MySQL,cURL 和 GD 支持

# apt-get install php4-mysql php4-curl php4-gd

APT 会自动把适当的行添加到不同的 php.ini/etc/php4/apache/php.ini/etc/php4/cgi/php.ini 等)中去。

例子 4-15. 在 PHP 中激活 MySQL,cURL 和 GD 的配置行

extension=mysql.so
extension=curl.so
extension=gd.so

只需像之前那样重新启动 Apache 来激活这些模块。


常见问题

  • 如果看到了 PHP 源代码而不是脚本应该产生的结果,则 APT 可能没有 /etc/apache/conf.d/php4 包括到 Apache 1.3 配置中去。请确保下面一行出现在 /etc/apache/httpd.conf 文件中并重启动 Apache:

    例子 4-16. 下面这行在 Apache 中激活了 PHP 4

    # Include /etc/apache/conf.d/
  • 如果安装了更多模块但其函数不能在脚本中使用,请确保相应的配置行出现在 php.ini 中,如上面所说。APT 可能会由于混乱的 debconf 配置而在安装附加模块时失败。


章 5. Mac OS X 系统下的安装

本章包括在 Mac OS X 平台下安装 PHP 的说明和提示。Mac OS X 有两个不同的版本,客户版和服务器版,本手册两者均会介绍。请注意 PHP 不能在 Mac OS 9 和更早版本下运行。


使用软件包

Mac OS X 下有几个预编译和打包的 PHP 版本。可以通过它使用标准的配置的 PHP,但是若需要不同的功能集(比如一个安全服务器,或者一个不同的数据库驱动程序),可能需要自己编译 PHP 和/或 web 服务器。如果不熟悉如何自己编译软件,可以试着找一下包含自己所需功能的 PHP 预编译版本。


在 Mac OS X 服务器版编译

Mac OS X 服务器安装.

  1. 获得最新版本的 Apache 和 PHP。

  2. 将它们的 tar 包解压,然后如下运行 Apache 的 configure 程序。
    ./configure --exec-prefix=/usr \
    --localstatedir=/var \
    --mandir=/usr/share/man \
    --libexecdir=/System/Library/Apache/Modules \
    --iconsdir=/System/Library/Apache/Icons \
    --includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers \
    --enable-shared=max \
    --enable-module=most \
    --target=apache

  3. 如果想对编译做些优化,可以添加下面一行:
    setenv OPTIM=-O2

  4. 接下来,进入 PHP 4 源代码目录,并进行 configure 操作。
    ./configure --prefix=/usr \
        --sysconfdir=/etc \
        --localstatedir=/var \
        --mandir=/usr/share/man \
        --with-xml \
        --with-apache=/src/apache_1.3.12
    如果需要其它附加功能(MySQL、GD 等),务必将它们添加到这里。对于 --with-apache 参数,需要将其路径指向 Apache 源代码目录,例如 /src/apache_1.3.12

  5. 输入 makemake install。这样在 Apache 源代码目录中会创建一名为 src/modules/php4 的目录。

  6. 现在,重新配置 Apache 以编译 PHP 4。
    ./configure --exec-prefix=/usr \
    --localstatedir=/var \
    --mandir=/usr/share/man \
    --libexecdir=/System/Library/Apache/Modules \
    --iconsdir=/System/Library/Apache/Icons \
    --includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers \
    --enable-shared=max \
    --enable-module=most \
    --target=apache \
    --activate-module=src/modules/php4/libphp4.a
    可能会被告知 libmodphp4.a 太旧了。如果出现这个情况,进入 Apache 源代码目录中的 src/modules/php4 目录,并运行该命令: ranlib libmodphp4.a。然后返回到 Apache 源代码根目录,再次运行上面的 configure 命令。这样便会更新连接表。然后再次运行 makemake install 命令。

  7. 从 PHP 4 源代码目录复制并重命名 php.ini-dist 文件到 bin 目录:cp php.ini-dist /usr/local/bin/php.ini 或(如果没有 local 目录)cp php.ini-dist /usr/bin/php.ini


在 Mac OS X 客户版编译

以下说明将会帮助在 Mac OS X 下为 Apache 服务器安装 PHP 模块,并添加 MySQL 和 PostgreSQL 的支持。本说明是由 Marc Liyanage 提供的。

警告

请注意,在按照下面的步骤操作时,应该停止 Apache 服务器!

按照下面的步骤安装:

  1. 打开终端窗口。

  2. 输入 wget http://www.diax.ch/users/liyanage/software/macosx/libphp4.so.gz,等待下载完毕。

  3. 输入 gunzip libphp4.so.gz

  4. 输入 sudo apxs -i -a -n php4 libphp4.so

  5. 现在输入 sudo open -a TextEdit /etc/httpd/httpd.conf。TextEdit 将把 web 服务器的配置文件打开。在文件的末尾找到下面两行(使用查找命令):
    #AddType application/x-httpd-php .php
    #AddType application/x-httpd-php-source .phps
    将它们前面的两个井号(#)去掉,然后保存文件并退出 TextEdit。

  6. 最后,输入 sudo apachectl graceful 重新启动 web 服务器。

PHP 现在应该已经配置好,并且正在运行了。可以在 Sites 文件夹创建一名为 test.php 的文件。该文件的内容为: <?php phpinfo() ?>

现在在 web 浏览器浏览 127.0.0.1/~your_username/test.php。应该可以看到一个表格列出了 PHP 模块的信息。


章 6. Windows 系统下的安装

本节内容适用于 Windows 98/Me 以及 Windows NT/2000/XP/2003。PHP 不能在 16 位平台例如 Windows 3.1 下运行。有时把支持 PHP 的 Windows 平台称为 Win32。自 PHP 4.3.0 开始不再支持 Windows 95。

有两种方法在 Windows 下安装 PHP:手工安装或者使用安装程序安装。

如果有 Microsoft Visual Studio,也可以编译 PHP 的源程序。

一旦在 Windows 系统下安装好 PHP 之后,可能需要加载各种扩展库以实现更多的功能。

警告

互联网上还有一些多合一的安装程序,但是它们没有一个是被 PHP.net 认可的,因为我们相信,手动安装是系统安全和优化的最好选择。


Windows 安装程序

PHP 的 Windows 安装程序可以在 http://www.php.net/downloads.php 下载。它会为 IIS、PWS 和 Xitami 安装 CGI 版本的 PHP,并配置好 web 服务器。该安装程序不包含任何外部的 PHP 扩展(PHP_*.dll)。如果需要,可以在 Windows ZIP 包和 PECL 中找到。

注: 虽然 Windows 安装程序是让 PHP 工作的最容易的方法,但是它有很多限制。例如,它不支持自动安装 PHP 扩展。使用安装程序安装 PHP 不是最好的方式。

首先,在系统中安装自己选择的 HTTP(web)服务器,并确认它正常工作。

运行安装程序,按照向导说明一步步安装。它支持两种安装类型:标准,将使用合理的默认配置进行安装;高级,会在配置中询问几个问题。

安装向导会收集足够的信息来设置 php.ini 文件,并配置好 web 浏览器以使用 PHP。PHP 安装程序不能自动配置 Apache,因此需要手动进行配置。

一旦安装完成,安装程序会提示重新启动系统,重启服务器,或直接开始使用 PHP。

警告

请注意,这种安装方式安装的 PHP 不是安全的。如果需要一个安全的 PHP 设置,最好使用手动方式安装,并手动设置好每个选项。该自动安装程序能够让用户立即使用 PHP,但是这不意味着可以用于在线的服务器中。


手工安装步骤

本安装指南指导手动在一个 Microsoft Windows 的 web 服务器下安装和配置 PHP。安装前需要从 http://www.php.net/downloads.php 下载 PHP 的 ZIP 二进制发布包。

虽然目前有很多多合一的安装包,而且也发布了一个 Microsoft Windows 的 PHP 安装程序,但是仍然建议用户花些时间自己手动安装 PHP。因为这样才可以更加了解这套系统,并能够在需要的时候更方便的安装 PHP 扩展。

从旧版本的 PHP 升级: 上一版的手册建议将 ini 和多个 DLL 文件移动到系统文件夹(例如 C:\WINDOWS)。这一步骤虽然简化了安装过程,却导致升级上的困难。建议在使用新版本的 PHP 前删除所有这些文件(比如从 Windows 系统文件夹删除 php.ini 和 PHP 相关的 DLL 文件)。务必在删除前备份这些文件,因为这一操作可能破坏整个系统。原有的 php.ini 在安装新版本的 PHP 时也可用来参考。不久用户便会明白,安装 PHP 最好的方式便是将所有 PHP 有关的文件都放入同一目录,并在系统的 PATH 环境变量中设置此目录。

MDAC 需求: 如果使用 Microsoft Windows 98/NT4,需要下载适用于系统最新版本的 Microsoft Data Access Components(MDAC)。MDAC 可在 http://msdn.microsoft.com/data/ 下载。需要 MDAC 的原因是 Windows 二进制包中编译进了 ODBC 支持。

不论何种 web 服务器,都需要先进行以下步骤:

将 PHP 压缩包释放到选择的目录中。若使用 PHP 4,可以解压缩到 C:\,压缩包会被释放到一个类似 php-4.3.7-Win32 的新目录中。若使用 PHP 5,请解压缩到 C:\php,因为其 ZIP 包内没有类似 php-4.3.7-Win32 的目录信息。可以选择其它的路径但最好不要用中间有空格的路径(例如:C:\Program Files\PHP 就不太好),如果这样做有些 web 服务器会崩溃。

解压缩后的目录对应 PHP 4 和 5 是不同的。它们的目录结构分别为:

例子 6-1. PHP 4 目录结构

c:\php
   |
   +--cli
   |  |
   |  |-php.exe           -- CLI 可执行程序 - 仅使用在命令行脚本
   |
   +--dlls                -- 某些扩展需要的 DLL 文件
   |  |
   |  |-expat.dll
   |  |
   |  |-fdftk.dll
   |  |
   |  |-...
   |
   +--extensions          -- PHP 的扩展 DLL 文件
   |  |
   |  |-php_bz2.dll
   |  |
   |  |-php_cpdf.dll
   |  |
   |  |-..
   |
   +--mibs                -- SNMP 支持文件
   |
   +--openssl             -- Openssl 支持文件
   |
   +--pdf-related         -- PDF 支持文件
   |
   +--sapi                -- SAPI(服务器模块支持)DLL 文件
   |  |
   |  |-php4apache.dll
   |  |
   |  |-php4apache2.dll
   |  |
   |  |-..
   |
   +--PEAR                -- PEAR 的初始复本
   |
   |
   |-go-pear.bat          -- PEAR 安装脚本
   |
   |-..
   |
   |-php.exe              -- CGI 可执行文件
   |
   |-..
   |
   |-php.ini-dist         -- 默认的 php.ini 设置
   |
   |-php.ini-recommended  -- 推荐的 php.ini 设置
   |
   |-php4ts.dll           -- 核心 PHP DLL 文件
   |
   |-...

或:

例子 6-2. PHP 5 目录结构

c:\php
   |
   +--dev
   |  |
   |  |-php5ts.lib
   |
   +--ext                 -- PHP 的扩展 DLL 文件
   |  |
   |  |-php_bz2.dll
   |  |
   |  |-php_cpdf.dll
   |  |
   |  |-..
   |
   +--extras
   |  |
   |  +--mibs             -- SNMP 支持文件
   |  |
   |  +--openssl          -- Openssl 支持文件
   |  |
   |  +--pdf-related      -- PDF 支持文件
   |  |
   |  |-mime.magic
   |
   +--pear                -- PEAR 的初始复本
   |
   |
   |-go-pear.bat          -- PEAR 安装脚本
   |
   |-fdftk.dll
   |
   |-..
   |
   |-php-cgi.exe          -- CGI 可执行文件
   |
   |-php-win.exe          -- 执行脚本时不弹出命令提示行窗口
   |
   |-php.exe              -- CLI 可执行程序 - 仅使用在命令行脚本
   |
   |-..
   |
   |-php.ini-dist         -- 默认的 php.ini 设置
   |
   |-php.ini-recommended  -- 推荐 php.ini 设置
   |
   |-php5activescript.dll
   |
   |-php5apache.dll
   |
   |-php5apache2.dll
   |
   |-..
   |
   |-php5ts.dll           -- 核心 PHP DLL 文件
   |
   |-...

请注意它们之间的不同和相似之处。PHP 4 和 PHP 5 都有一个 CGI 可执行文件、一个 CLI 可执行文件和服务器模块,但是它们位于不同的文件夹和/或有着不同的命名。PHP 4 将服务器模块放在 sapi 文件夹,而 PHP 5 并没有此目录,它的服务器模块文件位于 PHP 根文件夹中。PHP 5 的扩展支持 DLL 文件也并没有放在一个单独的目录中。

注: 在 PHP 4 中,需要将位于 dllsapi 文件夹中的文件移动到主文件夹中(例如 C:\php)。

下面是 PHP 4 和 PHP 5 附带的服务器模块列表:

  • sapi/php4activescript.dll (php5activescript.dll) - ActiveScript 引擎,允许将 PHP 嵌入 Windows 应用程序中。

  • sapi/php4apache.dll(php5apache.dll) - Apache 1.3.x 模块。

  • sapi/php4apache2.dll(php5apache2.dll) - Apache 2.0.x 模块。

  • sapi/php4isapi.dll(php5isapi.dll) - ISAPI 模块,支持 ISAPI 兼容的 web 服务器,比如 IIS 4.0/PWS 4.0 或更新版本。

  • sapi/php4nsapi.dll(php5nsapi.dll) - Sun/iPlanet/Netscape 服务器模块。

  • sapi/php4pi3web.dll(PHP 5 无此模块) - Pi3Web 服务器模块。

服务器模块比 CGI 可执行程序提供了更好的性能和更多的功能。CLI 版本是为使用 PHP 命令行脚本而设计的。关于 CLI 的更多信息可以在 PHP 的命令行模式一章中找到。

警告

SAPI 模块在 4.1 中有较多的增强。但是,在老系统中可能会产生服务器错误,或导致服务器的其它模块停止工作,比如 ASP。

CGI 和 CLI 可执行文件以及 web 服务器模块都需要 php4ts.dllphp5ts.dll)。必须确认该文件可以在 PHP 安装路径中找到。对该 DLL 的搜索顺序为:

  • 调用 php.exe 时所在的目录,或者若使用 SAPI 模块时,web 服务器的目录(例如 C:\Program Files\Apache Group\Apache2\bin)。

  • 任何在 Windows 的 PATH 环境变量中指定的目录。

要让 php4ts.dll / php5ts.dll 能正确被搜索到,有下面三个选择:复制该文件到 Windows 系统目录,复制该文件到 web 服务器的目录,或者把 PHP 目录(例如 C:\php)添加到 PATH 环境变量中。为了将来更好的维护,建议使用最后一个选择,将 PHP 目录添加到 PATH 环境变量中,因为这样更便于将来升级 PHP。在相应的常见问题解答项目中可以了解如何将 PHP 目录添加到 PATH 环境变量中。

下一步是为 PHP 设置一个有效的配置文件,php.ini。在 ZIP 包中有两个 ini 文件,php.ini-distphp.ini-recommended。建议使用 php.ini-recommended,因为在该文件中优化了性能和安全。请仔细阅读该文件中的注释,因为它从 php.ini-dist 修改而来,会对设置产生较大的影响。例如将 display_errors 设置为 off,将 magic_quotes_gpc 设置为 off。除了阅读这些部分,还可以学习一下 ini 设置,并手动设置每一个配置项目。如果想要最安全的设置,这是最好的方法,虽然 PHP 在默认配置下也是很安全的。复制所选择的 ini 文件到 PHP 能找到的目录中,并将其重命名为 php.ini。PHP 搜索 php.ini 的路径在配置文件一节已有介绍。

如果使用 Apache 2,更简单的选择是使用 PHPIniDir 指令(请阅读在 Apache 2 下的安装);若不是,最好的选择是设置 PHPRC 环境变量。它在此常见问题解答项目中进行了解释。

注: 如果在 Windows NT、2000、XP 或 2003 中使用 NTFS 分区,请确认运行 web 服务器的用户有权限读取 php.ini(例如将其设置为 Everyone 可读)

下面的步骤是可选的:

  • 编辑新的 php.ini 文件。如果计划使用 OmniHTTPd,不要执行下一步。设置 doc_root 并指向 web 服务器的 document_root。例如:

    doc_root = c:\inetpub\wwwroot // for IIS/PWS
    
    doc_root = c:\apache\htdocs // for Apache

  • 选择 PHP 装载的扩展库。请阅读关于 Windows 扩展一节以了解如何设置扩展库,以及哪些功能已经内置无需扩展库。请注意建议在全新安装时先不要在 php.ini 中加载任何扩展库,首先要保证 PHP 自身能够正常工作。

  • 在 PWS 和 IIS,可以设置 browscap 配置:在 Windows 9x/Me 中指向 c:\windows\system\inetsrv\browscap.ini,在 NT/2000 中指向 c:\winnt\system32\inetsrv\browscap.ini,在 XP 中指向 c:\windows\system32\inetsrv\browscap.ini。要得到最新版本的 browscap.ini,请阅读如下常见问题解答项目

PHP 现在已经安装在系统中了。接下来一步是选择一个 web 服务器,并为之启用 PHP。请在本章目录中选择一个 web 服务器以了解更详细的安装步骤。


ActiveScript

本节将介绍有关 ActiveScript 安装需要注意的方面。

ActiveScript 是一个只运行在 Windows 下的 SAPI,可以在任何兼容 ActiveScript 的主机上使用 PHP 脚本,例如 Windows Script Host、ASP/ASP.NET、Windows Script Components 或 Microsoft Scriptlet control。

PHP 5.0.1 以后,ActiveScript 被移动到了PECL 库。可以从 PHP 下载页面或者 http://snaps.php.net/ 下载此 PECL 扩展的 DLL 文件。

注: 应该首先阅读手动安装步骤

PHP 安装完成后,应该下载 ActiveScript DLL(php5activescript.dll)并将其放入 PHP 主目录(例如 C:\php)。

准备好全部所需文件后,必须在系统中注册 DLL。做法是打开命令提示行窗口(位于开始菜单),然后输入类似 cd C:\php 的命令进入 PHP 目录,最后输入 regsvr32 php5activescript.dll 注册该 DLL。

要测试 ActiveScript 是否正确工作,请创建一个新文件,命名为 test.wsf(这个扩展名很重要)然后输入:
<job id="test">

 <script language="PHPScript">
  $WScript->Echo("Hello World!");
 </script>

</job>
保存并双击这个文件。如果您看到一个小窗口,内容为“Hello World!",说明安装成功。

注: 在 PHP 4 中,该引擎被命名为“ActivePHP”,如果使用 PHP 4,应该将上例中的“PHPScript”替换为“ActivePHP”。

注: ActiveScript 不使用默认的 php.ini 文件,而仅在调用它的 .exe 文件所在目录中寻找。如果想装载 PHP 扩展等,应该创建 php-activescript.ini 并将其放入那个目录。


Microsoft IIS/PWS

本节包括针对 IIS(Microsoft Internet Information Server)的说明与提示。

警告

如果使用 CGI 方式安装,则服务器对于某些可能的攻击是开放的。请阅读 CGI 安全一章以学习如何防御这些攻击。


PHP 与 IIS 安装的通用事项

  • 首先请阅读手工安装步骤。不要跳过这一步,这里提供了将 PHP 安装到 Windows 中的极其重要的信息。

  • CGI 用户必须在 php.ini 中将 cgi.force_redirect 指令设为 0。其重要细节请阅读 FAQ 中的cgi.force_redirect。此外,CGI 用户可能需要设定 cgi.redirect_status_env 指令。在使用这些指令时,确保它们没有在 php.ini 中被注释掉。

  • PHP 4 的 CGI 文件名是 php.exe 而在 PHP 5 中是 php-cgi.exe。在 PHP 5 中,php.exe 是 CLI 版本,不是 CGI。

  • 修改 Windows 的 PATH 环境变量以把 PHP 目录包括进去。这样 PHP 的 DLL 文件,可执行文件和 php.ini 就都可以保留在 PHP 目录中而不用把 Windows 系统目录搞乱了。更多细节见 FAQ 中的设定路径 PATH

  • IIS 专用用户(通常为 IUSR_MACHINENAME)需要能够读取各个文件和目录的权限,例如 php.ini,docroot 和 session 的 tmp 目录。

  • 确保在 php.ini 中正确设定了 extension_dirdoc_root 指令的值。这些指令依赖于 PHP 被安装的系统。在 PHP 4 中,extension_dir 是 extensions 而在 PHP 5 中是 ext。因此在 PHP 5 中 extensions_dir 的一个取值例子是 "c:\php\ext",IIS 的 doc_root 的取值例子是 "c:\Inetpub\wwwroot"

  • PHP 扩展库的 DLL 文件,如 php_mysql.dllphp_curl.dll,存放于 PHP 下载的 ZIP 包中(自动安装包里没有)。在 PHP 5 中,很多扩展库都是 PECL 的一部分,可以从“Collection of PECL modules”包中下载,例如 php_zip.dllphp_ssh2.dll点击进入 PHP 下载页

  • 在定义应用程序扩展名映射时,应选中“检查文件是否存在”。以极小的性能为代价,IIS(或者 PWS)会在调用 PHP 之前检查脚本文件是否存在并选出认证方法。这意味着 web 服务器会提供一个有道理的 404 形式错误信息而不是一条 CGI 错误说什么 PHP 没有输出任何数据。


Windows NT/200x/XP 和 IIS 4 或更高版本

PHP 可以安装为 CGI 或者 ISAPI 模块。不管哪种,都需要启动 Microsoft 管理控制台(也可能是“Internet 信息服务”,在 Windows NT 4.0 Option Pack 中或者在 Windows 2000/XP 下的控制面板=>管理工具)。然后右键点击 web 服务器节点(通常为“默认网站”),并选择“属性”。

如果想用 CGI 方式,按如下方法进行:

  • 选择“主目录”,“虚拟目录”或“目录”标签页,然后进行:

  • 将执行权限改为“纯脚本”

  • 点“配置”按钮,选择“映射”标签页。点击“添加”按钮,将“可执行文件”指向适当的 CGI 文件名。例如 PHP 5 的值可能是:C:\php\php-cgi.exe。在“扩展名”中填入 .php。选择“全部动作”(或者“限制为”留空),选中“脚本引擎”。然后点击“确定”。

  • 设定合适的目录安全性(在 Internet 信息服务中完成)。如果 NT 服务器使用 NTFS 文件系统,给 I_USR_ 用户加上 php.exe/php-cgi.exe 文件所在目录的可执行权限(通过资源管理器完成)。

要用 ISAPI 模块方式,按如下方法进行:

  • 如果不想用 PHP 进行 HTTP 认证,应该跳过这一步。在“ISAPI 筛选器”标签页中添加一个新的 ISAPI 筛选器。“筛选器名称”设为 PHP,“可执行文件”设为 php4isapi.dll/php5isapi.dll 的路径。

  • 选择“主目录”,“虚拟目录”或“目录”标签页,然后进行:

  • 将执行权限改为“纯脚本”

  • 点“配置”按钮,选择“映射”标签页。点击“添加”按钮,将“可执行文件”指向适当的 ISAPI DLL。例如 PHP 5 的值可能是:C:\php\php5isapi.dll。在“扩展名”中填入 .php。选择“全部动作”(或者“限制为”留空),选中“脚本引擎”。然后点击“确定”。

  • 完全停止 IIS(NET STOP iisadmin)

  • 重新启动 IIS(NET START w3svc)

对于 IIS 6(2003 Server),打开 IIS 管理器,进入 web 服务扩展,点击“添加一个新的 web 服务扩展”,“扩展名”中输入名称,例如 PHP,再点击“添加”按钮,点击“浏览”选择要么 ISAPI 文件(php4isapi.dllphp5isapi.dll)或者 CGI 文件(php.exephp-cgi.exe)作为“文件路径”后点“确定”,然后选中“设置扩展状态为允许”并点“确定”。

要使用 index.php 作为默认文档,在“文档”标签页中选择“添加”。输入 index.php 并点“确定”。用上下箭头按钮调整顺序。这和在 Apache 中设定 DirectoryIndex 相似。

对于每个要关联为 PHP 脚本的后缀都要重复以上步骤。.php 是最常用的,此外为兼容一些遗留下来的老程序可能还需要加上 .php3

如果过些时候之后碰到 CPU 占用率达到 100%,则取消选中“缓存 ISAPI 应用程序”(“主目录”下点“配置”按钮”)。


Windows 和 PWS 4

PWS 4 不支持 ISAPI,只能使用 PHP CGI。

  • 编辑包里附上的 pws-php4cgi.reg/pws-php5cgi.reg 文件(PHP 4 在 SAPI 目录下,PHP 5 在主目录下)改为自己的 php.exe/php-cgi.exe 文件的路径。反斜线应双写,例如:[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\w3svc\parameters\Script Map] ".php"="C:\\php\\php.exe"(如果用 PHP 5 则改为 C:\\php\\php-cgi.exe)。然后将此注册表文件合并入系统;鼠标双击此文件即可。

  • 在 PWS 管理器中,右键点击需要加入 PHP 支持的目录并选择“属性”。选中“执行”,并确认。


Windows 和 PWS/IIS 3

配置此服务器的推荐方法是使用随包发布的注册表文件(PHP 4 是 SAPI 目录下的 pws-php4cgi.reg,PHP 5 是主目录下的 pws-php5cgi.reg)。可能要编辑此文件已确保其中的 PHP 安装目录和扩展库目录符合用户自己的设置。或者按以下步骤手工完成。

警告

以下步骤涉及到直接操作 Windows 注册表。如果出错可能使系统不稳定,强烈建议先备份注册表。如果用户损坏了注册表 PHP 开发组不负任何责任。

  • 运行 Regedit。

  • 找到:HKEY_LOCAL_MACHINE /System /CurrentControlSet /Services /W3Svc /Parameters /ScriptMap

  • 在编辑菜单选择:新建->字符串值

  • 输入 PHP 脚本想要使用的后缀,例如 .php

  • 双击新建的字符串值并在“数值数据”栏里输入 php.exe 的路径,例如 PHP 4 是 C:\php\php.exe "%s" %s,或者 PHP 5 是 C:\php\php-cgi.exe "%s" %s

  • 对每个要关联为 PHP 脚本的文件后缀名重复以上步骤。

以下步骤不影响 web 服务器安装,仅适用于想在命令行下运行 PHP 脚本(例如运行 C:\myscripts\test.php)或者在资源管理器窗口中双击文件名就运行程序。如果更希望双击 PHP 文件名是将其调入文本编辑器,则跳过以下步骤。

  • 找到:HKEY_CLASSES_ROOT

  • 在编辑菜单选择:新建->项

  • 将新项命名为前一节设的后缀,例如:.php

  • 选中新项,在右边栏双击“默认”并输入 phpfile

  • 对每个在前一节设定的后缀都重复以上步骤。

  • HKEY_CLASSES_ROOT 下再创建另一个新建->项 并命名为 phpfile

  • 选中新项 phpfile,在右边栏双击“默认”并输入 PHP Script

  • 右键点击 phpfile 项并选择新建->项,命名为 Shell

  • 右键点击 Shell 项并选择新建->项,命名为 open

  • 右键点击 open 项并选择新建->项,命名为 command

  • 选中新项 command,在右边栏双击“默认”并输入 php.exe 的路径,例如:c:\php\php.exe -q %1(不要忘了 %1)。

  • 退出 Regedit。

  • 如果是 Windows 下的 PWS,重启动以重新加载注册表。

PWS 和 IIS 3 的用户现在就拥有了完全可运作的系统。IIS 3 用户可以使用来自 Steven Genusa 的漂亮工具来配置脚本映射。


Microsoft Windows 下的 Apache 1.3.x

本节包括在 Microsoft Windows 平台的 Apache 下安装 PHP 的说明和提示。在另外的页面也有 Apache 2 的安装和说明

注: 应该首先阅读手动安装步骤

有两种方式让 PHP 工作在 Windows 下的 Apache 1.3.x 中。首先是使用 CGI 可执行程序(PHP 4 下为 php.exe,PHP 5 下为 php-cgi.exe),另外一种方式是使用 Apache 模块 DLL。无论是那种方式,都需要修改 httpd.conf 来配置 Apache,使 PHP 能够在其上运行,然后都需要重启服务。

值得注意的是,现在 Windows 下的 SAPI 模块已经稳定得多,我们建议首先考虑使用 SAPI 而不要使用 CGI 可执行程序。因为 SAPI 更加透明和安全。

虽然还有些其它的方法来在 Apache 下配置 PHP,下面介绍的方法是最简单并适用于新手的。请参考 Apache 的文档以获得更多的配置参数。

在修改完配置文件后,请记得重启 Apache 服务。例如,如果把 Apache 作为 Windows 的一个服务来运行,那么在命令提示行下使用 NET STOP APACHE 命令然后再使用 NET START APACHE 命令便可重启服务。也可以使用重启 Apache 服务的快捷方式来重启。

注: 记住在 Windows 下给 Apache 的配置文件中加入路径值的时候,所有的反斜线例如 c:\directory\file.ext 必须转换成正斜线,如 c:/directory/file.ext


作为 Apache 的模块安装

应该将下面几行加入 Apache 的 httpd.conf 文件:

例子 6-3. PHP 作为 Apache 1.3.x 的一个模块

这里假设 PHP 安装在 c:\php。如果不是这样请根据情况修改路径。

对于 PHP 4:

# 在 LoadModule 一节的末尾添加
# 不要忘记将该文件从 sapi 复制出来
LoadModule php4_module "C:/php/php4apache.dll"

# 在 AddModule 一节的末尾添加
AddModule mod_php4.c

对于 PHP 5:

# 在 LoadModule 一节的末尾添加
LoadModule php5_module "C:/php/php5apache.dll"

# 在 AddModule 一节的末尾添加
AddModule mod_php5.c

两个 PHP 版本都需要添加的内容:

# 将下面这行添加到 <IfModule mod_mime.c> 条件块中
AddType application/x-httpd-php .php

# 如果要使用语法高亮的 .phps 文件,需要添加
AddType application/x-httpd-php-source .phps


作为 CGI 可执行文件的安装

如果按照手动安装步骤将 PHP 解压到 C:\php\,需要在 Apache 的配置文件中添加如下内容以使 PHP 按照 CGI 方式运行:

例子 6-4. PHP 以 CGI 方式运行在 Apache 1.3.x

ScriptAlias /php/ "c:/php/"
AddType application/x-httpd-php .php

# 对于 PHP 4
Action application/x-httpd-php "/php/php.exe"

# 对于 PHP 5
Action application/x-httpd-php "/php/php-cgi.exe"

# 指定 php.ini 所在目录
SetEnv PHPRC C:/php
请注意第二行的配置可以在默认的 httpd.conf 中找到,但是是被注释掉的。也请记得将 c:/php/ 替换为 PHP 所在的真实路径。

警告

如果使用 CGI 方式安装,则服务器对于某些可能的攻击是开放的。请阅读 CGI 安全一章以学习如何防御这些攻击。

如果想发布语法高亮的 php 文件,没有类似于模块方式下 PHP 那种方便的方法。选择了使用 CGI 方式运行 PHP,需要使用 highlight_file() 函数来进行语法高亮。创建一个 PHP 文件,加入下述代码即可:<?php highlight_file('some_php_script.php'); ?>


Microsoft Windows 下的 Apache 2.0.x

本节包括在 Microsoft Windows 系统中针对 Apache 2.0.x 安装 PHP 的指导与说明。在其它页面也有 Apache 1.3.x 用户指导与说明

注: 应该先阅读手工安装步骤

警告

不推荐将线程化 MPM 用于实际运作的 Apache 2 环境中去。用 prefork MPM 替代,或者用 Apache 1。其原因见 FAQ 中的使用线程化 MPM 的 Apache2

强烈建议阅读 Apache 文档来加深对 Apache 2.0.x 服务器的基本理解。此外在继续下去之前考虑先阅读一下 Apache 2.0.x 的 Windows 下使用说明

PHP 和 Apache 2.0.x 兼容性注意事项: 已知下列版本的 PHP 可以工作于最近版本的 Apache 2.0.x 之下:

以上版本的 PHP 与 Apache 2.0.40 或更高版本兼容。

Apache 2.0 SAPI 支持自 PHP 4.2.0 起。PHP 4.2.3 可工作于 2.0.39,不要用任何其它版本的 Apache 与 PHP 4.2.3 配合。不过推荐的设置是用 PHP 4.3.0 或更高版本与最新版的 Apache2 配合使用。

所有提及的 PHP 版本仍然能工作于 Apache 1.3.x 之下。

警告

Apache 2.0.x 被设计运行于 Windows NT 4.0,Windows 2000 或 Windows XP 之下。目前为止对 Windows 9x 的支持尚未完成,此时尚不指望 Apache 2.0.x 在此类平台下工作。

下载最新版本的 Apache 2.0.x 以及适合的 PHP 版本。先完成手工安装步骤后再回来继续将 PHP 集成入 Apache。

Windows 下有两种方法使 PHP 工作于 Apache 2.0.x 之中。一种是 使用 CGI 可执行程序,另一种是适用 Apache 模块的 DLL。不管哪种都需要编辑 httpd.conf 来配置 Apache 支持 PHP 并重新启动服务器。

注: 记住在 Windows 下给 Apache 的配置文件中加入路径值的时候,所有的反斜线例如 c:\directory\file.ext 必须转换成正斜线,如 c:/directory/file.ext


以 CGI 方式安装

需要将以下三行加入到 Apache 的 httpd.conf 配置文件中以设定 CGI:

例子 6-5. PHP 在 Apache 2.0 中的 CGI 方式

ScriptAlias /php/ "c:/php/"
AddType application/x-httpd-php .php

# 对 PHP 4 用这行
Action application/x-httpd-php "/php/php.exe"

# 对 PHP 5 用这行
Action application/x-httpd-php "/php/php-cgi.exe"

警告

如果使用 CGI 方式安装,则服务器对于某些可能的攻击是开放的。请阅读 CGI 安全一章以学习如何防御这些攻击。


以 Apache 模块方式安装

需要将以下两行加入到 Apache 的 httpd.conf 配置文件中以设定 Apache 2.0 的 PHP 模块:

例子 6-6. PHP 在 Apache 2.0 中的模块方式

# 对 PHP 4 用这两行:
LoadModule php4_module "c:/php/php4apache2.dll"
# 别忘了从 sapi 目录中把 php4apache2.dll 拷贝出来!
AddType application/x-httpd-php .php

# 对 PHP 5 用这两行:
LoadModule php5_module "c:/php/php5apache2.dll"
AddType application/x-httpd-php .php

# 配置 php.ini 的路径
PHPIniDir "C:/php"

注: 记得用自己 PHP 实际所在的路径替换掉上例中的 c:/php/。要留意在 LoadModule 指令中用的是 php4apache2.dllphp5apache2.dll,而不是 php4apache.dllphp5apache.dll,后者是设计用于 Apache 1.3.x 的。

注: 如果要使用内容协商机制,请阅读有关 FAQ

警告

不要在安装中混合使用来自不同 PHP 版本的 DLL。使用下载回来的 PHP 版本中所提供的 DLL 和扩展库是唯一选择。


Microsoft Windows 下的 Sun,iPlanet 和 Netscape 服务器

本节包含针对在 Windows 下 Sun Java System web 服务器,Sun ONE web 服务器,iPlanet 和 Netscape 服务器的 PHP 安装说明与提示。

自 PHP 4.3.3 起可以通过 NSAPI 模块使用 PHP 脚本来产生定制目录列表于错误页面。也可以使用为兼容 Apache 的附加函数。目前使用的 web 服务器的支持请阅读有关子请求的说明


Sun,iPlanet 和 Netscape 服务器的 CGI 方式安装

要将 PHP 安装为 CGI 处理器,按以下步骤进行:

  • php4ts.dll 拷贝到 systemroot(即 Windows 的安装目录)

  • 在命令行做文件关联,输入以下两行命令:
    assoc .php=PHPScript
    ftype PHPScript=c:\php\php.exe %1 %*

  • 在 Netscape Enterprise Administration Server 中建一个空的 shellcgi 目录并随即删除(此步骤在 obj.conf 中新建了 5 行重要指令以允许 web 服务器处理 shellcgi 脚本)。

  • 在 Netscape Enterprise Administration Server 中新建一个新的 MIME 类型(Category: type,Content-Type: magnus-internal/shellcgi,File Suffix: php)。

  • 对每个要运行 PHP 的 web 服务器实例都进行以上步骤。

更多将 PHP 设置为 CGI 可执行程序的内容见:http://benoit.noss.free.fr/php/install-php.html


Sun,iPlanet 和 Netscape 服务器的 NSAPI 方式

要将 PHP 以 NSAPI 方式安装,按以下步骤进行:

  • php4ts.dll 拷贝到 systemroot(即 Windows 的安装目录)

  • 在命令行做文件关联,输入以下两行命令:
    assoc .php=PHPScript
    ftype PHPScript=c:\php\php.exe %1 %*

  • 在 Netscape Enterprise Administration Server 中新建一个新的 MIME 类型(Category: type,Content-Type: magnus-internal/x-httpd-php,File Suffix: php)。

  • 编辑 magnus.conf(服务器版本 >= 6)或 obj.conf(服务器版本 < 6)并加入下面两行;要将新行放在 mime types init 之后:
    Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="c:/php/sapi/php4nsapi.dll"
    Init fn="php4_init" LateInit="yes" errorString="Failed to initialise PHP!" [php_ini="c:/path/to/php.ini"]
    (PHP >= 4.3.3)php_ini 参数为可选项,但加上后就可以把 php.ini 放到 web 服务器的配置目录中去。

  • obj.conf 中配置默认对象(对于虚拟服务器类 [Sun web Server 6.0+] 是 vserver.obj.conf 文件):在 <Object name="default"> 一节,在所有的“ObjectType”行之后和所有的“AddLog”行之前加上这一行:
    Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...]
    (PHP >= 4.3.3)作为附加参数可以加入一些特殊的 php.ini 值,例如可以在调用 php4_execute 时设定专门的 docroot="/path/to/docroot"。对于布尔的 ini 选项请用 0/1 作为值,而不是 "On","Off",...(这样不能正确工作),例如要用 zlib.output_compression=1 而不是 zlib.output_compression="On"

  • 这几行仅在想要配置一个只有 PHP 脚本的目录时需要(类似 cgi-bin 目录):
    <Object name="x-httpd-php">
    ObjectType fn="force-type" type="magnus-internal/x-httpd-php"
    Service fn=php4_execute [inikey=value inikey=value ...]
    </Object>
    在此之后可以在管理服务器中配置目录并将其类型设为 x-httpd-php。其中的所有文件都将作为 PHP 执行。这样可以隐藏 PHP 的使用,文件名还保留为 .html

  • 重启动 web 服务使改动生效。

  • 对每个要运行 PHP 的 web 服务器实例都进行以上步骤。

注: 更多将 PHP 设置为 NSAPI内容见:http://benoit.noss.free.fr/php/install-php4.html

注: PHP 使用的堆栈大小(stacksize)依赖于 web 服务器的配置。如果在运行很大的 PHP 脚本时死掉,建议在管理服务器中增大此值(在 "MAGNUS EDITOR" 一节中)。


CGI 环境以及推荐在 php.ini 中进行的修改

在写 PHP 脚本时很重要一点是 Sun JSWS/Sun ONE WS/iPlanet/Netscape 是多线程 web 服务器。因此所有的请求都运行于同一个进程空间(即 web 服务器自己的空间)而此空间只有一个环境。如果想取得 CGI 变量例如 PATH_INFOHTTP_HOST 等时不能用老的 PHP 3.x 的方式 getenv() 或者类似手段($_ENV)进行。只能取得运行的 web 服务器的环境变量而没有任何有效的 CGI 变量!

注: 为什么环境中有一些(无效的)CGI 变量?

解答:这是因为从管理服务器启动了 web 服务器进程,这将运行 web 服务器的启动脚本,而你想要启动的是 CGI 脚本(CGI 脚本在管理服务器内部!)。这是为什么 web 服务器启动的环境中有一些 CGI 环境变量的原因。可以不从管理服务器启动 web 服务器来试验一下。用管理员用户从命令行手工启动――这样就不会看到类似 CGI 的环境变量了。

PHP 4.x 中取得 CGI 变量的正确方式是使用超全局变量 $_SERVER。如果有一些老的脚本用了 $HTTP_HOST 等,那应该在 php.ini 中打开 register_globals 选项并改变变量顺序(重要提示:去掉 "E",因为这里不需要环境变量):
variables_order = "GPCS"
register_globals = On


错误页面的特殊使用或定制目录列表(PHP >= 4.3.3)

可以用 PHP 来为 "404 Not Found" 或类似的错误提示生成错误页面。对每个想要覆盖的错误页面在 obj.conf 中的对象里加入下面这行:
Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...]
其中的 XXX 是 HTTP 错误代码。删除掉可能干扰到自己设置的任何其它 Error 指令。如果对所有可能出现的错误都用同一个脚本处理,不要 code 参数即可。脚本里可以用 $_SERVER['ERROR_TYPE'] 取得 HTTP 状态代码。

还可以生成自己定制的目录列表。只要创建一个显示目录列表的 PHP 脚本并用下面一行在 obj.conf 中替换掉相应 type="magnus-internal/directory" 默认的 Service 设置:
Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...]
对于错误和目录列表页面,原始的 URI 和转换后的 URI 都在变量 $_SERVER['PATH_INFO']$_SERVER['PATH_TRANSLATED'] 中。


有关 nsapi_virtual() 和子请求(PHP >= 4.3.3)的说明

NSAPI 模块现在支持 nsapi_virtual() 函数(别名:virtual())来进行子请求并将结果插入到 web 页面里。问题是,此函数用到了一些 NSAPI 库中没有文档说明的特性。

在 Unix 下这不是问题,因为模块会自动寻找所需的函数并使用。如果找不到,nsapi_virtual() 被禁用。

在 Windows 下 DLL 处理的局限性需要使用最新的 ns-httpdXX.dll 文件中的自动检测功能。这已在版本 6.1 及以下的服务器中测试过。如果用了更高版本的 Sun 服务器,检测会失败并禁用 nsapi_virtual()

在这种情况下,试试下面的方法。在 magnus.conf/obj.conf 中的 php4_init 里加入下面的参数:
Init fn=php4_init ... server_lib="ns-httpdXX.dll"
其中 XX 是正确的 DLL 版本号。在 server-root 目录下去找合适的 DLL 的名字。文件大小最大的 DLL 就是了。

可以用 phpinfo() 函数来检查状态。

注: 但要注意:对 nsapi_virtual() 的支持是试验性质的!


OmniHTTPd Server

本节包括针对 Windows 下的 OmniHTTPd 的内容与提示。

注: 应该首先阅读手工安装步骤

警告

如果使用 CGI 方式安装,则服务器对于某些可能的攻击是开放的。请阅读 CGI 安全一章以学习如何防御这些攻击。

要在 OmniHTTPd 中安装 PHP 需要完成以下步骤。这是 CGI 方式的安装。OmniHTTPd 支持 SAPI,但是有测试显示以 ISAPI 模块方式使用 PHP 不太稳定。

CGI 用户重要提示: 请阅读 FAQ:cgi.force_redirect 中的重要细节。此选项需要被设为 0

  1. 安装 OmniHTTPd 服务器。

  2. 右键点击系统托盘中蓝色的 OmniHTTPd 图标并选择 Properties

  3. 点击 web Server Global Settings

  4. 在“External”标签页,输入:virtual = .php | actual = c:\php\php.exe(如果是 PHP 5 则用 php-cgi.exe),并点击 Add 按钮

  5. Mime 标签页,输入:virtual = wwwserver/stdcgi | actual = .php,并点击 Add 按钮

  6. 点击 OK

对每个想要和 PHP 关联的后缀都重复 2 - 6 步。

注: 有些 OmniHTTPd 安装包中内置了 PHP 支持。可以在安装时选择自定义安装,取消选中 PHP 部分。推荐使用最新的 PHP 可执行包。有些 OmniHTTPd 服务器内置了 PHP 4 beta 版,应该选择不安装内置版而安装自己的版本。如果服务器已经安装了,则在上面的第 4 和 5 步用 Replace 按钮来设置新的准确的信息。


Microsoft Windows 下的 Sambar 服务器

本节包含针对 Windows 下的 Sambar 服务器的说明和提示。

注: 应该首先阅读手工安装步骤

下面列出了怎样在 Windows 下设置 Sambar 服务器的 ISAPI 模块。

  • 在 Sambar 安装目录中找到 mappings.ini 文件(在 config 目录中)。

  • 打开 mappings.ini 并在 [ISAPI] 部分加入下面一行:

    例子 6-7. Sambar 的 ISAPI 设置

    #对 PHP 4
    *.php = c:\php\php4isapi.dll
    
    #对 PHP 5
    *.php = c:\php\php5isapi.dll
    (上面假定 PHP 安装在 c:\php。)

  • 重启动 Sambar 服务器以使改动生效。


Microsoft Windows 下的 Xitami

本节包含针对 Windows 下的 Xitami 的说明与提示。

注: 应该首先阅读手工安装步骤

下面列出了怎样在 Windows 下在 Xitami 中设置 PHP 的 CGI 方式。

CGI 用户重要提示: 请阅读 FAQ:cgi.force_redirect 中的重要细节。此选项需要被设为 0。如果想要使用 $_SERVER['PHP_SELF'],还必须激活 cgi.fix_pathinfo 选项。

警告

如果使用 CGI 方式安装,则服务器对于某些可能的攻击是开放的。请阅读 CGI 安全一章以学习如何防御这些攻击。

  • 确保 web 服务器在运行,在浏览器中打开 Xitami 的管理控制台(通常是 http://127.0.0.1/admin),并点击 Configuration。

  • 找到 Filters,在 File extensions(.xxx)字段中加入想要 PHP 解析的后缀名(例如 .php)。

  • 在 Filter command 或 script 中输入 PHP 的 CGI 可执行文件名,例如 PHP 4 是 C:\php\php.exe,PHP 5 是 C:\php\php-cgi.exe

  • 点击“Save”图标。

  • 重启动服务器以使改动生效。


从源程序编译

开始之前,很值得回答一下这个问题:为什么在 Windows 下编译这么难?两个原因:

  1. Windows 下还没有愿意免费共享代码的开发人员群体。直接结果就是没有足够的投资去建立支持这种开发方式的体系。大体上,尽量得到的可用资源都是从 Unix 下的工具来的。不要奇怪这种传统不会时出现。

  2. 下面几乎所有的说明都是“看过就忘”的类型。所以坐稳当并且尽可能忠实地按照说明来做。


需求

要编译 PHP 需要 Microsoft 开发环境。推荐使用 Microsoft Visuaul C++ 6.0。要释放下载的文件还需要一个解压缩工具(例如:Winzip)。如果还没有解压缩的工具,可以从 InfoZip 下载一个免费版本。

在开始之前,需要先下载...

最后,还需要 PHP 本身的源代码。可以通过匿名 CVS 得到最新的开发版本,一个快照或者最新发行版本的源程序的打包文件。


放到一起

下载了所有的包后需要将他们解压缩到适当的位置。

  • 建立一个工作目录作为解压缩后存放所有文件的地方,例如:C:\work

  • 在工作目录(C:\work)下新建一个目录 win32build 并将 win32build.zip 解压缩到其中。

  • 在工作目录(C:\work)下新建一个目录 bindlib_w32 并将 bindlib_w32.zip 解压缩到其中。

  • 将下载的 PHP 源程序解压缩到工作目录(C:\work)中。

经过以上步骤后目录结构应该如下:

+--c:\work
|  |
|  +--bindlib_w32
|  |  |
|  |  +--arpa
|  |  |
|  |  +--conf
|  |  |
|  |  +--...
|  |
|  +--php-4.x.x
|  |  |
|  |  +--build
|  |  |
|  |  +--...
|  |  |
|  |  +--win32
|  |  |
|  |  +--...
|  |
|  +--win32build
|  |  |
|  |  +--bin
|  |  |
|  |  +--include
|  |  |
|  |  +--lib

新建一个目录 c:\usr\local\lib。将 bison.simplec:\work\win32build\bin 拷贝到 c:\usr\local\lib

注: Cygwin 用户应省略上一步。正确安装的 Cygwin 环境已强制提供了 bison.simplebison.exe 文件。


配置 MVC ++

下一步是配置 MVC ++ 来准备编译。运行 Microsoft Visual C++,在菜单中选择 Tools => Options。在对话框中,选择 directories 标签。依次将下拉框改为 Executables,Includes 和 Library files。其看上去应该是:

  • Executable files: c:\work\win32build\bin, Cygwin users: cygwin\bin

  • Include files: c:\work\win32build\include

  • Library files: c:\work\win32build\lib


编译 resolv.lib

必须编译 resolv.lib 库。自己决定是需要调试信息(bindlib - Win32 Debug)还是不需要(bindlib - Win32 Release)。编译适当的配置:

  • 图形界面用户,运行 VC++,选择 File => Open Workspace,找到 c:\work\bindlib_w32 目录并选择 bindlib.dsw 文件。接着选择 Build => Set Active Configuration 菜单并选择需要的配置。最后选择 Build => Rebuild All。

  • 命令行用户,确认要么注册了 C++ 环境变量,要么运行了 vcvars.bat,然后运行下面任意一行命令:

    • msdev bindlib.dsp /MAKE "bindlib - Win32 Debug"

    • msdev bindlib.dsp /MAKE "bindlib - Win32 Release"

到这一步,应该得到了一个 resolv.libc:\work\bindlib_w32\Debug 或者 Release 目录下。将此文件拷贝到 c:\work\win32build\lib 目录下并覆盖同名的文件。


编译

对于初学者最好的上手方法是编译 CGI 版本。

  • 图形界面用户,运行 VC++,选择 File => Open Workspace 菜单并选择 c:\work\php-4.x.x\win32\php4ts.dsw。接着选择 Build => Set Active Configuration 菜单并选择想要的配置,要么是 php4ts - Win32 Debug_TS 要么是 php4ts - Win32 Release_TS。最后选择 Build => Rebuild All。

  • 命令行用户,确认要么注册了 C++ 环境变量,要么运行了 vcvars.bat,然后从 c:\work\php-4.x.x\win32 目录下运行下面任意一行命令:

    • msdev php4ts.dsp /MAKE "php4ts - Win32 Debug_TS"

    • msdev php4ts.dsp /MAKE "php4ts - Win32 Release_TS"

    • 到这一步,应该得到一个可用的 php.exec:\work\php-4.x.x.\Debug_TSRelease_TS 目录下。

有可能通过编辑 main/config.win32.h 文件对编译做少量的定制。例如可以改变 php.ini 文件的默认位置,内置的扩展库,以及扩展库的默认位置。

下一步可能想要编译 CLI 版本,这是设计用于 PHP 的命令行方式。步骤和编译 CGI 版本相同,只除了要选择 php4ts_cli - Win32 Debug_TS 或者 php4ts_cli - Win32 Release_TS 项目文件。成功编译后会在 Release_TS\cli\ 或者 Debug_TS\cli\ 目录下找到 php.exe 文件。

注: 如果想使用 PEAR 以及舒适的命令行安装程序,就非要用 CLI-SAPI。有关 PEAR 和安装程序的更多信息见 PEAR 网站。

要编译 SAPI 模块(php4isapi.dll)来将 PHP 和 Microsoft IIS 集成起来,将 active configuration 设为 php4isapi-whatever-config 并编译所需要的 dll。.


Windows 下安装扩展库

在 Windows 下安装完 PHP 和 web 服务器之后,可能想要安装一些扩展库来获得更多功能。可以通过修改 php.ini 来选择当 PHP 启动时加载哪些扩展库。也可以在脚本中通过使用 dl() 来动态加载。

PHP 扩展库的 DLL 文件都具有 php_ 前缀。

很多扩展库都内置于 Windows 版的 PHP 之中。这意味着要加载这些扩展库不需要额外的 DLL 文件和 extension 配置指令。Windows 下的 PHP 扩展库列表列出了需要或曾经需要额外 PHP DLL 文件的扩展库。下面是内置的扩展库列表:

PHP 4 中(截止到 PHP 4.3.11):BCMathCaledarCOMCtypeFTPMySQLODBCOverloadPCRESessionTokenizerWDDXXMLZlib

PHP 5 中(截止到 5.0.4)有以下修改。新增内置:DOMLibXMLIconvSimpleXMLSPLSQLite。以下不再内置:MySQLOverload

PHP 搜索扩展库的默认位置在 PHP 4 中是 C:\php4\extensions,在 PHP 5 中是 C:\php5。要修改此项以符合用户自己的 PHP 设置,需要编辑 php.ini 文件:

  • 需要修改 extension_dir 设置以指向用户放置扩展库的目录或者说放置 php_*.dll 文件的位置。例如:

    extension_dir = C:\php\extensions

  • 要在 php.ini 中启用某扩展库,需要去掉该行 extension=php_*.dll 前的注释符号,将想要加载的扩展库前的分号(;)删除即可。

    例子 6-8. 启用 Bzip2 扩展库

    // 将这一行
    ;extension=php_bz2.dll
    
    // 改成这样
    extension=php_bz2.dll

  • 有些扩展库需要额外的 DLL 才能工作。其中一部分包括在发行包里,PHP 4 中在 C:\php\dlls\ 目录下,PHP 5 中在主目录下,但还有一些,例如 Oracle(php_oci8.dll)所需要的 DLL 没有绑定在发行包里。如果安装 PHP 4,将绑定的 DLL 从 C:\php\dlls 拷贝到主目录 C:\php 中。别忘了将 C:\php 放到系统路径 PATH 中去(此过程在另外的 FAQ 条目中有说明)。

  • 某些 DLL 没有绑定在 PHP 发行包中,详情见每个扩展库的文档页。此外有关 PECL 的说明见手册页 PECL 扩展库安装。在 PECL 中有日益增加数目巨大的 PHP 扩展库,这些扩展库需要单独下载

注: 如果运行服务器模块版的 PHP,在修改了 php.ini 之后别忘了重新启动 web 服务器以使其改动生效。

下表说明了哪些扩展库需要额外的 DLL。

表格 6-1. PHP 扩展库

扩展库说明注解
php_bz2.dllbzip2 压缩函数库
php_calendar.dll历法转换函数库自 PHP 4.0.3 起内置
php_cpdf.dllClibPDF 函数库
php_crack.dll密码破解函数库
php_ctype.dllctype 家族函数库自 PHP 4.3.0 起内置
php_curl.dllCURL,客户端 URL 库函数库需要:libeay32.dllssleay32.dll(已附带)
php_cybercash.dll网络现金支付函数库PHP <= 4.2.0
php_db.dllDBM 函数库已废弃。用 DBA 替代之(php_dba.dll
php_dba.dllDBA:数据库(dbm 风格)抽象层函数库
php_dbase.dlldBase 函数库
php_dbx.dlldbx 函数库 
php_domxml.dllDOM XML 函数库 PHP <= 4.2.0 需要:libxml2.dll(已附带),PHP >= 4.3.0 需要:iconv.dll(已附带)
php_dotnet.dll.NET 函数库PHP <= 4.1.1
php_exif.dllEXIF 函数库 需要 php_mbstring.dll。并且在 php.ini 中,php_exif.dll 必须在 php_mbstring.dll之后加载。
php_fbsql.dllFrontBase 函数库PHP <= 4.2.0
php_fdf.dllFDF:表单数据格式化函数库需要:fdftk.dll(已附带)
php_filepro.dllfilePro 函数库只读访问
php_ftp.dllFTP 函数库自 PHP 4.0.3 起内置
php_gd.dllGD 库图像函数库 在 PHP 4.3.2 中删除。此外注意在 GD1 中不能用真彩色函数,用 php_gd2.dll 替代。
php_gd2.dllGD 库图像函数库GD2
php_gettext.dllGettext 函数库 PHP <= 4.2.0 需要 gnu_gettext.dll(已附带),PHP >= 4.2.3 需要 libintl-1.dlliconv.dll(已附带)。
php_hyperwave.dllHyperWave 函数库
php_iconv.dllICONV 字符集转换需要:iconv-1.3.dll(已附带),PHP >=4.2.1 需要 iconv.dll
php_ifx.dllInformix 函数库需要:Informix 库
php_iisfunc.dllIIS 管理函数库
php_imap.dllIMAP,POP3 和 NNTP 函数库
php_ingres.dllIngres II 函数库需要:Ingres II 库
php_interbase.dllInterBase functions需要:gds32.dll(已附带)
php_java.dllJava 函数库PHP <= 4.0.6 需要:jvm.dll(已附带)
php_ldap.dllLDAP 函数库 PHP <= 4.2.0 需要 libsasl.dll(已附带),PHP >= 4.3.0 需要 libeay32.dllssleay32.dll(已附带)
php_mbstring.dll多字节字符串函数库
php_mcrypt.dllMcrypt 加密函数库需要:libmcrypt.dll
php_mhash.dllMhash 函数库PHP >= 4.3.0 需要:libmhash.dll(已附带)
php_mime_magic.dllMimetype 函数库需要:magic.mime(已附带)
php_ming.dllMing 函数库(Flash)
php_msql.dllmSQL 函数库需要:msql.dll(已附带)
php_mssql.dllMSSQL 函数库需要:ntwdblib.dll(已附带)
php_mysql.dllMySQL 函数库PHP >= 5.0.0 需要 libmysql.dll(已附带)
php_mysqli.dllMySQLi 函数库PHP >= 5.0.0 需要 libmysql.dll(PHP <= 5.0.2 中是 libmysqli.dll)(已附带)
php_oci8.dllOracle 8 函数库需要:Oracle 8.1+ 客户端库
php_openssl.dllOpenSSL 函数库需要:libeay32.dll(已附带)
php_oracle.dllOracle 函数库需要:Oracle 7 客户端库
php_overload.dll对象重载函数库自 PHP 4.3.0 起内置
php_pdf.dllPDF 函数库
php_pgsql.dllPostgreSQL 函数库
php_printer.dll打印机函数库
php_shmop.dll共享内存函数库
php_snmp.dllSNMP 函数库仅用于 Windows NT!
php_soap.dllSOAP 函数库PHP >= 5.0.0
php_sockets.dllSocket 函数库
php_sybase_ct.dllSybase 函数库需要:Sybase 客户端库
php_tidy.dllTidy 函数库PHP >= 5.0.0
php_tokenizer.dllTokenizer 函数库自 PHP 4.3.0 起内置
php_w32api.dllW32api 函数库
php_xmlrpc.dllXML-RPC 函数库PHP >= 4.2.1 需要 iconv.dll(已附带)
php_xslt.dllXSLT 函数库 PHP <= 4.2.0 需要 sablot.dllexpat.dll(已附带)。PHP >= 4.2.1 需要 sablot.dllexpat.dlliconv.dll(已附带)。
php_yaz.dllYAZ 函数库需要:yaz.dll(已附带)
php_zip.dllZip 文件函数库只读访问
php_zlib.dllZLib 压缩函数库自 PHP 4.3.0 起内置


章 7. PECL 扩展库安装

PECL 安装介绍

PECL 是通过 PEAR 打包系统来的 PHP 扩展库仓库,本章内容示范了怎样取得并安装 PECL 扩展。

以下指南中假定 /your/phpsrcdir/ 是 PHP 源程序的路径,extname 是 PECL 扩展库的名字。自己根据实际情况调整。此外还假定用户熟悉 pear 命令

要使用共享扩展库,必须经过编译,安装,然后加载。以下说明的方法提供了怎样编译和安装扩展库德各种指导,但并不会自动加载它们。可以通过将其包括在 php.ini 中用 extension PHP 指令加载,或者 用 dl() 函数。

当编译 PHP 模块时,拥有各种工具(autoconf,automake,libtool 等)的已知好使的版本很重要。所需工具和所需版本的详情见匿名 CVS 说明


下载 PECL 扩展库

下载 PECL 扩展库有几种方法,如:

  • http://pecl.php.net

    PECL 网站包括有 PHP 开发组提供的不同扩展库的信息。这里的信息包括:更新记录,版本说明,需求,以及其它信息。

  • pear download extname

    PECL 网站中列出的 PECL 扩展库的发行版本可以用 pear 命令来下载和安装。也可以指明具体的修正版。

  • CVS

    大多数 PECL 扩展库也在 CVS 中。其 web 页面见 http://cvs.php.net/pecl/。要直接从 CVS 中下载,用以下命令,其中用户 cvsread 的密码是 phpfi

    $ cvs -d:pserver:cvsread@cvs.php.net:/repository login
    $ cvs -d:pserver:cvsread@cvs.php.net:/repository co pecl/extname

  • Windows 下载

    Windows 用户可以通过在 PHP 下载页面下载 Collection of PECL modules 来找到已编译的 PECL 可执行程序,或下载 PECL Snapshot。要在 Windows 下编译 PHP,请阅读 Win32 Build README


Windows 用户的 PECL

和其它任何 PHP 扩展库的 DLL 一样,把 PECL 扩展库的 DLL 移动到 extension_dir 目录并将其包括入 php.ini 来安装。例如:

extension=php_extname.dll

然后重新启动 web 服务器。


用 PEAR 编译共享 PECL 扩展库

PEAR 使建立共享 PHP 扩展库更容易。用 pear 命令这样做:

$ pear install extname

这将下载 extname 的源代码,编译之,并将 extname.so 安装到 extension_dir 中。然后 extname.so 就可以通过 php.ini 加载了。

默认情况下,pear 命令不会安装标记为 alphabeta 状态的包。如果没有 stable 包可用,也可以用以下命令安装一个 beta 包:

$ pear install extname-beta

也可以用此命令安装一个指定的版本:

$ pear install extname-0.1


用 phpize 编译共享 PECL 扩展库

有时候不能用 pear 安装命令。这可能是因为在防火墙后面,或者是因为想要安装的扩展库还没有 PEAR 兼容的包,例如 CVS 中尚未发布的扩展库。如果要编译这种扩展库,可以用更底层的编译工具来手工进行编译。

phpize 命令是用来准备 PHP 扩展库的编译环境的。下面例子中,扩展库的源程序位于 extname 目录中:

$ cd extname
$ phpize
$ ./configure
$ make
# make install

成功的安装将创建 extname.so 并放置于 PHP 的扩展库目录中。需要调整 php.ini,加入 extension=extname.so 这一行之后才能使用此扩展库。


将 PECL 扩展库静态编译入 PHP

有时可能需要将扩展库静态编译到 PHP 中。这需要将扩展库源程序放入 php-src/ext/ 目录中去并告诉 PHP 编译系统来生成其配置脚本。

$ cd /your/phpsrcdir/ext
$ pear download extname
$ gzip -d < extname.tgz | tar -xvf -
$ mv extname-x.x.x extname

这将产生以下目录:

/your/phpsrcdir/ext/extname

此时强制 PHP 重新生成配置脚本,然后正常编译 PHP:

$ cd /your/phpsrcdir
$ rm configure
$ ./buildconf --force
$ ./configure --help
$ ./configure --with-extname --enable-someotherext --with-foobar
$ make
$ make install

注: 要运行“buildconf”脚本,需要 autoconf 2.13 和 automake 1.4+(更新版本的 autoconf 也许能工作,但不被支持)。

是否用 --enable-extname--with-extname 取决于扩展库。通常不需要外部库文件的扩展库使用 --enable。要确认的话,在 buildconf 之后运行:

$ ./configure --help | grep extname


章 8. 还有问题?

阅读 FAQ

有些问题比其它的更为普遍。最常见的列在 PHP 常见问题中,是本手册的一部分。


其它问题

如果还卡着,PHP 安装邮件列表中的人可能会帮你。应该先查看归档,也许有人已经回答了另一个人提出的和你相同的问题。归档可以从支持页 http://www.php.net/support.php 访问到。要订阅 PHP 安装邮件列表,发送一封空邮件去 php-install-subscribe@lists.php.net。邮件列表地址是 php-install@lists.php.net

如果想从邮件列表中取得帮助,请准确给出有关你的环境的必要细节(哪个操作系统,PHP 的版本,哪个 web 服务器,是否以 CGI 方式还是以服务器模块方式运行 PHP,安全模式,等等),并给出足够的代码让别人能重现和测试你碰到的问题。


错误报告

如果你觉得自己发现了一个 PHP 的 bug,请提出报告。PHP 开发人员也许还不知道有问题,除非你报告了,否则有可能不会被修正。可以通过错误跟踪系统 http://bugs.php.net/ 来报告错误。请不要在邮件列表或私人信件中发送错误报告。错误跟踪系统也可以用来提出对新特性的要求。

在提交错误报告之前请先阅读怎样报告错误


章 9. 运行时配置

配置文件

配置文件(PHP 3 中是 php3.ini,自 PHP 4 起是 php.ini)在 PHP 启动时被读取。对于服务器模块版本的 PHP,仅在 web 服务器启动时读取一次。对于 CGICLI 版本,每次调用都会读取。

php.ini 的搜索路径如下(按顺序):

  • SAPI 模块所指定的位置(Apache 2 中的 PHPIniDir 指令,CGI 和 CLI 中的 -c 命令行选项,NSAPI 中的 php_ini 参数,THTTPD 中的 PHP_INI_PATH 环境变量)

  • HKEY_LOCAL_MACHINE\SOFTWARE\PHP\IniFilePath(Windows 注册表位置)

  • PHPRC 环境变量

  • 当前工作目录(对于 CLI)

  • web 服务器目录(对于 SAPI 模块)或 PHP 所在目录(Windows 下其它情况)

  • Windows 目录(C:\windowsC:\winnt),或 --with-config-file-path 编译时选项指定的位置

如果存在 php-SAPI.ini(SAPI 是当前所用的 SAPI 名称,因此实际文件名为 php-cli.iniphp-apache.ini 等),则会用它替代 php.ini。SAPI 的名称可以用 php_sapi_name() 来测定。

注: Apache web 服务器在启动时会把目录转到根目录,这将导致 PHP 尝试在根目录下读取 php.ini,如果存在的话。

由扩展库处理的 php.ini 指令,其文档分别在各扩展库的页面。内核配置选项见附录。不过也许不是所有的 PHP 指令都在手册中有文档说明。要得到自己的 PHP 版本中的配置指令完整列表,请阅读 php.ini 文件,其中都有注释。此外,也许从 CVS 得到的最新版 php.ini 也有帮助。

例子 9-1. php.ini 例子

; any text on a line after an unquoted semicolon (;) is ignored
[php] ; section markers (text within square brackets) are also ignored
; Boolean values can be set to either:
;    true, on, yes
; or false, off, no, none
register_globals = off
track_errors = yes

; you can enclose strings in double-quotes
include_path = ".:/usr/local/lib/php"

; backslashes are treated the same as any other character
include_path = ".;c:\php\lib"

自 PHP 5.1.0 起,有可能在 .ini 文件内引用已存在的 .ini 变量。例如:open_basedir = ${open_basedir} ":/new/dir"


怎样修改配置设定

PHP 运行于 Apache 模块方式

当使用 PHP 作为 Apache 模块时,也可以用 Apache 的配置文件(例如 httpd.conf)和 .htaccess 文件中的指令来修改 PHP 的配置设定。需要有“AllowOverride Options”或“AllowOverride All”权限才可以。

在 PHP 4 和 PHP 5 中,有几个 Apache 指令可以使用户在 Apache 配置文件内部修改 PHP 的配置。哪些指令属于 PHP_INI_ALLPHP_INI_PERDIRPHP_INI_SYSTEM 中的哪一个,请参考附录中的 php.ini 配置选项列表

注: 在 PHP 3 中,每个 php3.ini 中的配置设定都有相应的 Apache 指令,不过名字前要加上前缀“php3_”。

php_value name value

设定指定的值。只能用于 PHP_INI_ALLPHP_INI_PERDIR 类型的指令。要清除先前设定的值,把 value 设为 none

注: 不要用 php_value 设定布尔值。应该用 php_flag(见下面)。

php_flag name on|off

用来设定布尔值的配置指令。仅能用于 PHP_INI_ALLPHP_INI_PERDIR 类型的指令。

php_admin_value name value

设定指定的指令的值。不能用于 .htaccess 文件。任何用 php_admin_value 设定的指令都不能被 .htaccess 或 virtualhost 中的指令覆盖。要清除先前设定的值,把 value 设为 none

php_admin_flag name on|off

用来设定布尔值的配置指令。不能用于 .htaccess 文件。任何用 php_admin_flag 设定的指令都不能被 .htaccess 或 virtualhost 中的指令覆盖。

例子 9-2. Apache 配置例子

<IfModule mod_php5.c>
  php_value include_path ".:/usr/local/lib/php"
  php_admin_flag safe_mode on
</IfModule>
<IfModule mod_php4.c>
  php_value include_path ".:/usr/local/lib/php"
  php_admin_flag safe_mode on
</IfModule>
<IfModule mod_php3.c>
  php3_include_path ".:/usr/local/lib/php"
  php3_safe_mode on
</IfModule>

注意

PHP 常量不存在于 PHP 之外。例如在 httpd.conf 中不能使用 PHP 常量如 E_ALLE_NOTICE 来设定 error_reporting 指令,因为其无意义,实际等于 0。应该用相应的掩码值来替代。这些常量可以在 php.ini 中使用。


通过 Windows 注册表修改 PHP 配置

在 Windows 下运行 PHP 时,可以用 Windows 注册表以目录为单位来修改配置。配置值存放于注册表项 HKLM\SOFTWARE\PHP\Per Directory Values 下面,子项对应于路径名。例如对于目录 c:\inetpub\wwwroot 的配置值会存放于 HKLM\SOFTWARE\PHP\Per Directory Values\c\inetpub\wwwroot 项下面。其中的设定对于任何位于此目录及其任何子目录的脚本都有效。项中的值的名称是 PHP 配置指令的名字,值的数据是字符串格式的指令值。值中的 PHP 常量不被解析。不过只有可修改范围是 PHP_INI_USER 的配置值可以用此方法设定,PHP_INI_PERDIR 的值就不行。


其它接口下的 PHP

无论怎样运行 PHP,都可以在脚本中通过 ini_set() 而在运行时修改某个值。更多信息见手册中 ini_set() 的页面。

如果对自己系统中的配置设定及其当前值的完整列表感兴趣,可以运行 phpinfo() 函数并查看其结果的页面。也可以在运行时用 ini_get()get_cfg_var() 取得个别配置指令的值。


章 10. 基本语法

从 HTML 中分离

当 PHP 解析一个文件时,会寻找开始和结束标记,标记告诉 PHP 开始和停止解释其中的代码。此种方式的解析可以使 PHP 嵌入到各种不同的文档中,凡是在一对开始和结束标记之外的内容都会被 PHP 解析器忽略。大多数情况下 PHP 都是嵌入在 HTML 文档中的,如下例所示。

<p>This is going to be ignored.</p>
<?php echo 'While this is going to be parsed.'; ?>
<p>This will also be ignored.</p>

还可以用更高级的结构:

例子 10-1. 高级分离术

<?php
if ($expression) {
    ?>
    <strong>This is true.</strong>
    <?php
} else {
    ?>
    <strong>This is false.</strong>
    <?php
}
?>
上例可正常工作,因为当 PHP 碰到结束标记 ?> 时,就简单地将其后的内容原样输出直到碰到下一个开始标记为止。当然,上面的例子很做作,但是对输出大块的文本而言,脱离 PHP 解析模式通常比将所有内容用 echo() 或者 print() 输出更有效率。

可以在 PHP 中使用四对不同的开始和结束标记。其中两种,<?php ?> 和 <script language="php"> </script> 总是可用的。另两种是短标记和 ASP 风格标记,可以在 php.ini 配置文件中打开或关闭。尽管有些人觉得短标记和 ASP 风格标记很方便,但移植性较差,通常不推荐。

注: 此外注意如果将 PHP 嵌入到 XML 或 XHTML 中则需要使用 <?php ?> 以保持符合标准。

例子 10-2. PHP 开始和结束标记

1.  <?php echo 'if you want to serve XHTML or XML documents, do like this'; ?>

2.  <script language="php">
        echo 'some editors (like FrontPage) don\'t
              like processing instructions';
    </script>

3.  <? echo 'this is the simplest, an SGML processing instruction'; ?>
    <?= expression ?> This is a shortcut for "<? echo expression ?>"

4.  <% echo 'You may optionally use ASP-style tags'; %>
    <%= $variable; # This is a shortcut for "<% echo . . ." %>

上例中的 1 和 2 总是可用的,其中 1 是最常用,并建议使用的。

短标记(上例 3)仅在通过 php.ini 配置文件中的指令 short_open_tag 打开后才可用,或者在 PHP 编译时加入了 --enable-short-tags 选项。

注: 如果用 PHP 3 还可以通过 short_tags() 函数激活使用短标记。此方法只适用于 PHP 3!

ASP 风格标记(上例 4)仅在通过 php.ini 配置文件中的指令 asp_tags 打开后才可用。

注: ASP 风格标记的支持是 3.0.4 版添加的。

注: 在以下情况应避免使用短标记:开发需要发行的程序或者库,或者在用户不能控制的服务器上开发。因为目标服务器可能不支持短标记。为了代码的移植及发行,确保不要使用短标记。


指令分隔符

同 C 或 Perl 一样,PHP 需要在每个语句后用分号结束指令。一段 PHP 代码中的结束标记隐含表示了一个分号;在一个 PHP 代码段中的最后一行可以不用分号结束。如果后面还有新行,则代码段的结束标记包含了行结束。

<?php
    echo "This is a test";
?>

<?php echo "This is a test" ?>

注: 文件末尾的 PHP 代码段结束标记可以不要,有些情况下当使用输出缓冲和 include() 或者 require() 时省略掉会更好些。


注释

PHP 支持 C,C++ 和 Unix Shell 风格(Perl 风格)的注释。例如:

<?php
    echo "This is a test"; // This is a one-line c++ style comment
    /* This is a multi line comment
       yet another line of comment */
    echo "This is yet another test";
    echo "One Final Test"; # This is shell-style style comment
?>

单行注释仅仅注释到行末或者当前的 PHP 代码块,视乎哪个首先出现。这意味着在 // ?> 之后的 HTML 代码将被显示出来:?> 跳出了 PHP 模式并返回了 HTML 模式,// 并不能影响到这一点。如果启用了 asp_tags 配置选项,其行为和 // %> 相同。不过,</script> 标记在单行注释中不会跳出 PHP 模式。

<h1>This is an <?php # echo "simple";?> example.</h1>
<p>The header above will say 'This is an example'.

C 风格的注释在碰到第一个 */ 时结束。小心不要嵌套 C 风格的注释,当注释大量代码时,可能犯该错误。

<?php
 /*
    echo "This is a test"; /* This comment will cause a problem */
 */
?>


章 11. 类型

介绍

PHP 支持八种原始类型。

四种标量类型:

两种复合类型:

最后是两种特殊类型:

为了确保代码的易读性,本手册还介绍了一些伪类型

可能还会读到一些关于“双精度(double)”类型的参考。实际上 double 和 float 是相同的,由于一些历史的原因,这两个名称同时存在。

变量的类型通常不是由程序员设定的,确切地说,是由 PHP 根据该变量使用的上下文在运行时决定的。

注: 如果想查看某个表达式的值和类型,用 var_dump()

注: 如果只是想得到一个易读懂的类型的表达方式用于调试,用 gettype()。要查看某个类型,不要gettype(),而用 is_type 函数。以下是一些范例:

<?php
$bool = TRUE;   // a boolean
$str  = "foo";  // a string
$int  = 12;     // an integer

echo gettype($bool); // prints out "boolean"
echo gettype($str);  // prints out "string"

// If this is an integer, increment it by four
if (is_int($int)) {
    $int += 4;
}

// If $bool is a string, print it out
// (does not print out anything)
if (is_string($bool)) {
    echo "String: $bool";
}
?>

如果要将一个变量强制转换为某类型,可以对其使用强制转换或者 settype() 函数。

注意变量根据其当时的类型在特定场合下会表现出不同的值。更多信息见类型戏法。此外,你还可以参考 PHP 类型比较表看不同类型相互比较的例子。


布尔型

这是最简单的类型。boolean 表达了真值,可以为 TRUEFALSE

注: 布尔类型是 PHP 4 引进的。


语法

要指定一个布尔值,使用关键字 TRUEFALSE。两个都不区分大小写。

<?php
$foo = True; // assign the value TRUE to $foo
?>

通常你用某些运算符返回 boolean 值,并将其传递给控制流程

// == is an operator which test
// equality and returns a boolean
if ($action == "show_version") {
    echo "The version is 1.23";
}

// this is not necessary...
if ($show_separators == TRUE) {
    echo "<hr>\n";
}

// ...because you can simply type
if ($show_separators) {
    echo "<hr>\n";
}


转换为布尔值

要明示地将一个值转换成 boolean,用 (bool) 或者 (boolean) 来强制转换。但是很多情况下不需要用强制转换,因为当运算符,函数或者流程控制需要一个 boolean 参数时,该值会被自动转换。

参见类型戏法

当转换为 boolean 时,以下值被认为是 FALSE

所有其它值都被认为是 TRUE(包括任何资源)。

警告

-1 和其它非零值(不论正负)一样,被认为是 TRUE

<?php
var_dump((bool) "");        // bool(false)
var_dump((bool) 1);         // bool(true)
var_dump((bool) -2);        // bool(true)
var_dump((bool) "foo");     // bool(true)
var_dump((bool) 2.3e5);     // bool(true)
var_dump((bool) array(12)); // bool(true)
var_dump((bool) array());   // bool(false)
var_dump((bool) "false");   // bool(true)
?>


整型

一个 integer 是集合 Z = {..., -2, -1, 0, 1, 2, ...} 中的一个数。

参见任意长度整数(GMP)浮点数任意精度数学库(BCMath)


语法

整型值可以用十进制,十六进制或八进制符号指定,前面可以加上可选的符号(- 或者 +)。

如果用八进制符号,数字前必须加上 0(零),用十六进制符号数字前必须加上 0x

例子 11-1. 整数文字表达

<?php
$a = 1234; // 十进制数
$a = -123; // 一个负数
$a = 0123; // 八进制数(等于十进制的 83)
$a = 0x1A; // 十六进制数(等于十进制的 26)
?>
在字面上,整型变量正式的结构可以为:

decimal     : [1-9][0-9]*
            | 0

hexadecimal : 0[xX][0-9a-fA-F]+

octal       : 0[0-7]+

integer     : [+-]?decimal
            | [+-]?hexadecimal
            | [+-]?octal

整型数的字长和平台有关,尽管通常最大值是大约二十亿(32 位有符号)。PHP 不支持无符号整数。

警告

如果向八进制数传递了一个非法数字(即 8 或 9),则后面其余数字会被忽略。

例子 11-2. 八进制数的怪事

<?php
var_dump(01090); // 010 octal = 8 decimal
?>


整数溢出

如果给定的一个数超出了 integer 的范围,将会被解释为 float。同样如果执行的运算结果超出了 integer 范围,也会返回 float

<?php
$large_number =  2147483647;
var_dump($large_number);
// 输出为:int(2147483647)

$large_number =  2147483648;
var_dump($large_number);
// 输出为:float(2147483648)

// 同样也适用于十六进制表示的整数:
var_dump( 0x80000000 );
// 输出为:float(2147483648)

$million = 1000000;
$large_number =  50000 * $million;
var_dump($large_number);
// 输出为:float(50000000000)
?>

警告

不幸的是 PHP 中有个 bug,因此当有负数参与时结果并不总是正确。例如当运算 -50000 * $million 时结果是 -429496728。不过当两个运算数都是正数时就没问题。

这个问题已经在 PHP 4.1.0 中解决了。

PHP 中没有整除的运算符。1/2 产生出 float 0.5。可以总是舍弃小数部分,或者使用 round() 函数。

<?php
var_dump(25/7);         // float(3.5714285714286)
var_dump((int) (25/7)); // int(3)
var_dump(round(25/7));  // float(4)
?>


转换为整形

要明示地将一个值转换为 integer,用 (int)(integer) 强制转换。不过大多数情况下都不需要强制转换,因为当运算符,函数或流程控制需要一个 integer 参数时,值会自动转换。还可以通过函数 intval() 来将一个值转换成整型。

参见类型戏法


布尔值转换

FALSE 将产生出 0(零),TRUE 将产生出 1(壹)。


浮点数转换

当从浮点数转换成整数时,数字将被取整(丢弃小数位)。

如果浮点数超出了整数范围(通常为 +/- 2.15e+9 = 2^31),则结果不确定,因为没有足够的精度使浮点数给出一个确切的整数结果。在此情况下没有警告,甚至没有任何通知!

【译者注】在 Linux 下返回结果是最小负数(-2147483648),而在 Windows 下返回结果是零(0)。

警告

决不要将未知的分数强制转换为 integer,这样有时会导致意外的结果。

<?php
echo (int) ( (0.1+0.7) * 10 ); // 显示 7!
?>

更多信息见浮点数精度


从其它类型转换

注意

没有定义从其它类型转换为整型的行为。目前的行为和值先转换为布尔值一样。不过不要依靠此行为,因为它会未加通知地改变。


浮点型

浮点数(也叫浮点数,双精度数或实数)可以用以下任何语法定义:

<?php
$a = 1.234;
$a = 1.2e3;
$a = 7E-10;
?>

形式上:

LNUM          [0-9]+
DNUM          ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
EXPONENT_DNUM ( ({LNUM} | {DNUM}) [eE][+-]? {LNUM})

浮点数的字长和平台相关,尽管通常最大值是 1.8e308 并具有 14 位十进制数字的精度(64 位 IEEE 格式)。

浮点数精度

显然简单的十进制分数如同 0.10.7 不能在不丢失一点点精度的情况下转换为内部二进制的格式。这就会造成混乱的结果:例如,floor((0.1+0.7)*10) 通常会返回 7 而不是预期中的 8,因为该结果内部的表示其实是类似 7.9999999999...

这和一个事实有关,那就是不可能精确的用有限位数表达某些十进制分数。例如,十进制的 1/3 变成了 0.3333333. . .

所以永远不要相信浮点数结果精确到了最后一位,也永远不要比较两个浮点数是否相等。如果确实需要更高的精度,应该使用任意精度数学函数或者 gmp 函数


转换为浮点数

如果希望了解有关何时和如何将字符串转换成浮点数的信息,请查阅“将字符串转换为数值”一节。对于其它类型的值,其情况类似于先将值转换成整型,然后再转换成浮点。请参阅“转换为整型”一节以获取更多信息。自 PHP 5 起,如果试图将对象转换为浮点数,会发出一条通知。


字符串

string 是一系列字符。在 PHP 中,字符和字节一样,也就是说,一共有 256 种不同字符的可能性。这也暗示 PHP 对 Unicode 没有本地支持。请参阅函数 utf8_encode()utf8_decode() 以了解有关 Unicode 支持。

注: 一个字符串变得非常巨大也没有问题,PHP 没有给字符串的大小强加实现范围,所以完全没有理由担心长字符串。


语法

字符串可以用三种字面上的方法定义。


单引号

指定一个简单字符串的最简单的方法是用单引号(字符 ')括起来。

要表示一个单引号,需要用反斜线(\)转义,和很多其它语言一样。如果在单引号之前或字符串结尾需要出现一个反斜线,需要用两个反斜线表示。注意如果试图转义任何其它字符,反斜线本身也会被显示出来!所以通常不需要转义反斜线本身。

注: 在 PHP 3 中,此情况下将发出一个 E_NOTICE 级的警告。

注: 和其他两种语法不同,单引号字符串中出现的变量和转义序列不会被变量的值替代。

<?php
echo 'this is a simple string';

echo 'You can also have embedded newlines in
strings this way as it is
okay to do';

// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';

// Outputs: You deleted C:\*.*?
echo 'You deleted C:\\*.*?';

// Outputs: You deleted C:\*.*?
echo 'You deleted C:\*.*?';

// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';

// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>


双引号

如果用双引号(")括起字符串,PHP 懂得更多特殊字符的转义序列:

表格 11-1. 转义字符

序列含义
\n换行(LF 或 ASCII 字符 0x0A(10))
\r回车(CR 或 ASCII 字符 0x0D(13))
\t水平制表符(HT 或 ASCII 字符 0x09(9))
\\反斜线
\$美元符号
\"双引号
\[0-7]{1,3} 此正则表达式序列匹配一个用八进制符号表示的字符
\x[0-9A-Fa-f]{1,2} 此正则表达式序列匹配一个用十六进制符号表示的字符

此外,如果试图转义任何其它字符,反斜线本身也会被显示出来!

双引号字符串最重要的一点是其中的变量名会被变量值替代。细节参见字符串解析


定界符

另一种给字符串定界的方法使用定界符语法(“<<<”)。应该在 <<< 之后提供一个标识符,然后是字符串,然后是同样的标识符结束字符串。

结束标识符必须从行的第一列开始。同样,标识符也必须遵循 PHP 中其它任何标签的命名规则:只能包含字母数字下划线,而且必须以下划线或非数字字符开始。

警告

很重要的一点必须指出,结束标识符所在的行不能包含任何其它字符,可能除了一个分号(;)之外。这尤其意味着该标识符不能被缩进,而且在分号之前和之后都不能有任何空格或制表符。同样重要的是要意识到在结束标识符之前的第一个字符必须是你的操作系统中定义的换行符。例如在 Macintosh 系统中是 \r

如果破坏了这条规则使得结束标识符不“干净”,则它不会被视为结束标识符,PHP 将继续寻找下去。如果在这种情况下找不到合适的结束标识符,将会导致一个在脚本最后一行出现的语法错误。

不能用定界符语法初始化类成员。用其它字符串语法替代。

例子 11-3. 非法的例子

<?php
class foo {
    public $bar = <<<EOT
bar
EOT;
}
?>

定界符文本表现的就和双引号字符串一样,只是没有双引号。这意味着在定界符文本中不需要转义引号,不过仍然可以用以上列出来的转义代码。变量会被展开,但当在定界符文本中表达复杂变量时和字符串一样同样也要注意。

例子 11-4. 定界符字符串例子

<?php
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;

/* More complex example, with variables. */
class foo
{
    var $foo;
    var $bar;

    function foo()
    {
        $this->foo = 'Foo';
        $this->bar = array('Bar1', 'Bar2', 'Bar3');
    }
}

$foo = new foo();
$name = 'MyName';

echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>

注: 定界符支持是 PHP 4 中加入的。


变量解析

当用双引号或者定界符指定字符串时,其中的变量会被解析。

有两种语法,一种简单的和一种复杂的。简单语法最通用和方便,它提供了解析变量,数组值,或者对象属性的方法。

复杂语法是 PHP 4 引进的,可以用花括号括起一个表达式。


简单语法

如果遇到美元符号($),解析器会尽可能多地取得后面的字符以组成一个合法的变量名。如果想明示指定名字的结束,用花括号把变量名括起来。

<?php
$beer = 'Heineken';
echo "$beer's taste is great"; // works, "'" is an invalid character for varnames
echo "He drank some $beers";   // won't work, 's' is a valid character for varnames
echo "He drank some ${beer}s"; // works
echo "He drank some {$beer}s"; // works
?>

同样也可以解析数组索引或者对象属性。对于数组索引,右方括号(])标志着索引的结束。对象属性则和简单变量适用同样的规则,尽管对于对象属性没有像变量那样的小技巧。

<?php
// These examples are specific to using arrays inside of strings.
// When outside of a string, always quote your array string keys
// and do not use {braces} when outside of strings either.

// Let's show all errors
error_reporting(E_ALL);

$fruits = array('strawberry' => 'red', 'banana' => 'yellow');
// Works but note that this works differently outside string-quotes
echo "A banana is $fruits[banana].";
// Works
echo "A banana is {$fruits['banana']}.";

// Works but PHP looks for a constant named banana first
// as described below.
echo "A banana is {$fruits[banana]}.";

// Won't work, use braces.  This results in a parse error.
echo "A banana is $fruits['banana'].";

// Works
echo "A banana is " . $fruits['banana'] . ".";

// Works

echo "This square is $square->width meters broad.";
// Won't work. For a solution, see the complex syntax.
echo "This square is $square->width00 centimeters broad.";
?>

对于任何更复杂的情况,应该使用复杂语法。


复杂(花括号)语法

不是因为语法复杂而称其为复杂,而是因为用此方法可以包含复杂的表达式。

事实上,用此语法可以在字符串中包含任何在名字空间的值。仅仅用和在字符串之外同样的方法写一个表达式,然后用 { 和 } 把它包含进来。因为不能转义“{”,此语法仅在 $ 紧跟在 { 后面时被识别(用“{\$”或者“\{$”来得到一个字面上的“{$”)。用一些例子可以更清晰:

<?php
// Let's show all errors
error_reporting(E_ALL);

$great = 'fantastic';

// 不行,输出为:This is { fantastic}
echo "This is { $great}";

// 可以,输出为:This is fantastic
echo "This is {$great}";
echo "This is ${great}";

// Works
echo "This square is {$square->width}00 centimeters broad.";

// Works
echo "This works: {$arr[4][3]}";
// This is wrong for the same reason as $foo[bar] is wrong
// outside a string.  In otherwords, it will still work but
// because PHP first looks for a constant named foo, it will
// throw an error of level E_NOTICE (undefined constant).
echo "This is wrong: {$arr[foo][3]}";
// Works.  When using multi-dimensional arrays, always use
// braces around arrays when inside of strings
echo "This works: {$arr['foo'][3]}";

// Works.
echo "This works: " . $arr['foo'][3];

echo "You can even write {$obj->values[3]->name}";

echo "This is the value of the var named $name: {${$name}}";
?>


访问和修改字符串中的字符

字符串中的字符可以通过在字符串之后用花括号指定所要字符从零开始的偏移量来访问和修改。

注: 为了向下兼容,仍然可以用方括号。不过此语法自 PHP 4 起已过时。

例子 11-5. 一些字符串例子

<?php
// Get the first character of a string
$str = 'This is a test.';
$first = $str{0};
// Get the third character of a string
$third = $str{2};

// Get the last character of a string.
$str = 'This is still a test.';
$last = $str{strlen($str)-1};

// Modify the last character of a string
$str = 'Look at the sea';
$str{strlen($str)-1} = 'e';

?>


实用函数及操作符

字符串可以用“.”(点)运算符连接。注意这里不能用“+”(加)运算符。更多信息参见字符串运算符

有很多实用函数来改变字符串。

普通函数见字符串函数一节,高级搜索和替换见正则表达式函数(两种风格:PerlPOSIX 扩展)。

还有 URL 字符串函数,以及加密/解密字符串的函数(mcryptmhash)。

最后,如果还是找不到想要的函数,参见字符类型函数


字符串转换

可以用 (string) 标记或者 strval() 函数将一个值转换为字符串。当某表达式需要字符串时,字符串的转换会在表达式范围内自动完成。例如当使用 echo() 或者 print() 函数时,或者将一个变量值与一个字符串进行比较的时候。阅读手册中有关类型类型戏法中的部分有助于更清楚一些。参见 settype()

布尔值 TRUE 将被转换为字符串 "1",而值 FALSE 将被表示为 ""(即空字符串)。这样就可以随意地在布尔值和字符串之间进行比较。

整数或浮点数数值在转换成字符串时,字符串由表示这些数值的数字字符组成(浮点数还包含有指数部分)。

数组将被转换成字符串 "Array",因此无法通过 echo() 或者 print() 函数来输出数组的内容。请参考下文以获取更多提示。

对象将被转换成字符串 "Object"。如果因为调试需要,需要将对象的成员变量打印出来,请阅读下文。如果希望得到该对象所依附的类的名称,请使用函数 get_class()。自 PHP 5 起,如果合适可以用 __toString() 方法。

资源类型总是以 "Resource id #1" 的格式被转换成字符串,其中 1 是 PHP 在运行时给资源指定的唯一标识。如果希望获取资源的类型,请使用函数 get_resource_type()

NULL 将被转换成空字符串。

正如以上所示,将数组、对象或者资源打印出来,并不能提供任何关于这些值本身的有用的信息。请参阅函数 print_r()var_dump(),对于调试来说,这些是更好的打印值的方法。

可以将 PHP 的值转换为字符串以永久地储存它们。这种方法被称为序列化,可以用函数 serialize() 来完成该操作。如果在安装 PHP 时建立了 WDDX 支持,还可以将 PHP 的值序列化为 XML 结构。


字符串转换为数值

当一个字符串被当作数字来求值时,根据以下规则来决定结果的类型和值。

如果包括“.”,“e”或“E”其中任何一个字符的话,字符串被当作 float 来求值。否则就被当作整数。

该值由字符串最前面的部分决定。如果字符串以合法的数字数据开始,就用该数字作为其值,否则其值为 0(零)。合法数字数据由可选的正负号开始,后面跟着一个或多个数字(可选地包括十进制分数),后面跟着可选的指数。指数是一个“e”或者“E”后面跟着一个或多个数字。

<?php
$foo = 1 + "10.5";                // $foo is float (11.5)
$foo = 1 + "-1.3e3";              // $foo is float (-1299)
$foo = 1 + "bob-1.3e3";           // $foo is integer (1)
$foo = 1 + "bob3";                // $foo is integer (1)
$foo = 1 + "10 Small Pigs";       // $foo is integer (11)
$foo = 4 + "10.2 Little Piggies"; // $foo is float (14.2)
$foo = "10.0 pigs " + 1;          // $foo is float (11)
$foo = "10.0 pigs " + 1.0;        // $foo is float (11)
?>

此转换的更多信息见 Unix 手册中关于 strtod(3) 的部分。

如果想测试本节中的任何例子,可以拷贝和粘贴这些例子并且加上下面这一行自己看看会发生什么:

<?php
echo "\$foo==$foo; type is " . gettype ($foo) . "<br />\n";
?>

不要指望在将一个字符转换成整型时能够得到该字符的编码(可能也会在 C 中这么做)。如果希望在字符编码和字符之间转换,请使用 ord()chr() 函数。


数组

PHP 中的数组实际上是一个有序图。图是一种把 values 映射到 keys 的类型。此类型在很多方面做了优化,因此可以把它当成真正的数组来使用,或列表(矢量),散列表(是图的一种实现),字典,集合,栈,队列以及更多可能性。因为可以用另一个 PHP 数组作为值,也可以很容易地模拟树。

解释这些结构超出了本手册的范围,但对于每种结构至少会发现一个例子。要得到这些结构的更多信息,建议参考有关此广阔主题的外部著作。


语法

定义 array()

可以用 array() 语言结构来新建一个 array。它接受一定数量用逗号分隔的 key => value 参数对。

array( [key =>]
value
     , ...
     )
// key 可以是 integer 或者 string
// value 可以是任何值

<?php
$arr = array("foo" => "bar", 12 => true);

echo $arr["foo"]; // bar
echo $arr[12];    // 1
?>

key 可以是 integer 或者 string。如果键名是一个 integer 的标准表达方法,则被解释为整数(例如 "8" 将被解释为 8,而 "08" 将被解释为 "08")。key 中的浮点数被取整为 integer。PHP 中没有不同的数字下标和关联下标数组,数组的类型只有一种,它可以同时包含整型和字符串型的下标。

值可以是任何值。

<?php
$arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42));

echo $arr["somearray"][6];    // 5
echo $arr["somearray"][13];   // 9
echo $arr["somearray"]["a"];  // 42
?>

如果对给出的值没有指定键名,则取当前最大的整数索引值,而新的键名将是该值加一。如果指定的键名已经有了值,则该值会被覆盖。

<?php
// This array is the same as ...
array(5 => 43, 32, 56, "b" => 12);

// ...this array
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
?>

警告

自 PHP 4.3.0 起,上述的索引生成方法改变了。如今如果给一个当前最大键名是负值的数组添加一个新值,则新生成的的索引将为零(0)。以前新生成的索引为当前最大索引加一,和正值的索引相同。

使用 TRUE 作为键名将使 integer 1 成为键名。使用 FALSE 作为键名将使 integer 0 成为键名。使用 NULL 作为键名将等同于使用空字符串。使用空字符串作为键名将新建(或覆盖)一个用空字符串作为键名的值,这和用空的方括号不一样。

不能用数组和对象作为键名。这样做会导致一个警告:Illegal offset type


用方括号的语法新建/修改

可以通过明示地设定值来改变一个现有的数组。

这是通过在方括号内指定键名来给数组赋值实现的。也可以省略键名,在这种情况下给变量名加上一对空的方括号(“[]”)。
$arr[key] = value;
$arr[] = value;
// key 可以是 integer 或者 string
// value 可以为任何值。
如果 $arr 还不存在,将会新建一个。这也是一种定义数组的替换方法。要改变一个值,只要给它赋一个新值。如果要删除一个键名/值对,要对它用 unset()

<?php
$arr = array(5 => 1, 12 => 2);
$arr[] = 56;    // This is the same as $arr[13] = 56;
                // at this point of the script
$arr["x"] = 42; // This adds a new element to
                // the array with key "x"
unset($arr[5]); // This removes the element from the array
unset($arr);    // This deletes the whole array
?>

注: 如上所述,如果给出方括号但没有指定键名,则取当前最大整数索引值,新的键名将是该值 + 1。如果当前还没有整数索引,则键名将为 0。如果指定的键名已经有值了,该值将被覆盖。

警告

自 PHP 4.3.0 起,上述的索引生成方法改变了。如今如果给一个当前最大键名是负值的数组添加一个新值,则新生成的的索引将为零(0)。以前新生成的索引为当前最大索引加一,和正值的索引相同。

注意这里所使用的最大整数键名不一定当前就在数组中。它只要在上次数组重新生成索引后曾经存在过就行了。以下面的例子来说明:

<?php
// 创建一个简单的数组
$array = array(1, 2, 3, 4, 5);
print_r($array);

// 现在删除其中的所有单元,但保持数组本身的结构
foreach ($array as $i => $value) {
    unset($array[$i]);
}
print_r($array);

// 添加一个单元(注意新的键名是 5,而不是你可能以为的 0)
$array[] = 6;
print_r($array);

// 重新索引:
$array = array_values($array);
$array[] = 7;
print_r($array);
?>

上例将输出:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Array
(
)
Array
(
    [5] => 6
)
Array
(
    [0] => 6
    [1] => 7
)


实用函数

有相当多的实用函数作用于数组,参见数组函数一节。

注: unset() 函数允许取消一个数组中的键名。要注意数组将不会重建索引。

<?PHP
$a = array( 1 => 'one', 2 => 'two', 3 => 'three' );
unset( $a[2] );
/* 将产生一个数组,定义为
   $a = array( 1=>'one', 3=>'three');
   而不是
   $a = array( 1 => 'one', 2 => 'three');
*/
$b = array_values($a);
// Now $b is array(0 => 'one', 1 =>'three')
?>

foreach 控制结构是专门用于数组的。它提供了一个简单的方法来遍历数组。


数组做什么和不做什么

为什么 $foo[bar] 错了?

应该始终在用字符串表示的数组索引上加上引号。例如用 $foo['bar'] 而不是 $foo[bar]。但是为什么 $foo[bar] 错了呢?可能在老的脚本中见过如下语法:

<?php
$foo[bar] = 'enemy';
echo $foo[bar];
// etc
?>

这样是错的,但可以正常运行。那么为什么错了呢?原因是此代码中有一个未定义的常量(bar)而不是字符串('bar'-注意引号),而 PHP 可能会在以后定义此常量,不幸的是你的代码中有同样的名字。它能运行,是因为 PHP 自动将裸字符串(没有引号的字符串且不对应于任何已知符号)转换成一个其值为该裸字符串的正常字符串。例如,如果没有常量定义为 bar,PHP 将把它替代为 'bar' 并使用之。

注: 这并不意味着总是给键名加上引号。用不着给键名为常量变量的加上引号,否则会使 PHP 不能解析它们。

<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('html_errors', false);
// Simple array:
$array = array(1, 2);
$count = count($array);
for ($i = 0; $i < $count; $i++) {
    echo "\nChecking $i: \n";
    echo "Bad: " . $array['$i'] . "\n";
    echo "Good: " . $array[$i] . "\n";
    echo "Bad: {$array['$i']}\n";
    echo "Good: {$array[$i]}\n";
}
?>

注: 上例将输出:

Checking 0:
Notice: Undefined index:  $i in /path/to/script.html on line 9
Bad:
Good: 1
Notice: Undefined index:  $i in /path/to/script.html on line 11
Bad:
Good: 1

Checking 1:
Notice: Undefined index:  $i in /path/to/script.html on line 9
Bad:
Good: 2
Notice: Undefined index:  $i in /path/to/script.html on line 11
Bad:
Good: 2

演示此效应的更多例子:

<?php
// 显示所有错误
error_reporting(E_ALL);

$arr = array('fruit' => 'apple', 'veggie' => 'carrot');

// 正确
print $arr['fruit'];  // apple
print $arr['veggie']; // carrot

// 不正确。This works but also throws a PHP error of
// level E_NOTICE because of an undefined constant named fruit
//
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
print $arr[fruit];    // apple

// Let's define a constant to demonstrate what's going on.  We
// will assign value 'veggie' to a constant named fruit.
define('fruit','veggie');

// Notice the difference now
print $arr['fruit'];  // apple
print $arr[fruit];    // carrot

// The following is okay as it's inside a string.  Constants are not
// looked for within strings so no E_NOTICE error here
print "Hello $arr[fruit]";      // Hello apple

// With one exception, braces surrounding arrays within strings
// allows constants to be looked for
print "Hello {$arr[fruit]}";    // Hello carrot
print "Hello {$arr['fruit']}";  // Hello apple

// This will not work, results in a parse error such as:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// This of course applies to using autoglobals in strings as well
print "Hello $arr['fruit']";
print "Hello $_GET['foo']";

// Concatenation is another option
print "Hello " . $arr['fruit']; // Hello apple
?>

当打开 error_reporting() 来显示 E_NOTICE 级别的错误(例如将其设为 E_ALL)时将看到这些错误。默认情况下 error_reporting 被关闭不显示这些。

和在语法一节中规定的一样,在方括号(“[”和“]”)之间必须有一个表达式。这意味着可以这样写:

<?php
echo $arr[somefunc($bar)];
?>

这是一个用函数返回值作为数组索引的例子。PHP 也可以用已知常量,可能之前已经见过 E_*

<?php
$error_descriptions[E_ERROR]   = "A fatal error has occured";
$error_descriptions[E_WARNING] = "PHP issued a warning";
$error_descriptions[E_NOTICE]  = "This is just an informal notice";
?>

注意 E_ERROR 也是个合法的标识符,就和第一个例子中的 bar 一样。但是上一个例子实际上和如下写法是一样的:

<?php
$error_descriptions[1] = "A fatal error has occured";
$error_descriptions[2] = "PHP issued a warning";
$error_descriptions[8] = "This is just an informal notice";
?>

因为 E_ERROR 等于 1,等等。

如同在以上例子中解释的那样,$foo[bar] 起作用但其实是错误的。它起作用是因为根据语法的预期,bar 被当成了一个常量表达式。然而,在这个例子中不存在名为 bar 的常量。PHP 就假定指的是字面上的 bar,也就是字符串 "bar",但忘记加引号了。


那么为什么这样做不好?

在未来的某一时刻,PHP 开发小组可能会想新增一个常量或者关键字,或者用户可能希望以后在自己的程序中引入新的常量,那就有麻烦了。例如已经不能这样用 emptydefault 这两个词了,因为他们是保留字

注: 重申一次,在双引号字符串中,不给索引加上引号是合法的因此 "$foo[bar]"是合法的。至于为什么参见以上的例子和字符串中的变量解析中的解释。


转换为数组

对于任何的类型:整型、浮点、字符串、布尔和资源,如果将一个值转换为数组,将得到一个仅有一个元素的数组(其下标为 0),该元素即为此标量的值。

如果将一个对象转换成一个数组,所得到的数组的元素为该对象的属性(成员变量),其键名为成员变量名。

如果将一个 NULL 值转换成数组,将得到一个空数组。


比较

有可能通过 array_diff()数组运算符来比较数组。


例子

PHP 中的数组类型有非常多的用途,因此这里有一些例子展示数组的完整威力。

<?php
// this
$a = array( 'color' => 'red',
            'taste' => 'sweet',
            'shape' => 'round',
            'name'  => 'apple',
                       4        // key will be 0
          );

// is completely equivalent with
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name']  = 'apple';
$a[]        = 4;        // key will be 0

$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// will result in the array array(0 => 'a' , 1 => 'b' , 2 => 'c'),
// or simply array('a', 'b', 'c')
?>

例子 11-6. 使用 array()

<?php
// Array as (property-)map
$map = array( 'version'    => 4,
              'OS'         => 'Linux',
              'lang'       => 'english',
              'short_tags' => true
            );

// strictly numerical keys
$array = array( 7,
                8,
                0,
                156,
                -10
              );
// this is the same as array(0 => 7, 1 => 8, ...)

$switching = array(         10, // key = 0
                    5    =>  6,
                    3    =>  7,
                    'a'  =>  4,
                            11, // key = 6 (maximum of integer-indices was 5)
                    '8'  =>  2, // key = 8 (integer!)
                    '02' => 77, // key = '02'
                    0    => 12  // the value 10 will be overwritten by 12
                  );
// empty array
$empty = array();
?>

例子 11-7. 集合

<?php
$colors = array('red', 'blue', 'green', 'yellow');

foreach ($colors as $color) {
    echo "Do you like $color?\n";
}

?>

上例将输出:

Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?

直接改变数组的值在 PHP 5 中可以通过引用传递来做到。之前的版本需要需要采取别的方法:

例子 11-8. 集合

<?php
// PHP 5
foreach ($colors as &$color) {
    $color = strtoupper($color);
}
unset($color); /* 确保下面对 $color 的覆盖不会影响到前一个数组单元 */
// 之前版本的方法
foreach ($colors as $key => $color) {
    $colors[$key] = strtoupper($color);
}

print_r($colors);
?>

上例将输出:

Array
(
    [0] => RED
    [1] => BLUE
    [2] => GREEN
    [3] => YELLOW
)

本例产生一个基于一的数组。

例子 11-9. 基于一的数组

<?php
$firstquarter  = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>

上例将输出:

Array
(
    [1] => 'January'
    [2] => 'February'
    [3] => 'March'
)
*/
?>

例子 11-10. 填充数组

<?php
// fill an array with all items from a directory
$handle = opendir('.');
while (false !== ($file = readdir($handle))) {
    $files[] = $file;
}
closedir($handle);
?>

数组是有序的。也可以使用不同的排序函数来改变顺序。更多信息参见数组函数。可以用 count() 函数来数出数组中元素的个数。

例子 11-11. 数组排序

<?php
sort($files);
print_r($files);
?>

因为数组中的值可以为任意值,也可是另一个数组。这样可以产生递归或多维数组。

例子 11-12. 递归和多维数组

<?php
$fruits = array ( "fruits"  => array ( "a" => "orange",
                                       "b" => "banana",
                                       "c" => "apple"
                                     ),
                  "numbers" => array ( 1,
                                       2,
                                       3,
                                       4,
                                       5,
                                       6
                                     ),
                  "holes"   => array (      "first",
                                       5 => "second",
                                            "third"
                                     )
                );

// Some examples to address values in the array above
echo $fruits["holes"][5];    // prints "second"
echo $fruits["fruits"]["a"]; // prints "orange"
unset($fruits["holes"][0]);  // remove "first"

// Create a new multi-dimensional array
$juices["apple"]["green"] = "good";
?>

需要注意数组的赋值总是会涉及到值的拷贝。需要在复制数组时用引用符号(&)。

<?php
$arr1 = array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 is changed,
             // $arr1 is still array(2,3)

$arr3 = &$arr1;
$arr3[] = 4; // now $arr1 and $arr3 are the same
?>


对象

对象初始化

要初始化一个对象,用 new 语句将对象实例到一个变量中。

<?php
class foo
{
    function do_foo()
    {
        echo "Doing foo.";
    }
}

$bar = new foo;
$bar->do_foo();
?>

完整的讨论见类与对象一章。


转换为对象

如果将一个对象转换成对象,它将不会有任何变化。如果其它任何类型的值被转换成对象,内置类 stdClass 的一个实例将被建立。如果该值为 NULL,则新的实例为空。对于任何其它的值,名为 scalar 的成员变量将包含该值。

<?php
$obj = (object) 'ciao';
echo $obj->scalar;  // outputs 'ciao'
?>


资源

资源是一种特殊变量,保存了到外部资源的一个引用。资源是通过专门的函数来建立和使用的。所有这些函数及其相应资源类型见附录

注: 资源类型是 PHP 4 引进的。

参见 get_resource_type()


转换为资源

由于资源类型变量保存有为打开文件、数据库连接、图形画布区域等的特殊句柄,因此无法将其它类型的值转换为资源。


释放资源

由于 PHP4 Zend 引擎引进了资源计数系统,可以自动检测到一个资源不再被引用了(和 Java 一样)。这种情况下此资源使用的所有外部资源都会被垃圾回收系统释放。由此原因,很少需要用某些 free-result 函数来手工释放内存。

注: 持久数据库连接比较特殊,它们不会被垃圾回收系统破坏。参见数据库永久连接一章。


NULL

特殊的 NULL 值表示一个变量没有值。NULL 类型唯一可能的值就是 NULL

注: NULL 类型是 PHP 4 引进的。

在下列情况下一个变量被认为是 NULL

  • 被赋值为 NULL

  • 尚未被赋值。

  • unset()


语法

NULL 类型只有一个值,就是大小写敏感的关键字 NULL

<?php
$var = NULL;
?>

参见 is_null()unset()


本文档中使用的伪类型

mixed

mixed 说明一个参数可以接受多种不同的(但并不必须是所有的)类型。

例如 gettype() 可以接受所有的 PHP 类型,str_replace() 可以接受字符串和数组。


number

number 说明一个参数可以是 integer 或者 float


callback

有些诸如 call_user_function()usort() 的函数接受用户自定义的函数作为一个参数。Callback 函数不仅可以是一个简单的函数,它还可以是一个对象的方法,包括静态类的方法。

一个 PHP 函数用函数名字符串来传递。可以传递任何内置的或者用户自定义的函数,除了 array()echo()empty()eval()exit()isset()list()print()unset()

一个对象的方法以数组的形式来传递,数组的下标 0 指明对象名,下标 1 指明方法名。

对于没有实例化为对象的静态类,要传递其方法,将数组 0 下标指明的对象名换成该类的名称即可。

例子 11-13. Callback 函数实例

<?php
// An example callback function
function my_callback_function() {
    echo 'hello world!';
}

// An example callback method
class MyClass {
    function myCallbackMethod() {
        echo 'Hello World!';
    }
}

// Type 1: Simple callback
call_user_func('my_callback_function');

// Type 2: Static class method call
call_user_func(array('MyClass', 'myCallbackMethod'));

// Type 3: Object method call
$obj = new MyClass();
call_user_func(array(&$obj, 'myCallbackMethod'));
?>


类型戏法

PHP 在变量定义中不需要(或不支持)明示的类型定义;变量类型是根据使用该变量的上下文所决定的。也就是说,如果把一个字符串值赋给变量 varvar 就成了一个字符串。如果又把一个整型值赋给 var,那它就成了一个整数。

PHP 的自动类型转换的一个例子是加号“+”。如果任何一个运算数是浮点数,则所有的运算数都被当成浮点数,结果也是浮点数。否则运算数会被解释为整数,结果也是整数。注意这并没有改变这些运算数本身的类型;改变的仅是这些运算数如何被求值。

<?php
$foo = "0";  // $foo is string (ASCII 48)
$foo += 2;   // $foo is now an integer (2)
$foo = $foo + 1.3;  // $foo is now a float (3.3)
$foo = 5 + "10 Little Piggies"; // $foo is integer (15)
$foo = 5 + "10 Small Pigs";     // $foo is integer (15)
?>

如果上面两个例子看上去古怪的话,参见字符串转换为数值

如果要强制将一个变量当作某种类型来求值,参见类型强制转换一节。如果要改变一个变量的类型,参见 settype()

如果想要测试本节中任何例子的话,可以用 var_dump() 函数。

注: 数组的自动转换行为目前没有定义。

<?php
$a = "1";     // $a 是字符串
$a[0] = "f";  // 是字符串偏移量吗?结果会是什么?
?>

由于一些历史原因,PHP 支持通过偏移量进行的字符串索引,这和数组索引的语法一样。以上的例子就产生了一个问题:$a 应该变成一个第一个元素是“f”的数组呢,还是“f”成了字符串 $a 的第一个字符?

目前版本的 PHP 将以上第二个赋值理解成字符串的偏移量标识,即 $a 变成了 "f",尽管如此,这种自动转换的地结果应该被认为未定义。PHP 4 引入了新的花括号语法来访问字符串的字符,请使用该语法来替代以上的操作:

<?php
$a    = "abc"; // $a 为一个字符串
$a{1} = "f";   // $a 目前为 "afc"
?>

请参阅访问和修改字符串中的字符一节以获取更多信息。


类型强制转换

PHP 中的类型强制转换和 C 中的非常像:在要转换的变量之前加上用括号括起来的目标类型。

<?php
$foo = 10;   // $foo is an integer
$bar = (boolean) $foo;   // $bar is a boolean
?>

允许的强制转换有:

  • (int),(integer) - 转换成整型

  • (bool),(boolean) - 转换成布尔型

  • (float),(double),(real) - 转换成浮点型

  • (string) - 转换成字符串

  • (array) - 转换成数组

  • (object) - 转换成对象

注意在括号内允许有空格和制表符,所以下面两个例子功能相同:

<?php
$foo = (int) $bar;
$foo = ( int ) $bar;
?>

注: 为了将一个变量还原为字符串,还可以将变量放置在双引号中。

<?php
$foo = 10;            // $foo is an integer
$str = "$foo";        // $str is a string
$fst = (string) $foo; // $fst is also a string

// This prints out that "they are the same"
if ($fst === $str) {
    echo "they are the same";
}
?>

当在某些类型之间强制转换时确切地会发生什么可能不是很明显。更多信息见如下小节:


章 12. 变量

基础

PHP 中的变量用一个美元符号后面跟变量名来表示。变量名是区分大小写的。

变量名与 PHP 中其它的标签一样遵循相同的规则。一个有效的变量名由字母或者下划线开头,后面跟上任意数量的字母,数字,或者下划线。按照正常的正则表达式,它将被表述为:'[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'。

注: 在此所说的字母是 a-z,A-Z,以及 ASCII 字符从 127 到 255(0x7f-0xff)。

有关变量的函数信息见变量函数

<?php
$var = 'Bob';
$Var = 'Joe';
echo "$var, $Var";      // 输出 "Bob, Joe"

$4site = 'not yet';     // 非法变更名;以数字开头
$_4site = 'not yet';    // 合法变量名;以下划线开头
$i站点is = 'mansikka';  // 合法变量名;可以用中文
?>

PHP 3 中,变量总是传值赋值。那也就是说,当将一个表达式的值赋予一个变量时,整个原始表达式的值被赋值到目标变量。这意味着,例如,当一个变量的值赋予另外一个变量时,改变其中一个变量的值,将不会影响到另外一个变量。有关这种类型的赋值操作,请参阅表达式一章。

PHP 4 提供了另外一种方式给变量赋值:引用赋值。这意味着新的变量简单的引用(换言之,“成为其别名” 或者 “指向”)了原始变量。改动新的变量将影响到原始变量,反之亦然。这同样意味着其中没有执行复制操作;因而,这种赋值操作更加快速。不过只有在密集的循环中或者对很大的数组对象赋值时才有可能注意到速度的提升。

使用引用赋值,简单地将一个 & 符号加到将要赋值的变量前(源变量)。例如,下列代码片断将输出“My name is Bob”两次:

<?php
$foo = 'Bob';              // Assign the value 'Bob' to $foo
$bar = &$foo;              // Reference $foo via $bar.
$bar = "My name is $bar";  // Alter $bar...
echo $bar;
echo $foo;                 // $foo is altered too.
?>

有一点重要事项必须指出,那就是只有有名字的变量才可以引用赋值。

<?php
$foo = 25;
$bar = &$foo;      // This is a valid assignment.
$bar = &(24 * 7);  // Invalid; references an unnamed expression.

function test()
{
   return 25;
}

$bar = &test();    // Invalid.
?>


预定义变量

PHP 提供了大量的预定义变量。由于许多变量依赖于运行的服务器的版本和设置,及其它因素,所以并没有详细的说明文档。一些预定义变量在 PHP 以命令行形式运行时并不生效。有关这些变量的详细列表,请参阅预定义变量一章。

警告

PHP 4.2.0 以及后续版本中,PHP 指令 register_globals 的默认值为 off。这是 PHP 的一个主要变化。让 register_globals 的值为 off 将影响到预定义变量集在全局范围内的有效性。例如,为了得到 DOCUMENT_ROOT 的值,将必须使用 $_SERVER['DOCUMENT_ROOT'] 代替 $DOCUMENT_ROOT,又如,使用 $_GET['id'] 来代替 $id 从 URL http://www.example.com/test.php?id=3 中获取 id 值,亦或使用 $_ENV['HOME'] 来代替 $HOME 获取环境变量 HOME 的值。

更多相关信息,请阅读 register_globals 的配置项条目,安全一章中的使用 Register Globals,以及 PHP 4.1.04.2.0 的发行通告。

如果有可用的 PHP 预定义变量那最好用,如超全局变量

从 PHP 4.1.0 开始,PHP 提供了一套附加的预定数组,这些数组变量包含了来自 web 服务器(如果可用),运行环境,和用户输入的数据。这些数组非常特别,它们在全局范围内自动生效,例如,在任何范围内自动生效。因此通常被称为自动全局变量(autoglobals)或者超全局变量(superglobals)。(PHP 中没有用户自定义超全局变量的机制。)超全局变量罗列于下文中;但是为了得到它们的内容和关于 PHP 预定义变量的进一步的讨论以及它们的本质,请参阅预定义变量。而且,你也将注意到旧的预定义数组($HTTP_*_VARS)仍旧存在。自 PHP 5.0.0 起,长格式的 PHP 预定义变量可以通过设置 register_long_arrays 来屏蔽。

可变变量: 超级全局变量不能被用作可变变量

注: 尽管超全局变量和 HTTP_*_VARS 同时存在。但是他们并不是同一个变量,所以改变一个的值并不会对另一个产生影响。

如果某些 variables_order 中的变量没有设定,它们的对应的 PHP 预定义数组也是空的。

PHP 超全局变量

$GLOBALS

包含一个引用指向每个当前脚本的全局范围内有效的变量。该数组的键名为全局变量的名称。从 PHP 3 开始存在 $GLOBALS 数组。

$_SERVER

变量由 web 服务器设定或者直接与当前脚本的执行环境相关联。类似于旧数组 $HTTP_SERVER_VARS 数组(依然有效,但反对使用)。

$_GET

经由 URL 请求提交至脚本的变量。类似于旧数组 $HTTP_GET_VARS 数组(依然有效,但反对使用)。

$_POST

经由 HTTP POST 方法提交至脚本的变量。类似于旧数组 $HTTP_POST_VARS 数组(依然有效,但反对使用)。

$_COOKIE

经由 HTTP Cookies 方法提交至脚本的变量。类似于旧数组 $HTTP_COOKIE_VARS 数组(依然有效,但反对使用)。

$_FILES

经由 HTTP POST 文件上传而提交至脚本的变量。类似于旧数组 $HTTP_POST_FILES 数组(依然有效,但反对使用)。详细信息请参阅 POST 方法上传

$_ENV

执行环境提交至脚本的变量。类似于旧数组 $HTTP_ENV_VARS 数组(依然有效,但反对使用)。

$_REQUEST

经由 GET,POST 和 COOKIE 机制提交至脚本的变量,因此该数组并不值得信任。所有包含在该数组中的变量的存在与否以及变量的顺序均按照 php.ini 中的 variables_order 配置指示来定义。此数组在 PHP 4.1.0 之前没有直接对应的版本。参见 import_request_variables()

注意

自 PHP 4.3.0 起,$_FILES 中的文件信息不再存在于 $_REQUEST 中。

注: 当运行于命令行模式时,此数组将不会包含 argvargc 条目;它们已经存在于数组 $_SERVER 中。

$_SESSION

当前注册给脚本会话的变量。类似于旧数组 $HTTP_SESSION_VARS 数组(依然有效,但反对使用)。详细信息,请参照 Session 处理函数章节。


变量范围

变量的范围即它定义的上下文背景(也就是它的生效范围)。大部分的 PHP 变量只有一个单独的范围。这个单独的范围跨度同样包含了 include 和 require 引入的文件。例如:

<?php
$a = 1;
include 'b.inc';
?>

这里变量 $a 将会在包含文件 b.inc 中生效。但是,在用户自定义函数中,一个局部函数范围将被引入。任何用于函数内部的变量按缺省情况将被限制在局部函数范围内。例如:

<?php
$a = 1; /* global scope */

function Test()
{
    echo $a; /* reference to local scope variable */
}

Test();
?>

这个脚本不会有任何输出,因为 echo 语句引用了一个局部版本的变量 $a,而且在这个范围内,它并没有被赋值。你可能注意到 PHP 的全局变量和 C 语言有一点点不同,在 C 语言中,全局变量在函数中自动生效,除非被局部变量覆盖。这可能引起一些问题,有些人可能漫不经心的改变一个全局变量。PHP 中全局变量在函数中使用时必须申明为全局。


global 关键字

首先,一个使用 global 的例子:

例子 12-1. 使用 global

<?php
$a = 1;
$b = 2;

function Sum()
{
    global $a, $b;

    $b = $a + $b;
}

Sum();
echo $b;
?>

以上脚本的输出将是“3”。在函数中申明了全局变量 $a$b,任何变量的所有引用变量都会指向到全局变量。对于一个函数能够申明的全局变量的最大个数,PHP 没有限制。

在全局范围内访问变量的第二个办法,是用特殊的 PHP 自定义 $GLOBALS 数组。前面的例子可以写成:

例子 12-2. 使用 $GLOBALS 替代 global

<?php
$a = 1;
$b = 2;

function Sum()
{
    $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}

Sum();
echo $b;
?>

$GLOBALS 数组中,每一个变量为一个元素,键名对应变量名,值对应变量的内容。$GLOBALS 之所以在全局范围内存在,是因为 $GLOBALS 是一个超全局变量。以下范例显示了超全局变量的用处:

例子 12-3. 演示超全局变量和作用域的例子

<?php
function test_global()
{
    // 大多数的预定义变量并不 "super",它们需要用 'global' 关键字来使它们在函数的本地区域中有效。
    global $HTTP_POST_VARS;

    echo $HTTP_POST_VARS['name'];

    // Superglobals 在任何范围内都有效,它们并不需要 'global' 声明。Superglobals 是在 PHP 4.1.0 引入的。
    echo $_POST['name'];
}
?>


使用静态变量

变量范围的另一个重要特性是静态变量(static variable)。静态变量仅在局部函数域中存在,但当程序执行离开此作用域时,其值并不丢失。看看下面的例子:

例子 12-4. 演示需要静态变量的例子

<?php
function Test()
{
    $a = 0;
    echo $a;
    $a++;
}
?>

本函数没什么用处,因为每次调用时都会将 $a 的值设为 0 并输出 "0"。将变量加一的 $a++ 没有作用,因为一旦退出本函数则变量 $a 就不存在了。要写一个不会丢失本次计数值的计数函数,要将变量 $a 定义为静态的:

例子 12-5. 使用静态变量的例子

<?php
function Test()
{
    static $a = 0;
    echo $a;
    $a++;
}
?>

现在,每次调用 Test() 函数都会输出 $a 的值并加一。

静态变量也提供了一种处理递归函数的方法。递归函数是一种调用自己的函数。写递归函数时要小心,因为可能会无穷递归下去。必须确保有充分的方法来中止递归。一下这个简单的函数递归计数到 10,使用静态变量 $count 来判断何时停止:

例子 12-6. 静态变量与递归函数

<?php
function Test()
{
    static $count = 0;

    $count++;
    echo $count;
    if ($count < 10) {
        Test();
    }
    $count--;
}
?>

注: 静态变量可以按照上面的例子声明。如果在声明中用表达式的结果对其赋值会导致解析错误。

例子 12-7. 声明静态变量

<?php
function foo(){
    static $int = 0;          // correct
    static $int = 1+2;        // wrong  (as it is an expression)
    static $int = sqrt(121);  // wrong  (as it is an expression too)

    $int++;
    echo $int;
}
?>


全局和静态变量的引用

在 Zend 引擎 1 代,它驱动了 PHP4,对于变量的 staticglobal 定义是以 references 的方式实现的。例如,在一个函数域内部用 global 语句导入的一个真正的全局变量实际上是建立了一个到全局变量的引用。这有可能导致预料之外的行为,如以下例子所演示的:

<?php
function test_global_ref() {
    global $obj;
    $obj = &new stdclass;
}

function test_global_noref() {
    global $obj;
    $obj = new stdclass;
}

test_global_ref();
var_dump($obj);
test_global_noref();
var_dump($obj);
?>

执行以上例子会导致如下输出:

NULL
object(stdClass)(0) {
}

类似的行为也适用于 static 语句。引用并不是静态地存储的:

<?php
function &get_instance_ref() {
    static $obj;

    echo 'Static object: ';
    var_dump($obj);
    if (!isset($obj)) {
        // 将一个引用赋值给静态变量
        $obj = &new stdclass;
    }
    $obj->property++;
    return $obj;
}

function &get_instance_noref() {
    static $obj;

    echo 'Static object: ';
    var_dump($obj);
    if (!isset($obj)) {
        // 将一个对象赋值给静态变量
        $obj = new stdclass;
    }
    $obj->property++;
    return $obj;
}

$obj1 = get_instance_ref();
$still_obj1 = get_instance_ref();
echo "\n";
$obj2 = get_instance_noref();
$still_obj2 = get_instance_noref();
?>

执行以上例子会导致如下输出:

Static object: NULL
Static object: NULL

Static object: NULL
Static object: object(stdClass)(1) {
  ["property"]=>
  int(1)
}

上例演示了当把一个引用赋值给一个静态变量时,第二次调用 &get_instance_ref() 函数时其值并没有被记住


可变变量

有时候使用可变变量名是很方便的。就是说,一个变量的变量名可以动态的设置和使用。一个普通的变量通过声明来设置,例如:

<?php
$a = 'hello';
?>

一个可变变量获取了一个普通变量的值作为这个可变变量的变量名。在上面的例子中 hello 使用了两个美元符号($)以后,就可以作为一个可变变量的变量了。例如:

<?php
$$a = 'world';
?>

这时,两个变量都被定义了:$a 的内容是“hello”并且 $hello 的内容是“world”。因此,可以表述为:

<?php
echo "$a ${$a}";
?>

以下写法更准确并且会输出同样的结果:

<?php
echo "$a $hello";
?>

它们都会输出:hello world

要将可变变量用于数组,必须解决一个模棱两可的问题。这就是当写下 $$a[1] 时,解析器需要知道是想要 $a[1] 作为一个变量呢,还是想要 $$a 作为一个变量并取出该变量中索引为 [1] 的值。解决此问题的语法是,对第一种情况用 ${$a[1]},对第二种情况用 ${$a}[1]

警告

注意,在 PHP 的函数和类的方法中,超全局变量不能用作可变变量。


来自 PHP 之外的变量

HTML 表单(GET 和 POST)

当一个表单体交给 PHP 脚本时,表单中的信息会自动在脚本中可用。有很多方法访问此信息,例如:

例子 12-8. 一个简单的 HTML 表单

<form action="foo.php" method="POST">
    Name:  <input type="text" name="username"><br />
    Email: <input type="text" name="email"><br />
    <input type="submit" name="submit" value="Submit me!" />
</form>

根据特定的设置和个人的喜好,有很多种方法访问 HTML 表单中的数据。例如:

例子 12-9. 从一个简单的 POST HTML 表单访问数据

<?php
// 自 PHP 4.1.0 起可用
   echo $_POST['username'];
   echo $_REQUEST['username'];
   import_request_variables('p', 'p_');
   echo $p_username;
// 自 PHP 3 起可用。自 PHP 5.0.0 起,这些较长的预定义变量
// 可用 register_long_arrays 指令关闭。
   echo $HTTP_POST_VARS['username'];
// 如果 PHP 指令 register_globals = on 时可用。不过自
// PHP 4.2.0 起默认值为 register_globals = off。
// 不提倡使用/依赖此种方法。
   echo $username;
?>

使用 GET 表单也类似,只不过要用适当的 GET 预定义变量。GET 也适用于 QUERY_STRING(URL 中在“?”之后的信息)。因此,举例说,http://www.example.com/test.php?id=3 包含有可用 $_GET['id'] 访问的 GET 数据。参见 $_REQUESTimport_request_variables()

注: 超全局变量$_POST 以及 $_GET 一样,自 PHP 4.1.0 起可用。

如上所示,在 PHP 4.2.0 之前 register_globals 的默认值是 on。在 PHP 3 中其值总是 on。PHP 社区鼓励大家不要依赖此指令,建议在编码时假定其为 off

注: magic_quotes_gpc 配置指令影响到 Get,Post 和 Cookie 的值。如果打开,值 (It's "PHP!") 会自动转换成 (It\'s \"PHP!\")。数据库的插入就需要转义。参见 addslashes()stripslashes()magic_quotes_sybase

PHP 也懂得表单变量上下文中的数组(参见相关常见问题)。例如可以将相关的变量编成组,或者用此特性从多选输入框中取得值。例如,将一个表单 POST 给自己并在提交时显示数据:

例子 12-10. 更复杂的表单变量

<?php
if (isset($_POST['action']) && $_POST['action'] == 'submitted') {
    echo '<pre>';

    print_r($_POST);
    echo '<a href="'. $_SERVER['PHP_SELF'] .'">Please try again</a>';

    echo '</pre>';
} else {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    Name:  <input type="text" name="personal[name]"><br />
    Email: <input type="text" name="personal[email]"><br />
    Beer: <br>
    <select multiple name="beer[]">
        <option value="warthog">Warthog</option>
        <option value="guinness">Guinness</option>
        <option value="stuttgarter">Stuttgarter Schwabenbr</option>
    </select><br />
    <input type="hidden" name="action" value="submitted" />
    <input type="submit" name="submit" value="submit me!" />
</form>
<?php
}
?>

在 PHP 3 中,变量使用中的数组仅限于一维数组。在 PHP 4 中,没有此种限制。


IMAGE SUBMIT 变量名

当提交表单时,可以用一幅图像代替标准的提交按钮,用类似这样的标记:

<input type="image" src="image.gif" name="sub" />

当用户点击到图像中的某处时,相应的表单会被传送到服务器,并加上两个变量 sub_x 和 sub_y。它们包含了用户点击图像的坐标。有经验的用户可能会注意到被浏览器发送的实际变量名包含的是一个点而不是下划线(即 sub.x 和 sub.y),但 PHP 自动将点转换成了下划线。


HTTP Cookies

PHP 透明地支持 Netscape 规范定义中的 HTTP cookies。Cookies 是一种在远端浏览器端存储数据并能追踪或识别再次访问的用户的机制。可以用 setcookie() 函数设定 cookies。Cookies 是 HTTP 信息头中的一部分,因此 SetCookie 函数必须在向浏览器发送任何输出之前调用。对于 header() 函数也有同样的限制。Cookie 数据会在相应的 cookie 数据数组中可用,例如 $_COOKIE$HTTP_COOKIE_VARS$_REQUEST。更多细节和例子见 setcookie() 手册页面。

如果要将多个值赋给一个 cookie 变量,必须将其赋成数组。例如:

<?php
  setcookie("MyCookie[foo]", 'Testing 1', time()+3600);
  setcookie("MyCookie[bar]", 'Testing 2', time()+3600);
?>

这将会建立两个单独的 cookie,尽管 MyCookie 在脚本中是一个单一的数组。如果想在仅仅一个 cookie 中设定多个值,考虑先在值上使用 serialize()explode()

注意在浏览器中一个 cookie 会替换掉上一个同名的 cookie,除非路径或者域不同。因此对于购物车程序可以保留一个计数器并一起传递,例如:

例子 12-11. 一个 setcookie() 的示例

<?php
if (isset($_COOKIE['count'])) {
    $count = $_COOKIE['count'] + 1;
} else {
    $count = 1;
}
setcookie('count', $count, time()+3600);
setcookie("Cart[$count]", $item, time()+3600);
?>

变量名中的点

通常,PHP 不会改变传递给脚本中的变量名。然而应该注意到点(句号)不是 PHP 变量名中的合法字符。至于原因,看看:
<?php
$varname.ext;  /* 非法变量名 */
?>
这时,解析器看到是一个名为 $varname 的变量,后面跟着一个字符串连接运算符,后面跟着一个裸字符串(即没有加引号的字符串,且不匹配任何已知的健名或保留字)'ext'。很明显这不是想要的结果。

出于此原因,要注意 PHP 将会自动将变量名中的点替换成下划线。


确定变量类型

因为 PHP 会判断变量类型并在需要时进行转换(通常情况下),因此在某一时刻给定的变量是何种类型并不明显。PHP 包括几个函数可以判断变量的类型,例如:gettype()is_array()is_float()is_int()is_object()is_string()。参见类型一章。


章 13. 常量

常量是一个简单值的标识符(名字)。如同其名称所暗示的,在脚本执行期间该值不能改变(除了所谓的魔术常量,它们其实不是常量)。常量默认为大小写敏感。按照惯例常量标识符总是大写的。

常量名和其它任何 PHP 标签遵循同样的命名规则。合法的常量名以字母或下划线开始,后面跟着任何字母,数字或下划线。用正则表达式是这样表达的:[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

例子 13-1. 合法与非法的常量名

<?php

// 合法的常量名
define("FOO",     "something");
define("FOO2",    "something else");
define("FOO_BAR", "something more")

// 非法的常量名
define("2FOO",    "something");

// This is valid, but should be avoided:
// PHP may one day provide a magical constant
// that will break your script
define("__FOO__", "something");

?>

注: 在这里,字母是 a-z,A-Z,以及从 127 到 255(0x7f-0xff)的 ASCII 字符。

superglobals 一样,常量的范围是全局的。不用管作用域就可以在脚本的任何地方访问常量。有关作用得更多信息请阅读手册中的变量范围


语法

可以用 define() 函数来定义常量。一个常量一旦被定义,就不能再改变或者取消定义。

常量只能包含标量数据(booleanintegerfloatstring)。

可以简单的通过指定其名字来取得常量的值,不要在常量前面加上 $ 符号。如果常量名是动态的,也可以用函数 constant() 来读取常量的值。用 get_defined_constants() 可以获得所有已定义的常量列表。

注: 常量和(全局)变量在不同的名字空间中。这意味着例如 TRUE$TRUE 是不同的。

如果使用了一个未定义的常量,PHP 假定想要的是该常量本身的名字,如同用字符串调用它一样(CONSTANT 对应 "CONSTANT")。此时将发出一个 E_NOTICE 级的错误。参见手册中为什么 $foo[bar] 是错误的(除非事先用 define()bar 定义为一个常量)。如果只想检查是否定义了某常量,用 defined() 函数。

常量和变量不同:

  • 常量前面没有美元符号($);

  • 常量只能用 define() 函数定义,而不能通过赋值语句;

  • 常量可以不用理会变量范围的规则而在任何地方定义和访问;

  • 常量一旦定义就不能被重新定义或者取消定义;

  • 常量的值只能是标量。

例子 13-2. 定义常量

<?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
echo Constant; // outputs "Constant" and issues a notice.
?>

参见类常量


魔术常量

PHP 向它运行的任何脚本提供了大量的预定义常量。不过很多常量都是由不同的扩展库定义的,只有在加载了这些扩展库时才会出现,或者动态加载后,或者在编译时已经包括进去了。

有五个魔术常量根据它们使用的位置而改变。例如 __LINE__ 的值就依赖于它在脚本中所处的行来决定。这些特殊的常量不区分大小写,如下:

表格 13-1. 几个 PHP 的“魔术常量”

名称说明
__LINE__ 文件中的当前行号。
__FILE__ 文件的完整路径和文件名。如果用在包含文件中,则返回包含文件名。自 PHP 4.0.2 起,__FILE__ 总是包含一个绝对路径,而在此之前的版本有时会包含一个相对路径。
__FUNCTION__ 函数名称(PHP 4.3.0 新加)。自 PHP 5 起本常量返回该函数被定义时的名字(区分大小写)。在 PHP 4 中该值总是小写字母的。
__CLASS__ 类的名称(PHP 4.3.0 新加)。自 PHP 5 起本常量返回该类被定义时的名字(区分大小写)。在 PHP 4 中该值总是小写字母的。
__METHOD__ 类的方法名(PHP 5.0.0 新加)。返回该方法被定义时的名字(区分大小写)。

参见 get_class()get_object_vars()file_exists()function_exists()


章 14. 表达式

表达式是 PHP 最重要的基石。在 PHP 中,几乎所写的任何东西都是一个表达式。简单但却最精确的定义一个表达式的方式就是“任何有值的东西”。

最基本的表达式形式是常量和变量。当键入“$a = 5”,即将值“5”分配给变量 $a。“5”,很明显,其值为 5,换句话说“5”是一个值为 5 的表达式(在这里,“5”是一个整型常量)。

赋值之后,所期待情况是 $a 的值为 5,因而如果写下 $b = $a,期望的是它犹如 $b = 5 一样。换句话说,$a 是一个值也为 5 的表达式。如果一切运行正确,那这正是将要发生的正确结果。

稍微复杂的表达式例子就是函数。例如,考虑下面的函数:

<?php
function foo ()
{
    return 5;
}
?>

假定已经熟悉了函数的概念(如果不是的话,请看一下函数的相关章节),那么键入 $c = foo() 从本质上来说就如写下 $c = 5,这没错。函数也是表达式,表达式的值即为它们的返回值。既然 foo() 返回 5,表达式“foo()”的值也是 5。通常函数不会仅仅返回一个静态值,而可能会计算一些东西。

当然,PHP 中的值常常并非是整型的。PHP 支持四种标量值(标量值不能拆分为更小的单元,例如和数组不同)类型:整型值(integer),浮点数值(float),字符串值(string)和布尔值(boolean)。PHP 也支持两种复合类型:数组和对象。这两种类型具可以赋值给变量或者从函数返回。

PHP 和其它语言一样在表达式的道路上发展,但推进得更深远。PHP 是一种面向表达式的语言,从这一方面来讲几乎一切都是表达式。考虑刚才已经研究过的例子,“$a = 5”。很显然这里涉及到两个值,整型常量 5 的值以及而且变量 $a 的值,它也被更新为 5。但是事实是这里还涉及到一个额外的值,即附值语句本身的值。赋值语句本身求值为被赋的值,即 5。实际上这意味着“$a = 5”,不必管它是做什么的,是一个值为 5 的表达式。因而,这样写“$b = ($a = 5)”和这样写“$a =5; $b=5”(分号标志着语句的结束)是一样的。因为赋值操作的顺序是由右到左的,也可以这么写“$b = $a =5”。

另外一个很好的面向表达式的例子就是前、后递增和递减。PHP 和多数其它语言的用户应该比较熟悉变量 ++ 和变量 -- 符号。即递增和递减运算符。在 PHP/FI 2 中,语句“$a++”没有值(不是表达式),这样的话你便不能为其赋值或者以任何其它方式来使用它。PHP 通过将其变为了表达式,类似 C 语言,增强了递增/递减的能力。在 PHP 和 C 语言 中,有两种类型的递增前递增和后递增,本质上来讲,前递增和后递增均增加了变量的值,并且对于变量的影响是相同的。不同的是递增表达式的值。前递增,写做“++$variable”,求增加后的值(PHP 在读取变量的值之前,增加变量的值,因而称之为“前递增”)。后递增,写做“$variable++”,求变量未递增之前的原始值(PHP 在读取变量的值之后,增加变量的值,因而叫做“后递增”)。

一个常用到表达式类型是比较表达式。这些表达式求值 FALSETRUE。PHP 支持 >(大于),>=(大于等于),==(等于),!=(不等于),<(小于),<= (小于等于)。PHP 还支持全等运算符 ===(值和类型均相同)和非全等运算符 !==(值或者类型不同)。这些表达式都是在条件判断语句,比如,if 语句中最常用的。

这里,将要研究的最后一个例子是组合的运算赋值表达式。已经知道如果想要为变量 $a 加1,可以简单的写“$a++”或者“++$a”。但是如果想为变量增加大于 1 的值,比如 3,该怎么做?可以多次写“$a++”,但这样明显不是一种高效舒适的方法,一个更加通用的做法是“$a = $a + 3”。“$a + 3”计算 $a 加上 3 的值,并且得到的值重新赋予变量 $a,于是 $a 的值增加了3。在 PHP 及其它几种类似 C 的语言中,可以以一种更加简短的形式完成上述功能,因而也更加清楚快捷。为 $a 的当前值加 3,可以这样写:“$a += 3”。这里的意思是“取变量 $a 的值,加 3,得到的结果再次分配给变量 $a”。除了更简略和清楚外,也可以更快的运行。“$a += 3”的值,如同一个正常赋值操作的值,是赋值后的值。注意它不是 3,而是 $a 的值加上3 之后的值(此值将被赋给 $a)。任何二元运算符都可以用运算赋值模式,例如“$a -= 5”(从变量 $a 的值中减去 5),“$b *= 7”(变量 $b 乘以 7),等等。

还有一个表达式,如果没有在别的语言中看到过的话,可能看上去很奇怪,即三元条件运算符:

$first ? $second : $third

如果第一个子表达式的值是 TRUE(非零),那么计算第二个子表达式的值,其值即为整个表达式的值。否则,将是第三个子表达式的值。

下面的例子一般来说应该有助于理解前、后递增和表达式:

<?php
function double($i)
{
    return $i*2;
}
$b = $a = 5;        /* assign the value five into the variable $a and $b */
$c = $a++;          /* post-increment, assign original value of $a
                       (5) to $c */
$e = $d = ++$b;     /* pre-increment, assign the incremented value of
                       $b (6) to $d and $e */

/* at this point, both $d and $e are equal to 6 */

$f = double($d++);  /* assign twice the value of $d before
                       the increment, 2*6 = 12 to $f */
$g = double(++$e);  /* assign twice the value of $e after
                       the increment, 2*7 = 14 to $g */
$h = $g += 10;      /* first, $g is incremented by 10 and ends with the
                       value of 24. the value of the assignment (24) is
                       then assigned into $h, and $h ends with the value
                       of 24 as well. */
?>

一些表达式可以被当成语句。这时,一条语句的形式是 'expr' ';',即一个表达式加一个分号结尾。在“$b=$a=5;”中,$a=5 是一个有效的表达式,但它本身不是一条语句。“$b=$a=5;”是一条有效的语句。

最后一件值得提起的事情就是表达式的真值。在许多事件中,大体上主要是在条件执行和循环中,不要专注于表达式中明确的值,反而要注意表达式的值是否是 TRUE 或者 FALSE。常量 TRUEFALSE(大小写无关)是两种可能的 Boolean 值。如果有必要,一个表达式将自动转换为 Boolean。参见类型强制转换一节。

PHP 提供了一套完整强大的表达式,而为它提供完整的文件资料已经超出了本手册的范围。上面的例子应该为你提供了一个好的关于什么是表达式和怎样构建一个有用的表达式的概念。在本手册的其余部分,我们将始终使用 expr 来表示一个有效的 PHP 表达式。


章 15. 运算符

运算符是可以通过给出的一或多个值(用编程行话来说,表达式)来产生另一个值(因而整个结构成为一个表达式)的东西。所以可以认为函数或任何会返回一个值(例如 print)的结构是运算符,而那些没有返回值的(例如 echo)是别的东西。

有三种类型的运算符。第一种是一元运算符,只运算一个值,例如 !(取反运算符)或 ++(加一运算符)。第二种是有限二元运算符,PHP 支持的大多数运算符都是这种。列表见下节运算符优先级

第三种是三元运算符:?:。它应该被用来根据一个表达式在另两个表达式中选择一个,而不是用来在两个语句或者程序路线中选择。把整个三元表达式放在扩号里是个很好的主意。


运算符优先级

运算符优先级指定了两个表达式绑定得有多“紧密”。例如,表达式 1 + 5 * 3 的结果是 16 而不是 18 是因为乘号(“*”)的优先级比加号(“+”)高。必要时可以用括号来强制改变优先级。例如:(1 + 5) * 3 的值为 18。如果运算符优先级相同,则使用从左到右的左联顺序。

下表从高到低列出了运算符的优先级。同一行中的运算符具有相同优先级,此时它们的结合方向决定求值顺序。

表格 15-1. 运算符优先级

结合方向运算符附加信息
非结合newnew
[array()
非结合++ -- 递增/递减运算符
非结合! ~ - (int) (float) (string) (array) (object) @ 类型
* / % 算数运算符
+ - . 算数运算符字符串运算符
<< >> 位运算符
非结合< <= > >= 比较运算符
非结合== != === !== 比较运算符
& 位运算符引用
^ 位运算符
| 位运算符
&& 逻辑运算符
|| 逻辑运算符
? : 三元运算符
= += -= *= /= .= %= &= |= ^= <<= >>= 赋值运算符
and 逻辑运算符
xor 逻辑运算符
or 逻辑运算符
,多处用到

左联表示表达式从左向右求值,右联相反。

例子 15-1. 结合方向

<?php
$a = 3 * 3 % 5; // (3 * 3) % 5 = 4
$a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2

$a = 1;
$b = 2;
$a = $b += 3; // $a = ($b += 3) -> $a = 5, $b = 5
?>
使用括号可以增强代码的可读性。

注: 尽管 != 的优先级高,PHP 仍旧允许类似如下的表达式:if (!$a = foo()),在此例中 foo() 的输出被赋给了 $a


算术运算符

还记得学校里学到的基本数学知识吗?就和它们一样。

表格 15-2. 算术运算符

例子名称结果
-$a取反$a 的负值。
$a + $b加法$a 和 $b 的和。
$a - $b减法$a 和 $b 的差。
$a * $b乘法$a 和 $b 的积。
$a / $b除法$a 除以 $b 的商。
$a % $b取模$a 除以 $b 的余数。

除号(“/”)总是返回浮点数,即使两个运算数是整数(或由字符串转换成的整数)也是这样。

注: 取模 $a % $b$a 为负值时的结果也是负值。

参见手册中的数学函数


赋值运算符

基本的赋值运算符是“=”。一开始可能会以为它是“等于”,其实不是的。它实际上意味着把右边表达式的值赋给左边的运算数。

赋值运算表达式的值也就是所赋的值。也就是说,“$a = 3”的值是 3。这样就可以做一些小技巧:

<?php

$a = ($b = 4) + 5; // $a 现在成了 9,而 $b 成了 4。

?>

在基本赋值运算符之外,还有适合于所有二元算术和字符串运算符的“组和运算符”,这样可以在一个表达式中使用它的值并把表达式的结果赋给它,例如:

<?php

$a = 3;
$a += 5; // sets $a to 8, as if we had said: $a = $a + 5;
$b = "Hello ";
$b .= "There!"; // sets $b to "Hello There!", just like $b = $b . "There!";

?>

注意赋值运算将原变量的值拷贝到新变量中(传值赋值),所以改变其中一个并不影响另一个。这也适合于在很密集的循环中拷贝一些值例如大数组。自 PHP 4 起支持引用赋值,用 $var = &$othervar; 语法,但在 PHP 3 中不可能这样做。引用赋值意味着两个变量都指向同一个数据,没有任何数据的拷贝。有关引用的更多信息见引用的说明


位运算符

位运算符允许对整型数中指定的位进行置位。如果左右参数都是字符串,则位运算符将操作字符的 ASCII 值。

<?php
echo 12 ^ 9; // 输出为 '5'

echo "12" ^ "9"; // 输出退格字符(ascii 8)
                    // ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8

echo "hallo" ^ "hello"; // 输出 ascii 值 #0 #4 #0 #0 #0
                            // 'a' ^ 'e' = #4
?>

表格 15-3. 位运算符

例子名称结果
$a & $bAnd(按位与)将把 $a 和 $b 中都为 1 的位设为 1。
$a | $bOr(按位或)将把 $a 或者 $b 中为 1 的位设为 1。
$a ^ $bXor(按位异或)将把 $a 和 $b 中不同的位设为 1。
~ $aNot(按位非)将 $a 中为 0 的位设为 1,反之亦然。
$a << $bShift left(左移)将 $a 中的位向左移动 $b 次(每一次移动都表示“乘以 2”)。
$a >> $bShift right(右移)将 $a 中的位向右移动 $b 次(每一次移动都表示“除以 2”)。

警告

在 32 位系统上不要右移超过 32 位。不要在结果可能超过 32 位的情况下左移。


比较运算符

比较运算符,如同它们名称所暗示的,允许对两个值进行比较。还可以参考 PHP 类型比较表看不同类型相互比较的例子。

表格 15-4. 比较运算符

例子名称结果
$a == $b等于TRUE,如果 $a 等于 $b。
$a === $b全等TRUE,如果 $a 等于 $b,并且它们的类型也相同。(PHP 4 引进)
$a != $b不等TRUE,如果 $a 不等于 $b。
$a <> $b不等TRUE,如果 $a 不等于 $b。
$a !== $b非全等TRUE,如果 $a 不等于 $b,或者它们的类型不同。(PHP 4 引进)
$a < $b小与TRUE,如果 $a 严格小于 $b。
$a > $b大于TRUE,如果 $a 严格 $b。
$a <= $b小于等于TRUE,如果 $a 小于或者等于 $b。
$a >= $b大于等于TRUE,如果 $a 大于或者等于 $b。

如果比较一个整数和字符串,则字符串会被转换为整数。如果比较两个数字字符串,则作为整数比较。此规则也适用于 switch 语句。

<?php
var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true

switch ("a") {
case 0:
    echo "0";
    break;
case "a": // never reached because "a" is already matched with 0
    echo "a";
    break;
}
?>

对于多种的类型,比较运算符根据下表比较(按顺序)。

表格 15-5. 比较多种类型

运算数 1 类型运算数 1 类型结果
nullstringstringNULL 转换为 "",进行数字或词汇比较
boolnull任何其它类型转换为 boolFALSE < TRUE
objectobject 内置类可以定义自己的比较,不同类不能比较,相同类和数组同样方式比较属性(PHP 4 中),PHP 5 有其自己的说明
stringresourcenumberstringresourcenumber将字符串和资源转换成数字,按普通数学比较
arrayarray 具有较少成员的数组较小,如果运算数 1 中的键不存在于运算数 2 中则数组无法比较,否则挨个值比较(见下例)
array任何其它类型array 总是更大
object任何其它类型object 总是更大

例子 15-2. 标准数组比较代码

<?php
// 数组是用标准比较运算符这样比较的
function standard_array_compare($op1, $op2)
{
    if (count($op1) < count($op2)) {
        return -1; // $op1 < $op2
    } elseif (count($op1) > count($op2)) {
        return 1; // $op1 > $op2
    }
    foreach ($op1 as $key => $val) {
        if (!array_key_exists($key, $op2)) {
            return null; // uncomparable
        } elseif ($val < $op2[$key]) {
            return -1;
        } elseif ($val > $op2[$key]) {
            return 1;
        }
    }
    return 0; // $op1 == $op2
}
?>

参见 strcasecmp()strcmp()数组运算符类型一章。


三元运算符

另一个条件运算符是“?:”(或三元)运算符 。

例子 15-3. 赋默认值

<?php
 // Example usage for: Ternary Operator
 $action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

 // The above is identical to this if/else statement
 if (empty($_POST['action'])) {
     $action = 'default';
 } else {
     $action = $_POST['action'];
 }

 ?>
表达式 (expr1) ? (expr2) : (expr3)expr1 求值为 TRUE 时的值为 expr2,在 expr1 求值为 FALSE 时的值为 expr3

注: 注意三元运算符是个语句,因此其求值不是变量,而是语句的结果。如果想通过引用返回一个变量这点就很重要。在一个通过引用返回的函数中语句 return $var == 42 ? $a : $b; 将不起作用,以后的 PHP 版本会为此发出一条警告。


错误控制运算符

PHP 支持一个错误控制运算符:@。当将其放置在一个 PHP 表达式之前,该表达式可能产生的任何错误信息都被忽略掉。

如果激活了 track_errors 特性,表达式所产生的任何错误信息都被存放在变量 $php_errormsg 中。此变量在每次出错时都会被覆盖,所以如果想用它的话就要尽早检查。

<?php
/* Intentional file error */
$my_file = @file ('non_existent_file') or
    die ("Failed opening file: error was '$php_errormsg'");

// this works for any expression, not just functions:
$value = @$cache[$key];
// will not issue a notice if the index $key doesn't exist.

?>

注: @ 运算符只对表达式有效。对新手来说一个简单的规则就是:如果能从某处得到值,就能在它前面加上 @ 运算符。例如,可以把它放在变量,函数和 include() 调用,常量,等等之前。不能把它放在函数或类的定义之前,也不能用于条件结构例如 ifforeach 等。

参见 error_reporting() 及手册中错误处理及日志函数的有关章节。

警告

目前的“@”错误控制运算符前缀甚至使导致脚本终止的严重错误的错误报告也失效。这意味着如果在某个不存在或类型错误的函数调用前用了“@”来抑制错误信息,那脚本会没有任何迹象显示原因而死在那里。


执行运算符

PHP 支持一个执行运算符:反引号(``)。注意这不是单引号!PHP 将尝试将反引号中的内容作为外壳命令来执行,并将其输出信息返回(例如,可以赋给一个变量而不是简单地丢弃到标准输出)。使用反引号运算符“`”的效果与函数 shell_exec() 相同。

<?php
$output = `ls -al`;
echo "<pre>$output</pre>";
?>

注: 反引号运算符在激活了安全模式或者关闭了 shell_exec() 时是无效的。

参见函数 popen()proc_open() 及手册中程序执行函数PHP 的命令行模式的有关章节。


递增/递减运算符

PHP 支持 C 风格的前/后递增与递减运算符。

注: 递增/递减运算符不影响布尔值。递减 NULL 值也没有效果,但是递增 NULL 的结果是 1

表格 15-6. 递增/递减运算符

例子名称效果
++$a前加$a 的值加一,然后返回 $a。
$a++后加返回 $a,然后将 $a 的值加一。
--$a前减$a 的值减一, 然后返回 $a。
$a--后减返回 $a,然后将 $a 的值减一。

一个简单的示例脚本:

<?php
echo "<h3>Postincrement</h3>";
$a = 5;
echo "Should be 5: " . $a++ . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";

echo "<h3>Preincrement</h3>";
$a = 5;
echo "Should be 6: " . ++$a . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";

echo "<h3>Postdecrement</h3>";
$a = 5;
echo "Should be 5: " . $a-- . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";

echo "<h3>Predecrement</h3>";
$a = 5;
echo "Should be 4: " . --$a . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";
?>

在处理字符变量的算数运算时,PHP 沿袭了 Perl 的习惯,而非 C 的。例如,在 Perl 中 'Z'+1 将得到 'AA',而在 C 中,'Z'+1 将得到 '['(ord('Z') == 90,ord('[') == 91)。注意字符变量只能递增,不能递减。

例子 15-4. 涉及字符变量的算数运算

<?php
$i = 'W';
for ($n=0; $n<6; $n++) {
    echo ++$i . "\n";
}
?>

上例将输出:

X
Y
Z
AA
AB
AC

递增或递减布尔值没有效果。


逻辑运算符

表格 15-7. 逻辑运算符

例子名称结果
$a and $bAnd(逻辑与)TRUE,如果 $a 与 $b 都为 TRUE
$a or $bOr(逻辑或)TRUE,如果 $a 或 $b 任一为 TRUE
$a xor $bXor(逻辑异或)TRUE,如果 $a 或 $b 任一为 TRUE,但不同时是。
! $aNot(逻辑非)TRUE,如果 $a 不为 TRUE
$a && $bAnd(逻辑与)TRUE,如果 $a 与 $b 都为 TRUE
$a || $bOr(逻辑或)TRUE,如果 $a 或 $b 任一为 TRUE

“与”和“或”有两种不同形式运算符的原因是它们运算的优先级不同(见运算符优先级)。


字符串运算符

有两个字符串运算符。第一个是连接运算符(“.”),它返回其左右参数连接后的字符串。第二个是连接赋值运算符(“.=”),它将右边参数附加到左边的参数后。更多信息见赋值运算符

<?php
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"

$a = "Hello ";
$a .= "World!";     // now $a contains "Hello World!"
?>

参见字符串类型字符串函数章节。


数组运算符

表格 15-8. 数组运算符

例子名称结果
$a + $b联合$a 和 $b 的联合。
$a == $b相等如果 $a 和 $b 具有相同的键/值对则为 TRUE
$a === $b全等如果 $a 和 $b 具有相同的键/值对并且顺序和类型都相同则为 TRUE
$a != $b不等如果 $a 不等于 $b 则为 TRUE
$a <> $b不等如果 $a 不等于 $b 则为 TRUE
$a !== $b不全等如果 $a 不全等于 $b 则为 TRUE

+ 运算符把右边的数组附加到左边的数组后面,但是重复的键值不会被覆盖。

<?php
$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");

$c = $a + $b; // Union of $a and $b
echo "Union of \$a and \$b: \n";
var_dump($c);

$c = $b + $a; // Union of $b and $a
echo "Union of \$b and \$a: \n";
var_dump($c);
?>

执行后,此脚本会显示:
Union of $a and $b:
array(3) {
  ["a"]=>
  string(5) "apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  string(6) "cherry"
}
Union of $b and $a:
array(3) {
  ["a"]=>
  string(4) "pear"
  ["b"]=>
  string(10) "strawberry"
  ["c"]=>
  string(6) "cherry"
}

数组中的单元如果具有相同的键名和值则比较时相等。

例子 15-5. 比较数组

<?php
$a = array("apple", "banana");
$b = array(1 => "banana", "0" => "apple");

var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false)
?>

参见数组类型数组函数章节。


类型运算符

PHP 有一个类型运算符:instanceofinstanceof 用来测定一个给定的对象是否来自指定的对象类

instanceof 运算符是 PHP 5 引进的。在此之前用 is_a(),但是 is_a() 已经过时了,最好用 instanceof

<?php
class A { }
class B { }

$thing = new A;

if ($thing instanceof A) {
    echo 'A';
}
if ($thing instanceof B) {
    echo 'B';
}
?>

由于 $thing 是类型 A 的一个 object,而不是 B 的,只有和类型 A 相符合的程序块被运行:

A

参见 get_class()is_a()


章 16. 流程控制

任何 PHP 脚本都是由一系列语句构成的。一条语句可以是一个赋值语句,一个函数调用,一个循环,甚至一个什么也不做的(空语句)条件语句。语句通常以分号结束。此外,还可以用花括号将一组语句封装成一个语句组。语句组本身可以当作是一行语句。本章讲述了各种语句类型。


if

if 结构是很多语言包括 PHP 在内最重要的特性之一,它允许按照条件执行代码片段。PHP 的 if 结构和 C 语言相似:

<?php
if (expression)
    statement
?>

如同在表达式一章中定义的,expression 按照布尔求值。如果 expression 的值为 TRUE,PHP 将执行 statement,如果值为 FALSE - 将忽略 statement。有关哪些值被视为 FALSE 的更多信息参见转换为布尔值一节。

如果 $a 大于 $b,则以下例子将显示 a is bigger than b

<?php
if ($a > $b)
    echo "a is bigger than b";
?>

经常需要按照条件执行不止一条语句,当然并不需要给每条语句都加上一个 if 子句。可以将这些语句放入语句组中。例如,如果 $a 大于 $b,以下代码将显示 a is bigger than b 并且将 $a 的值赋给 $b

<?php
if ($a > $b) {
    echo "a is bigger than b";
    $b = $a;
}
?>

if 语句可以无限层地嵌套在其它 if 语句中,这给程序的不同部分的条件执行提供了充分的弹性。


else

经常需要在满足某个条件时执行一条语句,而在不满足该条件时执行其它语句,这正是 else 的功能。else 延伸了 if 语句,可以在 if 语句中的表达式的值为 FALSE 时执行语句。例如以下代码在 $a 大于 $b 时显示 a is bigger than b,反之则显示 a is NOT bigger than b

<?php
if ($a > $b) {
    echo "a is bigger than b";
} else {
    echo "a is NOT bigger than b";
}
?>

else 语句仅在 if 以及 elseif(如果有的话)语句中的表达式的值为 FALSE 时执行(参见 elseif)。


elseif

elseif,和此名称暗示的一样,是 ifelse 的组合。和 else 一样,它延伸了 if 语句,可以在原来的 if 表达式值为 FALSE 时执行不同语句。但是和 else 不一样的是,它仅在 elseif 的条件表达式值为 TRUE 时执行语句。例如以下代码将根据条件分别显示 a is bigger than ba equal to b 或者 a is smaller than b

<?php
if ($a > $b) {
    echo "a is bigger than b";
} elseif ($a == $b) {
    echo "a is equal to b";
} else {
    echo "a is smaller than b";
}
?>

在同一个 if 结构中可以有多个 elseif 语句。第一个表达式值为 TRUEelseif 语句(如果有的话)将会执行。在 PHP 中,也可以写成“else if”(两个单词),它和“elseif”(一个单词)的行为完全一样。句法分析的含义有少许区别(如果你熟悉 C 语言的话,这是同样的行为),但是底线是两者会产生完全一样的行为。

elseif 的语句仅在之前的 ifelseif 的表达式值为 FALSE,而当前的 elseif 表达式值为 TRUE 时执行。


流程控制的替代语法

PHP 提供了一些流程控制的替代语法,包括 ifwhileforforeachswitch。替代语法的基本形式是把左花括号({)换成冒号(:),把右花括号(})分别换成 endif;endwhile;endfor;endforeach; 以及 endswitch;

<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>

在上面的例子中,HTML 内容“A is equal to 5”用替代语法嵌套在 if 语句中。该 HTML 的内容仅在 $a 等于 5 时显示。

替代语法同样可以用在 elseelseif 中。下面是一个包括 elseifelseif 结构用替代语法格式写的例子:

<?php
if ($a == 5):
    echo "a equals 5";
    echo "...";
elseif ($a == 6):
    echo "a equals 6";
    echo "!!!";
else:
    echo "a is neither 5 nor 6";
endif;
?>

更多例子参见 whileforif


while

while 循环是 PHP 中最简单的循环类型。它和 C 语言中的 while 表现得一样。while 语句的基本格式是:

while (expr)
    statement

while 语句的含意很简单,它告诉 PHP 只要 while 表达式的值为 TRUE 就重复执行嵌套中的循环语句。表达式的值在每次开始循环时检查,所以即使这个值在循环语句中改变了,语句也不会停止执行,直到本次循环结束。有时候如果 while 表达式的值一开始就是 FALSE,则循环语句一次都不会执行。

if 语句一样,可以在 while 循环中用花括号括起一个语句组,或者用替代语法:

while (expr):
    statement
    ...
endwhile;

下面两个例子完全一样,都显示数字 1 到 10:

<?php
/* example 1 */

$i = 1;
while ($i <= 10) {
    echo $i++;  /* the printed value would be
                    $i before the increment
                    (post-increment) */
}

/* example 2 */

$i = 1;
while ($i <= 10):
    print $i;
    $i++;
endwhile;
?>


do-while

do-whilewhile 循环非常相似,区别在于表达式的值是在每次循环结束时检查而不是开始时。和正规的 while 循环主要的区别是 do-while 的循环语句保证会执行一次(表达式的真值在每次循环结束后检查),然而在正规的 while 循环中就不一定了(表达式真值在循环开始时检查,如果一开始就为 FALSE 则整个循环立即终止)。

do-while 循环只有一种语法:

<?php
$i = 0;
do {
   echo $i;
} while ($i > 0);
?>

以上循环将正好运行一次,因为经过第一次循环后,当检查表达式的真值时,其值为 FALSE($i 不大于 0)而导致循环终止。

资深的 C 语言用户可能熟悉另一种不同的 do-while 循环用法,把语句放在 do-while(0) 之中,在循环内部用 break 语句来结束执行循环。以下代码片段示范了此方法:

<?php
do {
    if ($i < 5) {
        echo "i is not big enough";
        break;
    }
    $i *= $factor;
    if ($i < $minimum_limit) {
        break;
    }
    echo "i is ok";

    /* process i */

} while(0);
?>

如果还不能立刻理解也不用担心。即使不用此“特性”也照样可以写出强大的代码来。


for

for 循环是 PHP 中最复杂的循环结构。它的行为和 C 语言的相似。 for 循环的语法是:

for (expr1; expr2; expr3)
    statement

第一个表达式(expr1)在循环开始前无条件求值一次。

expr2 在每次循环开始前求值。如果值为 TRUE,则继续循环,执行嵌套的循环语句。如果值为 FALSE,则终止循环。

expr3 在每次循环之后被求值(执行)。

每个表达式都可以为空。expr2 为空意味着将无限循环下去(和 C 一样,PHP 认为其值为 TRUE)。这可能不像想象中那样没有用,因为经常会希望用 break 语句来结束循环而不是用 for 的表达式真值判断。

考虑以下的例子,它们都显示数字 1 到 10:

<?php
/* example 1 */

for ($i = 1; $i <= 10; $i++) {
    echo $i;
}

/* example 2 */

for ($i = 1; ; $i++) {
    if ($i > 10) {
        break;
    }
    echo $i;
}

/* example 3 */

$i = 1;
for (;;) {
    if ($i > 10) {
        break;
    }
    echo $i;
    $i++;
}

/* example 4 */

for ($i = 1; $i <= 10; echo $i, $i++);
?>

当然,第一个例子看上去最正常(或者第四个),但用户可能会发现在 for 循环中用空的表达式在很多场合下会很方便。

PHP 也支持用冒号的 for 循环的替代语法。

for (expr1; expr2; expr3):
    statement;
    ...
endfor;


foreach

PHP 4 引入了 foreach 结构,和 Perl 以及其他语言很像。这只是一种遍历数组简便方法。foreach 仅能用于数组,当试图将其用于其它数据类型或者一个未初始化的变量时会产生错误。有两种语法,第二种比较次要但却是第一种的有用的扩展。

foreach (array_expression as $value)
    statement
foreach (array_expression as $key => $value)
    statement

第一种格式遍历给定的 array_expression 数组。每次循环中,当前单元的值被赋给 $value 并且数组内部的指针向前移一步(因此下一次循环中将会得到下一个单元)。

第二种格式做同样的事,只除了当前单元的键名也会在每次循环中被赋给变量 $key

自PHP 5 起,还可能遍历对象

注: foreach 开始执行时,数组内部的指针会自动指向第一个单元。这意味着不需要在 foreach 循环之前调用 reset()

注: 除非数组是被引用foreach 所操作的是指定数组的一个拷贝,而不是该数组本身。因此数组指针不会被 each() 结构改变,对返回的数组单元的修改也不会影响原数组。不过原数组的内部指针的确在处理数组的过程中向前移动了。假定 foreach 循环运行到结束,原数组的内部指针将指向数组的结尾。

自 PHP 5 起,可以很容易地通过在 $value 之前加上 & 来修改数组的单元。此方法将以引用赋值而不是拷贝一个值。

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
?>

此方法仅在被遍历的数组可以被引用时才可用(例如是个变量)。

注: foreach 不支持用“@”来抑制错误信息的能力。

用户可能注意到了以下的代码功能完全相同:

<?php
$arr = array("one", "two", "three");
reset($arr);
while (list(, $value) = each($arr)) {
    echo "Value: $value<br>\n";
}

foreach ($arr as $value) {
    echo "Value: $value<br />\n";
}
?>

以下代码功能也完全相同:

<?php
$arr = array("one", "two", "three");
reset($arr);
while (list($key, $value) = each($arr)) {
    echo "Key: $key; Value: $value<br />\n";
}

foreach ($arr as $key => $value) {
    echo "Key: $key; Value: $value<br />\n";
}
?>

示范用法的更多例子:

<?php
/* foreach example 1: value only */

$a = array(1, 2, 3, 17);

foreach ($a as $v) {
   echo "Current value of \$a: $v.\n";
}

/* foreach example 2: value (with key printed for illustration) */

$a = array(1, 2, 3, 17);

$i = 0; /* for illustrative purposes only */

foreach ($a as $v) {
    echo "\$a[$i] => $v.\n";
    $i++;
}

/* foreach example 3: key and value */

$a = array(
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "seventeen" => 17
);

foreach ($a as $k => $v) {
    echo "\$a[$k] => $v.\n";
}

/* foreach example 4: multi-dimensional arrays */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";

foreach ($a as $v1) {
    foreach ($v1 as $v2) {
        echo "$v2\n";
    }
}

/* foreach example 5: dynamic arrays */

foreach (array(1, 2, 3, 4, 5) as $v) {
    echo "$v\n";
}
?>


break

break 结束当前 forforeachwhiledo-while 或者 switch 结构的执行。

break 可以接受一个可选的数字参数来决定跳出几重循环。

<?php
$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
while (list (, $val) = each($arr)) {
    if ($val == 'stop') {
        break;    /* You could also write 'break 1;' here. */
    }
    echo "$val<br />\n";
}

/* Using the optional argument. */

$i = 0;
while (++$i) {
    switch ($i) {
    case 5:
        echo "At 5<br />\n";
        break 1;  /* Exit only the switch. */
    case 10:
        echo "At 10; quitting<br />\n";
        break 2;  /* Exit the switch and the while. */
    default:
        break;
    }
}
?>


continue

continue 在循环结构用用来跳过本次循环中剩余的代码并在条件求值为真时开始执行下一次循环。

注: 注意在 PHP 中 switch 语句被认为是可以使用 continue 的一种循环结构。

continue 接受一个可选的数字参数来决定跳过几重循环到循环结尾。

<?php
while (list ($key, $value) = each($arr)) {
    if (!($key % 2)) { // skip odd members
        continue;
    }
    do_something_odd($value);
}

$i = 0;
while ($i++ < 5) {
    echo "Outer<br />\n";
    while (1) {
        echo "&nbsp;&nbsp;Middle<br />\n";
        while (1) {
            echo "&nbsp;&nbsp;Inner<br />\n";
            continue 3;
        }
        echo "This never gets output.<br />\n";
    }
    echo "Neither does this.<br />\n";
}
?>

省略 continue 后面的分号会导致混淆。以下例子示意了不应该这样做。

<?php
  for ($i = 0; $i < 5; ++$i) {
      if ($i == 2)
          continue
      print "$i\n";
  }
?>

希望得到的结果是:

0
1
3
4

可实际的输出是:

2

因为 print() 调用的返回值是 int(1),看上去作为了上述可选的数字参数。


switch

switch 语句和具有同样表达式的一系列的 IF 语句相似。很多场合下需要把同一个变量(或表达式)与很多不同的值比较,并根据它等于哪个值来执行不同的代码。这正是 switch 语句的用途。

注: 注意和其它语言不同,continue 语句作用到 switch 上的作用类似于 break。如果在循环中有一个 switch 并希望 continue 到外层循环中的下一个轮回,用 continue 2

下面两个例子使用两种不同方法实现同样的事,一个用一系列的 if 语句,另一个用 switch 语句:

例子 16-1. switch 结构

<?php
if ($i == 0) {
    echo "i equals 0";
} elseif ($i == 1) {
    echo "i equals 1";
} elseif ($i == 2) {
    echo "i equals 2";
}

switch ($i) {
    case 0:
        echo "i equals 0";
        break;
    case 1:
        echo "i equals 1";
        break;
    case 2:
        echo "i equals 2";
        break;
}
?>

例子 16-2. switch 结构可以用字符串

<?php
switch ($i) {
case "apple":
    echo "i is apple";
    break;
case "bar":
    echo "i is bar";
    break;
case "cake":
    echo "i is cake";
    break;
}
?>

为避免错误,理解 switch 是怎样执行的非常重要。switch 语句一行接一行地执行(实际上是语句接语句)。开始时没有代码被执行。仅当一个 case 语句中的值和 switch 表达式的值匹配时 PHP 才开始执行语句,直到 switch 的程序段结束或者遇到第一个 break 语句为止。如果不在 case 的语句段最后写上 break 的话,PHP 将继续执行下一个 case 中的语句段。例如:

<?php
switch ($i) {
    case 0:
        echo "i equals 0";
    case 1:
        echo "i equals 1";
    case 2:
        echo "i equals 2";
}
?>

这里如果 $i 等于 0,PHP 将执行所有的 print 语句!如果 $i 等于 1,PHP 将执行后面两条 print 语句。只有当 $i 等于 2 时,才会得到“预期”的结果――只显示“i equals 2”。所以,别忘了 break 语句就很重要(即使在某些情况下故意想避免提供它们时)。

switch 语句中条件只求值一次并用来和每个 case 语句比较。在 elseif 语句中条件会再次求值。如果条件比一个简单的比较要复杂得多或者在一个很多次的循环中,那么用 switch 语句可能会快一些。

在一个 case 中的语句也可以为空,这样只不过将控制转移到了下一个 case 中的语句。

<?php
switch ($i) {
    case 0:
    case 1:
    case 2:
        echo "i is less than 3 but not negative";
        break;
    case 3:
        echo "i is 3";
}
?>

一个 case 的特例是 default。它匹配了任何和其它 case 都不匹配的情况,并且应该是最后一条 case 语句。例如:

<?php
switch ($i) {
    case 0:
        echo "i equals 0";
        break;
    case 1:
        echo "i equals 1";
        break;
    case 2:
        echo "i equals 2";
        break;
    default:
        echo "i is not equal to 0, 1 or 2";
}
?>

case 表达式可以是任何求值为简单类型的表达式,即整型或浮点数以及字符串。不能用数组或对象,除非它们被解除引用成为简单类型。

switch 支持替代语法的流程控制。更多信息见流程控制的替代语法一节。

<?php
switch ($i):
    case 0:
        echo "i equals 0";
        break;
    case 1:
        echo "i equals 1";
        break;
    case 2:
        echo "i equals 2";
        break;
    default:
        echo "i is not equal to 0, 1 or 2";
endswitch;
?>


declare

declare 结构用来设定一段代码的执行指令。declare 的语法和其它流程控制结构相似:

declare (directive)
    statement

directive 部分允许设定 declare 代码段的行为。目前只认识一个指令:ticks(更多信息见下面 ticks 指令)。

declare 代码段中的 statement 部分将被执行――怎样执行以及执行中有什么副作用出现取决于 directive 中设定的指令。

declare 结构也可用于全局范围,影响到其后的所有代码。

<?php
// these are the same:

// you can use this:
declare(ticks=1) {
    // entire script here
}

// or you can use this:
declare(ticks=1);
// entire script here
?>


Ticks

Tick 是一个在 declare 代码段中解释器每执行 N 条低级语句就会发生的事件。N 的值是在 declare 中的 directive 部分用 ticks=N 来指定的。

在每个 tick 中出现的事件是由 register_tick_function() 来指定的。更多细节见下面的例子。注意每个 tick 中可以出现多个事件。

例子 16-3. 评估一段 PHP 代码的执行时间

<?php
// A function that records the time when it is called
function profile($dump = FALSE)
{
    static $profile;

    // Return the times stored in profile, then erase it
    if ($dump) {
        $temp = $profile;
        unset($profile);
        return ($temp);
    }

    $profile[] = microtime();
}

// Set up a tick handler
register_tick_function("profile");

// Initialize the function before the declare block
profile();

// Run a block of code, throw a tick every 2nd statement
declare(ticks=2) {
    for ($x = 1; $x < 50; ++$x) {
        echo similar_text(md5($x), md5($x*$x)), "<br />;";
    }
}

// Display the data stored in the profiler
print_r(profile (TRUE));
?>
这个例子评估“declare”中的 PHP 代码,每执行两条低级语句就记录一次时间。此信息可以用来找到一段特定代码中速度慢的部分。这个过程也可以用其它方法完成,但用 tick 更方便也更容易实现。

Ticks 很适合用来做调试,以及实现简单的多任务,后台 I/O 和很多其它任务。

参见 register_tick_function()unregister_tick_function()


return

如果在一个函数中调用 return() 语句,将立即结束此函数的执行并将它的参数作为函数的值返回。return() 也会终止 eval() 语句或者脚本文件的执行。

如果在全局范围中调用,则当前脚本文件中止运行。如果当前脚本文件是被 include() 的或者 require() 的,则控制交回调用文件。此外,如果当前脚本是被 include() 的,则 return() 的值会被当作 include() 调用的返回值。如果在主脚本文件中调用 return(),则脚本中止运行。如果当前脚本文件是在 php.ini 中的配置选项 auto_prepend_file 或者 auto_append_file 所指定的,则此脚本文件中止运行。

更多信息见返回值

注: 注意既然 return() 是语言结构而不是函数,仅在参数包含表达式时才需要用括号将其括起来。当返回一个变量时通常不用括号,也建议不要用,这样可以降低 PHP 的负担。

注: 当用引用返回值时永远不要使用括号,这样行不通。只能通过引用返回变量,而不是语句的结果。如果使用 return ($a); 时其实不是返回一个变量,而是表达式 ($a) 的值(当然,此时该值也正是 $a 的值)。


require()

require() 语句包含并运行指定文件。

require() 语句包含并运行指定文件。有关包括如何工作的详细信息见 include() 的文档。

require()include() 除了怎样处理失败之外在各方面都完全一样。include() 产生一个警告require() 则导致一个致命错误。换句话说,如果想在丢失文件时停止处理页面,那就别犹豫了,用 require() 吧。include() 就不是这样,脚本会继续运行。同时也要确认设置了合适的include_path

例子 16-4. 基本的 require() 例子

<?php

require 'prepend.php';

require $somefile;

require ('somefile.txt');

?>

更多例子参见 include() 文档。

注: 在 PHP 4.0.2 之前适用以下规则:require() 总是会尝试读取目标文件,即使它所在的行根本就不会执行。条件语句不会影响 require()。不过如果 require() 所在的行没有执行,则目标文件中的代码也不会执行。同样,循环结构也不影响 require() 的行为。尽管目标文件中包含的代码仍然是循环的主体,但 require() 本身只会运行一次。

注: 由于这是一个语言结构而非函数,因此它无法被变量函数调用。

警告

Windows 版本的 PHP 在 4.3.0 版之前不支持本函数的远程文件访问,即使 allow_url_fopen 选项已被激活。

参见 include()require_once()include_once()eval()file()readfile()virtual()include_path


include()

include() 语句包含并运行指定文件。

以下文档也适用于 require()。这两种结构除了在如何处理失败之外完全一样。include() 产生一个警告require() 则导致一个致命错误。换句话说,如果想在遇到丢失文件时停止处理页面就用 require()include() 就不是这样,脚本会继续运行。同时也要确认设置了合适的 include_path。注意在 PHP 4.3.5 之前,包含文件中的语法错误不会导致程序停止,但从此版本之后会。

寻找包含文件的顺序先是在当前工作目录的相对的 include_path 下寻找,然后是当前运行脚本所在目录相对的 include_path 下寻找。例如 include_path 是 .,当前工作目录是 /www/,脚本中要 include 一个 include/a.php 并且在该文件中有一句 include "b.php",则寻找 b.php 的顺序先是 /www/,然后是 /www/include/。如果文件名以 ../ 开始,则只在当前工作目录相对的 include_path 下寻找。

当一个文件被包含时,其中所包含的代码继承了 include 所在行的变量范围。从该处开始,调用文件在该行处可用的任何变量在被调用的文件中也都可用。不过所有在包含文件中定义的函数和类都具有全局作用域。

例子 16-5. 基本的 include() 例子

vars.php
<?php

$color = 'green';
$fruit = 'apple';

?>

test.php
<?php

echo "A $color $fruit"; // A

include 'vars.php';

echo "A $color $fruit"; // A green apple

?>

如果 include 出现于调用文件中的一个函数里,则被调用的文件中所包含的所有代码将表现得如同它们是在该函数内部定义的一样。所以它将遵循该函数的变量范围。

例子 16-6. 函数中的包含

<?php

function foo()
{
    global $color;

    include 'vars.php';

    echo "A $color $fruit";
}

/* vars.php is in the scope of foo() so     *
 * $fruit is NOT available outside of this  *
 * scope.  $color is because we declared it *
 * as global.                               */

foo();                    // A green apple
echo "A $color $fruit";   // A green

?>

当一个文件被包含时,语法解析器在目标文件的开头脱离 PHP 模式并进入 HTML 模式,到文件结尾处恢复。由于此原因,目标文件中应被当作 PHP 代码执行的任何代码都必须被包括在有效的 PHP 起始和结束标记之中。

如果“URL fopen wrappers”在 PHP 中被激活(默认配置),可以用 URL(通过 HTTP 或者其它支持的封装协议――所支持的协议见附录 L)而不是本地文件来指定要被包含的文件。如果目标服务器将目标文件作为 PHP 代码解释,则可以用适用于 HTTP GET 的 URL 请求字符串来向被包括的文件传递变量。严格的说这和包含一个文件并继承父文件的变量空间并不是一回事;该脚本文件实际上已经在远程服务器上运行了,而本地脚本则包括了其结果。

警告

Windows 版本的 PHP 在 4.3.0 版之前不支持本函数的远程文件访问,即使 allow_url_fopen 选项已被激活。

例子 16-7. 通过 HTTP 进行的 include()

<?php

/* This example assumes that www.example.com is configured to parse .php *
 * files and not .txt files. Also, 'Works' here means that the variables *
 * $foo and $bar are available within the included file.                 */

// Won't work; file.txt wasn't handled by www.example.com as PHP
include 'http://www.example.com/file.txt?foo=1&bar=2';

// Won't work; looks for a file named 'file.php?foo=1&bar=2' on the
// local filesystem.
include 'file.php?foo=1&bar=2';

// Works.
include 'http://www.example.com/file.php?foo=1&bar=2';

$foo = 1;
$bar = 2;
include 'file.txt';  // Works.
include 'file.php';  // Works.

?>

安全警告

远程文件可能会经远程服务器处理(根据文件后缀以及远程服务器是否在运行 PHP 而定),但必须产生出一个合法的 PHP 脚本,因为其将被本地服务器处理。如果来自远程服务器的文件应该在远端运行而只输出结果,那用 readfile() 函数更好。另外还要格外小心以确保远程的脚本产生出合法并且是所需的代码。

相关信息参见使用远程文件fopen()file()

因为 include()require() 是特殊的语言结构,在条件语句中使用必须将其放在语句组中(花括号中)。

例子 16-8. include() 与条件语句组

<?php

// This is WRONG and will not work as desired.
if ($condition)
    include $file;
else
    include $other;


// This is CORRECT.
if ($condition) {
    include $file;
} else {
    include $other;
}

?>

处理返回值:可以在被包括的文件中使用 return() 语句来终止该文件中程序的执行并返回调用它的脚本。同样也可以从被包含的文件中返回值。可以像普通函数一样获得 include 调用的返回值。不过这在包含远程文件时却不行,除非远程文件的输出具有合法的 PHP 开始和结束标记(如同任何本地文件一样)。可以在标记内定义所需的变量,该变量在文件被包含的位置之后就可用了。

因为 include() 是一个特殊的语言结构,其参数不需要括号。在比较其返回值时要注意。

例子 16-9. 比较 include 的返回值

<?php
// won't work, evaluated as include(('vars.php') == 'OK'), i.e. include('')
if (include('vars.php') == 'OK') {
    echo 'OK';
}

// works
if ((include 'vars.php') == 'OK') {
    echo 'OK';
}
?>

注: 在 PHP 3 中,除非是在函数中调用否则被包含的文件中不能出现 return。在此情况下 return() 作用于该函数而不是整个文件。

例子 16-10. include()return() 语句

return.php
<?php

$var = 'PHP';

return $var;

?>

noreturn.php
<?php

$var = 'PHP';

?>

testreturns.php
<?php

$foo = include 'return.php';

echo $foo; // prints 'PHP'

$bar = include 'noreturn.php';

echo $bar; // prints 1

?>

$bar 的值为 1 是因为 include 成功运行了。注意以上例子中的区别。第一个在被包含的文件中用了 return() 而另一个没有。如果文件不能被包含,则返回 FALSE 并发出一个 E_WARNING 警告。

如果在包含文件中定义有函数,这些函数可以独立于是否在 return() 之前还是之后在主文件中使用。如果文件被包含两次,PHP 5 发出致命错误因为函数已经被定义,但是 PHP 在 return() 之后不会抱怨函数已定义。推荐使用 include_once() 而不是检查文件是否已包含并在包含文件中有条件返回。

另一个将 PHP 文件“包含”到一个变量中的方法是用输出控制函数结合 include() 来捕获其输出,例如:

例子 16-11. 使用输出缓冲来将 PHP 文件包含入一个字符串

<?php
$string = get_include_contents('somefile.php');

function get_include_contents($filename) {
    if (is_file($filename)) {
        ob_start();
        include $filename;
        $contents = ob_get_contents();
        ob_end_clean();
        return $contents;
    }
    return false;
}

?>

要在脚本中自动包含文件,参见 php.ini 中的 auto_prepend_fileauto_append_file 配置选项。

注: 由于这是一个语言结构而非函数,因此它无法被变量函数调用。

参见 require()require_once()include_once()readfile()virtual()include_path


require_once()

require_once() 语句在脚本执行期间包含并运行指定文件。此行为和 require() 语句类似,唯一区别是如果该文件中的代码已经被包含了,则不会再次包含。有关此语句怎样工作参见 require() 的文档。

require_once() 应该用于在脚本执行期间同一个文件有可能被包含超过一次的情况下,想确保它只被包含一次以避免函数重定义,变量重新赋值等问题。

使用 require_once()include_once() 的例子见最新的 PHP 源程序发行包中的 PEAR 代码。

返回值和 include() 相同。如果文件已被包含,本函数返回 TRUE

注: require_once() 是 PHP 4.0.1pl2 中新加入的。

注: 要注意 require_once()include_once() 在大小写不敏感的操作系统中(例如 Windows)的行为可能不是所期望的。

例子 16-12. require_once() 在 Windows 下不区分大小写

<?php
require_once("a.php"); // this will include a.php
require_once("A.php"); // this will include a.php again on Windows!
?>
此行为在 PHP 5 中改了,路径先被规格化,因此 C:\PROGRA~1\A.phpC:\Program Files\a.php 的实现一样,文件只会被包含一次。

警告

Windows 版本的 PHP 在 4.3.0 版之前不支持本函数的远程文件访问,即使 allow_url_fopen 选项已被激活。

参见 require()include()include_once()get_required_files()get_included_files()readfile()virtual()


include_once()

The include_once() 语句在脚本执行期间包含并运行指定文件。此行为和 include() 语句类似,唯一区别是如果该文件中的代码已经被包含了,则不会再次包含。如同此语句名字暗示的那样,只会包含一次。

include_once() 应该用于在脚本执行期间同一个文件有可能被包含超过一次的情况下,想确保它只被包含一次以避免函数重定义,变量重新赋值等问题。

使用 require_once()include_once() 的更多例子见最新的 PHP 源程序发行包中的 PEAR 代码。

返回值和 include() 相同。如果文件已被包含,本函数返回 TRUE

注: include_once() 是 PHP 4.0.1pl2 中新加入的。

注: 要注意 include_once()require_once() 在大小写不敏感的操作系统中(例如 Windows)的行为可能不是所期望的。

例子 16-13. include_once() 在 Windows 下不区分大小写

<?php
include_once("a.php"); // this will include a.php
include_once("A.php"); // this will include a.php again on Windows! (PHP 4 only)
?>
此行为在 PHP 5 中改了,路径先被规格化,因此 C:\PROGRA~1\A.phpC:\Program Files\a.php 的实现一样,文件只会被包含一次。

警告

Windows 版本的 PHP 在 4.3.0 版之前不支持本函数的远程文件访问,即使 allow_url_fopen 选项已被激活。

参见 include()require()require_once()get_required_files()get_included_files()readfile()virtual()


章 17. 函数

用户自定义函数

一个函数可由以下的语法来定义:

例子 17-1. 展示函数用途的伪代码

<?php
function foo($arg_1, $arg_2, ..., $arg_n)
{
    echo "Example function.\n";
    return $retval;
}
?>

任何有效的 PHP 代码都有可能出现在函数内部,甚至包括其它函数和定义。

在 PHP 3 中,函数必须在被调用之前定义。而 PHP 4 则不再有这样的条件。除非函数如以下两个范例中有条件的定义。

如果一个函数以以下两个范例的方式有条件的定义,其定义必须在调用之前完成。

例子 17-2. 有条件的函数

<?php

$makefoo = true;

/* We can't call foo() from here
   since it doesn't exist yet,
   but we can call bar() */

bar();

if ($makefoo) {
  function foo()
  {
    echo "I don't exist until program execution reaches me.\n";
  }
}

/* Now we can safely call foo()
   since $makefoo evaluated to true */

if ($makefoo) foo();

function bar()
{
  echo "I exist immediately upon program start.\n";
}

?>

例子 17-3. 函数中的函数

<?php
function foo()
{
  function bar()
  {
    echo "I don't exist until foo() is called.\n";
  }
}

/* We can't call bar() yet
   since it doesn't exist. */

foo();

/* Now we can call bar(),
   foo()'s processesing has
   made it accessable. */

bar();

?>

PHP 中的所有函数和类都具有全局域,可以在内部定义外部调用,反之亦然。

PHP 不支持函数重载,也不可能取消定义或者重定义已声明的函数。

注: 函数名是非大小写敏感的,不过在调用函数的时候,通常使用其在定义时相同的形式。

PHP 3 虽然支持默认参数(更多信息请参照默认参数的值),但是却不支持可变的参数个数。PHP 4 支持:见可变长度的参数列表和涉及到的相关函数 func_num_args()func_get_arg(),以及 func_get_args() 以获取更多的信息。

在 PHP 中可以调用递归函数。但是要避免递归函数/方法调用超过 100-200 层,因为可能会破坏堆栈从而使当前脚本终止。

例子 17-4. 递归函数

<?php
function recursion($a)
{
    if ($a < 20) {
        echo "$a\n";
        recursion($a + 1);
    }
}
?>


函数的参数

通过参数列表可以传递信息到函数,即以逗号作为分隔符的表达式列表。

PHP 支持按值传递参数(默认),通过引用传递以及默认参数。可变长度参数列表仅在 PHP 4 和后续版本中支持;更多信息请参照可变长度参数列表和涉及到的相关函数 func_num_args()func_get_arg() 以及 func_get_args()。PHP 3 中通过传递一个数组参数可以达到类似的效果:

例子 17-5. 向函数传递数组

<?php
function takes_array($input)
{
    echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
?>


通过引用传递参数

缺省情况下,函数参数通过值传递(因而即使在函数内部改变参数的值,它并不会改变函数外部的值)。如果希望允许函数修改它的参数值,必须通过引用传递参数。

如果想要函数的一个参数总是通过引用传递,可以在函数定义中该参数的前面预先加上符号 &:

例子 17-6. 用引用传递函数参数

<?php
function add_some_extra(&$string)
{
    $string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str;    // outputs 'This is a string, and something extra.'
?>


默认参数的值

函数可以定义 C++ 风格的标量参数默认值,如下:

例子 17-7. 函数中默认参数的用途

<?php
function makecoffee($type = "cappuccino")
{
    return "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee("espresso");
?>

上面代码段的输出是:

Making a cup of cappuccino.
Making a cup of espresso.

PHP 还允许使用数组和特殊类型 NULL 作为默认参数,例如:

例子 17-8. 使用非标量类型作为默认参数

<?php
function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL)
{
    $device = is_null($coffeeMaker) ? "hands" : $coffeeMaker;
    return "Making a cup of ".join(", ", $types)." with $device.\n";
}
echo makecoffee();
echo makecoffee(array("cappuccino", "lavazza"), "teapot");
?>

默认值必须是常量表达式,不是(例如)变量,类成员,或者函数调用。

请注意当使用默认参数时,任何默认参数必须放在任何非默认参数的右侧;否则,可能函数将不会按照预期的情况工作。考虑下面的代码片断:

例子 17-9. 函数默认参数不正确的用法

<?php
function makeyogurt($type = "acidophilus", $flavour)
{
    return "Making a bowl of $type $flavour.\n";
}

echo makeyogurt("raspberry");   // won't work as expected
?>

上述例子的输出是:

Warning: Missing argument 2 in call to makeyogurt() in
/usr/local/etc/httpd/htdocs/php3test/functest.html on line 41
Making a bowl of raspberry .

现在,比较上面的例子和这个例子:

例子 17-10. 函数默认参数正确的用法

<?php
function makeyogurt($flavour, $type = "acidophilus")
{
    return "Making a bowl of $type $flavour.\n";
}

echo makeyogurt("raspberry");   // works as expected
?>

这个例子的输出是:

Making a bowl of acidophilus raspberry.

注: 自 PHP 5 起,默认值可以通过引用传递。


可变长度参数列表

PHP 4 及更高版本已经在用户自定义函数中支持可变长度参数列表。这个真的很简单,用 func_num_args()func_get_arg(),和 func_get_args() 函数。

无需特别的语法,参数列表仍然能够被明确无误的传递给函数并且正常运转。


返回值

值通过使用可选的返回语句返回。任何类型都可以返回,其中包括列表和对象。这导致函数立即结束它的运行,并且将控制权传递回它被调用的行。更多信息见 return()

例子 17-11. return() 的用法

<?php
function square($num)
{
    return $num * $num;
}
echo square(4);   // outputs '16'.
?>

函数不能返回多个值,但为了获得简单的结果,可以返回一个列表。

例子 17-12. 返回一个数组以得到多个返回值

<?php
function small_numbers()
{
    return array (0, 1, 2);
}
list ($zero, $one, $two) = small_numbers();
?>

从函数返回一个引用,必须在函数声明和指派返回值给一个变量时都使用引用操作符 & :

例子 17-13. 由函数返回一个引用

<?php
function &returns_reference()
{
    return $someref;
}

$newref =& returns_reference();
?>

有关引用的更多信息, 请查看引用的解释


变量函数

PHP 支持变量函数的概念。这意味着如果一个变量名后有圆括号,PHP 将寻找与变量的值同名的函数,并且将尝试执行它。除了别的事情以外,这个可以被用于实现回调函数,函数表等等。

变量函数不能用于语言结构,例如 echo()print()unset()isset()empty()include()require() 以及类似的语句。需要使用自己的外壳函数来将这些结构用作变量函数。

例子 17-14. 变量函数示例

<?php
function foo() {
    echo "In foo()<br />\n";
}

function bar($arg = '') {
    echo "In bar(); argument was '$arg'.<br />\n";
}

// This is a wrapper function around echo
function echoit($string)
{
    echo $string;
}

$func = 'foo';
$func();        // This calls foo()

$func = 'bar';
$func('test');  // This calls bar()

$func = 'echoit';
$func('test');  // This calls echoit()
?>

还可以利用变量函数的特性来调用一个对象的方法。

例子 17-15. 变量方法范例

<?php
class Foo
{
    function Variable()
    {
        $name = 'Bar';
        $this->$name(); // This calls the Bar() method
    }

    function Bar()
    {
        echo "This is Bar";
    }
}

$foo = new Foo();
$funcname = "Variable";
$foo->$funcname();   // This calls $foo->Variable()

?>

请参阅 call_user_func()可变变量function_exists()


内部(内置)函数

PHP 有很多标准的函数和结构。还有一些函数需要和特定地 PHP 扩展模块一起编译,否则在使用它们的时候就会得到一个致命的“未定义函数”错误。例如,要使用图像函数比如 imagecreatetruecolor(),需要在编译 PHP 的时候加上 GD 的支持。或者,要使用 mysql_connect() 函数,就需要在编译 PHP 的时候加上 MySQL 支持。有很多核心函数已包含在每个版本的 PHP 中如字符串变量函数。调用 phpinfo() 或者 get_loaded_extensions() 可以得知 PHP 加载了那些扩展库。同时还应该注意,很多扩展库默认就是有效的。PHP 手册按照不同的扩展库组织了它们的文档。请参阅配置安装以及各自的扩展库章节以获取有关如何设置 PHP 的信息。

手册中如何阅读函数原型讲解了如何阅读和理解一个函数的原型。确认一个函数将返回什么,或者函数是否直接作用于传递的参数是很重要的。例如,str_replace() 函数将返回修改过的字符串,而 usort() 却直接作用于传递的参数变量本身。手册中,每一个函数的页面中都有关于函数参数、行为改变、成功与否的返回值以及使用条件等信息。了解这些重要的(常常是细微的)差别是编写正确的 PHP 代码的关键。

参见 function_exists()函数参考get_extension_funcs()dl()


章 18. 类与对象(PHP 4)

类是变量与作用于这些变量的函数的集合。使用下面的语法定义一个类:

<?php
class Cart {
    var $items;  // 购物车中的物品

    // 将 $num 个 $artnr 物品加入购物车

    function add_item($artnr, $num) {
        $this->items[$artnr] += $num;
    }

    // 将 $num 个 $artnr 物品从购物车中取出

    function remove_item($artnr, $num) {
        if ($this->items[$artnr] > $num) {
            $this->items[$artnr] -= $num;
            return true;
        } elseif ($this->items[$artnr] == $num) {
            unset($this->items[$artnr]);
            return true;
        } else {
            return false;
        }
    }
}
?>

上面的例子定义了一个 Cart 类,这个类由购物车中的商品构成的数组和两个用于从购物车中添加和删除商品的函数组成。

警告

不能将一个类的定义分割到多个文件中。也不能将一个类的定义分割到多个 PHP 块中,除非该分割是在一个方法声明内部。以下用法将不起作用:

<?php
class test {
?>
<?php
    function test() {
        print 'OK';
    }
}
?>

但是以下用法是可以的:

<?php
class test {
    function test() {
        ?>
        <?php
        print 'OK';
    }
}
?>

以下警告仅用于 PHP 4。

注意

名称 stdClass 已经被 Zend 使用并保留。不能在 PHP 代码中定义名为 stdClass 的类。

注意

函数名 __sleep__wakeup 在 PHP 类中是魔术函数。除非想要与之联系的魔术功能,否则在任何类中都不能以此命名函数。

注意

PHP 将所有以 __ 开头的函数名保留为魔术函数。除非想要使用一些见于文档中的魔术功能,否则建议不要在 PHP 中将函数名以 __ 开头。

在 PHP 4 中,var 变量的值只能初始化为常量。用非常量值初始化变量,需要一个初始化函数,该函数在对象被创建时自动被调用。这样一个函数被称之为构造函数(见下面)。

<?php
/* PHP 4 中不能这样用 */
class Cart {
    var $todays_date = date("Y-m-d");
    var $name = $firstname;
    var $owner = 'Fred ' . 'Jones';
    /* 不过包含有常量的数组可以 */
    var $items = array("VCR", "TV");
}

/* 应该这样进行 */
class Cart {
    var $todays_date;
    var $name;
    var $owner;
    var $items = array("VCR", "TV");
    function Cart() {
        $this->todays_date = date("Y-m-d");
        $this->name = $GLOBALS['firstname'];
        /* etc. . . */
    }
}
?>

类也是一种类型,就是说,它们是实际变量的蓝图。必须用 new 运算符来创建相应类型的变量。

<?php
$cart = new Cart;
$cart->add_item("10", 1);

$another_cart = new Cart;
$another_cart->add_item("0815", 3);
?>

上述代码创建了两个 Cart 类的对象 $cart$another_cart,对象 $cart 的方法 add_item() 被调用时,添加了 1 件 10 号商品。对于对象 $another_cart,3 件 0815 号商品被添加到购物车中。

$cart$another_cart 都有方法 add_item(),remove_item() 和一个 items 变量。它们都是明显的函数和变量。可以把它们当作文件系统中的某些类似目录的东西来考虑。在文件系统中,可以拥有两个不同的 README.TXT 文件,只要不在相同的目录中。正如从为了根目录访问每个文件需要输入该文件的完整的路径名一样,必须指定需要调用的函数的完整名称:在 PHP 术语中,根目录将是全局名字空间,路径名符号将是 ->。因而,名称 $cart->items$another_cart->items 命名了两个不同的变量。注意变量名为 $cart->items,不是 $cart->$items,那是因为在 PHP 中一个变量名只有一个单独的美元符号。

<?php
// 正确,只有一个 $
$cart->items = array("10" => 1);

// 不正确,因为 $cart->$items 变成了 $cart->""
$cart->$items = array("10" => 1);

// 正确,但可能不是想要的结果:
// $cart->$myvar 变成了 $cart->items
$myvar = 'items';
$cart->$myvar = array("10" => 1);
?>

在定义类的时候,无法得知将使什么名字的对象来访问:在编写 Cart 类时,并不知道之后对象的名称将会命名为 $cart 或者 $another_cart。因而你不能在类中使用 $cart->items。然而为了类定义的内部访问自身的函数和变量,可以使用伪变量 $this 来达到这个目的。$this 变量可以理解为“我自己的”或者“当前对象”。因而 '$this->items[$artnr] += $num' 可以理解为“我自己的物品数组的 $artnr 计数器加 $num”或者“在当前对象的物品数组的 $artnr 计数器加 $num”。

注: 伪变量 $this 通常未定义,如果其所在的方法是被静态调用的话。但这不是个严格规定:如果一个方法被从另一个对象内静态调用的话,则 $this 会被定义。此时 $this 的值是那个发出调用的对象。用下例演示:

<?php
class A
{
    function foo()
    {
        if (isset($this)) {
            echo '$this is defined (';
            echo get_class($this);
            echo ")\n";
        } else {
            echo "\$this is not defined.\n";
        }
    }
}

class B
{
    function bar()
    {
        A::foo();
    }
}

$a = new A();
$a->foo();
A::foo();
$b = new B();
$b->bar();
B::bar();
?>

上例将输出:

$this is defined (a)
$this is not defined.
$this is defined (b)
$this is not defined.

注: 有一些不错的函数用来处理类和对象。应该关注一下类/对象函数


继承

通常需要这样一些类,这些类与其它现有的类拥有相同变量和函数。实际上,定义一个通用类用于所有的项目,并且不断丰富这个类以适应每个具体项目将是一个不错的练习。为了使这一点变得更加容易,类可以从其它的类中扩展出来。扩展或派生出来的类拥有其基类(这称为“继承”,只不过没人死)的所有变量和函数,并包含所有派生类中定义的部分。类中的元素不可能减少,就是说,不可以注销任何存在的函数或者变量。一个扩充类总是依赖一个单独的基类,也就是说,不支持多继承。使用关键字“extends”来扩展一个类。

<?php
class Named_Cart extends Cart {
    var $owner;

    function set_owner ($name) {
        $this->owner = $name;
    }
}
?>

上述示例定义了名为 Named_Cart 的类,该类拥有 Cart 类的所有变量和函数,加上附加的变量 $owner 和一个附加函数 set_owner()。现在,以正常的方式创建了一个有名字的购物车,并且可以设置并取得该购物车的主人。而正常的购物车类的函数依旧可以在有名字的购物车类中使用:

<?php
$ncart = new Named_Cart;    // 新建一个有名字的购物车
$ncart->set_owner("kris");  // 给该购物车命名
print $ncart->owner;        // 输出该购物车主人的名字
$ncart->add_item("10", 1);  // (从购物车类中继承来的功能)
?>

这个也可以叫做“父-子”关系。创建一个类,父类,并使用 extends 来创建一个基于父类的新类:子类。甚至可以使用这个新的子类来创建另外一个基于这个子类的类。

注: 类只有在定义后才可以使用!如果需要类 Named_Cart 继承类 Cart,必须首先定义 Cart 类。如果需要创建另一个基于 Named_Cart 类的 Yellow_named_cart 类,必须首先定义 Named_Cart 类。简捷的说:类定义的顺序是非常重要的。


构造函数

构造函数是类中的一个特殊函数,当使用 new 操作符创建一个类的实例时,构造函数将会自动调用。当函数与类同名时,这个函数将成为构造函数。如果一个类没有构造函数,则调用基类的构造函数,如果有的话。

<?php
class Auto_Cart extends Cart {
    function Auto_Cart() {
        $this->add_item ("10", 1);
    }
}
?>

上文定义了一个 Auto_Cart 类,即 Cart 类加上一个构造函数,当每次使用“new”创建一个新的 Auto_Cart 类实例时,构造函数将自动调用并将一件商品的数目初始化为“10”。构造函数可以使用参数,而且这些参数可以是可选的,它们可以使构造函数更加有用。为了依然可以不带参数地使用类,所有构造函数的参数应该提供默认值,使其可选。

<?php
class Constructor_Cart extends Cart {
    function Constructor_Cart($item = "10", $num = 1) {
        $this->add_item ($item, $num);
    }
}

// 买些同样的无聊老货
$default_cart = new Constructor_Cart;
// 买些实在货...
$different_cart = new Constructor_Cart("20", 17);
?>

也可以使用 @ 操作符来抑制发生在构造函数中的错误。例如 @new

<?php
class A
{
    function A()
    {
      echo "I am the constructor of A.<br>\n";
    }

    function B()
    {
        echo "I am a regular function named B in class A.<br>\n";
        echo "I am not a constructor in A.<br>\n";
    }
}

class B extends A
{
    function C()
    {
        echo "I am a regular function.<br>\n";
    }
}

// 调用 B() 作为构造函数
$b = new B;
?>

类 A 中的函数 B() 将立即成为类 B 中的构造函数,虽然并不是有意如此。PHP 4 并不关心函数是否在类 B 中定义的,或者是否被继承来的。

注意

PHP 4 不会从派生类的构造函数中自动调用基类的构造函数。恰当地逐次调用上一级的构造函数是用户的责任。

析构函数是一种当对象被销毁时,无论使用了 unset() 或者简单的脱离范围,都会被自动调用的函数。PHP 中没有析构函数。可以用 register_shutdown_function() 来替代模拟大多数析构函数的效果。


作用域分辨运算符(::

注意

下列内容仅在 PHP 4 及以后版本中有效。

有时,在没有声明任何实例的情况下访问类中的函数或者基类中的函数和变量很有用处。而 :: 运算符即用于此情况。

<?php
class A {
    function example() {
        echo "I am the original function A::example().<br />\n";
    }
}

class B extends A {
    function example() {
        echo "I am the redefined function B::example().<br />\n";
        A::example();
    }
}

// A 类没有对象,这将输出
//   I am the original function A::example().<br />
A::example();

// 建立一个 B 类的对象
$b = new B;

// 这将输出
//   I am the redefined function B::example().<br />
//   I am the original function A::example().<br />
$b->example();
?>

上面的例子调用了 A 类的函数 example(),但是这里并不存在 A 类的对象,因此不能这样用 $a->example() 或者类似的方法调用 example()。反而我们将 example() 作为一个类函数来调用,也就是说,作为一个类自身的函数来调用,而不是这个类的任何对象。

这里有类函数,但没有类的变量。实际上,在调用函数时完全没有任何对象。因而一个类的函数可以不使用任何对象(但可以使用局部或者全局变量),并且可以根本不使用 $this 变量。

上面的例子中,类 B 重新定义了函数 example()。A 类中原始定义的函数 example() 将被屏蔽并且不再生效,除非使用 :: 运算符来访问 A 类中的 example() 函数。如:A::example()(实际上,应该写为 parent::example(),下一章介绍该内容)。

就此而论,对于当前对象,它可能有对象变量。因此可以在对象函数的内部使用 $this 和对象变量。


parent

用户可能会发现自己写的代码访问了基类的变量和函数。如果派生类非常精炼或者基类非常专业化的时候尤其是这样。

不要用代码中基类文字上的名字,应该用特殊的名字 parent,它指的就是派生类在 extends 声明中所指的基类的名字。这样做可以避免在多个地方使用基类的名字。如果继承树在实现的过程中要修改,只要简单地修改类中 extends 声明的部分。

<?php
class A {
    function example() {
        echo "I am A::example() and provide basic functionality.<br />\n";
    }
}

class B extends A {
    function example() {
        echo "I am B::example() and provide additional functionality.<br />\n";
        parent::example();
    }
}

$b = new B;

// 这将调用 B::example(),而它会去调用 A::example()。
$b->example();
?>


序列化对象 - 会话中的对象

注: 在 PHP 3 中,在序列化和解序列化的过程中对象会失去类的关联。结果的变量是对象类型,但是没有类和方法,因此就没什么用了(就好像一个用滑稽的语法定义的数组一样)。

注意

以下信息仅在 PHP >= 4 中有效。

serialize() 返回一个字符串,包含着可以储存于 PHP 的任何值的字节流表示。unserialize() 可以用此字符串来重建原始的变量值。用序列化来保存对象可以保存对象中的所有变量。对象中的函数不会被保存,只有类的名称。

要能够 unserialize() 一个对象,需要定义该对象的类。也就是,如果序列化了 page1.php 中类 A 的对象 $a,将得到一个指向类 A 的字符串并包含有所有 $a 中变量的值。如果要在 page2.php 中将其解序列化,重建类 A 的对象 $a,则 page2.php 中必须要出现类 A 的定义。例如可以这样实现,将类 A 的定义放在一个包含文件中,并在 page1.php 和 page2.php 都包含此文件。

<?php
// classa.inc:
  class A {
      var $one = 1;

      function show_one() {
          echo $this->one;
      }
  }

// page1.php:
  include("classa.inc");

  $a = new A;
  $s = serialize($a);
  // 将 $s 存放在某处使 page2.php 能够找到
  $fp = fopen("store", "w");
  fwrite($fp, $s);
  fclose($fp);

// page2.php:
  // 为了正常解序列化需要这一行
  include("classa.inc");

  $s = implode("", @file("store"));
  $a = unserialize($s);

  // 现在可以用 $a 对象的 show_one() 函数了
  $a->show_one();
?>

如果在用会话并使用了 session_register() 来注册对象,这些对象会在每个 PHP 页面结束时被自动序列化,并在接下来的每个页面中自动解序列化。基本上是说这些对象一旦成为会话的一部分,就能在任何页面中出现。

强烈建议在所有的页面中都包括这些注册的对象的类的定义,即使并不是在所有的页面中都用到了这些类。如果没有这样做,一个对象被解序列化了但却没有其类的定义,它将失去与之关联的类并成为 stdClass 的一个对象而完全没有任何可用的函数,这样就很没有用处。

因此如果在以上的例子中 $a 通过运行 session_register("a") 成为了会话的一部分,应该在所有的页面中包含 classa.inc 文件,而不只是 page1.php 和 page2.php。


魔术函数 __sleep__wakeup

serialize() 检查类中是否有魔术名称 __sleep 的函数。如果这样,该函数将在任何序列化之前运行。它可以清除对象并应该返回一个包含有该对象中应被序列化的所有变量名的数组。

使用 __sleep 的目的是关闭对象可能具有的任何数据库连接,提交等待中的数据或进行类似的清除任务。此外,如果有非常大的对象而并不需要完全储存下来时此函数也很有用。

相反地,unserialize() 检查具有魔术名称 __wakeup 的函数的存在。如果存在,此函数可以重建对象可能具有的任何资源。

使用 __wakeup 的目的是重建在序列化中可能丢失的任何数据库连接以及处理其它重新初始化的任务。


构造函数中的引用

在构造函数中创建引用可能会导致混淆的结果。本节以教程形式帮助避免问题。

<?php
class Foo {
    function Foo($name) {
        // 在全局数组 $globalref 中建立一个引用
        global $globalref;
        $globalref[] = &$this;
        // 将名字设定为传递的值
        $this->setName($name);
        // 并输出之
        $this->echoName();
    }

    function echoName() {
        echo "<br />",$this->name;
    }

    function setName($name) {
        $this->name = $name;
    }
}
?>

下面来检查一下用拷贝运算符 = 创建的 $bar1 和用引用运算符 =& 创建的 $bar2 有没有区别...

<?php
$bar1 = new Foo('set in constructor');
$bar1->echoName();
$globalref[0]->echoName();

/* 输出:
set in constructor
set in constructor
set in constructor */

$bar2 =& new Foo('set in constructor');
$bar2->echoName();
$globalref[1]->echoName();

/* 输出:
set in constructor
set in constructor
set in constructor */
?>

显然没有区别,但实际上有一个非常重要的区别:$bar1$globalref[0] 并没有被引用,它们不是同一个变量。这是因为“new”默认并不返回引用,而返回一个拷贝。

注: 在返回拷贝而不是引用中并没有性能上的损失(因为 PHP 4 及以上版本使用了引用计数)。相反更多情况下工作于拷贝而不是引用上更好,因为建立引用需要一些时间而建立拷贝实际上不花时间(除非它们都不是大的数组或对象,而其中之一跟着另一个变,那使用引用来同时修改它们会更聪明一些)。

要证明以上写的,看看下面的代码。

<?php
// 现在改个名字,你预期什么结果?
// 你可能预期 $bar1 和 $globalref[0] 二者的名字都改了...
$bar1->setName('set from outside');

// 但如同前面说的,并不是这样。
$bar1->echoName();
$globalref[0]->echoName();

/* 输出为:
set from outside
set in constructor */

// 现在看看 $bar2 和 $globalref[1] 有没有区别
$bar2->setName('set from outside');

// 幸运的是它们不但相同,根本就是同一个变量。
// 因此 $bar2->name 和 $globalref[1]->name 也是同一个变量。
$bar2->echoName();
$globalref[1]->echoName();

/* 输出为:
set from outside
set from outside */
?>

最后给出另一个例子,试着理解它。

<?php
class A {
    function A($i) {
        $this->value = $i;
        // 试着想明白为什么这里不需要引用
        $this->b = new B($this);
    }

    function createRef() {
        $this->c = new B($this);
    }

    function echoValue() {
        echo "<br />","class ",get_class($this),': ',$this->value;
    }
}


class B {
    function B(&$a) {
        $this->a = &$a;
    }

    function echoValue() {
        echo "<br />","class ",get_class($this),': ',$this->a->value;
    }
}

// 试着理解为什么这里一个简单的拷贝会在下面用 *
// 标出来的行中产生预期之外的结果
$a =& new A(10);
$a->createRef();

$a->echoValue();
$a->b->echoValue();
$a->c->echoValue();

$a->value = 11;

$a->echoValue();
$a->b->echoValue(); // *
$a->c->echoValue();
?>

上例将输出:

class A: 10
class B: 10
class B: 10
class A: 11
class B: 11
class B: 11


对象的比较

在 PHP 4 中,对象比较的规则十分简单:如果两个对象是同一个类的实例,且它们有相同的属性和值,则这两个对象相等。类似的规则还适用与用全等符(===)对两个对象的比较。

如果执行以下范例中的代码:

例子 18-1. PHP 4 中对象比较范例

<?php
function bool2str($bool) {
    if ($bool === false) {
            return 'FALSE';
    } else {
            return 'TRUE';
    }
}

function compareObjects(&$o1, &$o2) {
    echo 'o1 == o2 : '.bool2str($o1 == $o2)."\n";
    echo 'o1 != o2 : '.bool2str($o1 != $o2)."\n";
    echo 'o1 === o2 : '.bool2str($o1 === $o2)."\n";
    echo 'o1 !== o2 : '.bool2str($o1 !== $o2)."\n";
}

class Flag {
    var $flag;

    function Flag($flag=true) {
            $this->flag = $flag;
    }
}

class SwitchableFlag extends Flag {

    function turnOn() {
        $this->flag = true;
    }

    function turnOff() {
        $this->flag = false;
    }
}

$o = new Flag();
$p = new Flag(false);
$q = new Flag();

$r = new SwitchableFlag();

echo "Compare instances created with the same parameters\n";
compareObjects($o, $q);

echo "\nCompare instances created with different parameters\n";
compareObjects($o, $p);

echo "\nCompare an instance of a parent class with one from a subclass\n";
compareObjects($o, $r);
?>

上例将输出:

Compare instances created with the same parameters
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSE

Compare instances created with different parameters
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE

Compare an instance of a parent class with one from a subclass
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE
这和按照比较规则推测的结果一致。当且仅当出自同一个类且属性及其值都相同的对象被认为是相等且完全相同的。

即使对于具有对象成分的类,比较的规则也相同。在以下的范例中建立了一个容器类来储存 Flag 对象的一个相关数组。

例子 18-2. PHP 4 中复合对象的比较

<?php
class FlagSet {
    var $set;

    function FlagSet($flagArr = array()) {
        $this->set = $flagArr;
    }

    function addFlag($name, $flag) {
        $this->set[$name] = $flag;
    }

    function removeFlag($name) {
        if (array_key_exists($name, $this->set)) {
            unset($this->set[$name]);
        }
    }
}


$u = new FlagSet();
$u->addFlag('flag1', $o);
$u->addFlag('flag2', $p);
$v = new FlagSet(array('flag1'=>$q, 'flag2'=>$p));
$w = new FlagSet(array('flag1'=>$q));

echo "\nComposite objects u(o,p) and v(q,p)\n";
compareObjects($u, $v);

echo "\nu(o,p) and w(q)\n";
compareObjects($u, $w);
?>

上例将输出:

Composite objects u(o,p) and v(q,p)
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSE

u(o,p) and w(q)
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE


章 19. 类与对象(PHP 5)

前言

PHP 5 引入了新的对象模型(Object Model)。完全重写了 PHP 处理对象的方式,允许更佳性能和更多特性。


基本概念

class

每个类的定义都以关键字 class 开头,后面跟着类名,可以是任何非 PHP 保留字的名字。后面跟着一对花括号,里面包含有类成员和方法的定义。伪变量 $this 可以在当一个方法在对象内部调用时使用。$this 是一个到调用对象(通常是方法所属于的对象,但也可以是另一个对象,如果该方法是从第二个对象内静态调用的话)的引用。看下面例子:

<?php
class A
{
    function foo()
    {
        if (isset($this)) {
            echo '$this is defined (';
            echo get_class($this);
            echo ")\n";
        } else {
            echo "\$this is not defined.\n";
        }
    }
}

class B
{
    function bar()
    {
        A::foo();
    }
}

$a = new A();
$a->foo();
A::foo();
$b = new B();
$b->bar();
B::bar();
?>

上例将输出:

$this is defined (a)
$this is not defined.
$this is defined (b)
$this is not defined.

例子 19-1. 简单的类定义

<?php
class SimpleClass
{
    // 成员声明
    public $var = 'a default value';

    // 方法声明
    public function displayVar() {
        echo $this->var;
    }
}
?>

new

要创建一个对象的实例,必须创建一个新对象并将其赋给一个变量。当创建新对象时该对象总是被赋值,除非该对象定义了构造函数并且在出错时抛出了一个异常

例子 19-2. 创建一个实例e

<?php
$instance = new SimpleClass()
?>

当把一个对象已经创建的实例赋给一个新变量时,新变量会访问同一个实例,就和用该对象赋值一样。此行为和给函数传递入实例时一样。可以用克隆给一个已创建的对象建立一个新实例。

例子 19-3. 对象赋值

<?php
$assigned   =  $instance;
$reference  =& $instance;

$instance->var = '$assigned will have this value';

$instance = null; // $instance and $reference become null

var_dump($instance);
var_dump($reference);
var_dump($assigned);
?>

上例将输出:

NULL
NULL
object(SimpleClass)#1 (1) {
   ["var"]=>
     string(30) "$assigned will have this value"
}

extends

一个类可以在声明中用 extends 关键字继承另一个类的方法和成员。不能扩展多个类,只能继承一个基类。

被继承的方法和成员可以通过用同样的名字重新声明被覆盖,除非父类定义方法时使用了 final 关键字。可以通过 parent:: 来访问被覆盖的方法或成员。

例子 19-4. 简单的类继承

<?php
class ExtendClass extends SimpleClass
{
    // Redefine the parent method
    function displayVar()
    {
        echo "Extending class\n";
        parent::displayVar();
    }
}

$extended = new ExtendClass();
$extended->displayVar();
?>

上例将输出:

Extending class
a default value

自动加载对象

很多开发者写面向对象的应用程序时对每个类的定义建立一个 PHP 源文件。一个很大的烦恼是不得不在每个脚本(每个类一个文件)开头写一个常常的包含文件列表。

在 PHP 5 中,不再需要这样了。可以定义一个 __autoload 函数,它会在试图使用尚未被定义的类时自动调用。通过调用此函数,脚本引擎在 PHP 出错失败前有了最后一个机会加载所需的类。

注: 在 __autoload 函数中抛出的异常不能被 catch 语句块捕获并导致致命错误。

例子 19-5. Autoload 例子

本例尝试分别从 MyClass1.phpMyClass2.php 文件中加载 MyClass1MyClass2 类。

<?php
function __autoload($class_name) {
    require_once $class_name . '.php';
}

$obj  = new MyClass1();
$obj2 = new MyClass2();
?>


构造函数和析构函数

构造函数

void __construct ( [mixed args [, ...]] )

PHP 5 允行开发者在一个类中定义一个方法作为构造函数。具有构造函数的类会在每次创建对象时先调用此方法,所以非常适合在使用对象之前做一些初始化工作。

注: 如果子类中定义了构造函数则不会暗中调用其父类的构造函数。要执行父类的构造函数,需要在子类的构造函数中调用 parent::__construct()

例子 19-6. 使用新标准的构造函数

<?php
class BaseClass {
   function __construct() {
       print "In BaseClass constructor\n";
   }
}

class SubClass extends BaseClass {
   function __construct() {
       parent::__construct();
       print "In SubClass constructor\n";
   }
}

$obj = new BaseClass();
$obj = new SubClass();
?>

为了实现向后兼容性,如果 PHP 5 在类中找不到 __construct() 函数,它就会尝试寻找旧式的构造函数,也就是和类同名的函数。因此唯一会产生兼容性问题的情况是:类中已有一个名为 __construct() 的方法,但它却又不是构造函数。


析构函数

void __destruct ( void )

PHP 5 引入了析构函数的概念,这类似于其它面向对象的语言,如 C++。析构函数会在到某个对象的所有引用都被删除或者当对象被显式销毁时执行。

例子 19-7. 析构函数示例

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

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

$obj = new MyDestructableClass();
?>

和构造函数一样,父类的析构函数不会被引擎暗中调用。要执行父类的析构函数,必须在子类的析构函数体中显式调用 parent::__destruct()

注: 析构函数在脚本关闭时调用,此时所有的头信息已经发出。

注: 试图在析构函数中抛出一个异常会导致致命错误。


Visibility

The visibility of a property or method can be defined by prefixing the declaration with the keywords: public, protected or private. Public declared items can be accessed everywhere. Protected limits access to inherited and parent classes (and to the class that defines the item). Private limits visibility only to the class that defines the item.


Members Visibility

Class members must be defined with public, private, or protected.

例子 19-8. Member declaration

<?php
/**
 * Define MyClass
 */
class MyClass
{
    public $public = 'Public';
    protected $protected = 'Protected';
    private $private = 'Private';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private


/**
 * Define MyClass2
 */
class MyClass2 extends MyClass
{
    // We can redeclare the public and protected method, but not private
    protected $protected = 'Protected2';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj2 = new MyClass2();
echo $obj->public; // Works
echo $obj2->private; // Undefined
echo $obj2->protected; // Fatal Error
$obj2->printHello(); // Shows Public, Protected2, not Private

?>

注: The PHP 4 method of declaring a variable with the var keyword is no longer valid for PHP 5 objects. For compatibility a variable declared in php will be assumed with public visibility, and a E_STRICT warning will be issued.


Method Visibility

Class methods must be defined with public, private, or protected. Methods without any declaration are defined as public.

例子 19-9. Method Declaration

<?php
/**
 * Define MyClass
 */
class MyClass
{
    // Contructors must be public
    public function __construct() { }

    // Declare a public method
    public function MyPublic() { }

    // Declare a protected method
    protected function MyProtected() { }

    // Declare a private method
    private function MyPrivate() { }

    // This is public
    function Foo()
    {
        $this->MyPublic();
        $this->MyProtected();
        $this->MyPrivate();
    }
}

$myclass = new MyClass;
$myclass->MyPublic(); // Works
$myclass->MyProtected(); // Fatal Error
$myclass->MyPrivate(); // Fatal Error
$myclass->Foo(); // Public, Protected and Private work


/**
 * Define MyClass2
 */
class MyClass2 extends MyClass
{
    // This is public
    function Foo2()
    {
        $this->MyPublic();
        $this->MyProtected();
        $this->MyPrivate(); // Fatal Error
    }
}

$myclass2 = new MyClass2;
$myclass2->MyPublic(); // Works
$myclass2->Foo2(); // Public and Protected work, not Private
?>


Scope Resolution Operator (::)

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden members or methods of a class.

When referencing these items from outside the class definition, use the name of the class.

Paamayim Nekudotayim would, at first, seem like a strange choice for naming a double-colon. However, while writing the Zend Engine 0.5 (which powers PHP 3), that's what the Zend team decided to call it. It actually does mean double-colon - in Hebrew!

例子 19-10. :: from outside the class definition

<?php
class MyClass {
    const CONST_VALUE = 'A constant value';
}

echo MyClass::CONST_VALUE;
?>

Two special keywords self and parent are used to access members or methods from inside the class definition.

例子 19-11. :: from inside the class definition

<?php
class OtherClass extends MyClass
{
    public static $my_static = 'static var';

    public static function doubleColon() {
        echo parent::CONST_VALUE . "\n";
        echo self::$my_static . "\n";
    }
}

OtherClass::doubleColon();
?>

When an extending class overrides the parents definition of a method, PHP will not call the parent's method. It's up to the extended class on whether or not the parent's method is called. This also applies to Constructors and Destructors, Overloading, and Magic method definitions.

例子 19-12. Calling a parent's method

<?php
class MyClass
{
    protected function myFunc() {
        echo "MyClass::myFunc()\n";
    }
}

class OtherClass extends MyClass
{
    // Override parent's definition
    public function myFunc()
    {
        // But still call the parent function
        parent::myFunc();
        echo "OtherClass::myFunc()\n";
    }
}

$class = new OtherClass();
$class->myFunc();
?>

Static Keyword

Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static can not be accessed with an instantiated class object (though a static method can). Static members and methods cannot be re-defined in subclasses.

The static declaration must be after the visibility declaration. For compatibility with PHP 4, if no visibility declaration is used, then the member or method will be treated as if it was declared as public.

Because static methods are callable without an instance of the object created, the pseudo variable $this is not available inside the method declared as static.

In fact static method calls are resolved at compile time. When using an explicit class name the method is already identified completely and no inheritance rules apply. If the call is done by self then self is translated to the current class, that is the class the code belongs to. Here also no inheritance rules apply.

Static properties cannot be accessed through the object using the arrow operator ->.

Calling non-static methods statically generates an E_STRICT level warning.

例子 19-13. Static member example

<?php
class Foo
{
    public static $my_static = 'foo';

    public function staticValue() {
        return self::$my_static;
    }
}

class Bar extends Foo
{
    public function fooStatic() {
        return parent::$my_static;
    }
}


print Foo::$my_static . "\n";

$foo = new Foo();
print $foo->staticValue() . "\n";
print $foo->my_static . "\n";      // Undefined "Property" my_static 

// $foo::my_static is not possible

print Bar::$my_static . "\n";
$bar = new Bar();
print $bar->fooStatic() . "\n";
?>

例子 19-14. Static method example

<?php
class Foo {
    public static function aStaticMethod() {
        // ...
    }
}

Foo::aStaticMethod();
?>

Class Constants

It is possible to define constant values on a per-class basis remaining the same and unchangeable. Constants differ from normal variables in that you don't use the $ symbol to declare or use them. Like static members, constant values cannot be accessed from an instance of the object (using $object::constant).

例子 19-15. Defining and using a constant

<?php
class MyClass
{
    const constant = 'constant value';

    function showConstant() {
        echo  self::constant . "\n";
    }
}

echo MyClass::constant . "\n";

$class = new MyClass();
$class->showConstant();
// echo $class::constant;  is not allowed
?>

Class Abstraction

PHP 5 introduces abstract classes and methods. It is not allowed to create an instance of a class that has been defined as abstract. Any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method's signature they cannot define the implementation.

When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or weaker) visibillity. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public.

例子 19-16. Abstract class example

<?php
abstract class AbstractClass
{
    // Force Extending class to define this method
    abstract protected function getValue();
    abstract protected function prefixValue($prefix);

    // Common method
    public function printOut() {
        print $this->getValue() . "\n";
    }
}

class ConcreteClass1 extends AbstractClass
{
    protected function getValue() {
        return "ConcreteClass1";
    }

    public function prefixValue($prefix) {
        return "{$prefix}ConcreteClass1";
    }
}

class ConcreteClass2 extends AbstractClass
{
    public function getValue() {
        return "ConcreteClass2";
    }

    public function prefixValue($prefix) {
        return "{$prefix}ConcreteClass2";
    }
}

$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue('FOO_') ."\n";

$class2 = new ConcreteClass2;
$class2->printOut();
echo $class2->prefixValue('FOO_') ."\n";
?>

上例将输出:

ConcreteClass1
FOO_ConcreteClass1
ConcreteClass2
FOO_ConcreteClass2

Old code that has no user-defined classes or functions named 'abstract' should run without modifications.


Object Interfaces

Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.

Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined.

All methods declared in an interface must be public, this is the nature of an interface.


implements

To implement an interface, the implements operator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma.


范例

例子 19-17. Interface example

<?php
// Declare the interface 'iTemplate'
interface iTemplate
{
    public function setVariable($name, $var);
    public function getHtml($template);
}

// Implement the interface
// This will work
class Template implements iTemplate
{
    private $vars = array();
  
    public function setVariable($name, $var)
    {
        $this->vars[$name] = $var;
    }
  
    public function getHtml($template)
    {
        foreach($this->vars as $name => $value) {
            $template = str_replace('{' . $name . '}', $value, $template);
        }
 
        return $template;
    }
}

// This will not work
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (iTemplate::getHtml)
class BadTemplate implements iTemplate
{
    private $vars = array();
  
    public function setVariable($name, $var)
    {
        $this->vars[$name] = $var;
    }
}

?>

See also the instanceof operator.


Overloading

Both method calls and member accesses can be overloaded via the __call, __get and __set methods. These methods will only be triggered when your object or inherited object doesn't contain the member or method you're trying to access. All overloading methods must not be defined as static.

Since PHP 5.1.0 it is also possible to overload the isset() and unset() functions via the __isset and __unset methods respectively.


Member overloading

void __set ( string name, mixed value )

mixed __get ( string name )

bool __isset ( string name )

void __unset ( string name )

Class members can be overloaded to run custom code defined in your class by defining these specially named methods. The $name parameter used is the name of the variable that should be set or retrieved. The __set() method's $value parameter specifies the value that the object should set the $name.

例子 19-18. overloading with __get, __set, __isset and __unset example

<?php
class Setter
{
    public $n;
    private $x = array("a" => 1, "b" => 2, "c" => 3);

    private function __get($nm)
    {
        echo "Getting [$nm]\n";

        if (isset($this->x[$nm])) {
            $r = $this->x[$nm];
            print "Returning: $r\n";
            return $r;
        } else {
            echo "Nothing!\n";
        }
    }

    private function __set($nm, $val)
    {
        echo "Setting [$nm] to $val\n";

        if (isset($this->x[$nm])) {
            $this->x[$nm] = $val;
            echo "OK!\n";
        } else {
            echo "Not OK!\n";
        }
    }

    private function __isset($nm)
    {
        echo "Checking if $nm is set\n";

        return isset($this->x[$nm]);
    }

    private function __unset($nm)
    {
        echo "Unsetting $nm\n";

        unset($this->x[$nm]);
    }
}

$foo = new Setter();
$foo->n = 1;
$foo->a = 100;
$foo->a++;
$foo->z++;

var_dump(isset($foo->a)); //true
unset($foo->a);
var_dump(isset($foo->a)); //false

// this doesn't pass through the __isset() method
// because 'n' is a public property
var_dump(isset($foo->n));

var_dump($foo);
?>

上例将输出:

Setting [a] to 100
OK!
Getting [a]
Returning: 100
Setting [a] to 101
OK!
Getting [z]
Nothing!
Setting [z] to 1
Not OK!

Checking if a is set
bool(true)
Unsetting a
Checking if a is set
bool(false)
bool(true)

object(Setter)#1 (2) {
  ["n"]=>
  int(1)
  ["x:private"]=>
  array(2) {
    ["b"]=>
    int(2)
    ["c"]=>
    int(3)
  }
}

Method overloading

mixed __call ( string name, array arguments )

Class methods can be overloaded to run custom code defined in your class by defining this specially named method. The $name parameter used is the name as the function name that was requested to be used. The arguments that were passed in the function will be defined as an array in the $arguments parameter. The value returned from the __call() method will be returned to the caller of the method.

例子 19-19. overloading with __call example

<?php
class Caller
{
    private $x = array(1, 2, 3);

    public function __call($m, $a)
    {
        print "Method $m called:\n";
        var_dump($a);
        return $this->x;
    }
}

$foo = new Caller();
$a = $foo->test(1, "2", 3.4, true);
var_dump($a);
?>

上例将输出:

Method test called:
array(4) {
    [0]=>
    int(1)
    [1]=>
    string(1) "2"
    [2]=>
    float(3.4)
    [3]=>
    bool(true)
}
array(3) {
    [0]=>
    int(1)
    [1]=>
    int(2)
    [2]=>
    int(3)
}

Object Iteration

PHP 5 provides a way for objects to be defined so it is possible to iterate through a list of items, with, for example a foreach statement. By default, all visible properties will be used for the iteration.

例子 19-20. Simple Object Iteration

<?php
class MyClass
{
    public $var1 = 'value 1';
    public $var2 = 'value 2';
    public $var3 = 'value 3';

    protected $protected = 'protected var';
    private   $private   = 'private var';

    function iterateVisible() {
       echo "MyClass::iterateVisible:\n";
       foreach($this as $key => $value) {
           print "$key => $value\n";
       }
    }
}

$class = new MyClass();

foreach($class as $key => $value) {
    print "$key => $value\n";
}
echo "\n";


$class->iterateVisible();

?>

上例将输出:

var1 => value 1
var2 => value 2
var3 => value 3

MyClass::iterateVisible:
var1 => value 1
var2 => value 2
var3 => value 3
protected => protected var
private => private var

As the output shows, the foreach iterated through all visible variables that can be accessed. To take it a step further you can implement one of PHP 5's internal interface named Iterator. This allows the object to decide what and how the object will be iterated.

例子 19-21. Object Iteration implementing Iterator

<?php
class MyIterator implements Iterator
{
    private $var = array();

    public function __construct($array)
    {
        if (is_array($array)) {
            $this->var = $array;
        }
    }

    public function rewind() {
        echo "rewinding\n";
        reset($this->var);
    }

    public function current() {
        $var = current($this->var);
        echo "current: $var\n";
        return $var;
    }

    public function key() {
        $var = key($this->var);
        echo "key: $var\n";
        return $var;
    }

    public function next() {
        $var = next($this->var);
        echo "next: $var\n";
        return $var;
    }

    public function valid() {
        $var = $this->current() !== false;
        echo "valid: {$var}\n";
        return $var;
    }
}

$values = array(1,2,3);
$it = new MyIterator($values);

foreach ($it as $a => $b) {
    print "$a: $b\n";
}
?>

上例将输出:

rewinding
current: 1
valid: 1
current: 1
key: 0
0: 1
next: 2
current: 2
valid: 1
current: 2
key: 1
1: 2
next: 3
current: 3
valid: 1
current: 3
key: 2
2: 3
next:
current:
valid:

You can also define your class so that it doesn't have to define all the Iterator functions by simply implementing the PHP 5 IteratorAggregate interface.

例子 19-22. Object Iteration implementing IteratorAggregate

<?php
class MyCollection implements IteratorAggregate
{
    private $items = array();
    private $count = 0;

    // Required definition of interface IteratorAggregate
    public function getIterator() {
        return new MyIterator($this->items);
    }

    public function add($value) {
        $this->items[$this->count++] = $value;
    }
}

$coll = new MyCollection();
$coll->add('value 1');
$coll->add('value 2');
$coll->add('value 3');

foreach ($coll as $key => $val) {
    echo "key/value: [$key -> $val]\n\n";
}
?>

上例将输出:

rewinding
current: value 1
valid: 1
current: value 1
key: 0
key/value: [0 -> value 1]

next: value 2
current: value 2
valid: 1
current: value 2
key: 1
key/value: [1 -> value 2]

next: value 3
current: value 3
valid: 1
current: value 3
key: 2
key/value: [2 -> value 3]

next:
current:
valid:

注: For more examples of iterators, see the SPL Extension.


Patterns

Patterns are ways to describe best practices and good designs. They show a flexible solution to common programming problems.


Factory

The Factory pattern allows for the instantiation of objects at runtime. It is called a Factory Pattern since it is responsible for "manufacturing" an object.

例子 19-23. Factory Method

<?php
class Example
{
    // The factory method
    public static function factory($type)
    {
        if (include_once 'Drivers/' . $type . '.php') {
            $classname = 'Driver_' . $type;
            return new $classname;
        } else {
            throw new Exception ('Driver not found');
        }
    }
}
?>

Defining this method in a class allows drivers to be loaded on the fly. If the Example class was a database abstraction class, loading a MySQL and SQLite driver could be done as follows:

<?php
// Load a MySQL Driver
$mysql = Example::factory('MySQL');

// Load a SQLite Driver
$sqlite = Example::factory('SQLite');
?>

Singleton

The Singleton pattern applies to situations in which there needs to be a single instance of a class. The most common example of this is a database connection. Implementing this pattern allows a programmer to make this single instance easily accessible by many other objects.

例子 19-24. Singleton Function

<?php
class Example
{
    // Hold an instance of the class
    private static $instance;
    
    // A private constructor; prevents direct creation of object
    private function __construct() 
    {
        echo 'I am constructed';
    }

    // The singleton method
    public static function singleton() 
    {
        if (!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
        }

        return self::$instance;
    }
    
    // Example method
    public function bark()
    {
        echo 'Woof!';
    }

    // Prevent users to clone the instance
    public function __clone()
    {
        trigger_error('Clone is not allowed.', E_USER_ERROR);
    }

}

?>

This allows a single instance of the Example class to be retrieved.

<?php
// This would fail because the constructor is private
$test = new Example;

// This will always retrieve a single instance of the class
$test = Example::singleton();
$test->bark();

// This will issue an E_USER_ERROR.
$test_clone = clone($test);

?>

Magic Methods

The function names __construct, __destruct (see Constructors and Destructors), __call, __get, __set, __isset, __unset (see Overloading), __sleep, __wakeup, __toString, __clone and __autoload are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.

注意

PHP reserves all function names starting with __ as magical. It is recommended that you do not use function names with __ in PHP unless you want some documented magic functionality.


__sleep and __wakeup

serialize() checks if your class has a function with the magic name __sleep. If so, that function is executed prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized.

The intended use of __sleep is to close any database connections that the object may have, commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which do not need to be saved completely.

Conversely, unserialize() checks for the presence of a function with the magic name __wakeup. If present, this function can reconstruct any resources that the object may have.

The intended use of __wakeup is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.


__toString

The __toString method allows a class to decide how it will react when it is converted to a string.

例子 19-25. Simple example

<?php
// Declare a simple class
class TestClass
{
    public $foo;

    public function __construct($foo) {
        $this->foo = $foo;
    }

    public function __toString() {
        return $this->foo;
    }
}

$class = new TestClass('Hello');
echo $class;
?>

上例将输出:

Hello

It is worth noting that the __toString method will only be called when it is directly combined with echo() or print().

例子 19-26. Cases where __toString is called

<?php
// __toString called
echo $class;

// __toString called (still a normal parameter for echo)
echo 'text', $class;

// __toString not called (concatenation operator used first)
echo 'text' . $class;

// __toString not called (cast to string first)
echo (string) $class;

// __toString not called (cast to string first)
echo "text $class";
?>

Final Keyword

PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.

例子 19-27. Final methods example

<?php
class BaseClass {
   public function test() {
       echo "BaseClass::test() called\n";
   }
   
   final public function moreTesting() {
       echo "BaseClass::moreTesting() called\n";
   }
}

class ChildClass extends BaseClass {
   public function moreTesting() {
       echo "ChildClass::moreTesting() called\n";
   }
}
// Results in Fatal error: Cannot override final method BaseClass::moreTesting()
?>

例子 19-28. Final class example

<?php
final class BaseClass {
   public function test() {
       echo "BaseClass::test() called\n";
   }

   // Here it doesn't matter if you specify the function as final or not
   final public function moreTesting() {
       echo "BaseClass::moreTesting() called\n";
   }
}

class ChildClass extends BaseClass {
}
// Results in Fatal error: Class ChildClass may not inherit from final class (BaseClass)
?>

Object cloning

Creating a copy of an object with fully replicated properties is not always the wanted behavior. A good example of the need for copy constructors, is if you have an object which represents a GTK window and the object holds the resource of this GTK window, when you create a duplicate you might want to create a new window with the same properties and have the new object hold the resource of the new window. Another example is if your object holds a reference to another object which it uses and when you replicate the parent object you want to create a new instance of this other object so that the replica has its own separate copy.

An object copy is created by using the clone keyword (which calls the object's __clone() method if possible). An object's __clone() method cannot be called directly.

$copy_of_object = clone $object;

When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables, will remain references. If a __clone() method is defined, then the newly created object's __clone() method will be called, to allow any necessary properties that need to be changed.

例子 19-29. Cloning an object

<?php
class SubObject
{
    static $instances = 0;
    public $instance;

    public function __construct() {
        $this->instance = ++self::$instances;
    }

    public function __clone() {
        $this->instance = ++self::$instances;
    }
}

class MyCloneable
{
    public $object1;
    public $object2;

    function __clone()
    {
        // Force a copy of this->object, otherwise
        // it will point to same object.
        $this->object1 = clone($this->object1);
    }
}

$obj = new MyCloneable();

$obj->object1 = new SubObject();
$obj->object2 = new SubObject();

$obj2 = clone $obj;


print("Original Object:\n");
print_r($obj);

print("Cloned Object:\n");
print_r($obj2);

?>

上例将输出:

Original Object:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [instance] => 1
        )

    [object2] => SubObject Object
        (
            [instance] => 2
        )

)
Cloned Object:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [instance] => 3
        )

    [object2] => SubObject Object
        (
            [instance] => 2
        )

)

Comparing objects

In PHP 5, object comparison is more complicated than in PHP 4 and more in accordance to what one will expect from an Object Oriented Language (not that PHP 5 is such a language).

When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class.

On the other hand, when using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class.

An example will clarify these rules.

例子 19-30. Example of object comparison in PHP 5

<?php
function bool2str($bool)
{
    if ($bool === false) {
        return 'FALSE';
    } else {
        return 'TRUE';
    }
}

function compareObjects(&$o1, &$o2)
{
    echo 'o1 == o2 : ' . bool2str($o1 == $o2) . "\n";
    echo 'o1 != o2 : ' . bool2str($o1 != $o2) . "\n";
    echo 'o1 === o2 : ' . bool2str($o1 === $o2) . "\n";
    echo 'o1 !== o2 : ' . bool2str($o1 !== $o2) . "\n";
}

class Flag
{
    public $flag;

    function Flag($flag = true) {
        $this->flag = $flag;
    }
}

class OtherFlag
{
    public $flag;

    function OtherFlag($flag = true) {
        $this->flag = $flag;
    }
}

$o = new Flag();
$p = new Flag();
$q = $o;
$r = new OtherFlag();

echo "Two instances of the same class\n";
compareObjects($o, $p);

echo "\nTwo references to the same instance\n";
compareObjects($o, $q);

echo "\nInstances of two different classes\n";
compareObjects($o, $r);
?>

上例将输出:

Two instances of the same class
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : FALSE
o1 !== o2 : TRUE

Two references to the same instance
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSE

Instances of two different classes
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE


Reflection

Introduction

PHP 5 comes with a complete reflection API that adds the ability to reverse-engineer classes, interfaces, functions and methods as well as extensions. Additionally, the reflection API also offers ways of retrieving doc comments for functions, classes and methods.

The reflection API is an object-oriented extension to the Zend Engine, consisting of the following classes:

<?php
class Reflection { }
interface Reflector { }
class ReflectionException extends Exception { }
class ReflectionFunction implements Reflector { }
class ReflectionParameter implements Reflector { }
class ReflectionMethod extends ReflectionFunction { }
class ReflectionClass implements Reflector { }
class ReflectionObject extends ReflectionClass { }
class ReflectionProperty implements Reflector { }
class ReflectionExtension implements Reflector { }
?>

注: For details on these classes, have a look at the next chapters.

If we were to execute the code in the example below:

例子 19-31. Basic usage of the reflection API

<?php
Reflection::export(new ReflectionClass('Exception'));
?>

上例将输出:

Class [ <internal> class Exception ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [6] {
    Property [ <default> protected $message ]
    Property [ <default> private $string ]
    Property [ <default> protected $code ]
    Property [ <default> protected $file ]
    Property [ <default> protected $line ]
    Property [ <default> private $trace ]
  }

  - Methods [9] {
    Method [ <internal> final private method __clone ] {
    }

    Method [ <internal> <ctor> public method __construct ] {

      - Parameters [2] {
        Parameter #0 [ <required> $message ]
        Parameter #1 [ <required> $code ]
      }
    }

    Method [ <internal> final public method getMessage ] {
    }

    Method [ <internal> final public method getCode ] {
    }

    Method [ <internal> final public method getFile ] {
    }

    Method [ <internal> final public method getLine ] {
    }

    Method [ <internal> final public method getTrace ] {
    }

    Method [ <internal> final public method getTraceAsString ] {
    }

    Method [ <internal> public method __toString ] {
    }
  }
}


ReflectionException

ReflectionException extends the standard Exception and is thrown by Reflection API. No specific methods or properties are introduced.


ReflectionFunction

The ReflectionFunction class lets you reverse-engineer functions.

<?php
class ReflectionFunction implements Reflector
{
    final private __clone()
    public object __construct(string name)
    public string __toString()
    public static string export()
    public string getName()
    public bool isInternal()
    public bool isUserDefined()
    public string getFileName()
    public int getStartLine()
    public int getEndLine()
    public string getDocComment()
    public array getStaticVariables()
    public mixed invoke(mixed* args)
    public mixed invokeArgs(array args)
    public bool returnsReference()
    public ReflectionParameter[] getParameters()
    public int getNumberOfParameters()
    public int getNumberOfRequiredParameters()
}
?>

注: getNumberOfParameters() and getNumberOfRequiredParameters() were added in PHP 5.0.3, while invokeArgs() was added in PHP 5.1.0.

To introspect a function, you will first have to create an instance of the ReflectionFunction class. You can then call any of the above methods on this instance.

例子 19-32. Using the ReflectionFunction class

<?php
/**
 * A simple counter
 *
 * @return    int
 */
function counter() 
{
    static $c = 0;
    return $c++;
}

// Create an instance of the Reflection_Function class
$func = new ReflectionFunction('counter');

// Print out basic information
printf(
    "===> The %s function '%s'\n".
    "     declared in %s\n".
    "     lines %d to %d\n",
    $func->isInternal() ? 'internal' : 'user-defined',
    $func->getName(),
    $func->getFileName(),
    $func->getStartLine(),
    $func->getEndline()
);

// Print documentation comment
printf("---> Documentation:\n %s\n", var_export($func->getDocComment(), 1));

// Print static variables if existant
if ($statics = $func->getStaticVariables())
{
    printf("---> Static variables: %s\n", var_export($statics, 1));
}

// Invoke the function
printf("---> Invokation results in: ");
var_dump($func->invoke());


// you may prefer to use the export() method
echo "\nReflectionFunction::export() results:\n";
echo ReflectionFunction::export('counter');
?>

注: The method invoke() accepts a variable number of arguments which are passed to the function just as in call_user_func().


ReflectionParameter

The ReflectionParameter class retrieves information about a function's or method's parameters.

<?php
class ReflectionParameter implements Reflector
{
    final private __clone()
    public object __construct(string name)
    public string __toString()
    public static string export()
    public string getName()
    public bool isPassedByReference()
    public ReflectionClass getClass()
    public bool isArray()
    public bool allowsNull()
    public bool isOptional()
    public bool isDefaultValueAvailable()
    public mixed getDefaultValue()
}
?>

注: getDefaultValue(), isDefaultValueAvailable() and isOptional() were added in PHP 5.0.3, while isArray() was added in PHP 5.1.0.

To introspect function parameters, you will first have to create an instance of the ReflectionFunction or ReflectionMethod classes and then use their getParameters() method to retrieve an array of parameters.

例子 19-33. Using the ReflectionParameter class

<?php
function foo($a, $b, $c) { }
function bar(Exception $a, &$b, $c) { }
function baz(ReflectionFunction $a, $b = 1, $c = null) { }
function abc() { }

// Create an instance of Reflection_Function with the
// parameter given from the command line.    
$reflect = new ReflectionFunction($argv[1]);

echo $reflect;

foreach ($reflect->getParameters() as $i => $param) {
    printf(
        "-- Parameter #%d: %s {\n".
        "   Class: %s\n".
        "   Allows NULL: %s\n".
        "   Passed to by reference: %s\n".
        "   Is optional?: %s\n".
        "}\n",
        $i, 
        $param->getName(),
        var_export($param->getClass(), 1),
        var_export($param->allowsNull(), 1),
        var_export($param->isPassedByReference(), 1),
        $param->isOptional() ? 'yes' : 'no'
    );
}
?>

ReflectionClass

The ReflectionClass class lets you reverse-engineer classes.

<?php
class ReflectionClass implements Reflector
{
    final private __clone()
    public object __construct(string name)
    public string __toString()
    public static string export()
    public string getName()
    public bool isInternal()
    public bool isUserDefined()
    public bool isInstantiable()
    public bool hasConstant(string name)
    public bool hasMethod(string name)
    public bool hasProperty(string name)
    public string getFileName()
    public int getStartLine()
    public int getEndLine()
    public string getDocComment()
    public ReflectionMethod getConstructor()
    public ReflectionMethod getMethod(string name)
    public ReflectionMethod[] getMethods()
    public ReflectionProperty getProperty(string name)
    public ReflectionProperty[] getProperties()
    public array getConstants()
    public mixed getConstant(string name)
    public ReflectionClass[] getInterfaces()
    public bool isInterface()
    public bool isAbstract()
    public bool isFinal()
    public int getModifiers()
    public bool isInstance(stdclass object)
    public stdclass newInstance(mixed* args)
    public ReflectionClass getParentClass()
    public bool isSubclassOf(ReflectionClass class)
    public array getStaticProperties()
    public mixed getStaticPropertyValue(string name [, mixed default])
    public void setStaticPropertyValue(string name, mixed value)
    public array getDefaultProperties()
    public bool isIterateable()
    public bool implementsInterface(string name)
    public ReflectionExtension getExtension()
    public string getExtensionName()
}
?>

注: hasConstant(), hasMethod(), hasProperty(), getStaticPropertyValue() and setStaticPropertyValue() were added in PHP 5.1.0.

To introspect a class, you will first have to create an instance of the ReflectionClass class. You can then call any of the above methods on this instance.

例子 19-34. Using the ReflectionClass class

<?php
interface Serializable
{
    // ...
}

class Object
{
    // ...
}

/**
 * A counter class
 */
class Counter extends Object implements Serializable 
{
    const START = 0;
    private static $c = Counter::START;

    /**
     * Invoke counter
     *
     * @access  public
     * @return  int
     */
    public function count() {
        return self::$c++;
    }
}

// Create an instance of the ReflectionClass class
$class = new ReflectionClass('Counter');

// Print out basic information
printf(
    "===> The %s%s%s %s '%s' [extends %s]\n" .
    "     declared in %s\n" .
    "     lines %d to %d\n" .
    "     having the modifiers %d [%s]\n",
        $class->isInternal() ? 'internal' : 'user-defined',
        $class->isAbstract() ? ' abstract' : '',
        $class->isFinal() ? ' final' : '',
        $class->isInterface() ? 'interface' : 'class',
        $class->getName(),
        var_export($class->getParentClass(), 1),
        $class->getFileName(),
        $class->getStartLine(),
        $class->getEndline(),
        $class->getModifiers(),
        implode(' ', Reflection::getModifierNames($class->getModifiers()))
);

// Print documentation comment
printf("---> Documentation:\n %s\n", var_export($class->getDocComment(), 1));

// Print which interfaces are implemented by this class
printf("---> Implements:\n %s\n", var_export($class->getInterfaces(), 1));

// Print class constants
printf("---> Constants: %s\n", var_export($class->getConstants(), 1));

// Print class properties
printf("---> Properties: %s\n", var_export($class->getProperties(), 1));

// Print class methods
printf("---> Methods: %s\n", var_export($class->getMethods(), 1));

// If this class is instantiable, create an instance
if ($class->isInstantiable()) {
    $counter = $class->newInstance();

    echo '---> $counter is instance? '; 
    echo $class->isInstance($counter) ? 'yes' : 'no';

    echo "\n---> new Object() is instance? ";
    echo $class->isInstance(new Object()) ? 'yes' : 'no';
}
?>

注: The method newInstance() accepts a variable number of arguments which are passed to the function just as in call_user_func().

注: $class = new ReflectionClass('Foo'); $class->isInstance($arg) is equivalent to $arg instanceof Foo or is_a($arg, 'Foo').


ReflectionMethod

The ReflectionMethod class lets you reverse-engineer class methods.

<?php
class ReflectionMethod extends ReflectionFunction
{
    public __construct(mixed class, string name)
    public string __toString()
    public static string export()
    public mixed invoke(stdclass object, mixed* args)
    public mixed invokeArgs(stdclass object, array args)
    public bool isFinal()
    public bool isAbstract()
    public bool isPublic()
    public bool isPrivate()
    public bool isProtected()
    public bool isStatic()
    public bool isConstructor()
    public bool isDestructor()
    public int getModifiers()
    public ReflectionClass getDeclaringClass()

    // Inherited from ReflectionFunction
    final private __clone()
    public string getName()
    public bool isInternal()
    public bool isUserDefined()
    public string getFileName()
    public int getStartLine()
    public int getEndLine()
    public string getDocComment()
    public array getStaticVariables()
    public bool returnsReference()
    public ReflectionParameter[] getParameters()
    public int getNumberOfParameters()
    public int getNumberOfRequiredParameters()
}
?>

To introspect a method, you will first have to create an instance of the ReflectionMethod class. You can then call any of the above methods on this instance.

例子 19-35. Using the ReflectionMethod class

<?php
class Counter
{
    private static $c = 0;

    /**
     * Increment counter
     *
     * @final
     * @static
     * @access  public
     * @return  int
     */
    final public static function increment()
    {
        return ++self::$c;
    }
}

// Create an instance of the Reflection_Method class
$method = new ReflectionMethod('Counter', 'increment');

// Print out basic information
printf(
    "===> The %s%s%s%s%s%s%s method '%s' (which is %s)\n" .
    "     declared in %s\n" .
    "     lines %d to %d\n" .
    "     having the modifiers %d[%s]\n",
        $method->isInternal() ? 'internal' : 'user-defined',
        $method->isAbstract() ? ' abstract' : '',
        $method->isFinal() ? ' final' : '',
        $method->isPublic() ? ' public' : '',
        $method->isPrivate() ? ' private' : '',
        $method->isProtected() ? ' protected' : '',
        $method->isStatic() ? ' static' : '',
        $method->getName(),
        $method->isConstructor() ? 'the constructor' : 'a regular method',
        $method->getFileName(),
        $method->getStartLine(),
        $method->getEndline(),
        $method->getModifiers(),
        implode(' ', Reflection::getModifierNames($method->getModifiers()))
);

// Print documentation comment
printf("---> Documentation:\n %s\n", var_export($method->getDocComment(), 1));

// Print static variables if existant
if ($statics= $method->getStaticVariables()) {
    printf("---> Static variables: %s\n", var_export($statics, 1));
}

// Invoke the method
printf("---> Invokation results in: ");
var_dump($method->invoke(NULL));
?>

注: Trying to invoke private, protected or abstract methods will result in an exception being thrown from the invoke() method.

注: For static methods as seen above, you should pass NULL as the first argument to invoke(). For non-static methods, pass an instance of the class.


ReflectionProperty

The ReflectionProperty class lets you reverse-engineer class properties.

<?php
class ReflectionProperty implements Reflector
{
    final private __clone()
    public __construct(mixed class, string name)
    public string __toString()
    public static string export()
    public string getName()
    public bool isPublic()
    public bool isPrivate()
    public bool isProtected()
    public bool isStatic()
    public bool isDefault()
    public int getModifiers()
    public mixed getValue(stdclass object)
    public void setValue(stdclass object, mixed value)
    public ReflectionClass getDeclaringClass()
    public string getDocComment()
}
?>

注: getDocComment() was added in PHP 5.1.0.

To introspect a property, you will first have to create an instance of the ReflectionProperty class. You can then call any of the above methods on this instance.

例子 19-36. Using the ReflectionProperty class

<?php
class String
{
    public $length  = 5;
}

// Create an instance of the ReflectionProperty class
$prop = new ReflectionProperty('String', 'length');

// Print out basic information
printf(
    "===> The%s%s%s%s property '%s' (which was %s)\n" .
    "     having the modifiers %s\n",
        $prop->isPublic() ? ' public' : '',
        $prop->isPrivate() ? ' private' : '',
        $prop->isProtected() ? ' protected' : '',
        $prop->isStatic() ? ' static' : '',
        $prop->getName(),
        $prop->isDefault() ? 'declared at compile-time' : 'created at run-time',
        var_export(Reflection::getModifierNames($prop->getModifiers()), 1)
);

// Create an instance of String
$obj= new String();

// Get current value
printf("---> Value is: ");
var_dump($prop->getValue($obj));

// Change value
$prop->setValue($obj, 10);
printf("---> Setting value to 10, new value is: ");
var_dump($prop->getValue($obj));

// Dump object
var_dump($obj);
?>

注: Trying to get or set private or protected class property's values will result in an exception being thrown.


ReflectionExtension

The ReflectionExtension class lets you reverse-engineer extensions. You can retrieve all loaded extensions at runtime using the get_loaded_extensions().

<?php
class ReflectionExtension implements Reflector {
    final private __clone()
    public __construct(string name)
    public string __toString()
    public static string export()
    public string getName()
    public string getVersion()
    public ReflectionFunction[] getFunctions()
    public array getConstants()
    public array getINIEntries()
    public ReflectionClass[] getClasses()
    public array getClassNames()
}
?>

To introspect an extension, you will first have to create an instance of the ReflectionExtension class. You can then call any of the above methods on this instance.

例子 19-37. Using the ReflectionExtension class

<?php
// Create an instance of the ReflectionProperty class
$ext = new ReflectionExtension('standard');

// Print out basic information
printf(
    "Name        : %s\n" .
    "Version     : %s\n" .
    "Functions   : [%d] %s\n" .
    "Constants   : [%d] %s\n" .
    "INI entries : [%d] %s\n" .
    "Classes     : [%d] %s\n",
        $ext->getName(),
        $ext->getVersion() ? $ext->getVersion() : 'NO_VERSION',
        sizeof($ext->getFunctions()),
        var_export($ext->getFunctions(), 1),

        sizeof($ext->getConstants()),
        var_export($ext->getConstants(), 1),

        sizeof($ext->getINIEntries()),
        var_export($ext->getINIEntries(), 1),

        sizeof($ext->getClassNames()),
        var_export($ext->getClassNames(), 1)
);
?>

Extending the reflection classes

In case you want to create specialized versions of the built-in classes (say, for creating colorized HTML when being exported, having easy-access member variables instead of methods or having utility methods), you may go ahead and extend them.

例子 19-38. Extending the built-in classes

<?php
/**
 * My Reflection_Method class
 */
class My_Reflection_Method extends ReflectionMethod
{
    public $visibility = '';

    public function __construct($o, $m)
    {
        parent::__construct($o, $m);
        $this->visibility= Reflection::getModifierNames($this->getModifiers());
    }
}

/**
 * Demo class #1
 *
 */
class T {
    protected function x() {}
}

/**
 * Demo class #2
 *
 */
class U extends T {
    function x() {}
}

// Print out information
var_dump(new My_Reflection_Method('U', 'x'));
?>

注: Caution: If you're overwriting the constructor, remember to call the parent's constructor _before_ any code you insert. Failing to do so will result in the following: Fatal error: Internal error: Failed to retrieve the reflection object


Type Hinting

PHP 5 introduces Type Hinting. Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype) or arrays (since PHP 5.1).

例子 19-39. Type Hinting examples

<?php
// An example class
class MyClass
{
    /**
     * A test function
     *
     * First parameter must be an object of type OtherClass
     */
    public function test(OtherClass $otherclass) {
        echo $otherclass->var;
    }


    /**
     * Another test function
     *
     * First parameter must be an array
     */
    public function test_array(array $input_array) {
        print_r($input_array);
    }
}

// Another example class
class OtherClass {
    public $var = 'Hello World';
}
?>

Failing to satisfy the type hint results in a fatal error.

<?php
// An instance of each class
$myclass = new MyClass;
$otherclass = new OtherClass;

// Fatal Error: Argument 1 must be an object of class OtherClass
$myclass->test('hello');

// Fatal Error: Argument 1 must be an instance of OtherClass
$foo = new stdClass;
$myclass->test($foo);

// Fatal Error: Argument 1 must not be null
$myclass->test(null);

// Works: Prints Hello World
$myclass->test($otherclass);

// Fatal Error: Argument 1 must be an array
$myclass->test_array('a string');

// Works: Prints the array
$myclass->test_array(array('a', 'b', 'c'));
?>

Type hinting also works with functions:

<?php
// An example class
class MyClass {
    public $var = 'Hello World';
}

/**
 * A test function
 *
 * First parameter must be an object of type MyClass
 */
function MyFunction (MyClass $foo) {
    echo $foo->var;
}

// Works
$myclass = new MyClass;
MyFunction($myclass);
?>

Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported.


章 20. 异常处理

PHP 5 添加了类似于其它语言的异常处理模块,可以在 PHP 内检测(try)、抛出(throw)和捕获(catch)异常。一个 try 至少要有一个与之对应的 catch。定义多个 catch 可以捕获不同的对象。PHP 会按这些 catch 被定义的顺序执行,直到完成最后一个为止。而在这些 catch 内,又可以抛出新的异常。

当一个异常被抛出时,其后(译者注:指抛出异常时所在的代码块)的代码将不会继续执行,而 PHP 就会尝试查找第一个能与之匹配的 catch。如果一个异常没有被捕获,而且又没用使用 set_exception_handler() 作相应的处理的话,那么 PHP 将会产生一个严重的错误,并且输出未能捕获异常的提示信息。

例子 20-1. 抛出一个异常

<?php
try {
    $error = 'Always throw this error';
    throw new Exception($error);

    // 从这里开始,tra 代码块内的代码将不会被执行
    echo 'Never executed';

} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

// 继续执行
echo 'Hello World';
?>

扩展 PHP 内置的异常处理类

用户可以用自定义的异常处理类来扩展 PHP 内置的异常处理类。以下的代码说明了在内置的异常处理类中,哪些属性和方法在子类中是可访问和可继承的。译者注:以下这段代码只为说明内置异常处理类的结构,它并不是一段有实际意义的可用代码。

例子 20-2. 内置的异常处理类

<?php
class Exception
{
    protected $message = 'Unknown exception';   // 异常信息
    protected $code = 0;                        // 用户自定义异常代码
    protected $file;                            // 发生异常的文件名
    protected $line;                            // 发生异常的代码行号

    function __construct($message = null, $code = 0);

    final function getMessage();                // 返回异常信息
    final function getCode();                   // 返回异常代码
    final function getFile();                   // 返回发生异常的文件名
    final function getLine();                   // 返回发生异常的代码行号
    final function getTrace();                  // backtrace() 数组
    final function getTraceAsString();          // 已格成化成字符串的 getTrace() 信息

    /* 可重载的方法 */
    function __toString();                       // 可输出的字符串
}
?>

如果使用自定义的类来扩展内置异常处理类,并且要重新定义构造函数的话,建议同时调用 parent::__construct() 来检查所有的变量是否已被赋值。当对象要输出字符串的时候,可以重载 __toString() 并自定义输出的样式。

例子 20-3. 扩展 PHP 内置的异常处理类

<?php
/**
 * 自定义一个异常处理类
 */
class MyException extends Exception
{
    // 重定义构造器使 message 变为必须被指定的属性
    public function __construct($message, $code = 0) {
        // 自定义的代码

        // 确保所有变量都被正确赋值
        parent::__construct($message, $code);
    }

    // 自定义字符串输出的样式 */
    public function __toString() {
        return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
    }

    public function customFunction() {
        echo "A Custom function for this type of exception\n";
    }
}


/**
 * 创建一个用于测试异常处理机制的类
 */
class TestException
{
    public $var;

    const THROW_NONE    = 0;
    const THROW_CUSTOM  = 1;
    const THROW_DEFAULT = 2;

    function __construct($avalue = self::THROW_NONE) {

        switch ($avalue) {
            case self::THROW_CUSTOM:
                // 抛出自定义异常
                throw new MyException('1 is an invalid parameter', 5);
                break;

            case self::THROW_DEFAULT:
                // 抛出默认的异常
                throw new Exception('2 isnt allowed as a parameter', 6);
                break;

            default:
                // 没有异常的情况下,创建一个对象
                $this->var = $avalue;
                break;
        }
    }
}


// 例子 1
try {
    $o = new TestException(TestException::THROW_CUSTOM);
} catch (MyException $e) {      // 捕获异常
    echo "Caught my exception\n", $e;
    $e->customFunction();
} catch (Exception $e) {        // 被忽略
    echo "Caught Default Exception\n", $e;
}

// 执行后续代码
var_dump($o);
echo "\n\n";


// 例子 2
try {
    $o = new TestException(TestException::THROW_DEFAULT);
} catch (MyException $e) {      // 不能匹配异常的种类,被忽略
    echo "Caught my exception\n", $e;
    $e->customFunction();
} catch (Exception $e) {        // 捕获异常
    echo "Caught Default Exception\n", $e;
}

// 执行后续代码
var_dump($o);
echo "\n\n";


// 例子 3
try {
    $o = new TestException(TestException::THROW_CUSTOM);
} catch (Exception $e) {        // 捕获异常
    echo "Default Exception caught\n", $e;
}

// 执行后续代码
var_dump($o);
echo "\n\n";


// 例子 4
try {
    $o = new TestException();
} catch (Exception $e) {        // 没有异常,被忽略
    echo "Default Exception caught\n", $e;
}

// 执行后续代码
var_dump($o);
echo "\n\n";
?>

章 21. 引用的解释

引用是什么

在 PHP 中引用意味着用不同的名字访问同一个变量内容。这并不像 C 的指针,替代的是,引用是符号表别名。注意在 PHP 中,变量名和变量内容是不一样的,因此同样的内容可以有不同的名字。最接近的比喻是 Unix 的文件名和文件本身――变量名是目录条目,而变量内容则是文件本身。引用可以被看作是 Unix 文件系统中的紧密连接。


引用做什么

PHP 的引用允许用两个变量来指向同一个内容。意思是,当这样做时:

<?php
$a =& $b;
?>

这意味着 $a$b 指向了同一个变量。

注: $a$b 在这里是完全相同的,这并不是 $a 指向了 $b 或者相反,而是 $a$b 指向了同一个地方。

注: 如果具有引用的数组被拷贝,其值不会解除引用。对于数组传值给函数也是如此。

同样的语法可以用在函数中,它返回引用,以及用在 new 运算符中(PHP 4.0.4 以及以后版本):

<?php
$bar =& new fooclass();
$foo =& find_var($bar);
?>

注: 不用 & 运算符导致对象生成了一个拷贝。如果在类中用 $this,它将作用于该类当前的实例。没有用 & 的赋值将拷贝这个实例(例如对象)并且 $this 将作用于这个拷贝上,这并不总是想要的结果。由于性能和内存消耗的问题,通常只想工作在一个实例上面。

尽管可以用 @ 运算符来抑制构造函数中的任何错误信息,例如用 @new,但用 &new 语句时这不起效果。这是 Zend 引擎的一个限制并且会导致一个解析错误。

警告

如果在一个函数内部给一个声明为 global 的变量赋于一个引用,该引用只在函数内部可见。可以通过使用 $GLOBALS 数组避免这一点。

例子 21-1. 在函数内引用全局变量

<?php
$var1 = "Example variable";
$var2 = "";

function global_references($use_globals)
{
    global $var1, $var2;
    if (!$use_globals) {
        $var2 =& $var1; // visible only inside the function
    } else {
        $GLOBALS["var2"] =& $var1; // visible also in global context
    }
}

global_references(false);
echo "var2 is set to '$var2'\n"; // var2 is set to ''
global_references(true);
echo "var2 is set to '$var2'\n"; // var2 is set to 'Example variable'
?>
global $var; 当成是 $var =& $GLOBALS['var']; 的简写。从而将其它引用赋给 $var 只改变了本地变量的引用。

注: 如果在 foreach 语句中给一个具有引用的变量赋值,被引用的对象也被改变。

例子 21-2. 引用与 foreach 语句

<?php
$ref = 0;
$row =& $ref;
foreach (array(1, 2, 3) as $row) {
    // do something
}
echo $ref; // 3 - last element of the iterated array
?>

警告

复杂数组最好拷贝而不是引用。下面的例子不会如期望中那样工作。

例子 21-3. 复杂数组的引用

<?php
$top = array(
    'A' => array(),
    'B' => array(
        'B_b' => array(),
    ),
);

$top['A']['parent'] = &$top;
$top['B']['parent'] = &$top;
$top['B']['B_b']['data'] = 'test';
print_r($top['A']['parent']['B']['B_b']); // array()
?>

引用做的第二件事是用引用传递变量。这是通过在函数内建立一个本地变量并且该变量在呼叫范围内引用了同一个内容来实现的。例如:

<?php
function foo(&$var)
{
    $var++;
}

$a=5;
foo($a);
?>

将使 $a 变成 6。这是因为在 foo 函数中变量 $var 指向了和 $a 指向的同一个内容。更多详细解释见引用传递

引用做的第三件事是引用返回


引用不是什么

如前所述,引用不是指针。这意味着下面的结构不会产生预期的效果:

<?php
function foo(&$var)
{
    $var =& $GLOBALS["baz"];
}
foo($bar);
?>

这将使 foo 函数中的 $var 变量在函数调用时和 $bar 绑定在一起,但接着又被重新绑定到了 $GLOBALS["baz"] 上面。不可能通过引用机制将 $bar 在函数调用范围内绑定到别的变量上面,因为在函数 foo 中并没有变量 $bar(它被表示为 $var,但是 $var 只有变量内容而没有调用符号表中的名字到值的绑定)。可以使用引用返回来引用被函数选择的变量。


引用传递

可以将一个变量通过引用传递给函数,这样该函数就可以修改其参数的值。语法如下:

<?php
function foo(&$var)
{
    $var++;
}

$a=5;
foo($a);
// $a is 6 here
?>

注意在函数调用时没有引用符号――只有函数定义中有。光是函数定义就足够使参数通过引用来正确传递了。在最近版本的 PHP 中如果把 & 用在 foo(&$a); 中会得到一条警告说“Call-time pass-by-reference”已经过时了。

以下内容可以通过引用传递:

  • 变量,例如 foo($a)

  • New 语句,例如 foo(new foobar())

  • 从函数中返回的引用,例如:

    <?php
    function &bar()
    {
        $a = 5;
        return $a;
    }
    foo(bar());
    ?>

    详细解释见引用返回

任何其它表达式都不能通过引用传递,结果未定义。例如下面引用传递的例子是无效的:

<?php
function bar() // Note the missing &
{
    $a = 5;
    return $a;
}
foo(bar()); // 自 PHP 5.1.0 起导致致命错误
foo($a = 5) // 表达式,不是变量
foo(5) // 导致致命错误
?>

这些条件是 PHP 4.0.4 以及以后版本有的。


引用返回

引用返回用在当想用函数找到引用应该被绑定在哪一个变量上面时。不要用返回引用来增加性能,引擎足够聪明来自己进行优化。仅在有合理的技术原因时才返回引用!要返回引用,使用此语法:

<?php
function &find_var($param)
{
    /* ...code... */
    return $found_var;
}

$foo =& find_var($bar);
$foo->x = 2;
?>

本例中 find_var 函数所返回的对象的属性将被赋值,而不是拷贝,就和没有用引用语法一样。

注: 和参数传递不同,这里必须在两个地方都用 & 符号――指出返回的是一个引用,而不是通常的一个拷贝,同样也指出 $foo 是作为引用的绑定,而不是通常的赋值。

注: 如果试图这样从函数返回引用:return ($found_var);,这将不会起作用,因为在试图返回一个表达式的结果而不是一个引用的变量。只能从函数返回引用变量――没别的方法。如果代码试图返回一个动态表达式或 new 运算符的结果,自 PHP 4.4.0 和 PHP 5.1.0 起会发出一条 E_NOTICE 错误。


取消引用

当 unset 一个引用,只是断开了变量名和变量内容之间的绑定。这并不意味着变量内容被销毁了。例如:

<?php
$a = 1;
$b =& $a;
unset($a);
?>

不会 unset $b,只是 $a

再拿这个和 Unix 的 unlink 调用来类比一下可能有助于理解。


引用定位

许多 PHP 的语法结构是通过引用机制实现的,所以上述有关引用绑定的一切也都适用于这些结构。一些结构,例如引用传递和返回,已经在上面提到了。其它使用引用的结构有:


global 引用

当用 global $var 声明一个变量时实际上建立了一个到全局变量的引用。也就是说和这样做是相同的:

<?php
$var =& $GLOBALS["var"];
?>

这意味着,例如,unset $var 不会 unset 全局变量。


$this

在一个对象的方法中,$this 永远是调用它的对象的引用。


章 22. 简介

PHP 作为一种强大的语言,无论是以模块还是 CGI 的方式安装,它的解释器都可以在服务器上访问文件、运行命令以及创建网络连接等。这些功能也许会给服务器添加很多不安全因素,但是只要正确地安装和配置 PHP,以及编写安全的代码,那么 PHP 相对于 Perl 和 C 来说,是能创建出更安全的 CGI 程序的。而且,也可以在可用性和安全性之间找到一个很好的平衡点。

PHP 可能会被用在很多不同的方面,因此,PHP 内置的选项以方便用户对其进行配置。虽然众多的选项可以使 PHP 完成很多工作,但是对这些选项的设定以及对服务器的配置很可能会产生安全问题。

PHP 的选项与其语法一样,具有很高的灵活性。使用 PHP,可以在只有 shell 用户权限的环境下创建完善的服务器端程序,或者在被严格限制环境下使用它来完成服务器端包含(Server-Side Includes)而无需承但太大的风险。如何建立这样一种环境,其安全性如何,很大程度上取决于 PHP 的开发者。

本章以一些常规的安全建议作开头,讲述如何在不同的环境下尽可能地提高安全性,以及介绍对于不同安全级别的一些编程原则。


章 23. 总则

绝对安全的系统是不存在的,因此安全业界常用的方法有助于平衡可用性和风险。对用户提交的每一个变量都进行双重验证可能是一个很负责任的行为,但会导致用户必须花很多时间去填写一张复杂无比的表格,从而迫使某些用户尝试绕过安全机制。

最好的安全机制应该能在不防碍用户,并且不过多地增加开发难度的情况下做到能满足需求。实际上,一些安全问题往往会发生在这种过度强化安全机制的系统上。

不要忘记著名的等强原则:一个系统的的强度是由它最薄弱的环节决定的(译者注:相当于木桶原理)。如果所有的事务都基于时间、地点、事务种类进行详细的记录,而用户验证却只依靠一个 cookie,那么用户所对应的事务记录的可信度就被大大剥弱了。

调试代码的时候一定要记住,就算是一个简单的页面也很难对所有可能发生的情况进行检测:对你不满的雇员不一定会输入如你所愿的东西,黑客也有足够的时间研究你的系统,当然,你的宠物猫也会跳到你的键盘上。这就是为什么必须检查所有的代码,去发现哪里可以引入不正当的数据,然后对代码改进、简化或者增强。

互联网上充满了为了成名而破坏你的代码、攻击你的网站并输入不正当数据的人,总之他们会使你的生活充满乐趣。无论是大网站还是小网站,只要能和互联网连接,就会成为一个目标。很多黑客程序并不理会网站的大小,只会机械地扫描 IP 地址并找寻受害者。我们希望那个不要是你。


章 24. 以 CGI 模式安装时

可能受到的攻击

如果不想把 PHP 嵌入到服务器端软件(如 Apache)作为一个模块安装的话,可以选择以 CGI 的模式安装。或者把 PHP 用于不同的 CGI 封装以便为代码创建安全的 chroot 和 setuid 环境。这种安装方式通常会把 PHP 的可执行文件安装到 web 服务器的 cgi-bin 目录。CERT 建议书 CA-96.11 建议不要把任何的解释器放到 cgi-bin 目录。尽管 PHP 可以作为一个独立的解释器,但是它的设计使它可以防止下面类型的攻击:

  • 访问系统文件:http://my.host/cgi-bin/php?/etc/passwd

    在 URL 请求的问号(?)后面的信息会传给 CGI 接口作为命名行的参数。其它的解释器会在命令行中打开并执行第一个参数所指定的文件。

    但是,以 CGI 模式安装的 PHP 解释器被调用时,它会拒绝解释这些参数。

  • 访问服务器上的任意目录:http://my.host/cgi-bin/php/secret/doc.html

    好像上面这种情况,PHP 解释器所在目录后面的 URL 信息 /secret/doc.html 将会例行地传给 CGI 程序并进行解释。通常一些 web 服务器的会将它重定向到页面,如 http://my.host/secret/script.php。如果是这样的话,某些服务器会先检查用户访问 /secret 目录的权限,然后才会创建 http://my.host/cgi-bin/php/secret/script.php 上的页面重定向。不幸的是,很多服务器并没有检查用户访问 /secret/script.php 的权限,只检查了 /cgi-bin/php 的权限,这样任何能访问 /cgi-bin/php 的用户就可以访问 web 目录下的任意文件了。

    在 PHP 里,编译时配置选项 --enable-force-cgi-redirect 以及运行时配置指令 doc_rootuser_dir 都可以为服务器上的文件和目录添加限制,用于防止这类攻击。下面将对各个选项的设置进行详细讲解。


情形一:只运行公开的文件

如果 web 服务器中所有内容都受到密码或 IP 地址的访问限制,就不需要设置这些选项。如果 web 服务器不支持重定向,或者 web 服务器不能和 PHP 通信而使访问请求变得更为安全,可以在 configure 脚本中指定 --enable-force-cgi-redirect 选项。除此之外,还要确认 PHP 程序不依赖其它方式调用,比如通过直接的 http://my.host/cgi-bin/php/dir/script.php 访问或通过重定向访问 http://my.host/dir/script.php

在Apache中,重定向可以使用 AddHandler 和 Action 语句来设置,请看下一节。


情形二:使用 --enable-force-cgi-redirect 选项

此编译选项可以防止任何人通过如 http://my.host/cgi-bin/php/secretdir/script.php 这样的 URL 直接调用 PHP。PHP 在此模式下只会解析已经通过了 web 服务器的重定向规则的 URL。

通常 Apache 中的重定向设置可以通过以下指令完成:

Action php-script /cgi-bin/php
AddHandler php-script .php

此选项只在 Apache 下进行过测试,并且要依赖于 Apache 在重定向操作中所设置的非标准 CGI 环境变量 REDIRECT_STATUS。如果 web 服务器不支持任何方式能够判断请求是直接的还是重定向的,就不能使用这个选项,而应该用其它方法。请看下一节。


情形三:设置 doc_root 或 user_dir

在 web 服务器的主文档目录中包含动态内容如脚本和可执行程序有时被认为是一种不安全的实践。如果因为配置上的错误而未能执行脚本而作为普通 HTML 文档显示,那就可能导致知识产权或密码资料的泄露。所以很多系统管理员都会专门设置一个只能通过 PHP CGI 来访问的目录,这样该目录中的内容只会被解析而不会原样显示出来。

对于前面所说无法判断是否重定向的情况,很有必要在主文档目录之外建立一个专用于脚本的 doc_root 目录。

可以通过配置文件内的 doc_root 或设置环境变量 PHP_DOCUMENT_ROOT 来定义 PHP 脚本主目录。如果设置了该项,那么 PHP 就只会解释 doc_root 目录下的文件,并确保目录外的脚本不会被 PHP 解释器执行(下面所说的 user_dir 除外)。

另一个可用的选项就是 user_dir。当 user_dir 没有设置的时候,doc_root 就是唯一能控制在哪里打开文件的选项。访问如 http://my.host/~user/doc.php 这个 URL 时,并不会打开用户主目录下文件,而只会执行 doc_root 目录下的 ~user/doc.php(这个子目录以 [~] 作开头)。

如果设置了 user_dir,例如 public_php,那么像 http://my.host/~user/doc.php 这样的请求将会执行用户主目录下的 public_php 子目录下的 doc.php 文件。假设用户主目录的绝对路径是 /home/user,那么被执行文件将会是 /home/user/public_php/doc.php

user_dir 的设置与 doc_root 无关,所以可以分别控制 PHP 脚本的主目录和用户目录。


情形四:PHP 解释器放在 web 目录以外

一个非常安全的做法就是把 PHP 解释器放在 web 目录外的地方,比如说 /usr/local/bin。这样做唯一不便的地方就是必须在每一个包含 PHP 代码的文件的第一行加入如下语句:

#!/usr/local/bin/php

还要将这些文件的属性改成可执行。也就是说,要像处理用 Perl 或 sh 或其它任何脚本语言写的 CGI 脚本一样,使用以 #! 开头的 shell-escape 机制来启动它们。

在这种情况下,要使 PHP 能正确处理 PATH_INFOPATH_TRANSLATED 等变量的话,在编译 PHP 解释器时必须加入 --enable-discard-path 参数。


章 25. 以 Apache 模块安装时

当 PHP 以 Apache 模块方式安装时,它将继承 Apache 用户(通常为“nobody”)的权限。这对安全和认证有一些影响。比如,如果用 PHP 来访问数据库,除非数据库有自己的访问控制,否则就要使“nobody”用户可以访问数据库。这意味着恶意的脚本在不用提供用户名和密码时就可能访问和修改数据库。一个 web Spider 也完全有可能偶然发现数据库的管理页面,并且删除所有的数据库。可以通过 Apache 认证来避免此问题,或者用 LDAP、.htaccess 等技术来设计自己的防问模型,并把这些代码作为 PHP 脚本的一部份。

通常,一但安全性达到可以使 PHP 用户(这里也就是 Apache 用户)承担的风险极小的程度时候,可能 PHP 已经到了阻止向用户目录写入任何文件或禁止访问和修改数据库的地步了。这就是说,无论是正常的文件还是非正常的文件,无论是正常的数据库事务来是恶意的请求,都会被拒之门外。

一个常犯的对安全性不利的错误就是让 Apache 拥有 root 权限,或者通过其它途径斌予 Apache 更强大的功能。

把 Apache 用户的权限提升为 root 是极度危险的做法,而且可能会危及到整个系统的安全。所以除非是安全专家,否则决不要考虑使用 su,chroot 或者以 root 权限运行。

除此之外还有一些比较简单的解决方案。比如说可以使用 open_basedir 来限制哪些目录可以被 PHP 使用。也可以设置 Apache 的专属区域,从而把所有的 web 活动都限制到非用户和非系统文件之中。


章 26. 文件系统安全

PHP 遵从大多数服务器系统中关于文件和目录权限的安全机制。这就使管理员可以控制哪些文件在文件系统内是可读的。必须特别注意的是全局的可读文件,并确保每一个有权限的用户对这些文件的读取动作都是安全的。

PHP 被设计为以用户级别来访问文件系统,所以完全有可能通过编写一段 PHP 代码来读取系统文件如 /etc/passwd,更改网络连接以及发送大量打印任务等等。因此必须确保 PHP 代码读取和写入的是合适的文件。

请看下面的代码,用户想要删除自己主目录中的一个文件。假设此情形是通过 web 界面来管理文件系统,因此 Apache 用户有权删除用户目录下的文件。

例子 26-1. 不对变量进行安全检查会导致……

<?php
// 从用户目录中删除指定的文件
$username = $_POST['user_submitted_name'];
$homedir = "/home/$username";
$file_to_delete = "$userfile";
unlink ("$homedir/$userfile");
echo "$file_to_delete has been deleted!";
?>
既然 username 变量可以通过用户表单来提交,那就可以提交别人的用户名和文件名,并删除该文件。这种情况下,就要考虑其它方式的认证。想想看如果提交的变量是“../etc/”和“passwd”会发生什么。上面的代码就等同于:

例子 26-2. ……文件系统攻击

<?php
// 删除硬盘中任何 PHP 有访问权限的文件。如果 PHP 有 root 权限:
$username = "../etc/";
$homedir = "/home/../etc/";
$file_to_delete = "passwd";
unlink ("/home/../etc/passwd");
echo "/home/../etc/passwd has been deleted!";
?>
有两个重要措施来防止此类问题。

  • 只给 PHP 的 web 用户很有限的权限。

  • 检查所有提交上来的变量。

下面是改进的脚本:

例子 26-3. 更安全的文件名检查

<?php
// 删除硬盘中 PHP 有权访问的文件
$username = $_SERVER['REMOTE_USER']; // 使用认证机制

$homedir = "/home/$username";

$file_to_delete = basename("$userfile"); // 去除变量中的路径
unlink ($homedir/$file_to_delete);

$fp = fopen("/home/logging/filedelete.log","+a"); // 记录删除动作
$logstring = "$username $homedir $file_to_delete";
fwrite ($fp, $logstring);
fclose($fp);

echo "$file_to_delete has been deleted!";
?>
然而,这样做仍然是有缺陷的。如果认证系统允许用户建立自己的登录用户名,而用户选择用“../etc/”作为用户名,系统又一次沦陷了。所以,需要加强检查:

例子 26-4. 更安全的文件名检查

<?php
$username = $_SERVER['REMOTE_USER']; // 使用认证机制
$homedir = "/home/$username";

if (!ereg('^[^./][^/]*$', $userfile))
     die('bad filename'); // 停止执行代码

if (!ereg('^[^./][^/]*$', $username))
     die('bad username'); // 停止执行代码
//后略……
?>

根据操作系统的不同,存在着各种各样需要注意的文件,包括联系到系统的设备(/dev/ 或者 COM1)、配置文件(/ect/ 文件和 .ini文件)、常用的存储区域(/home/ 或者 My Documents)等等。由于此原因,建立一个策略禁止所有权限而只开放明确允许的通常更容易些。


章 27. 数据库安全

今时今日,数据库系统已经成为各个动态网站上 web 应用程序的重要组成部分。由于非常敏感和机密的数据有可能保存在数据库中,所以对数据库实施保护就显得尤为重要了。

要从数据库中提取或者存入数据,就必须经过连接数据库、发送一条合法查询、获取结果、关闭连接等步骤。目前,能完成这一系列动作的最常用的查询语言是结构化查询语言 Structured Query Language (SQL)。可以看看攻击者是如何篡改 SQL 查询语句的

PHP 本身并不能保护数据库的安全。下面的章节只是讲述怎样用 PHP 脚本对数据库进行基本的访问和操作。

记住一条简单的原则:深入防御。保护数据库的措施越多,攻击者就越难获得和使用数据库内的信息。正确地设计和应用数据库可以减少被攻击的担忧。


设计数据库

第一步一般都是创建数据库,除非是使用第三方的数据库服务。当创建一个数据库的时候,会指定一个所有者来执行和新建语句。通常,只有所有者(或超级用户)才有权对数据库中的对象进行任意操作。如果想让其他用户使用,就必须赋予他们权限。

应用程序永远不要使用数据库所有者或超级用户帐号来连接数据库,因为这些帐号可以执行任意的操作,比如说修改数据库结构(例如删除一个表)或者清空整个数据库的内容。

应该为程序的每个方面创建不同的数据库帐号,并赋予对数据库对象的极有限的权限。仅分配给能完成其功能所需的权限,避免同一个用户可以完成另一个用户的事情。这样即使攻击者利用程序漏洞取得了数据库的访问权限,也最多只能做到和该程序一样的影响范围。

鼓励用户不要把所有的事务逻辑都用 web 应用程序(即用户的脚本)来实现。最好用视图(view)、触发器(trigger)或者规则(rule)在数据库层面完成。当系统升级的时候,需要为数据库开辟新的接口,这时就必须重做所有的数据库客户端。除此之外,触发器还可以透明和自动地处理字段,并在调试程序和跟踪事实时提供有用的信息。


连接数据库

把连接建立在 SSL 加密技术上可以增加客户端和服务器端通信的安全性,或者 SSH 也可以用于加密客户端和数据库之间的连接。如果使用了这些技术的话,攻击者要监视服务器的通信或者得到数据库的信息是很困难的。


加密存储模型

SSL/SSH 能保护客户端和服务器端交换的数据,但 SSL/SSH 并不能保护数据库中已有的数据。SSL 只是一个加密网络数据流的协议。

如果攻击者取得了直接访问数据库的许可(绕过 web 服务器),敏感数据就可能暴露或者被滥用,除非数据库自己保护了这些信息。对数据库内的数据加密是减少这类风险的有效途径,但是只有很少的数据库提供这些加密功能。

对于这个问题,有一个简单的解决办法,就是创建自己的加密机制,然后把它用在 PHP 程序内。PHP 有几个扩展库可以完成这个工作,比如说 McryptMhash 等,它们包含多种加密运算法则。脚本在插入数据库之前先把数据加密,以后提取出来时再解密。有关加密如何工作的例子请参考相关手册。

对某些真正隐蔽的数据,如果不需要以明文的形式存在(即不用显示),可以考虑用散列算法。使用散列算法最常见的例子就是把密码经过 MD5 加密后的散列存进数据库来代替原来的明文密码。参见 crypt()md5()

例子 27-1. 对密码字段进行散列加密

<?php

// 存储密码散列
$query  = sprintf("INSERT INTO users(name,pwd) VALUES('%s','%s');",
            addslashes($username), md5($password));
$result = pg_query($connection, $query);

// 发送请求来验证用户密码
$query = sprintf("SELECT 1 FROM users WHERE name='%s' AND pwd='%s';",
            addslashes($username), md5($password));
$result = pg_query($connection, $query);

if (pg_num_rows($result) > 0) {
    echo 'Welcome, $username!';
} else {
    echo 'Authentication failed for $username.';
}

?>

SQL 注入

很多 web 开发者没有注意到 SQL 查询是可以被篡改的,因而把 SQL 查询当作可信任的命令。殊不知道,SQL 查询可以绕开访问控制,从而绕过身份验证和权限检查。更有甚者,有可能通过 SQL 查询去运行主机操作系统级的命令。

直接 SQL 命令注入就是攻击者常用的一种创建或修改已有 SQL 语句的技术,从而达到取得隐藏数据,或覆盖关键的值,甚至执行数据库主机操作系统命令的目的。这是通过应用程序取得用户输入并与静态参数组合成 SQL 查询来实现的。下面将会给出一些真实的例子。

由于在缺乏对输入的数据进行验证,并且使用了超级用户或其它有权创建新用户的数据库帐号来连接,攻击者可以在数据库中新建一个超级用户。

例子 27-2. 一段实现数据分页显示的代码……也可以被用作创建一个超级用户(PostgreSQL系统)。

<?php

$offset = $argv[0]; // 注意,没有输入验证!
$query  = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
$result = pg_query($conn, $query);

?>
一般的用户会点击 $offset 已被斌值的“上一页”、“下一页”的链接。原本代码只会认为 $offset 是一个数值。然而,如果有人尝试把以下语句先经过 urlencode() 处理,然后加入URL中的话:

0;
insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd)
    select 'crack', usesysid, 't','t','crack'
    from pg_shadow where usename='postgres';
--

那么他就可以创建一个超级用户了。注意那个 0; 只不过是为了提供一个正确的偏移量以便补充完整原来的查询,使它不要出错而已。

注: -- 是 SQL 的注释标记,一般可以使用来它告诉 SQL 解释器忽略后面的语句。

对显示搜索结果的页面下手是一个能得到密码的可行办法。攻击者所要做的只不过是找出哪些提交上去的变量是用于 SQL 语句并且处理不当的。而这类的变量通常都被用于 SELECT 查询中的条件语句,如 WHERE, ORDER BY, LIMITOFFSET。如果数据库支持 UNION 构造的话,攻击者还可能会把一个完整的 SQL 查询附加到原来的语句上以便从任意数据表中得到密码。因此,对密码字段加密是很重要的。

例子 27-3. 显示文章……以及一些密码(任何数据库系统)

<?php

$query  = "SELECT id, name, inserted, size FROM products
                  WHERE size = '$size'
                  ORDER BY $order LIMIT $limit, $offset;";
$result = odbc_exec($conn, $query);

?>
可以在原来的查询的基础上添加另一个 SELECT 查询来获得密码:

'
union select '1', concat(uname||'-'||passwd) as name, '1971-01-01', '0' from usertable;
--

假如上述语句(使用 '--)被加入到 $query 中的任意一个变量的话,那么就麻烦了。

SQL 中的 UPDATE 也会受到攻击。这种查询也可能像上面的例子那样被插入或附加上另一个完整的请求。但是攻击者更愿意对 SET 子句下手,这样他们就可以更改数据表中的一些数据。这种情况下必须要知道数据库的结构才能修改查询成功进行。可以通过表单上的变量名对字段进行猜测,或者进行暴力破解。对于存放用户名和密码的字段,命名的方法并不多。

例子 27-4. 从重设密码……到获得更多权限(任何数据库系统)

<?php
$query = "UPDATE usertable SET pwd='$pwd' WHERE uid='$uid';";
?>
但是恶意的用户会把 ' or uid like'%admin%'; -- 作为变量的值提交给 $uid 来改变 admin 的密码,或者把 $pwd 的值提交为 "hehehe', admin='yes', trusted=100 "(后面有个空格)去获得更多的权限。这样做的话,查询语句实际上就变成了:

<?php

// $uid == ' or uid like'%admin%'; --
$query = "UPDATE usertable SET pwd='...' WHERE uid='' or uid like '%admin%'; --";

// $pwd == "hehehe', admin='yes', trusted=100 "
$query = "UPDATE usertable SET pwd='hehehe', admin='yes', trusted=100 WHERE
...;";

?>

下面这个可怕的例子将会演示如何在某些数据库上执行系统命令。

例子 27-5. 攻击数据库所在主机的操作系统(MSSQL Server)

<?php

$query  = "SELECT * FROM products WHERE id LIKE '%$prod%'";
$result = mssql_query($query);

?>
如果攻击提交 a%' exec master..xp_cmdshell 'net user test testpass /ADD' -- 作为变量 $prod的值,那么 $query 将会变成

<?php

$query  = "SELECT * FROM products
                    WHERE id LIKE '%a%'
                    exec master..xp_cmdshell 'net user test testpass /ADD'--";
$result = mssql_query($query);

?>

MSSQL 服务器会执行这条 SQL 语句,包括它后面那个用于向系统添加用户的命令。如果这个程序是以 sa 运行而 MSSQLSERVER 服务又有足够的权限的话,攻击者就可以获得一个系统帐号来访问主机了。

注: 虽然以上的例子是针对某一特定的数据库系统的,但是这并不代表不能对其它数据库系统实施类似的攻击。使用不同的方法,各种数据库都有可能遭殃。


预防措施

也许有人会自我安慰,说攻击者要知道数据库结构的信息才能实施上面的攻击。没错,确实如此。但没人能保证攻击者一定得不到这些信息,一但他们得到了,数据库有泄露的危险。如果你在用开放源代码的软件包来访问数据库,比如论坛程序,攻击者就很容得到到相关的代码。如果这些代码设计不良的话,风险就更大了。

这些攻击总是建立在发掘安全意识不强的代码上的。所以,永远不要信任外界输入的数据,特别是来自于客户端的,包括选择框、表单隐藏域和 cookie。就如上面的第一个例子那样,就算是正常的查询也有可能造成灾难。

  • 永远不要使用超级用户或所有者帐号去连接数据库。要用权限被严格限制的帐号。

  • 检查输入的数据是否具有所期望的数据格式。PHP 有很多可以用于检查输入的函数,从简单的变量函数字符类型函数(比如 is_numeric()ctype_digit())到复杂的 Perl 兼容正则表达式函数都可以完成这个工作。

  • 如果程序等待输入一个数字,可以考虑使用 is_numeric() 来检查,或者直接使用 settype() 来转换它的类型,也可以用 sprintf() 把它格式化为数字。

    例子 27-6. 一个实现分页更安全的方法

    <?php
    
    settype($offset, 'integer');
    $query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
    
    // 请注意格式字符串中的 %d,如果用 %s 就毫无意义了
    $query = sprintf("SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET %d;",
                     $offset);
    
    ?>

  • 使用数据库特定的敏感字符转义函数(比如 mysql_escape_string()sql_escape_string())把用户提交上来的非数字数据进行转义。如果数据库没有专门的敏感字符转义功能的话 addslashes()str_replace() 可以代替完成这个工作。看看第一个例子,此例显示仅在查询的静态部分加上引号是不够的,查询很容易被攻破。

  • 要不择手段避免显示出任何有关数据库的信心,尤其是数据库结构。参见错误报告错误处理函数

  • 也可以选择使用数据库的存储过程和预定义指针等特性来抽象数库访问,使用户不能直接访问数据表和视图。但这个办法又有别的影响。

除此之外,在允许的情况下,使用代码或数据库系统保存查询日志也是一个好办法。显然,日志并不能防止任何攻击,但利用它可以跟踪到哪个程序曾经被尝试攻击过。日志本身没用,要查阅其中包含的信息才行。毕竟,更多的信息总比没有要好。


章 28. 错误报告

对于 PHP 的安全性来说错误报告是一把双刃剑。一方面可以提高安全性,另一方面又有害。

攻击系统时经常使用的手法就是输入不正确的数据,然后查看错误提示的类型及上下文。这样做有利于攻击者收集服务器的信息以便寻找弱点。比如说,如果一个攻击者知道了一个页面所基于的表单信息,那么他就会尝试修改变量:

例子 28-1. 用自定义的 HTML 页面攻击变量

<form method="post" action="attacktarget?username=badfoo&amp;password=badfoo">
<input type="hidden" name="username" value="badfoo" />
<input type="hidden" name="password" value="badfoo" />
</form>

通常 PHP 所返回的错误提示都能帮助开发者调试程序,它会提出哪个文件的哪些函数或代码出错,并指出错误发生的在文件的第几行,这些就是 PHP 本身所能给出的信息。很多 PHP 开发者会使用 show_source()highlight_string() 或者 highlight_file() 函数来调试代码,但是在正式运行的网站中,这种做法可能会暴露出隐藏的变量、未检查的语法和其它的可能危及系统安全的信息。在运行一些具有内部调试处理的程序,或者使用通用调试技术是很危险的。如果让攻击者确定了程序是使用了哪种具体的调试技术,他们会尝试发送变量来打开调试功能:

例子 28-2. 利用变量打开调式功能

<form method="post" action="attacktarget?errors=Y&amp;showerrors=1&amp;debug=1">
<input type="hidden" name="errors" value="Y" />
<input type="hidden" name="showerrors" value="1" />
<input type="hidden" name="debug" value="1" />
</form>

不管错误处理机制如何,可以探测系统错误的能力会给攻击者提供更多信息。

比如说,PHP 的独有的错误提示风格可以说明系统在运行 PHP。如果攻击者在寻找一个 .html 为页面,想知道其后台的技术(为了寻找系统弱点),他们就会把错误的数据提交上去,然后就有可以得知系统是基于 PHP 的了。

一个函数错误就可能暴露系统正在使用的数据库,或者为攻击者提供有关网页、程序或设计方面的有用信息。攻击者往往会顺藤摸瓜地找到开放的数据库端口,以及页面上某些 bug 或弱点等。比如说,攻击者可以一些不正常的数据使程序出错,来探测脚本中认证的顺序(通过错误提示的行号数字)以及脚本中其它位置可能泄露的信息。

一个文件系统或者 PHP 的错误就会暴露 web 服务器具有什么权限,以及文件在服务器上的组织结构。开发者自己写的错误代码会加剧此问题,导致泄漏了原本隐藏的信息。

有三个常用的办法处理这些问题。第一个是彻底地检查所有函数,并尝试弥补大多数错误。第二个是对在线系统彻底关闭错误报告。第三个是使用 PHP 自定义的错误处理函数创建自己的错误处理机制。根据不同的安全策略,三种方法可能都适用。

一个能提前阻止这个问题发生的方法就是利用 error_reporting() 来帮助使代码更安全并发现变量使用的危险之处。在发布程序之前,先打开 E_ALL 测试代码,可以帮你很快找到变量使用不当的地方。一旦准备正式发布,就应该把 error_reporting() 的参数设为 0 来彻底关闭错误报告或者把 php.ini 中的 display_errors 设为 off 来关闭所有的错误显示以将代码隔绝于探测。当然,如果要迟一些再这样做,就不要忘记打开 ini 文件内的 log_errors 选项,并通过 error_log 指定用于记录错误信息的文件。

例子 28-3. 用 E_ALL 来查找危险的变量

<?php
if ($username) {  // Not initialized or checked before usage
    $good_login = 1;
}
if ($good_login == 1) { // If above test fails, not initialized or checked before usage
    readfile ("/highly/sensitive/data/index.html");
}
?>


章 29. 使用 Register Globals

可能 PHP 中最具争议的变化就是从 PHP 4.2.0 版开始配置文件中 register_globals 的默认值从 on 改为 off 了。对此选项的依赖是如此普遍以至于很多人根本不知道它的存在而以为 PHP 本来就是这么工作的。本节会解释用这个指令如何写出不安全的代码,但要知道这个指令本身没有不安全的地方,误用才会。

当 register_globals 打开以后,各种变量都被注入代码,例如来自 HTML 表单的请求变量。再加上 PHP 在使用变量之前是无需进行初始化的,这就使得更容易写出不安全的代码。这是个很艰难的抉择,但 PHP 社区还是决定默认关闭此选项。当打开时,人们使用变量时确实不知道变量是哪里来的,只能想当然。但是 register_globals 的关闭改变了这种代码内部变量和客户端发送的变量混杂在一起的糟糕情况。下面举一个错误使用 register_globals 的例子:

例子 29-1. 错误使用 register_globals = on 的例子

<?php
// 当用户合法的时候,赋值 $authorized = true
if (authenticated_user()) {
    $authorized = true;
}

// 由于并没有事先把 $authorized 初始化为 false,
// 当 register_globals 打开时,可能通过GET auth.php?authorized=1 来定义该变量值
// 所以任何人都可以绕过身份验证
if ($authorized) {
    include "/highly/sensitive/data.php";
}
?>

当 register_globals = on 的时候,上面的代码就会有危险了。如果是 off,$authorized 就不能通过如 URL 请求等方式来改变,这样就好多了,尽管初始化变量是一个良好的编程习惯。比如说,如果在上面的代码执行之前加入 $authorized = false 的话,无论 register_globals 是 on 还是 off 都可以,因为用户状态被初始化为未经认证。

另一个例子是关于会话的。当 register_globals = on 的时候,$username 也可以用在下面的代码中,但要意识到 $username 也可能会从其它途径进来,比如说通过 URL 的 GET。

例子 29-2. 使用会话时同时兼容 register_globals on 和 off 的例子

<?php
// 我们不知道 $username 的来源,但很清楚 $_SESSION 是
// 来源于会话数据
if (isset($_SESSION['username'])) {

    echo "Hello <b>{$_SESSION['username']}</b>";

} else {

    echo "Hello <b>Guest</b><br />";
    echo "Would you like to login?";

}
?>

采取相应的预防措施以便在伪造变量输入的时候给予警告是完全有可能的。如果事先确切知道变量是哪里来的,就可以检查所提交的数据是否是从不正当的表单提交而来。不过这不能保证变量未被伪造,这需要攻击者去猜测应该怎样去伪造。如果不在乎请求数据来源的话,可以使用 $_REQUEST 数组,它包括了 GET、POST 和 COOKIE 的所有数据。详情可参见本手册的来自 PHP 之外的变量

例子 29-3. 探测有害变量

<?php
if (isset($_COOKIE['MAGIC_COOKIE'])) {

    // MAGIC_COOKIE 来自 cookie
    // 这样做是确保是来自 cookie 的数据

} elseif (isset($_GET['MAGIC_COOKIE']) || isset($_POST['MAGIC_COOKIE'])) {

   mail("admin@example.com", "Possible breakin attempt", $_SERVER['REMOTE_ADDR']);
   echo "Security violation, admin has been alerted.";
   exit;

} else {

   // 这一次请求中并没有设置 MAGIC_COOKIE 变量

}
?>

当然,单纯地关闭 register_globals 并不代表所有的代码都安全了。对于每一段提交上来的数据,都要对其进行具体的检查。永远要验证用户数据和对变量进行初始化!把 error_reporting() 设为 E_NOTICE 级别可以检查未初始化的变量。

更多关于模拟 register_globals 为 on 或 off 的信息,请见此 FAQ

Superglobals 可用性说明: 自 PHP 4.1.0 起,可以使用超全局数组变量例如 $_GET$_POST$_SERVER 等等。更多信息请阅读手册中的 superglobals


章 30. 用户提交的数据

很多 PHP 程序所存在的重大弱点并不是 PHP 语言本身的问题,而是编程者的安全意识不高而导致的。因此,必须时时注意每一段代码可能存在的问题,去发现非正确数据提交时可能造成的影响。

例子 30-1. 危险的变量用法

<?php
// 从用户目录中删除一个文件,或者……能删除更多的东西?
unlink ($evil_var);

// 记录用户的登陆,或者……能否在 /etc/passwd 添加数据?
fwrite ($fp, $evil_var);

// 执行一些普通的命令,或者……可以执行 rm -rf * ?
system ($evil_var);
exec ($evil_var);

?>
必须时常留意你的代码,以确保每一个从客户端提交的变量都经过适当的检查,然后问自己以下一些问题:

  • 此脚本是否只能影响所预期的文件?

  • 非正常的数据被提交后能否产生作用?

  • 此脚本能用于计划外的用途吗?

  • 此脚本能否和其它脚本结合起来做坏事?

  • 是否所有的事务都被充分记录了?

在写代码的时候问自己这些问题,否则以后可能要为了增加安全性而重写代码了。注意了这些问题的话,也许还不完全能保证系统的安全,但是至少可以提高安全性。

还可以考虑关闭 register_globals,magic_quotes 或者其它使编程更方便但会使某个变量的合法性,来源和其值被搞乱的设置。在开发时,可以使用 error_reporting(E_ALL) 模式帮助检查变量使用前是否有被检查或被初始化,这样就可以防止某些非正常的数据的挠乱了。


章 31. 魔术引号

魔术引号(Magic Quote)是一个自动将进入 PHP 脚本的数据进行转义的过程。最好在编码时不要转义而在运行时根据需要而转义。


什么是魔术引号

当打开时,所有的 '(单引号),"(双引号),\(反斜线)和 NULL 字符都会被自动加上一个反斜线进行转义。这和 addslashes() 作用完全相同。

一共有三个魔术引号指令:

  • magic_quotes_gpc

    影响到 HTTP 请求数据(GET,POST 和 COOKIE)。不能在运行时改变。在 PHP 中默认值为 on

    参见 get_magic_quotes_gpc()

  • magic_quotes_runtime

    如果打开的话,大部份从外部来源取得数据并返回的函数,包括从数据库和文本文件,所返回的数据都会被反斜线转义。该选项可在运行的时改变,在 PHP 中的默认值为 off

    参见 set_magic_quotes_runtime()get_magic_quotes_runtime()

  • magic_quotes_sybase

    如果打开的话,将会使用单引号对单引号进行转义而非反斜线。此选项会完全覆盖 magic_quotes_gpc。如果同时打开两个选项的话,单引号将会被转义成 ''。而双引号、反斜线 和 NULL 字符将不会进行转义。

    如何取得其值参见 ini_get()


为什么要用魔术引号

  • 对初学者很有用

    魔术引号在 PHP 中用来实现避免初学者的代码更危险。尽管 SQL 注入在魔术引号打开的情况下仍然有可能实现,但起码系统的风险减少很多了。

  • 方便使用

    当向数据库中插入数据时,魔术引号所做的就是自动对所有的 GET、POST、COOKIE 数据运用 addslashes() 函数。


为什么不用魔术引号

  • 可移植性

    编程时认为其打开或并闭都会影响到移植性。可以用 get_magic_quotes_gpc() 来检查是否打开,并据此编程。

  • 性能

    由于并不是每一段被转义的数据都要插入数据库的,如果所有进入 PHP 的数据都被转义的话,那么会对程序的执行效率产生一定的影响。在运行时调用转义函数(如 addslashes())更有效率。

    尽管 php.ini-dist 默认打开了这个选项,但是 php.ini-recommended 默认却关闭了它,主要是出于性能的考虑。

  • 不便

    由于不是所有数据都需要转义,在不需要转义的地方看到转义的数据就很烦。比如说通过表单发送邮件,结果看到一大堆的 \'。针对这个问题,可以使用 stripslashes() 函数处理。


关闭魔术引号

magic_quotes_gpc 指令只能在系统级关闭,不能在运行时。也就是说不能用 ini_set()

例子 31-1. 在服务器端关闭魔术引号

下面是一个通过 php.ini 文件把这些选项设为 Off 的范例。更多信息请参见本手册的怎样修改配置设定

; Magic quotes
;

; Magic quotes for incoming GET/POST/Cookie data.
magic_quotes_gpc = Off

; Magic quotes for runtime-generated data, e.g. data from SQL, from exec(), etc.
magic_quotes_runtime = Off

; Use Sybase-style magic quotes (escape ' with '' instead of \').
magic_quotes_sybase = Off

如果不能修改服务器端的配置文件,使用 .htaccess 也可以。范例如下:

php_flag magic_quotes_gpc Off

为了能写出移植性较强的代码(可以运行于任何环境),例如不能修改服务器配置的情况,下面的例子可以在运行时关闭 magic_quotes_gpc。但是这样做比较低效,适当的修改配置才是更好的办法。

例子 31-2. 在运行时关闭魔术引号

<?php
if (get_magic_quotes_gpc()) {
    function stripslashes_deep($value)
    {
        $value = is_array($value) ?
                    array_map('stripslashes_deep', $value) :
                    stripslashes($value);

        return $value;
    }

    $_POST = array_map('stripslashes_deep', $_POST);
    $_GET = array_map('stripslashes_deep', $_GET);
    $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
}
?>


章 32. 隐藏 PHP

一般而言,通过隐藏的手段提高安全性被认为是作用不大的做法。但某些情况下,尽可能的多增加一份安全性都是值得的。

一些简单的方法可以帮助隐藏 PHP,这样做可以提高攻击者发现系统弱点的难度。在 php.ini 文件里设置 expose_php = off ,可以减少他们能获得的有用信息。

另一个策略就是让 web 服务器用 PHP 解析不同扩展名。无论是通过 .htaccess 文件还是 Apache 的配置文件,都可以设置能误导攻击者的文件扩展名:

例子 32-1. 把 PHP 隐藏为另一种语言

# 使PHP看上去像其它的编程语言
AddType application/x-httpd-php .asp .py .pl
或者干脆彻底隐藏它:

例子 32-2. 使用未知的扩展名作为 PHP 的扩展名

# 使 PHP 看上去像未知的文件类型
AddType application/x-httpd-php .bop .foo .133t
或者把它隐藏为 HTML 页面,这样所有的 HTML 文件都会通过 PHP 引擎,会为服务器增加一些负担:

例子 32-3. 用 HTML 做 PHP 的文件后缀

# 使 PHP 代码看上去像 HTML 页面
AddType application/x-httpd-php .htm .html
要让此方法生效,必须把 PHP 文件的扩展名改为以上的扩展名。这样就通过隐藏来提高了安全性,虽然防御能力很低而且有些缺点。


章 33. 保持更新

PHP 和其它的大型系统一样,在持续的研究和改进中。每一个版本都会有或多或少的改进,以便提高安全性和修复已发现的问题等,这样做有利于提高整个系统的安生性和稳定性。

和其它系统级的脚本语言一样,最好的途径是经常更新,并时刻留意最新版本及其改变。


章 34. 用 PHP 进行 HTTP 认证

PHP 的 HTTP 认证机制仅在 PHP 以 Apache 模块方式运行时才有效,因此该功能不适用于 CGI 版本。在 Apache 模块的 PHP 脚本中,可以用 header() 函数来向客户端浏览器发送“Authentication Required”信息,使其弹出一个用户名/密码输入窗口。当用户输入用户名和密码后,包含有 URL 的 PHP 脚本将会加上预定义变量 PHP_AUTH_USERPHP_AUTH_PWAUTH_TYPE 被再次调用,这三个变量分别被设定为用户名,密码和认证类型。预定义变量保存在 $_SERVER 或者 $HTTP_SERVER_VARS 数组中。支持“Basic”和“Digest”(自 PHP 5.1.0 起)认证方法。请参阅 header() 函数以获取更多信息。

PHP 版本问题: Autoglobals 全局变量,包括 $_SERVER等,自 PHP 4.1.0 起有效,$HTTP_SERVER_VARS 从 PHP 3 开始有效。

以下是在页面上强迫客户端认证的脚本范例:

例子 34-1. Basic HTTP 认证范例

<?php
  if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
    exit;
  } else {
    echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
    echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
  }
?>

例子 34-2. Digest HTTP 认证范例

本例演示怎样实现一个简单的 Digest HTTP 认证脚本。更多信息请参考 RFC 2617

<?php
$realm = 'Restricted area';

//user => password
$users = array('admin' => 'mypass', 'guest' => 'guest');


if (!isset($_SERVER['PHP_AUTH_DIGEST'])) {
    header('HTTP/1.1 401 Unauthorized');
    header('WWW-Authenticate: Digest realm="'.$realm.
           '" qop="auth" nonce="'.uniqid().'" opaque="'.md5($realm).'"');

    die('Text to send if user hits Cancel button');
}

// analize the PHP_AUTH_DIGEST variable
preg_match('/username="(?P<username>.*)",\s*realm="(?P<realm>.*)",\s*nonce="(?P<nonce>.*)",\s*uri="(?P<uri>.*)",\s*response="(?P<response>.*)",\s*opaque="(?P<opaque>.*)",\s*qop=(?P<qop>.*),\s*nc=(?P<nc>.*),\s*cnonce="(?P<cnonce>.*)"/', $_SERVER['PHP_AUTH_DIGEST'], $digest);

if (!isset($users[$digest['username']]))
    die('Username not valid!');


// generate the valid response
$A1 = md5($digest['username'] . ':' . $realm . ':' . $users[$digest['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$digest['uri']);
$valid_response = md5($A1.':'.$digest['nonce'].':'.$digest['nc'].':'.$digest['cnonce'].':'.$digest['qop'].':'.$A2);

if ($digest['response'] != $valid_response)
    die('Wrong Credentials!');

// ok, valid username & password
echo 'Your are logged in as: ' . $digest['username'];

?>

兼容性问题: 在编写 HTTP 标头代码时请格外小心。为了对所有的客户端保证兼容性,关键字“Basic”的第一个字母必须大写为“B”,分界字符串必须用双引号(不是单引号)引用;并且在标头行 HTTP/1.0 401 中,在 401 前必须有且仅有一个空格。

在以上例子中,仅仅只打印出了 PHP_AUTH_USERPHP_AUTH_PW 的值,但在实际运用中,可能需要对用户名和密码的合法性进行检查。或许进行数据库的查询,或许从 dbm 文件中检索。

注意有些 Internet Explorer 浏览器本身有问题。它对标头的顺序显得似乎有点吹毛求疵。目前看来在发送 HTTP/1.0 401 之前先发送 WWW-Authenticate 标头似乎可以解决此问题。

自 PHP 4.3.0 起,为了防止有人通过编写脚本来从用传统外部机制认证的页面上获取密码,当外部认证对特定页面有效,并且安全模式被开启时,PHP_AUTH 变量将不会被设置。但无论如何,REMOTE_USER 可以被用来辨认外部认证的用户,因此可以用 $_SERVER['REMOTE_USER'] 变量。

配置说明: PHP 用是否有 AuthType 指令来判断外部认证机制是否有效。

注意,这仍然不能防止有人通过未认证的 URL 来从同一服务器上认证的 URL 上偷取密码。

Netscape Navigator 和 Internet Explorer 浏览器都会在收到 401 的服务端返回信息时清空所有的本地浏览器整个域的 Windows 认证缓存。这能够有效的注销一个用户,并迫使他们重新输入他们的用户名和密码。有些人用这种方法来使登录状态“过期”,或者作为“注销”按钮的响应行为。

例子 34-3. 强迫重新输入用户名和密码的 HTTP 认证的范例

<?php
  function authenticate() {
    header('WWW-Authenticate: Basic realm="Test Authentication System"');
    header('HTTP/1.0 401 Unauthorized');
    echo "You must enter a valid login ID and password to access this resource\n";
    exit;
  }

  if (!isset($_SERVER['PHP_AUTH_USER']) ||
      ($_POST['SeenBefore'] == 1 && $_POST['OldAuth'] == $_SERVER['PHP_AUTH_USER'])) {
   authenticate();
  }
  else {
   echo "<p>Welcome: {$_SERVER['PHP_AUTH_USER']}<br />";
   echo "Old: {$_REQUEST['OldAuth']}";
   echo "<form action='{$_SERVER['PHP_SELF']}' METHOD='post'>\n";
   echo "<input type='hidden' name='SeenBefore' value='1' />\n";
   echo "<input type='hidden' name='OldAuth' value='{$_SERVER['PHP_AUTH_USER']}' />\n";
   echo "<input type='submit' value='Re Authenticate' />\n";
   echo "</form></p>\n";
  }

该行为对于 HTTP 的 Basic 认证标准来说并不是必须的,因此不能依靠这种方法。对 Lynx 浏览器的测试表明 Lynx 在收到 401 的服务端返回信息时不会清空认证文件,因此只要对认证文件的检查要求没有变化,只要用户点击“后退”按钮,再点击“前进”按钮,其原有资源仍然能够被访问。不过,用户可以通过按“_”键来清空他们的认证信息。

同时请注意,在 PHP 4.3.3 之前,由于微软 IIS 的限制,HTTP 认证无法工作在 IIS 服务器的 CGI 模式下。为了能够使其在 PHP 4.3.3 以上版本能够工作,需要编辑 IIS 的设置“目录安全”。点击“编辑”并且只选择“匿名访问”,其它所有的复选框都应该留空。

另一个限制是在 IIS 的 ISAPI 模式下使用 PHP 4 的时候,无法使用 PHP_AUTH_* 变量,而只能使用 HTTP_AUTHORIZATION。例如,考虑如下代码:list($user, $pw) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));

IIS 注意事项: 要 HTTP 认证能够在 IIS 下工作,PHP 配置选项 cgi.rfc2616_headers 必须设置成 0(默认值)。

注: 如果安全模式被激活,脚本的 UID 会被加到 WWW-Authenticate 标头的 realm 部分。


章 35. cookies

PHP 透明地支持 HTTP cookie。cookie 是一种在远程浏览器端储存数据并以此来跟踪和识别用户的机制。可以用 setcookie()setrawcookie() 函数来设置 cookie。cookie 是 HTTP 标头的一部分,因此 setcookie() 函数必须在其它信息被输出到浏览器前调用,这和对 header() 函数的限制类似。可以使用输出缓冲函数来延迟脚本的输出,直到按需要设置好了所有的 cookie 或者其它 HTTP 标头。

任何从客户端发送的 cookie 将会像 GETPOST 数据一样被自动的转换为 PHP 变量,该过程受 register_globalsvariables_order 两个配置选项的影响。如果希望对一个 cookie 变量设置多个值,则需在 cookie 的名称后加 [] 符号。

在 PHP 4.1.0 及更高版本,自动全局变量数组 $_COOKIE 将总是包含所有从客户端发来的 cookie 数据。在老版本的 PHP 中,当 track_vars 配置选项打开时(此选项自 PHP 4.0.3 后总是打开的),系统为 cookie 设置的数组变量是 $HTTP_COOKIE_VARS

关于更多细节以及有关浏览器问题的注意事项,参见 setcookie()setrawcookie() 函数。


章 36. 会话

会话机制(Session)在 PHP 中用于保存并发访问中的一些数据。这使可以帮助创建更为人性化的程序,增加站点的吸引力。关于会话机制的更多信息,请参见会话处理函数一章。


章 37. 处理 XForms

XForms 定义了一种传统 web 表单的变种,它可以用于更多的平台和浏览器,甚至非传统的媒体例如 PDF 文档。

XFroms 的第一个关键区别是表单怎样发送到客户端。XForms for HTML Authors 包含有怎样创建 XForms 的详细说明。本节只看一个简单例子。

例子 37-1. 一个简单的 XForms 搜索表单

<h:html xmlns:h="http://www.w3.org/1999/xhtml"
        xmlns="http://www.w3.org/2002/xforms">
<h:head>
 <h:title>Search</h:title>
 <model>
  <submission action="http://example.com/search"
              method="post" id="s"/>
 </model>
</h:head>
<h:body>
 <h:p>
  <input ref="q"><label>Find</label></input>
  <submit submission="s"><label>Go</label></submit>
 </h:p>
</h:body>
</h:html>

上面的表单显示一个文本输入框(命名为 q)和一个提交按钮。当点击提交按钮,表单将被发送到 action 所指示的页面。

下面是从 web 应用端的角度看上去的区别。在普通的 HTML 表单中,数据发送格式是 application/x-www-form-urlencoded,在 XForms 的世界中,该信息是以 XML 格式数据发送的。

如果选择使用 XForms,那么数据为 XML,这种情况下,在 $HTTP_RAW_POST_DATA 中包含了由浏览器产生的 XML 文档,可以将其传递给所偏好的 XSLT 引擎或者文档解析器。

如果对格式不感兴趣,只想让数据进入到传统的 $_POST 变量中,可以指示客户端浏览器将其以 application/x-www-form-urlencoded 格式发送,只要将 method 属性改成 urlencoded-post 即可。

例子 37-2. 使用 XForm 来产生 $_POST

<h:html xmlns:h="http://www.w3.org/1999/xhtml"
        xmlns="http://www.w3.org/2002/xforms">
<h:head>
 <h:title>Search</h:title>
 <model>
  <submission action="http://example.com/search"
              method="urlencoded-post" id="s"/>
 </model>
</h:head>
<h:body>
 <h:p>
  <input ref="q"><label>Find</label></input>
  <submit submission="s"><label>Go</label></submit>
 </h:p>
</h:body>
</h:html>

注: 在写本文档时,许多浏览器还不支持 XForms。如果上面例子失败请检查自己的浏览器版本。


章 38. 文件上传处理

POST 方法上传

本特性可以使用户上传文本和二进制文件。用 PHP 的认证和文件操作函数,可以完全控制允许哪些人上传以及文件上传后怎样处理。

PHP 能够接受任何来自符合 RFC-1867 标准的浏览器(包括 Netscape Navigator 3 及更高版本,打了补丁的 Microsoft Internet Explorer 3 或者更高版本)上传的文件。

相关的设置: 请参阅 php.inifile_uploadsupload_max_filesizeupload_tmp_dirpost_max_size 以及 max_input_time 设置选项。

请注意 PHP 也支持 PUT 方法的文件上传,Netscape Composer 和 W3C 的 Amaya 客户端使用这种方法。请参阅对 PUT 方法的支持以获取更多信息。

例子 38-1. 文件上传表单

可以如下建立一个特殊的表单来支持文件上传:

<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
    <!-- MAX_FILE_SIZE must precede the file input field -->
    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
    <!-- Name of input element determines name in $_FILES array -->
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>

以上范例中的 __URL__ 应该被换掉,指向一个真实的 PHP 文件。

MAX_FILE_SIZE 隐藏字段(单位为字节)必须放在文件输入字段之前,其值为接收文件的最大尺寸。这是对浏览器的一个建议,PHP 也会检查此项。在浏览器端可以简单绕过此设置,因此不要指望用此特性来阻挡大文件。实际上,PHP 设置中的上传文件最大值是不会失效的。但是最好还是在表单中加上此项目,因为它可以避免用户在花时间等待上传大文件之后才发现文件过大上传失败的麻烦。

注: 要确保文件上传表单的属性是 enctype="multipart/form-data",否则文件上传不了。

全局变量 $_FILES 自 PHP 4.1.0 起存在(在更早的版本中用 $HTTP_POST_FILES 替代)。此数组包含有所有上传的文件信息。

以上范例中 $_FILES 数组的内容如下所示。我们假设文件上传字段的名称如上例所示,为 userfile。名称可随意命名。

$_FILES['userfile']['name']

客户端机器文件的原名称。

$_FILES['userfile']['type']

文件的 MIME 类型,如果浏览器提供此信息的话。一个例子是“image/gif”。不过此 MIME 类型在 PHP 端并不检查,因此不要想当然认为有这个值。

$_FILES['userfile']['size']

已上传文件的大小,单位为字节。

$_FILES['userfile']['tmp_name']

文件被上传后在服务端储存的临时文件名。

$_FILES['userfile']['error']

和该文件上传相关的错误代码。此项目是在 PHP 4.2.0 版本中增加的。

文件被上传后,默认地会被储存到服务端的默认临时目录中,除非 php.ini 中的 upload_tmp_dir 设置为其它的路径。服务端的默认临时目录可以通过更改 PHP 运行环境的环境变量 TMPDIR 来重新设置,但是在 PHP 脚本内部通过运行 putenv() 函数来设置是不起作用的。该环境变量也可以用来确认其它的操作也是在上传的文件上进行的。

例子 38-2. 使文件上传生效

请查阅函数 is_uploaded_file()move_uploaded_file() 以获取进一步的信息。以下范例处理由表单提供的文件上传。

<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.

$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    echo "File is valid, and was successfully uploaded.\n";
} else {
    echo "Possible file upload attack!\n";
}

echo 'Here is some more debugging info:';
print_r($_FILES);

print "</pre>";

?>

接受上传文件的 PHP 脚本为了决定接下来要对该文件进行哪些操作,应该实现任何逻辑上必要的检查。例如可以用 $_FILES['userfile']['size'] 变量来排除过大或过小的文件,也可以通过 $_FILES['userfile']['type'] 变量来排除文件类型和某种标准不相符合的文件,但只把这个当作一系列检查中的第一步,因为此值完全由客户端控制而在 PHP 端并不检查。自 PHP 4.2.0 起,还可以通过 $_FILES['userfile']['error'] 变量来根据不同的错误代码来计划下一步如何处理。不管怎样,要么将该文件从临时目录中删除,要么将其移动到其它的地方。

如果表单中没有选择上传的文件,则 PHP 变量 $_FILES['userfile']['size'] 的值将为 0,$_FILES['userfile']['tmp_name'] 将为空。

如果该文件没有被移动到其它地方也没有被改名,则该文件将在表单请求结束时被删除。

例子 38-3. 上传一组文件

PHP 的 HTML 数组特性甚至支持文件类型。

<form action="" method="post" enctype="multipart/form-data">
<p>Pictures:
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="submit" value="Send" />
</p>
</form>
<?php
foreach ($_FILES["pictures"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
        $name = $_FILES["pictures"]["name"][$key];
        move_uploaded_file($tmp_name, "data/$name");
    }
}
?>

错误信息说明

从 PHP 4.2.0 开始,PHP 将随文件信息数组一起返回一个对应的错误代码。该代码可以在文件上传时生成的文件数组中的 error 字段中被找到,也就是 $_FILES['userfile']['error']

UPLOAD_ERR_OK

其值为 0,没有错误发生,文件上传成功。

UPLOAD_ERR_INI_SIZE

其值为 1,上传的文件超过了 php.iniupload_max_filesize 选项限制的值。

UPLOAD_ERR_FORM_SIZE

其值为 2,上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。

UPLOAD_ERR_PARTIAL

其值为 3,文件只有部分被上传。

UPLOAD_ERR_NO_FILE

其值为 4,没有文件被上传。

UPLOAD_ERR_NO_TMP_DIR

其值为 6,找不到临时文件夹。PHP 4.3.10 和 PHP 5.0.3 引进。

UPLOAD_ERR_CANT_WRITE

其值为 7,文件写入失败。PHP 5.1.0 引进。

注: 以上值在 PHP 4.3.0 之后变成了 PHP 常量。


常见缺陷

MAX_FILE_SIZE 设置的值,不能大于 ini 设置中 upload_max_filesize 选项设置的值。其默认值为 2M 字节。

如果内存限制设置被激活,可能需要将 memory_limit 设置的更大些,请确认 memory_limit 的设置足够的大。

如果 max_execution_time 设置的值太小,脚本运行的时间可能会超过该设置。因此,也请保证 max_execution_time 足够的大。

注: max_execution_time 仅仅只影响脚本本身运行的时间。任何其它花费在脚本运行之外的时间,诸如用函数 system() 对系统的调用、sleep() 函数的使用、数据库查询、文件上传等,在计算脚本运行的最大时间时都不包括在内。

警告

max_input_time 以秒为单位设定了脚本接收输入的最大时间,包括文件上传。对于较大或多个文件,或者用户的网速较慢时,可能会超过默认的 60 秒

如果 post_max_size 设置的值太小,则较大的文件会无法被上传。因此,请保证 post_max_size 的值足够的大。

不对正在操作的文件进行验证可能意味着用户能够访问其它目录下的敏感信息。

请注意 CERN httpd 似乎会丢弃它从客户端获得的 content-type mime 头信息中第一个空格后所有的内容,基于这一点,CERN httpd 不支持文件上传特性。

鉴于文件路径的表示方法有很多种,我们无法确保用使用各种外语的文件名(尤其是包含空格的)能够被正确的处理。

开发人员不应将普通的输入字段和文件上传的字段混用同一个表单变量(例如都用 foo[])。


上传多个文件

可以对 input 域使用不同的 name 来上传多个文件。

PHP 支持同时上传多个文件并将它们的信息自动以数组的形式组织。要完成这项功能,需要在 HTML 表单中对文件上传域使用和多选框与复选框相同的数组式提交语法。

注: 对多文件上传的支持是在 PHP 3.0.10 版本添加的。

例子 38-4. 上传多个文件

<form action="file-upload.php" method="post" enctype="multipart/form-data">
  Send these files:<br />
  <input name="userfile[]" type="file" /><br />
  <input name="userfile[]" type="file" /><br />
  <input type="submit" value="Send files" />
</form>

当以上表单被提交后,数组 $_FILES['userfile']$_FILES['userfile']['name']$_FILES['userfile']['size'] 将被初始化(在 PHP 4.1.0 以前版本是 $HTTP_POST_FILES)。如果 register_globals 的设置为 on,则和文件上传相关的全局变量也将被初始化。所有这些提交的信息都将被储存到以数字为索引的数组中。

例如,假设名为 /home/test/review.html/home/test/xwp.out 的文件被提交,则 $_FILES['userfile']['name'][0] 的值将是 review.html,而 $_FILES['userfile']['name'][1] 的值将是 xwp.out。类似的,$_FILES['userfile']['size'][0] 将包含文件 review.html 的大小,依此类推。

此外也同时设置了 $_FILES['userfile']['name'][0]$_FILES['userfile']['tmp_name'][0]$_FILES['userfile']['size'][0] 以及 $_FILES['userfile']['type'][0]


对 PUT 方法的支持

PHP 3 和 PHP 4 对 PUT 方法的支持有所不同。在 PHP 4 中,必须使用标准的输入流来读取一个 HTTP PUT 的内容。

例子 38-5. 用 PHP 4 来保存 HTTP PUT 文件

<?php
/* PUT data comes in on the stdin stream */
$putdata = fopen("php://stdin", "r");

/* Open a file for writing */
$fp = fopen("myputfile.ext", "w");

/* Read the data 1 KB at a time
   and write to the file */
while ($data = fread($putdata, 1024))
  fwrite($fp, $data);

/* Close the streams */
fclose($fp);
fclose($putdata);
?>

注: 以下文档的内容仅对 PHP 3 适用。

PHP 提供对诸如 Netscape Composer 和 W3C Amaya 等客户端使用的 HTTP PUT 方法的支持。PUT 请求比文件上传要简单的多,它们一般的形式为:

PUT /path/filename.html HTTP/1.1

这通常意味着远程客户端会将其中的 /path/filename.html 存储到 web 目录树。让 Apache 或者 PHP 自动允许所有人覆盖 web 目录树下的任何文件显然是很不明智的。因此,要处理类似的请求,必须先告诉 web 服务器需要用特定的 PHP 脚本来处理该请求。在 Apache 下,可以用 Script 选项来设置。它可以被放置到 Apache 配置文件中几乎所有的位置。通常我们把它放置在 <Directory> 区域或者 <Virtualhost> 区域。可以用如下一行来完成该设置:

Script PUT /put.php

这将告诉 Apache 将所有对 URI 的 PUT 请求全部发送到 put.php 脚本,这些 URI 必须和 PUT 命令中的内容相匹配。当然,这是建立在 PHP 支持 .php 扩展名,并且 PHP 已经在运行的假设之上。

在 put.php 文件中,可以作如下操作:

<?php copy($PHP_UPLOADED_FILE_NAME, $DOCUMENT_ROOT . $REQUEST_URI); ?>

这将会把文件拷贝到远程客户端请求的位置。可能希望在文件拷贝之前进行一些检查或者对用户认证之类的操作。这里唯一的问题是,当 PHP 接受到 PUT 方法的请求时,它将会把上传的文件储存到和其它用 POST 方法处理过的文件相同的临时目录。在请求结束时,临时文件将被删除。因此,用来处理 PUT 的 PHP 脚本必须将该文件拷贝到其它的地方。该临时文件的文件名被储存在变量 $PHP_PUT_FILENAME 中,也可以通过 $REQUEST_URI 变量获得建议的目标文件名(在非 Apache web 服务器上可能会有较大的变化)。该目标文件名是由远程客户端指定的。也可以不听从改客户端的信息,而把所有上传的文件存储到一个特殊的上传目录下。


章 39. 使用远程文件

只要在 php.ini 文件中激活了 allow_url_fopen 选项,就可以在大多数需要用文件名作为参数的函数中使用 HTTPFTP 的 URL 来代替文件名。同时,也可以在 include()include_once()require()require_once() 语句中使用 URL。PHP 所支持协议的更多信息参见附录 L

注: 要在 PHP 4.0.3 及其更早的版本中使用 URL 封装协议,需要在编译时用 --enable-url-fopen-wrapper 参数来配置 PHP。

注: Windows 版本的 PHP 4.3 版之前不支持以下函数的远程访问:include()include_once()require()require_once() 以及参考 LV, Image 图像函数中的 imagecreatefromXXX 函数。

例如,可以用以下范例来打开远程 web 服务器上的文件,解析需要的输出数据,然后将这些数据用在数据库的检索中,或者简单地以和自己网站其它页面相同的风格输出其内容。

例子 39-1. 获取远程文件的标题

<?php
$file = fopen ("http://www.example.com/", "r");
if (!$file) {
    echo "<p>Unable to open remote file.\n";
    exit;
}
while (!feof ($file)) {
    $line = fgets ($file, 1024);
    /* This only works if the title and its tags are on one line */
    if (eregi ("<title>(.*)</title>", $line, $out)) {
        $title = $out[1];
        break;
    }
}
fclose($file);
?>

如果有合法的访问权限,以一个用户的身份和某 FTP 服务器建立了链接,还可以向该 FTP 服务器端的文件进行写操作。仅能用该方法来创建新的文件;如果尝试覆盖已经存在的文件,fopen() 函数的调用将会失败。

要以“anonymous”以外的用户名连接服务器,需要指明用户名(可能还有密码),例如“ftp://user:password@ftp.example.com/path/to/file”(也可以在通过需要 Basic 认证的 HTTP 协议访问远程文件时使用相同的语法)。

例子 39-2. 将数据保存到远程服务器

<?php
$file = fopen ("ftp://ftp.example.com/incoming/outputfile", "w");
if (!$file) {
    echo "<p>Unable to open remote file for writing.\n";
    exit;
}
/* Write the data here. */
fwrite ($file, $_SERVER['HTTP_USER_AGENT'] . "\n");
fclose ($file);
?>

注: 或许可以从以上范例中得到启发,用该技术来存储远程日志文件。但是正如以上提到的,在用 fopen() 方式打开的 URL 中,仅能对新文件进行写操作。如果远程文件已经存在则 fopen() 函数的操作将会失败。要做类似于分布式日志的事,可以参考 syslog() 函数。


章 40. 连接处理

注: 以下内容对 PHP 3.0.7 及更高版本适用。

在 PHP 内部,系统维护着连接状态,其状态有三种可能的情况:

  • 0 - NORMAL(正常)

  • 1 - ABORTED(异常退出)

  • 2 - TIMEOUT(超时)

当 PHP 脚本正常地运行 NORMAL 状态时,连接为有效。当远程客户端中断连接时,ABORTED 状态的标记将会被打开。远程客户端连接的中断通常是由用户点击 STOP 按钮导致的。当连接时间超过 PHP 的时限(请参阅 set_time_limit() 函数)时,TIMEOUT 状态的标记将被打开。

可以决定脚本是否需要在客户端中断连接时退出。有时候让脚本完整地运行会带来很多方便,即使没有远程浏览器接受脚本的输出。默认的情况是当远程客户端连接中断时脚本将会退出。该处理过程可由 php.ini 的 ignore_user_abort 或由 Apache .conf 设置中对应的“php_value ignore_user_abort”以及 ignore_user_abort() 函数来控制。如果没有告诉 PHP 忽略用户的中断,脚本将会被中断,除非通过 register_shutdown_function() 设置了关闭触发函数。通过该关闭触发函数,当远程用户点击 STOP 按钮后,脚本再次尝试输出数据时,PHP 将会检测到连接已被中断,并调用关闭触发函数。

脚本也有可能被内置的脚本计时器中断。默认的超时限制为 30 秒。这个值可以通过设置 php.inimax_execution_time 或 Apache .conf 设置中对应的“php_value max_execution_time”参数或者 set_time_limit() 函数来更改。当计数器超时的时候,脚本将会类似于以上连接中断的情况退出,先前被注册过的关闭触发函数也将在这时被执行。在该关闭触发函数中,可以通过调用 connection_status() 函数来检查超时是否导致关闭触发函数被调用。如果超时导致了关闭触发函数的调用,该函数将返回 2。

需要注意的一点是 ABORTED 和 TIMEOUT 状态可以同时有效。这在告诉 PHP 忽略用户的退出操作时是可能的。PHP 将仍然注意用户已经中断了连接但脚本仍然在运行的情况。如果到了运行的时间限制,脚本将被退出,设置过的关闭触发函数也将被执行。在这时会发现函数 connection_status() 返回 3。


章 41. 数据库永久连接

永久的数据库连接是指在脚本结束运行时不关闭的连接。当收到一个永久连接的请求时。PHP 将检查是否已经存在一个(前面已经开启的)相同的永久连接。如果存在,将直接使用这个连接;如果不存在,则建立一个新的连接。所谓“相同”的连接是指用相同的用户名和密码到相同主机的连接。

对 web 服务器的工作和分布负载没有完全理解的读者可能会错误地理解永久连接的作用。特别的,永久连接不会在相同的连接上提供建立“用户会话”的能力,也不提供有效建立事务的能力。实际上,从严格意义上来讲,永久连接不会提供任何非永久连接无法提供的特殊功能。

为什么?

这和 web 服务器工作的方式有关。web 服务器可以用三种方法来利用 PHP 生成 web 页面。

第一种方法是将 PHP 用作一个“外壳”。以这种方法运行,PHP 会为向 web 服务器提出的每个 PHP 页面请求生成并结束一个 PHP 解释器线程。由于该线程会随每个请求的结束而结束,因此任何在这个线程中利用的任何资源(例如指向 SQL 数据库服务器的连接)都会随线程的结束而关闭。在这种情况下,使用永久连接不会获得任何地改变――因为它们根本不是永久的。

第二,也是最常用的方法,是把 PHP 用作多进程 web 服务器的一个模块,这种方法目前只适用于 Apache。对于一个多进程的服务器,其典型特征是有一个父进程和一组子进程协调运行,其中实际生成 web 页面的是子进程。每当客户端向父进程提出请求时,该请求会被传递给还没有被其它的客户端请求占用的子进程。这也就是说当相同的客户端第二次向服务端提出请求时,它将有可能被一个不同的子进程来处理。在开启了一个永久连接后,所有请求 SQL 服务的后继页面都能够重新使用这个已经建立的 SQL Server 连接。

最后一种方法是将 PHP 用作多线程 web 服务器的一个插件。目前 PHP 4 已经支持 ISAPI、WSAPI 和 NSAPI(在 Windows 环境下),这些使得 PHP 可以被用作诸如 Netscape FastTrack (iPlanet)、Microsoft's Internet Information Server (IIS) 和 O'Reilly's WebSite Pro 等多线程 web 服务器的插件。永久连接的行为和前面所描述的多过程模型在本质上是相同的。注意 PHP 3 不支持 SAPI。

如果永久连接并没有任何附加的功能,那么使用它有什么好处?

答案非常简单――效率。当客户端对 SQL 服务器的连接请求非常频繁时,永久连接将更加高效。连接请求频繁的标准取决于很多因素。例如,数据库的种类,数据库服务和 web 服务是否在同一台服务器上,SQL 服务器如何加载负载等。但我们至少知道,当连接请求很频繁时,永久连接将显著的提高效率。它使得每个子进程在其生命周期中只做一次连接操作,而非每次在处理一个页面时都要向 SQL 服务器提出连接请求。这也就是说,每个子进程将对服务器建立各自独立的永久连接。例如,如果有 20 个不同的子进程运行某脚本建立了永久的 SQL 服务器永久连接,那么实际上向该 SQL 服务器建立了 20 个不同的永久连接,每个进程占有一个。

注意,如果永久连接的子进程数目超过了设定的数据库连接数限制,系统将会产生一些缺陷。如果数据库的同时连接数限制为 16,而在繁忙会话的情况下,有 17 个线程试图连接,那么有一个线程将无法连接。如果这个时候,在脚本中出现了使得连接无法关闭的错误(例如无限循环),则该数据库的 16 个连接将迅速地受到影响。请查阅使用的数据库的文档,以获取关于如何处理已放弃的及闲置的连接的方法。

警告

在使用永久连接时还有一些特别的问题需要注意。例如在永久连接中使用数据表锁时,如果脚本不管什么原因无法释放该数据表锁,其随后使用相同连接的脚本将会被永久的阻塞,使得需要重新启动 httpd 服务或者数据库服务。另外,在使用事务处理时,如果脚本在事务阻塞产生前结束,则该阻塞也会影响到使用相同连接的下一个脚本。不管在什么情况下,都可以通过使用 register_shutdown_function() 函数来注册一个简单的清理函数来打开数据表锁,或者回滚事务。或者更好的处理方法,是不在使用数据表锁或者事务处理的脚本中使用永久连接,这可以从根本上解决这个问题(当然还可以在其它地方使用永久连接)。

以下是一点重要的总结。永久连接是为通常连接建立一对一的分布而设计的。这意味着必须能够保证在将永久连接替换为非永久连接时,脚本的行为不会改变。使用永久连接将(非常)有可能改变脚本的效率,但不改变其行为!

参见 fbsql_pconnect()ibase_pconnect()ifx_pconnect()ingres_pconnect()msql_pconnect()mssql_pconnect()mysql_pconnect()ociplogon()odbc_pconnect()ora_plogon()pfsockopen()pg_pconnect()sybase_pconnect()


章 42. 安全模式

PHP 的安全模式是为了试图解决共享服务器(shared-server)安全问题而设立的。在结构上,试图在 PHP 层上解决这个问题是不合理的,但修改 web 服务器层和操作系统层显得非常不现实。因此许多人,特别是 ISP,目前使用安全模式。


保安措施和安全模式

表格 42-1. 保安措施和安全模式配置指令

名称默认值可修改范围更新记录
safe_mode"0"PHP_INI_SYSTEM 
safe_mode_gid"0"PHP_INI_SYSTEM自 PHP 4.1.0 起可用
safe_mode_include_dirNULLPHP_INI_SYSTEM自 PHP 4.1.0 起可用
safe_mode_exec_dir""PHP_INI_SYSTEM 
safe_mode_allowed_env_vars"PHP_"PHP_INI_SYSTEM 
safe_mode_protected_env_vars"LD_LIBRARY_PATH"PHP_INI_SYSTEM 
open_basedirNULLPHP_INI_SYSTEM 
disable_functions""php.ini自 PHP 4.0.1 起可用
disable_classes""php.ini自 PHP 4.3.2 起可用
PHP_INI_* 常量的进一步详细说明与定义见 ini_set()

以下是配置选项的简要解释。

safe_mode boolean

是否启用 PHP 的安全模式。更多信息请阅读安全一章。

safe_mode_gid boolean

默认情况下,安全模式在打开文件时会做 UID 比较检查。如果想将其放宽到 GID 比较,则打开 safe_mode_gid。是否在文件访问时使用 UIDFALSE)或者 GIDTRUE)来做检查。

safe_mode_include_dir string

当从此目录及其子目录(目录必须在 include_path 中或者用完整路径来包含)包含文件时越过 UID/GID 检查。

从 PHP 4.2.0 开始,本指令可以接受和 include_path 指令类似的风格用冒号(Windows 中是分号)隔开的路径,而不只是一个目录。

指定的限制实际上是一个前缀,而非一个目录名。这也就是说“safe_mode_include_dir = /dir/incl”将允许访问“/dir/include”和“/dir/incls”,如果它们存在的话。如果希望将访问控制在一个指定的目录,那么请在结尾加上一个斜线,例如:“safe_mode_include_dir = /dir/incl/”。

如果本指令的值为空,在 PHP 4.2.3 中以及 PHP 4.3.3 起具有不同 UID/GID 的文件将不能被包含。在较早版本中,所有文件都能被包含。

safe_mode_exec_dir string

如果 PHP 使用了安全模式,system() 和其它程序执行函数将拒绝启动不在此目录中的程序。必须使用 / 作为目录分隔符,包括 Windows 中。

safe_mode_allowed_env_vars string

设置某些环境变量可能是潜在的安全缺口。本指令包含有一个逗号分隔的前缀列表。在安全模式下,用户只能改变那些名字具有在这里提供的前缀的环境变量。默认情况下,用户只能设置以 PHP_ 开头的环境变量(例如 PHP_FOO = BAR)。

注: 如果本指令为空,PHP 将使用户可以修改任何环境变量!

safe_mode_protected_env_vars string

本指令包含有一个逗号分隔的环境变量的列表,最终用户不能用 putenv() 来改变这些环境变量。甚至在 safe_mode_allowed_env_vars 中设置了允许修改时也不能改变这些变量。

open_basedir string

将 PHP 所能打开的文件限制在指定的目录树,包括文件本身。本指令不受安全模式打开或者关闭的影响。

当一个脚本试图用例如 fopen() 或者 gzopen() 打开一个文件时,该文件的位置将被检查。当文件在指定的目录树之外时 PHP 将拒绝打开它。所有的符号连接都会被解析,所以不可能通过符号连接来避开此限制。

特殊值 . 指明脚本的工作目录将被作为基准目录。但这有些危险,因为脚本的工作目录可以轻易被 chdir() 而改变。

httpd.conf 文件中中,open_basedir 可以像其它任何配置选项一样用“php_admin_value open_basedir none”的方法关闭(例如某些虚拟主机中)。

在 Windows 中,用分号分隔目录。在任何其它系统中用冒号分隔目录。作为 Apache 模块时,父目录中的 open_basedir 路径自动被继承。

用 open_basedir 指定的限制实际上是前缀,不是目录名。也就是说“open_basedir = /dir/incl”也会允许访问“/dir/include”和“/dir/incls”,如果它们存在的话。如果要将访问限制在仅为指定的目录,用斜线结束路径名。例如:“open_basedir = /dir/incl/”。

注: 支持多个目录是 3.0.7 加入的。

默认是允许打开所有文件。

disable_functions string

本指令允许你基于安全原因禁止某些函数。接受逗号分隔的函数名列表作为参数。 disable_functions 不受安全模式的影响。

本指令只能设置在 php.ini 中。例如不能将其设置在 httpd.conf

disable_classes string

本指令可以使你出于安全的理由禁用某些类。用逗号分隔类名。disable_classes 不受安全模式的影响。

本指令只能设置在 php.ini 中。例如不能将其设置在 httpd.conf

可用性说明: 本指令自 PHP 4.3.2 起可用。

参见 register_globalsdisplay_errorslog_errors

safe_mode 设置为 on,PHP 将通过文件函数或其目录检查当前脚本的拥有者是否和将被操作的文件的拥有者相匹配。例如:
-rw-rw-r--    1 rasmus   rasmus       33 Jul  1 19:20 script.php
-rw-r--r--    1 root     root       1116 May 26 18:01 /etc/passwd
运行 script.php
<?php
 readfile('/etc/passwd');
?>
如果安全模式被激活,则将会导致以下错误:
Warning: SAFE MODE Restriction in effect. The script whose uid is 500 is not
allowed to access /etc/passwd owned by uid 0 in /docroot/script.php on line 2

同时,或许会存在这样的环境,在该环境下,宽松的 GID 检查已经足够,但严格的 UID 检查反而是不适合的。可以用 safe_mode_gid 选项来控制这种检查。如果设置为 On 则进行宽松的 GID 检查;设置为 Off(默认值)则进行 UID 检查。

除了 safe_mode 以外,如果设置了 open_basedir 选项,则所有的文件操作将被限制在指定的目录下。例如:
<Directory /docroot>
  php_admin_value open_basedir /docroot
</Directory>
如果在设置了 open_basedir 选项后运行同样的 script.php,则其结果会是:
Warning: open_basedir restriction in effect. File is in wrong directory in
/docroot/script.php on line 2

也可以单独地屏蔽某些函数。请注意 disable_functions 选项不能在 php.ini 文件外部使用,也就是说无法在 httpd.conf 文件的按不同虚拟主机或不同目录的方式来屏蔽函数。如果将如下内容加入到 php.ini 文件:
disable_functions readfile,system
则会得到如下的输出:
Warning: readfile() has been disabled for security reasons in
/docroot/script.php on line 2

警告

当然,这些 PHP 限制不适用于可执行文件。


被安全模式限制或屏蔽的函数

以下安全模式列表可能不完整或不正确。

表格 42-2. 安全模式限制函数

函数名限制
dbmopen()检查被操作的文件或目录是否与正在执行的脚本有相同的 UID(所有者)。
dbase_open()检查被操作的文件或目录是否与正在执行的脚本有相同的 UID(所有者)。
filepro()检查被操作的文件或目录是否与正在执行的脚本有相同的 UID(所有者)。
filepro_rowcount()检查被操作的文件或目录是否与正在执行的脚本有相同的 UID(所有者)。
filepro_retrieve()检查被操作的文件或目录是否与正在执行的脚本有相同的 UID(所有者)。
ifx_*sql_safe_mode 限制, (!= safe mode)
ingres_*sql_safe_mode 限制, (!= safe mode)
mysql_*sql_safe_mode 限制, (!= safe mode)
pg_loimport()检查被操作的文件或目录是否与正在执行的脚本有相同的 UID(所有者)。
posix_mkfifo()检查被操作的目录是否与正在执行的脚本有相同的 UID(所有者)。
putenv() 遵循 ini 设置的 safe_mode_protected_env_vars 和 safe_mode_allowed_env_vars 选项。请参考 putenv() 函数的有关文档。
move_uploaded_file()检查被操作的文件或目录是否与正在执行的脚本有相同的 UID(所有者)。
chdir()检查被操作的目录是否与正在执行的脚本有相同的 UID(所有者)。
dl()本函数在安全模式下被禁用。
backtick operator本函数在安全模式下被禁用。
shell_exec()(在功能上和 backticks 函数相同)本函数在安全模式下被禁用。
exec() 只能在 safe_mode_exec_dir 设置的目录下进行执行操作。基于某些原因,目前不能在可执行对象的路径中使用 ..escapeshellcmd() 将被作用于此函数的参数上。
system() 只能在 safe_mode_exec_dir 设置的目录下进行执行操作。基于某些原因,目前不能在可执行对象的路径中使用 ..escapeshellcmd() 将被作用于此函数的参数上。
passthru() 只能在 safe_mode_exec_dir 设置的目录下进行执行操作。基于某些原因,目前不能在可执行对象的路径中使用 ..escapeshellcmd() 将被作用于此函数的参数上。
popen() 只能在 safe_mode_exec_dir 设置的目录下进行执行操作。基于某些原因,目前不能在可执行对象的路径中使用 ..escapeshellcmd() 将被作用于此函数的参数上。
fopen()检查被操作的目录是否与正在执行的脚本有相同的 UID(所有者)。
mkdir()检查被操作的目录是否与正在执行的脚本有相同的 UID(所有者)。
rmdir()检查被操作的目录是否与正在执行的脚本有相同的 UID(所有者)。
rename()检查被操作的文件或目录是否与正在执行的脚本有相同的 UID(所有者)。 检查被操作的目录是否与正在执行的脚本有相同的 UID(所有者)。
unlink()检查被操作的文件或目录是否与正在执行的脚本有相同的 UID(所有者)。 检查被操作的目录是否与正在执行的脚本有相同的 UID(所有者)。
copy()检查被操作的文件或目录是否与正在执行的脚本有相同的 UID(所有者)。 检查被操作的目录是否与正在执行的脚本有相同的 UID(所有者)。 (on source and target)
chgrp()检查被操作的文件或目录是否与正在执行的脚本有相同的 UID(所有者)。
chown()检查被操作的文件或目录是否与正在执行的脚本有相同的 UID(所有者)。
chmod()检查被操作的文件或目录是否与正在执行的脚本有相同的 UID(所有者)。 另外,不能设置 SUID、SGID 和 sticky bits
touch()检查被操作的文件或目录是否与正在执行的脚本有相同的 UID(所有者)。 检查被操作的目录是否与正在执行的脚本有相同的 UID(所有者)。
symlink()检查被操作的文件或目录是否与正在执行的脚本有相同的 UID(所有者)。 检查被操作的目录是否与正在执行的脚本有相同的 UID(所有者)。 (注意:仅测试 target)
link()检查被操作的文件或目录是否与正在执行的脚本有相同的 UID(所有者)。 检查被操作的目录是否与正在执行的脚本有相同的 UID(所有者)。 (注意:仅测试 target)
apache_request_headers()在安全模式下,以“authorization”(区分大小写)开头的标头将不会被返回。
header()在安全模式下,如果设置了 WWW-Authenticate,当前脚本的 uid 将被添加到该标头的 realm 部分。
PHP_AUTH 变量 在安全模式下,变量 PHP_AUTH_USERPHP_AUTH_PWPHP_AUTH_TYPE$_SERVER 中不可用。但无论如何,您仍然可以使用 REMOTE_USER 来获取用户名称(USER)。(注意:仅 PHP 4.3.0 以后有效)
highlight_file(), show_source() 检查被操作的文件或目录是否与正在执行的脚本有相同的 UID(所有者)。 检查被操作的目录是否与正在执行的脚本有相同的 UID(所有者)。 (注意,仅在 4.2.1 版本后有效)
parse_ini_file() 检查被操作的文件或目录是否与正在执行的脚本有相同的 UID(所有者)。 检查被操作的目录是否与正在执行的脚本有相同的 UID(所有者)。 (注意,仅在 4.2.1 版本后有效)
set_time_limit() 安全模式下不起作用。
max_execution_time 安全模式下不起作用。
mail() 在安全模式下,第五个参数被屏蔽。(注意,仅自 PHP 4.2.3 起受影响)
任何使用 php4/main/fopen_wrappers.c 的函数 ??


章 43. PHP 的命令行模式

从版本 4.3.0 开始,PHP 提供了一种新类型的 SAPI(Server Application Programming Interface,服务端应用编程端口)支持,名为 CLI,意为 Command Line Interface,即命令行接口。顾名思义,该 SAPI 模块主要用作 PHP 的开发外壳应用。CLI SAPI 和其它 SAPI 模块相比有很多的不同之处,我们将在本章中详细阐述。值得一提的是,CLICGI 是不同的 SAPI,尽管它们之间有很多共同的行为。

CLI SAPI 最先是随 PHP 4.2.0 版本发布的,但仍旧只是一个实验性的版本,并需要在运行 ./configure 时加上 --enable-cli 参数。从 PHP 4.3.0 版本开始,CLI SAPI 成为了正式模块,--enable-cli 参数会被默认得设置为 on,也可以用参数 --disable-cli 来屏蔽。

从 PHP 4.3.0开始,CLI/CGI 二进制执行文件的文件名、位置和是否存在会根据 PHP 在系统上的安装而不同。在默认情况下,当运行 make 时,CGI 和 CLI 都会被编译并且分别放置在 PHP 源文件目录的 sapi/cgi/phpsapi/cli/php 下。可以注意到两个文件都被命名为了 php。在 make install 的过程中会发生什么取决于配置行。如果在配置的时候选择了一个 SAPI 模块,如 apxs,或者使用了 --disable-cgi 参数,则在 make install 的过程中,CLI 将被拷贝到 {PREFIX}/bin/php,除非 CGI 已经被放置在了那个位置。因此,例如,如果在配置行中有 --with--apxs,则在 make install 的过程中,CLI 将被拷贝到 {PREFIX}/bin/php。如果希望撤销 CGI 执行文件的安装,请在 make install 之后运行 make install-cli。或者,也可以在配置行中加上 --disable-cgi 参数。

注: 由于 --enable-cli--enable-cgi 同时默认有效,因此,不必再配置行中加上 --enable-cli 来使得 CLI 在 make install 过程中被拷贝到 {PREFIX}/bin/php

在 PHP 4.2.0 到 PHP 4.2.3 之间的 Windows 发行包中,CLI 的文件名为 php-cli.exe,相同文件夹下的 php.exe 为 CGI。从 PHP 4.3.0 版本开始,Windows 的发行包中 CLI 的执行文件为 php.exe,被放置在一个单独的名为 cli 的文件夹下,即 cli/php.exe。在 PHP 5 中,CLI 存在于主文件夹中,名为 php.exe,而 CGI 版本名为 php-cgi.exe

从 PHP 5 起,一个名为 php-win.exe 的新文件随包发布。它相当于 CLI 版本,但是 php-win 不输出任何内容,便不提供控制台(不会弹出“DOS 窗口”)。这种方式类似于 php-gtk。需要使用 --enable-cli-win32 选项来配置它。

如何得知自己使用的是哪个 SAPI?: 在命令行下,运行 php -v 便能得知该 php 是 CGI 还是 CLI。请参考函数 php_sapi_name() 以及常量 PHP_SAPI

注: 在 PHP 4.3.2 中加入了 Unix 的 man 页面。可以在命令行中键入 man php 来查看。

以下为 CLI SAPI 和其它 SAPI 模块相比的显著区别:

  • CGI SAPI 不同,其输出没有任何头信息。

    尽管 CGI SAPI 提供了取消 HTTP 头信息的方法,但在 CLI SAPI 中并不存在类似的方法以开启 HTTP 头信息的输出。

    CLI 默认以安静模式开始,但为了保证兼容性,-q--no-header 参数为了向后兼容仍然保留,使得可以使用旧的 CGI 脚本。

    在运行时,不会把工作目录改为脚本的当前目录(可以使用 -C--no-chdir 参数来兼容 CGI 模式)。

    出错时输出纯文本的错误信息(非 HTML 格式)。

  • CLI SAPI 强制覆盖了 php.ini 中的某些设置,因为这些设置在外壳环境下是没有意义的。

    表格 43-1. 覆盖 php.ini 设置选项

    设置选项CLI SAPI 默认值备注
    html_errorsFALSE 无意义的 HTML 标记符会使得出错信息很凌乱,所以在外壳下阅读报错信息是十分困难的。因此将该选项的默认值改为 FALSE
    implicit_flushTRUE 在命令行模式下,所有来自 print()echo() 的输出将被立即写到输出端,而不作任何地缓冲操作。如果希望延缓或控制标准输出,仍然可以使用 output buffering 设置项。
    max_execution_time0(无限值) 鉴于在外壳环境下使用 PHP 的无穷的可能性,最大运行时间被设置为了无限值。为 web 开发的应用程序可能只需运行几秒钟时间,而外壳应用程序的运行时间可能会长的多。
    register_argc_argvTRUE

    由于该设置为 TRUE,将总是可以在 CLI SAPI 中访问到 argc(传送给应用程序参数的个数)和 argv(包含有实际参数的数组)。

    对于 PHP 4.3.0,在使用 CLI SAPI 时,PHP 变量 $argc$argv 已被注册并且设定了对应的值。而在这之前的版本,这两个变量在 CGI 或者 模块 版本中的建立依赖于将 PHP 的设置选项 register_globals 设为 on。除了版本和 register_globals 设定以外,可以随时通过调用 $_SERVER 或者 $HTTP_SERVER_VARS 来访问它们。例如:$_SERVER['argv']

    注: 这些设置无法在设置文件 php.ini 或任何指定的其它文件中被初始化为其它值。这些默认值被限制在所有其它的设置文件被解析后改变。不过,它们的值可以在程序运行的过程中被改变(尽管对于该运行过程来说,这些设置项是没有意义的)。

  • 为了减轻外壳环境下的工作,我们定义了如下常量:

    表格 43-2. CLI 专用常量

    常量名称描 述
    STDIN 一个已打开的指向 stdin 的流。可以用如下方法来调用:
    <?php
    
    $stdin = fopen('php://stdin', 'r');
    
    ?>
    如果想从 stdin 读取一行内容,可以使用
    <?php
    $line = trim(fgets(STDIN)); // 从 STDIN 读取一行
    fscanf(STDIN, "%d\n", $number); // 从 STDIN 读取数字
    ?>
    STDOUT 一个已打开的指向 stdout 的流。可以用如下方式来调用:
    <?php
    
    $stdout = fopen('php://stdout', 'w');
    
    ?>
    STDERR 一个已打开的指向 stderr 的流。可以用如下方式来调用:
    <?php
    
    $stderr = fopen('php://stderr', 'w');
    
    ?>

    有了以上常量,就无需自己建立指向诸如 stderr 的流,只需简单的使用这些常量来代替流指向:
    php -r 'fwrite(STDERR, "stderr\n");'
    无需自己来关闭这些流,PHP 会自动完成这些操作。

  • CLI SAPI 不会将当前目录改为已运行的脚本所在的目录。

    以下范例显示了本模块与 CGI SAPI 模块之间的不同:
    <?php
    // 名为 test.php 的简单测试程序
    echo getcwd(), "\n";
    ?>

    在使用 CGI 版本时,其输出为
    $ pwd
    /tmp
    
    $ php-cgi -f another_directory/test.php
    /tmp/another_directory

    明显可以看到 PHP 将当前目录改成了刚刚运行过的脚本所在的目录。

    使用 CLI SAPI 模式,得到:
    $ pwd
    /tmp
    
    $ php -q another_directory/test.php
    /tmp
    这使得在利用 PHP 编写外壳工具时获得了很大的便利。

    注: 可以在命令行运行时给该 CGI SAPI 加上 -C 参数,使其支持 CLI SAPI 的功能。

以下是 PHP 二进制文件(即 php.exe 程序)提供的命令行模式的选项参数,随时可以运行带 -h 参数的 PHP 命令来查询这些参数。
Usage: php [options] [-f] <file> [--] [args...]
       php [options] -r <code> [--] [args...]
       php [options] [-B <begin_code>] -R <code> [-E <end_code>] [--] [args...]
       php [options] [-B <begin_code>] -F <file> [-E <end_code>] [--] [args...]
       php [options] -- [args...]
       php [options] -a

  -a               Run interactively
  -c <path>|<file> Look for php.ini file in this directory
  -n               No php.ini file will be used
  -d foo[=bar]     Define INI entry foo with value 'bar'
  -e               Generate extended information for debugger/profiler
  -f <file>        Parse <file>.
  -h               This help
  -i               PHP information
  -l               Syntax check only (lint)
  -m               Show compiled in modules
  -r <code>        Run PHP <code> without using script tags <?..?>
  -B <begin_code>  Run PHP <begin_code> before processing input lines
  -R <code>        Run PHP <code> for every input line
  -F <file>        Parse and execute <file> for every input line
  -E <end_code>    Run PHP <end_code> after processing all input lines
  -H               Hide any passed arguments from external tools.
  -s               Display colour syntax highlighted source.
  -v               Version number
  -w               Display source with stripped comments and whitespace.
  -z <file>        Load Zend extension <file>.

  args...          Arguments passed to script. Use -- args when first argument
                   starts with - or script is read from stdin

CLI SAPI 模块有以下三种不同的方法来获取要运行的 PHP 代码:

  1. 让 PHP 运行指定文件。

    php my_script.php
    
    php -f my_script.php

    以上两种方法(使用或不使用 -f 参数)都能够运行给定的 my_script.php 文件。可以选择任何文件来运行,指定的 PHP 脚本并非必须要以 .php 为扩展名,它们可以有任意的文件名和扩展名。

  2. 在命令行直接运行 PHP 代码。

    php -r 'print_r(get_defined_constants());'

    在使用这种方法时,请注意外壳变量的替代及引号的使用。

    注: 请仔细阅读以上范例,在运行代码时没有开始和结束的标记符!加上 -r 参数后,这些标记符是不需要的,加上它们会导致语法错误。

  3. 通过标准输入(stdin)提供需要运行的 PHP 代码。

    以上用法提供了非常强大的功能,使得可以如下范例所示,动态地生成 PHP 代码并通过命令行运行这些代码:
    $ some_application | some_filter | php | sort -u >final_output.txt

以上三种运行代码的方法不能同时使用。

和所有的外壳应用程序一样,PHP 的二进制文件(php.exe 文件)及其运行的 PHP 脚本能够接受一系列的参数。PHP 没有限制传送给脚本程序的参数的个数(外壳程序对命令行的字符数有限制,但通常都不会超过该限制)。传递给脚本的参数可在全局变量 $argv 中获取。该数组中下标为零的成员为脚本的名称(当 PHP 代码来自标准输入获直接用 -r 参数以命令行方式运行时,该名称为“-”)。另外,全局变量 $argc 存有 $argv 数组中成员变量的个数(而非传送给脚本程序的参数的个数)。

只要传送给脚本的参数不是以 - 符号开头,就无需过多的注意什么。向脚本传送以 - 开头的参数会导致错误,因为 PHP 会认为应该由它自身来处理这些参数。可以用参数列表分隔符 -- 来解决这个问题。在 PHP 解析完参数后,该符号后所有的参数将会被原样传送给脚本程序。

# 以下命令将不会运行 PHP 代码,而只显示 PHP 命令行模式的使用说明:
$ php -r 'var_dump($argv);' -h
Usage: php [options] [-f] <file> [args...]
[...]

# 以下命令将会把“-h”参数传送给脚本程序,PHP 不会显示命令行模式的使用说明:
$ php -r 'var_dump($argv);' -- -h
array(2) {
  [0]=>
  string(1) "-"
  [1]=>
  string(2) "-h"
}

除此之外,还有另一个方法将 PHP 用于外壳脚本。可以在写一个脚本,并在第一行以 #!/usr/bin/php 开头,在其后加上以 PHP 开始和结尾标记符包含的正常的 PHP 代码,然后为该文件设置正确的运行属性(例如:chmod +x test)。该方法可以使得该文件能够像外壳脚本或 PERL 脚本一样被直接执行。
#!/usr/bin/php
<?php
    var_dump($argv);
?>

假设改文件名为 test 并被放置在当前目录下,可以做如下操作:
$ chmod +x test
$ ./test -h -- foo
array(4) {
  [0]=>
  string(6) "./test"
  [1]=>
  string(2) "-h"
  [2]=>
  string(2) "--"
  [3]=>
  string(3) "foo"
}

正如所看到的,在向该脚本传送以 - 开头的参数时,脚本仍然能够正常运行。

PHP 4.3.3 以来有效的长选项:

表格 43-3. 命令行选项

选项名称长名称说明
-a--interactive

交互式运行 PHP。如果编译 PHP 时加入了 Readline 扩展(Windows 下不可用),那将会得到一个很好的外壳,包括一个自动完成的功能(例如可以在键入变量名的时候,按下 TAB 键,PHP 会自动完成该变量名)以及命令历史记录,可以用上下键来访问。历史记录存在 ~/.php_history 文件中。

注: 通过 auto_prepend_fileauto_append_file 包含的文件在此模式下会被解析,但有些限制,例如函数必须在被调用之前定义。

-c--php-ini

用该参数,可以指定一个放置 php.ini 文件的目录,或者直接指定一个自定义的 INI 文件(其文件名可以不是 php.ini),例如:
$ php -c /custom/directory/ my_script.php

$ php -c /custom/directory/custom-file.ini my_script.php
如果不指定此选项,PHP 将在默认位置搜索文件。

-n--no-php-ini

完全忽略 php.ini。此参数在 PHP 4.3.0 以后有效。

-d--define

用该参数可以自行设置任何可以在 php.ini 文件中设置的配置选项的值,其语法为:
-d configuration_directive[=value]

例子(因版面原因而折行显示):
# 取值部分被省略,将会把配置选项设为 "1"
$ php -d max_execution_time
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(1) "1"

# 取值部分为空白,将会把配置选项设为 ""
php -d max_execution_time=
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(0) ""

# 配置选项将被设置成为任何 '=' 字符之后的值
$  php -d max_execution_time=20
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(2) "20"
$  php
        -d max_execution_time=doesntmakesense
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(15) "doesntmakesense"

-e--profile-info

激活扩展信息模式,被用于调试/测试。

-f--file

解析并运行 -f 选项给定的文件名。该参数为可选参数,可以省略,仅指明需要运行的文件名即可。

-h and -?--help and --usage 使用该参数,可以得到完整的命令行参数的列表及这些参数作用的简单描述。
-i--info 该命令行参数会调用 phpinfo() 函数并显示出结果。如果 PHP 没有正常工作,建议执行 php -i 命令来查看在信息表格之前或者对应的地方是否有任何错误信息输出。请注意当使用 CGI 摸索时,输出的内容为 HTML 格式,因此输出的信息篇幅较大。
-l--syntax-check

该参数提供了对指定 PHP 代码进行语法检查的方便的方法。如果成功,则向标准输出写入 No syntax errors detected in <filename> 字符串,并且外壳返回值为 0。如果失败,则输出 Errors parsing <filename> 以及内部解析器错误信息到标准输出,同时外壳返回值将别设置为 255

该参数将无法检查致命错误(如未定义函数),如果也希望检测致命错误,请使用 -f 参数。

注: 该参数不能和 -r 一同使用。

-m--modules

使用该参数,PHP 将打印出内置以及已加载的 PHP 及 Zend 模块:
$ php -m
[PHP Modules]
xml
tokenizer
standard
session
posix
pcre
overload
mysql
mbstring
ctype

[Zend Modules]

-r--run

使用该参数可以在命令行内运行单行 PHP 代码。无需加上 PHP 的起始和结束标识符(<?php?>),否则将会导致语法解析错误。

注: 使用这种形式的 PHP 时,应注意避免和外壳环境进行的命令行参数替换相冲突。

显示语法解析错误的范例
$ php -r "$foo = get_defined_constants();"
Command line code(1) : Parse error - parse error, unexpected '='
这里的问题在于即使使用了双引号 ",sh/bash 仍然实行了参数替换。由于 $foo 没有被定义,被替换后它所在的位置变成了空字符,因此在运行时,实际被 PHP 读取的代码为:
$ php -r " = get_defined_constants();"
正确的方法是使用单引号 '。在用单引号引用的字符串中,变量不会被 sh/bash 还原成其原值。
$ php -r '$foo = get_defined_constants(); var_dump($foo);'
array(370) {
  ["E_ERROR"]=>
  int(1)
  ["E_WARNING"]=>
  int(2)
  ["E_PARSE"]=>
  int(4)
  ["E_NOTICE"]=>
  int(8)
  ["E_CORE_ERROR"]=>
  [...]
如果使用的外壳不是 sh/bash,可能会碰到更多问题。请将碰到的 Bug 向 http://bugs.php.net/ 报告。注意,当试图将 shell 变量用到代码中或者使用反斜线时仍然很容易碰到问题。

注: -rCLI SAPI 中有效,在 CGI SAPI 中无效。

注: 此选项只用于非常基本的用途。因此一些配置指令(例如 auto_prepend_fileauto_append_file)在此模式下被忽略。

-B--process-begin

在处理 stdin 之前先执行 PHP 代码。PHP 5 新加。

-R--process-code

对每个输入行都执行 PHP 代码。PHP 5 新加。

此模式下有两个特殊变量:$argn$argi$argn 包含 PHP 当前处理的行内容,而 $argi 则包含该行号。

-F--process-file

对每个输入行都执行 PHP 文件。PHP 5 新加。

-E--process-end

在处理完输入后执行的 PHP 代码。PHP 5 新加。

使用 -B-R-E 选项来计算一个项目总行数的例子。
$ find my_proj | php -B '$l=0;' -R '$l += count(@file($argn));' -E 'echo "Total Lines: $l\n";'
Total Lines: 37328

-s--syntax-highlight and --syntax-highlight

显示有语法高亮色彩的源代码。

该参数使用内建机制来解析文件并为其生成一个 HTML 高亮版本并将结果写到标准输出。请注意该过程所做的只是生成了一个 <code> [...] </code>HTML 标记的块,并不包含任何的 HTML 头。

注: 该选项不能和 -r 参数同时使用。

-v--version

将 PHP,PHP SAPI 和 Zend 的版本信息写入标准输出。例如:
$ php -v
PHP 4.3.0 (cli), Copyright (c) 1997-2002 The PHP Group
Zend Engine v1.3.0, Copyright (c) 1998-2002 Zend Technologies

-w--strip

显示除去了注释和多余空白的源代码。

注: 该选项不能和 -r 参数同时使用。

-z--zend-extension

加载 Zend 扩展库。如果仅给定一个文件名,PHP 将试图从当前系统扩展库的默认路径(在 Linux 系统下,该路径通常由 /etc/ld.so.conf 指定)加载该扩展库。如果用一个绝对路径指定文件名,则不会使用系统的扩展库默认路径。如果用相对路径指定的文件名,则 PHP 仅试图在当前目录的相对目录加载扩展库。

PHP 的命令行模式能使得 PHP 脚本能完全独立于 web 服务器单独运行。如果使用 Unix 系统,需要在 PHP 脚本的最前面加上一行特殊的代码,使得它能够被执行,这样系统就能知道用哪个程序去运行该脚本。在 Windows 平台下可以将 php.exe.php 文件的双击属性相关联,也可以编写一个批处理文件来用 PHP 执行脚本。为 Unix 系统增加的第一行代码不会影响该脚本在 Windows 下的运行,因此也可以用该方法编写跨平台的脚本程序。以下是一个简单的 PHP 命令行程序的范例。

例子 43-1. 试图以命令行方式运行的 PHP 脚本(script.php)

#!/usr/bin/php
<?php

if ($argc != 2 || in_array($argv[1], array('--help', '-help', '-h', '-?'))) {
?>

This is a command line PHP script with one option.

  Usage:
  <?php echo $argv[0]; ?> <option>

  <option> can be some word you would like
  to print out. With the --help, -help, -h,
  or -? options, you can get this help.

<?php
} else {
    echo $argv[1];
}
?>

在以上脚本中,用第一行特殊的代码来指明该文件应该由 PHP 来执行。在这里使用 CLI 的版本,因此不会有 HTTP 头信息输出。在用 PHP 编写命令行应用程序时,可以使用两个参数:$argc$argv。前面一个的值是比参数个数大 1 的整数(运行的脚本本身的名称也被当作一个参数)。第二个是包含有参数的数组,其第一个元素为脚本的名称,下标为数字 0($argv[0])。

以上程序中检查了参数的个数是大于 1 个还是小于 1 个。此外如果参数是 --help-help-h-? 时,打印出帮助信息,并同时动态输出脚本的名称。如果还收到了其它参数,将其显示出来。

如果希望在 Unix 下运行以上脚本,需要使其属性为可执行文件,然后简单的运行 script.php echothisscript.php -h。在 Windows 下,可以为此编写一个批处理文件:

例子 43-2. 运行 PHP 命令行脚本的批处理文件(script.bat)

@C:\php\php.exe script.php %1 %2 %3 %

假设将上述程序命名为 script.php,且 CLI 版的 php.exe 文件放置在 c:\php\cli\php.exe,该批处理文件会帮助将附加的参数传给脚本程序:script.bat echothisscript.bat -h

请参阅 Readline 扩展模块的有关文档,以获取更多的函数的信息。这些函数可以帮助完善 PHP 命令行应用程序。

VI. 函数参考

目录
I. .NET 函数
II. Advanced PHP debugger
III. Alternative PHP Cache
IV. Apache 特有函数
V. Array 数组函数
VI. Aspell 函数(已废弃)
VII. BC math 高精度数学函数
VIII. Bzip2 压缩函数
IX. Calendar 日历函数
X. CCVS API Functions [deprecated]
XI. Character Type Functions
XII. Classes/Objects 类/对象函数
XIII. Classkit Functions
XIV. ClibPDF Functions
XV. COM 和 .Net(Windows)函数
XVI. Crack Functions
XVII. Credit Mutuel CyberMUT functions
XVIII. CURL, Client URL Library Functions
XIX. Cybercash Payment Functions
XX. Cyrus IMAP administration Functions
XXI. Database (dbm-style) Abstraction Layer Functions
XXII. Date/Time 日期/时间函数
XXIII. DB++ Functions
XXIV. dBase Functions
XXV. DBM Functions [deprecated]
XXVI. dbx Functions
XXVII. Direct IO Functions
XXVIII. Directory 目录函数
XXIX. DOM Functions
XXX. DOM XML Functions
XXXI. Error Handling and Logging Functions
XXXII. Exif Functions
XXXIII. File Alteration Monitor Functions
XXXIV. filePro Functions
XXXV. Filesystem 文件系统函数
XXXVI. Firebird/InterBase Functions
XXXVII. Firebird/Interbase Functions (PDO_FIREBIRD)
XXXVIII. Forms Data Format Functions
XXXIX. FriBiDi Functions
XL. FrontBase Functions
XLI. FTP 函数
XLII. Function Handling Functions
XLIII. Gettext
XLIV. GMP Functions
XLV. GNU Readline
XLVI. GNU Recode Functions
XLVII. HTTP 函数
XLVIII. Hyperwave API Functions
XLIX. Hyperwave Functions
L. IBM DB2, Cloudscape and Apache Derby Functions
LI. ICAP Functions [deprecated]
LII. iconv Functions
LIII. ID3 Functions
LIV. IIS Administration Functions
LV. Image 图像函数
LVI. IMAP, POP3 and NNTP Functions
LVII. Informix Functions
LVIII. Ingres II Functions
LIX. IRC Gateway Functions
LX. KADM5
LXI. LDAP Functions
LXII. libxml Functions
LXIII. Lotus Notes Functions
LXIV. LZF Functions
LXV. Mail Functions
LXVI. mailparse Functions
LXVII. Math 数学函数
LXVIII. MaxDB PHP Extension
LXIX. MCAL Functions
LXX. Mcrypt Encryption Functions
LXXI. MCVE Payment Functions
LXXII. Memcache Functions
LXXIII. Mhash Functions
LXXIV. Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
LXXV. Microsoft SQL Server Functions
LXXVI. Mimetype Functions
LXXVII. Ming functions for Flash
LXXVIII. Miscellaneous Functions
LXXIX. mnoGoSearch Functions
LXXX. Mohawk Software Session Handler Functions
LXXXI. mSQL Functions
LXXXII. Multibyte String Functions
LXXXIII. muscat Functions
LXXXIV. MySQL 函数
LXXXV. MySQL Functions (PDO_MYSQL)
LXXXVI. MySQL Improved Extension
LXXXVII. Ncurses Terminal Screen Control Functions
LXXXVIII. Network Functions
LXXXIX. Net_Gopher
XC. NSAPI-specific Functions
XCI. Object Aggregation/Composition Functions
XCII. Object property and method call overloading
XCIII. ODBC and DB2 functions (PDO_ODBC)
XCIV. ODBC Functions (Unified)
XCV. oggvorbis
XCVI. OpenAL Audio Bindings
XCVII. OpenSSL Functions
XCVIII. Oracle 函数
XCIX. Oracle Functions (PDO_OCI)
C. Oracle 函数(已废弃)
CI. Output Control 输出控制函数
CII. Ovrimos SQL Functions
CIII. Paradox File Access
CIV. Parsekit Functions
CV. PDF functions
CVI. PDO Functions
CVII. PHP / Java Integration
CVIII. PHP bytecode Compiler
CIX. PHP Options&Information
CX. POSIX Functions
CXI. PostgreSQL 数据库函数
CXII. PostgreSQL Functions (PDO_PGSQL)
CXIII. PostgreSQL Session Save Handler
CXIV. PostScript document creation
CXV. Printer Functions
CXVI. Process Control Functions
CXVII. Program Execution Functions
CXVIII. Pspell Functions
CXIX. qtdom Functions
CXX. Radius
CXXI. Rar Functions
CXXII. Perl 兼容正则表达式函数
CXXIII. POSIX 扩展正则表达式函数
CXXIV. runkit Functions
CXXV. SDO Functions
CXXVI. SDO Relational Data Access Service Functions
CXXVII. SDO XML Data Access Service Functions
CXXVIII. Secure Shell2 Functions
CXXIX. Semaphore, Shared Memory and IPC Functions
CXXX. SESAM Database Functions
CXXXI. Session Handling Functions
CXXXII. Shared Memory Functions
CXXXIII. Shockwave Flash Functions
CXXXIV. SimpleXML functions
CXXXV. SNMP 函数
CXXXVI. SOAP Functions
CXXXVII. Socket Functions
CXXXVIII. SQLite Functions
CXXXIX. SQLite Functions (PDO_SQLITE)
CXL. Standard PHP Library (SPL) Functions
CXLI. Stream Functions
CXLII. String 字符串处理函数
CXLIII. Sybase Functions
CXLIV. TCP Wrappers Functions
CXLV. Tidy Functions
CXLVI. Tokenizer Functions
CXLVII. Unicode Functions
CXLVIII. URL 函数
CXLIX. Variable 变量函数
CL. Verisign Payflow Pro Functions
CLI. vpopmail Functions
CLII. W32api 函数
CLIII. WDDX Functions
CLIV. xattr Functions
CLV. xdiff Functions
CLVI. XML 语法解析函数
CLVII. XML-RPC 函数
CLVIII. XMLReader functions
CLIX. XSL functions
CLX. XSLT Functions
CLXI. YAZ Functions
CLXII. YP/NIS Functions
CLXIII. Zip File Functions (Read Only Access)
CLXIV. Zlib Compression Functions

I. .NET 函数

简介

警告

本扩展模块是实验性的。本模块的行为,包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本扩展模块风险自担。

目录
dotnet_load -- 加载一个 DOTNET 模块

dotnet_load

(no version information, might be only in CVS)

dotnet_load -- 加载一个 DOTNET 模块

说明

int dotnet_load ( string assembly_name [, string datatype_name [, int codepage]] )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

警告

本函数暂无文档,仅有参数列表。

II. Advanced PHP debugger

简介

APD is the Advanced PHP Debugger. It was written to provide profiling and debugging capabilities for PHP code, as well as to provide the ability to print out a full stack backtrace. APD supports interactive debugging, but by default it writes data to trace files. It also offers event based logging so that varying levels of information (including function calls, arguments passed, timings, etc.) can be turned on or off for individual scripts.

注意

APD is a Zend Extension, modifying the way the internals of PHP handle function calls, and thus may or may not be compatible with other Zend Extensions (for example Zend Optimizer).


安装

APD is currently available as a PECL extension from http://pecl.php.net/package/apd. Make sure you have installed the CGI version of PHP and it is available in your current path along with the phpize script.

Run the following command to download, build, and install the latest stable version of APD:
pear install apd

This automatically installs the APD Zend module into your PHP extensions directory. It is not mandatory to keep it there; you can store the module in any directory PHP can read as long as you set the zend_extension parameter accordingly.

Windows users can download the extension dll php_apd.dll from http://snaps.php.net/win32/PECL_STABLE/.

In your INI file, add the following lines:

zend_extension = /absolute/path/to/apd.so
apd.dumpdir = /absolute/path/to/trace/directory
apd.statement_tracing = 0

Depending on your PHP build, the zend_extension directive can be one of the following:

zend_extension              (non ZTS, non debug build)
zend_extension_ts           (    ZTS, non debug build)
zend_extension_debug        (non ZTS,     debug build)
zend_extension_debug_ts     (    ZTS,     debug build)


Building on Win32

To build APD under Windows you need a working PHP compilation environment as described on http://php.net/ -- basically, it requires you to have Microsoft Visual C++, win32build.zip, bison/flex, and some know how to get it to work. Also ensure that adp.dsp has DOS line endings; if it has unix line endings, Microsoft Visual C++ will complain about it.


运行时配置

这些函数的行为受 php.ini 的影响。

表格 1. APD Configuration Options

NameDefaultChangeableChangelog
apd.dumpdirNULLPHP_INI_ALL 
apd.statement_tracing"0"PHP_INI_ALL 
有关 PHP_INI_* 常量进一步的细节与定义参见附录 G

以下是配置选项的简要解释。

apd.dumpdir string

Sets the directory in which APD writes profile dump files. You can specify an absolute path or a relative path.

You can specify a different directory as an argument to apd_set_pprof_trace().

apd.statement_tracing boolean

Specfies whether or not to do per-line tracings. Turning this on (1) will impact the performance of your application.


资源类型

本扩展模块未定义任何资源类型。


预定义常量

本扩展模块未定义任何常量。


How to use PHP-APD in your scripts

  1. As the first line of your PHP script, call the apd_set_pprof_trace() function to start the trace:

    apd_set_pprof_trace();

    You can insert the line anywhere in your script, but if you do not start tracing at the beginning of your script you discard profile data that might otherwise lead you to a performance bottleneck.

  2. Now run your script. The dump output will be written to apd.dumpdir/pprof_pid.ext.

    提示: If you're running the CGI version of PHP, you will need to add the '-e' flag to enable extended information for apd to work properly. For example: php -e -f script.php

  3. To display formatted profile data, issue the pprofp command with the sort and display options of your choice. The formatted output will look something like:
    bash-2.05b$ pprofp -R /tmp/pprof.22141.0
    
    Trace for /home/dan/testapd.php
    Total Elapsed Time = 0.00
    Total System Time  = 0.00
    Total User Time    = 0.00
    
    
    Real         User        System             secs/    cumm
    %Time (excl/cumm)  (excl/cumm)  (excl/cumm) Calls    call    s/call  Memory Usage Name
    --------------------------------------------------------------------------------------
    100.0 0.00 0.00  0.00 0.00  0.00 0.00     1  0.0000   0.0009            0 main
    56.9 0.00 0.00  0.00 0.00  0.00 0.00     1  0.0005   0.0005            0 apd_set_pprof_trace
    28.0 0.00 0.00  0.00 0.00  0.00 0.00    10  0.0000   0.0000            0 preg_replace
    14.3 0.00 0.00  0.00 0.00  0.00 0.00    10  0.0000   0.0000            0 str_replace

    The -R option used in this example sorts the profile table by the amount of real time the script spent executing a given function. The "cumm call" column reveals how many times each function was called, and the "s/call" column reveals how many seconds each call to the function required, on average.

  4. To generate a calltree file that you can import into the KCacheGrind profile analysis application, issue the pprof2calltree comand.


Contact information

If you have comments, bugfixes, enhancements or want to help developing this beast, you can send an mail to apd@mail.communityconnect.com. Any help is very welcome.

目录
apd_breakpoint -- Stops the interpreter and waits on a CR from the socket
apd_callstack -- Returns the current call stack as an array
apd_clunk -- Throw a warning and a callstack
apd_continue -- Restarts the interpreter
apd_croak -- Throw an error, a callstack and then exit
apd_dump_function_table -- Outputs the current function table
apd_dump_persistent_resources -- Return all persistent resources as an array
apd_dump_regular_resources -- Return all current regular resources as an array
apd_echo -- Echo to the debugging socket
apd_get_active_symbols -- Get an array of the current variables names in the local scope
apd_set_pprof_trace -- Starts the session debugging
apd_set_session_trace -- Starts the session debugging
apd_set_session -- Changes or sets the current debugging level
apd_set_socket_session_trace -- Starts the remote session debugging
override_function -- Overrides built-in functions
rename_function -- Renames orig_name to new_name in the global function_table

apd_breakpoint

(PECL)

apd_breakpoint -- Stops the interpreter and waits on a CR from the socket

Description

bool apd_breakpoint ( int debug_level )

This can be used to stop the running of your script, and await responses on the connected socket. To step the program, just send enter (a blank line), or enter a php command to be executed. A typical session using tcplisten would look like this.

bash#tcplisten localhost 7777

APD - Advanced PHP Debugger Trace File
---------------------------------------------------------------------------
Process Pid (6118)
Trace Begun at Sun Mar 10 23:13:12 2002
---------------------------------------------------------------------------
(  0.000000): apd_set_session_trace called at /home/alan/Projects/project2/test. 
php:5
(  0.074824): apd_set_session_trace_socket() at /home/alan/Projects/project2/tes 
t.php:5 returned.  Elapsed (0.074824)
(  0.074918): apd_breakpoint() /home/alan/Projects/project2/test.php:7
              ++ argv[0] $(??) = 9
apd_breakpoint() at /home/alan/Projects/project2/test.php:7 returned.  Elapsed ( 
-2089521468.1073275368)
>\n 
statement: /home/alan/Projects/project2/test.php:8
>\n 
statement: /home/alan/Projects/project2/test.php:8
>\n 
statement: /home/alan/Projects/project2/test.php:10
>apd_echo($i);
EXEC: apd_echo($i);
0
>apd_echo(serialize(apd_get_active_symbols()));
EXEC:  apd_echo(serialize(apd_get_active_symbols()));
a:47:{i:0;s:4:"PWD";i:1;s:10:"COLORFGBG";i:2;s:11:"XAUTHORITY";i:3;s:14:"
COLORTERM_BCE";i:4;s:9:"WINDOWID";i:5;s:14:"ETERM_VERSION";i:6;s:16:"SE
SSION_MANAGER";i:7;s:4:"PS1";i:8;s:11:"GDMSESSION";i:9;s:5:"USER";i:10;s:5:"
MAIL";i:11;s:7:"OLDPWD";i:12;s:5:"LANG";i:13;s:10:"COLORTERM";i:14;s:8:"DISP
LAY";i:15;s:8:"LOGNAME";i:16;s:6:"
>apd_echo(system('ls /home/mydir'));
........
>apd_continue(0);

apd_callstack

(no version information, might be only in CVS)

apd_callstack -- Returns the current call stack as an array

Description

array apd_callstack ( void )

Returns the current call stack as an array

例子 1. apd_callstack() example

<?php
print_r(apd_callstack());
?>

apd_clunk

(no version information, might be only in CVS)

apd_clunk -- Throw a warning and a callstack

Description

void apd_clunk ( string warning [, string delimiter] )

Behaves like perl's Carp::cluck. Throw a warning and a callstack. The default line delimiter is "<BR />\n".

例子 1. apd_clunk() example

<?php
apd_clunk("Some Warning","<P>");
?>

apd_continue

(PECL)

apd_continue -- Restarts the interpreter

Description

bool apd_continue ( int debug_level )

Usually sent via the socket to restart the interpreter.

例子 1. apd_continue() example

<?php
apd_continue(0);
?>

apd_croak

(no version information, might be only in CVS)

apd_croak -- Throw an error, a callstack and then exit

Description

void apd_croak ( string warning [, string delimiter] )

Behaves like perl's Carp::croak. Throw an error, a callstack and then exit. The default line delimiter is "<BR />\n".

例子 1. apd_croak() example

<?php
apd_croak("Some Warning","<P>");
?>

apd_dump_function_table

(no version information, might be only in CVS)

apd_dump_function_table -- Outputs the current function table

Description

void apd_dump_function_table ( void )

Outputs the current function table.

例子 1. apd_dump_function_table() example

<?php
apd_dump_function_table();
?>

apd_dump_persistent_resources

(no version information, might be only in CVS)

apd_dump_persistent_resources -- Return all persistent resources as an array

Description

array apd_dump_persistent_resources ( void )

Return all persistent resources as an array.

例子 1. apd_dump_persistent_resources() example

<?php
print_r(apd_dump_persistent_resources());
?>

apd_dump_regular_resources

(no version information, might be only in CVS)

apd_dump_regular_resources -- Return all current regular resources as an array

Description

array apd_dump_regular_resources ( void )

Return all current regular resources as an array.

例子 1. apd_dump_regular_resources() example

<?php
print_r(apd_dump_regular_resources());
?>

apd_echo

(PECL)

apd_echo -- Echo to the debugging socket

Description

bool apd_echo ( string output )

Usually sent via the socket to request information about the running script.

例子 1. apd_echo() example

<?php
apd_echo($i);
?>

apd_get_active_symbols

(no version information, might be only in CVS)

apd_get_active_symbols -- Get an array of the current variables names in the local scope

Description

array apd_get_active_symbols ( )

Returns the names of all the variables defined in the active scope, (not their values)

例子 1. apd_get_active_symbols() example

<?php
apd_echo(apd_get_active_symbols());
?>

apd_set_pprof_trace

(PECL)

apd_set_pprof_trace -- Starts the session debugging

Description

void apd_set_pprof_trace ( [string dump_directory] )

Starts debugging to {dump_directory}/pprof_{process_id}, if dump_directory is not set, then the apd.dumpdir setting from the php.ini file is used.

例子 1. apd_set_pprof_trace() example

<?php
apd_set_pprof_trace();
?>

apd_set_session_trace

(no version information, might be only in CVS)

apd_set_session_trace -- Starts the session debugging

Description

void apd_set_session_trace ( int debug_level [, string dump_directory] )

Starts debugging to {dump_directory}/apd_dump_{process_id}, if dump_directory is not set, then the apd.dumpdir setting from the php.ini file is used.

debug_level is an integer which is formed by adding together the following values:

FUNCTION_TRACE      1
        ARGS_TRACE          2
        ASSIGNMENT_TRACE    4
        STATEMENT_TRACE     8
        MEMORY_TRACE        16
        TIMING_TRACE        32
        SUMMARY_TRACE       64

I would seriously not recommend using MEMORY_TRACE. It is very slow and does not appear to be accurate (great, huh?) also ASSIGNMENT_TRACE is not implemented. So, to turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99

例子 1. apd_set_session_trace() example

<?php
apd_set_session_trace(99);
?>

apd_set_session

(no version information, might be only in CVS)

apd_set_session -- Changes or sets the current debugging level

Description

void apd_set_session ( int debug_level )

This can be used to increase or decrease debugging in a different area of your application,.debug_level is an integer which is formed by adding together the following values:

FUNCTION_TRACE      1
        ARGS_TRACE          2
        ASSIGNMENT_TRACE    4
        STATEMENT_TRACE     8
        MEMORY_TRACE        16
        TIMING_TRACE        32
        SUMMARY_TRACE       64

例子 1. apd_set_session() example

<?php
apd_set_session(9);
?>

apd_set_socket_session_trace

(no version information, might be only in CVS)

apd_set_socket_session_trace -- Starts the remote session debugging

Description

bool apd_set_socket_session_trace ( string ip_address_or_unix_socket_file, int socket_type, int port, int debug_level )

Connects to the tcp server (eg. tcplisten) specified IP or Unix Domain socket (like a file), and sends debugging data to the socket. You can use any port, but higher numbers are better as most of the lower numbers may be used by other system services.

the socket_type can be APD_AF_UNIX (for file based sockets) or APD_AF_INET (for standard tcp/ip)

debug_level is an integer which is formed by adding together the following values:

FUNCTION_TRACE      1
        ARGS_TRACE          2
        ASSIGNMENT_TRACE    4
        STATEMENT_TRACE     8
        MEMORY_TRACE        16
        TIMING_TRACE        32
        SUMMARY_TRACE       64

I would seriously not recommend setting the value to 'zero' to start with, and use the breakpoint methods to start debugging at a specific place in the file.

例子 1. apd_set_socket_session_trace() example

<?php
  apd_set_socket_session_trace("127.0.0.1",APD_AF_INET,7112,0);
?>

override_function

(PECL)

override_function -- Overrides built-in functions

Description

bool override_function ( string function_name, string function_args, string function_code )

Syntax similar to create_function(). Overrides built-in functions (replaces them in the symbol table).

例子 1. override_function() example

<?php
override_function('test', '$a,$b', 'echo "DOING TEST"; return $a * $b;');
?>

rename_function

(PECL)

rename_function -- Renames orig_name to new_name in the global function_table

Description

bool rename_function ( string original_name, string new_name )

Renames orig_name to new_name in the global function_table. Useful for temporarily overriding builtin functions.

例子 1. rename_function() example

<?php
rename_function('mysql_connect', 'debug_mysql_connect' );
?>

III. Alternative PHP Cache

简介

The Alternative PHP Cache (APC) is a free and open opcode cache for PHP. It was conceived of to provide a free, open, and robust framework for caching and optimizing PHP intermediate code.


安装

PECL 扩展未绑定于 PHP 中。

进一步信息例如新版本,下载,源程序,维护者信息以及更新日志可以在此找到: http://pecl.php.net/package/apc.

可以从 PHP 下载页面或者 http://snaps.php.net/ 下载此 PECL 扩展的 DLL 文件。

注: On Windows, APC expects c:\tmp to exist, and be writable by the web server.

注: For more in-depth, highly technical documentation, see the developer-supplied TECHNOTES file .


运行时配置

这些函数的行为受 php.ini 的影响。

Although the default APC settings are fine for many installations, serious users should consider tuning the following parameters.

表格 1. APC configuration options

NameDefaultChangeableChangelog
apc.enabled1PHP_INI_ALL 
apc.shm_segments1PHP_INI_SYSTEM 
apc.shm_size30PHP_INI_SYSTEM 
apc.optimization0PHP_INI_ALL 
apc.num_files_hint1000PHP_INI_SYSTEM 
apc.ttl0PHP_INI_SYSTEM 
apc.gc_ttl3600PHP_INI_SYSTEM 
apc.cache_by_defaultOnPHP_INI_SYSTEM 
apc.filters""PHP_INI_SYSTEM 
apc.mmap_file_mask""PHP_INI_SYSTEM 
apc.slam_defense0PHP_INI_SYSTEM 
apc.file_update_protection2PHP_INI_SYSTEM 
apc.enable_cli0PHP_INI_SYSTEM> APC 3.0.6
有关 PHP_INI_* 常量进一步的细节与定义参见附录 G

以下是配置选项的简要解释。

apc.enabled boolean

apc.enabled can be set to 0 to disable APC. This is primarily useful when APC is statically compiled into PHP, since there is no other way to disable it (when compiled as a DSO, the extension line in php.ini can just be commented-out).

apc.shm_segments integer

The number of shared memory segments to allocate for the compiler cache. If APC is running out of shared memory but you have already set apc.shm_size as high as your system allows, you can try raising this value.

apc.shm_size integer

The size of each shared memory segment in MB. By default, some systems (including most BSD variants) have very low limits on the size of a shared memory segment.

apc.optimization integer

The optimization level. Zero disables the optimizer, and higher values use more aggressive optimizations. Expect very modest speed improvements. This is experimental.

apc.num_files_hint integer

A "hint" about the number of distinct source files that will be included or requested on your web server. Set to zero or omit if you're not sure; this setting is mainly useful for sites that have many thousands of source files.

apc.ttl integer

The number of seconds a cache entry is allowed to idle in a slot in case this cache entry slot is needed by another entry. Leaving this at zero means that your cache could potentially fill up with stale entries while newer entries won't be cached.

apc.gc_ttl integer

The number of seconds that a cache entry may remain on the garbage-collection list. This value provides a failsafe in the event that a server process dies while executing a cached source file; if that source file is modified, the memory allocated for the old version will not be reclaimed until this TTL reached. Set to zero to disable this feature.

apc.cache_by_default boolean

On by default, but can be set to off and used in conjunction with positive apc.filters so that files are only cached if matched by a positive filter.

apc.filters string

A comma-separated list of POSIX extended regular expressions. If any pattern matches the source filename, the file will not be cached. Note that the filename used for matching is the one passed to include/require, not the absolute path. If the first character of the expression is a + then the expression will be additive in the sense that any files matched by the expression will be cached, and if the first character is a - then anything matched will not be cached. The - case is the default, so it can be left off.

apc.mmap_file_mask string

If compiled with MMAP support by using --enable-mmap this is the mktemp-style file_mask to pass to the mmap module for determing whether your mmap'ed memory region is going to be file-backed or shared memory backed. For straight file-backed mmap, set it to something like /tmp/apc.XXXXXX (exactly 6 Xs). To use POSIX-style shm_open/mmap put a .shm somewhere in your mask. e.g. /apc.shm.XXXXXX You can also set it to /dev/zero to use your kernel's /dev/zero interface to anonymous mmap'ed memory. Leaving it undefined will force an anonymous mmap.

apc.slam_defense integer

On very busy servers whenever you start the server or modify files you can create a race of many processes all trying to cache the same file at the same time. This option sets the percentage of processes that will skip trying to cache an uncached file. Or think of it as the probability of a single process to skip caching. For example, setting apc.slam_defense to 75 would mean that there is a 75% chance that the process will not cache an uncached file. So, the higher the setting the greater the defense against cache slams. Setting this to 0 disables this feature.

apc.file_update_protection integer

When you modify a file on a live web server you really should do so in an atomic manner. That is, write to a temporary file and rename (mv) the file into its permanent position when it is ready. Many text editors, cp, tar and other such programs don't do this. This means that there is a chance that a file is accessed (and cached) while it is still being written to. This apc.file_update_protection setting puts a delay on caching brand new files. The default is 2 seconds which means that if the modification timestamp (mtime) on a file shows that it is less than 2 seconds old when it is accessed, it will not be cached. The unfortunate person who accessed this half-written file will still see weirdness, but at least it won't persist. If you are certain you always atomically update your files by using something like rsync which does this correctly, you can turn this protection off by setting it to 0. If you have a system that is flooded with io causing some update procedure to take longer than 2 seconds, you may want to increase this a bit.

apc.enable-cli integer

Mostly for testing and debugging. Setting this enables APC for the CLI version of PHP. Normally you wouldn't want to create, populate and tear down the APC cache on every CLI request, but for various test scenarios it is handy to be able to enable APC for the CLI version of APC easily.


资源类型

本扩展模块未定义任何资源类型。


预定义常量

本扩展模块未定义任何常量。

目录
apc_cache_info --  Retrieves cached information (and meta-data) from APC's data store
apc_clear_cache --  Clears the APC cache
apc_define_constants --  Defines a set of constants for later retrieval and mass-definition
apc_delete --  Removes a stored variable from the cache
apc_fetch --  Fetch a stored variable from the cache
apc_load_constants --  Loads a set of constants from the cache
apc_sma_info --  Retrieves APC's Shared Memory Allocation information
apc_store --  Cache a variable in the data store

apc_cache_info

(PECL)

apc_cache_info --  Retrieves cached information (and meta-data) from APC's data store

说明

array apc_cache_info ( [string cache_type] )

返回值

Array of cached data (and meta-data), or FALSE on failure

注: apc_cache_info() will raise a warning if it is unable to retrieve APC cache data. This typically occurs when APC is not enabled.

范例

例子 1. A apc_cache_info() example

<?php
print_r(apc_cache_info());
?>

上例的输出类似于:

Array
(
    [num_slots] => 2000
    [ttl] => 0
    [num_hits] => 9
    [num_misses] => 3
    [start_time] => 1123958803
    [cache_list] => Array
        (
            [0] => Array
                (
                    [filename] => /path/to/apc_test.php
                    [device] => 29954
                    [inode] => 1130511
                    [type] => file
                    [num_hits] => 1
                    [mtime] => 1123960686
                    [creation_time] => 1123960696
                    [deletion_time] => 0
                    [access_time] => 1123962864
                    [ref_count] => 1
                    [mem_size] => 677
                )
            [1] => Array (...iterates for each cached file)
)

apc_clear_cache

(PECL)

apc_clear_cache --  Clears the APC cache

说明

bool apc_clear_cache ( [string cache_type] )

apc_define_constants

(PECL)

apc_define_constants --  Defines a set of constants for later retrieval and mass-definition

说明

bool apc_define_constants ( string key, array constants [, bool case_sensitive] )

define() is notoriously slow. Since the main benefit of APC is to increase the performance of scripts/applications, this mechanism is provided to streamline the process of mass constant definition.

注: To remove a set of stored constants (without clearing the entire cache), an empty array may be passed as the constants parameter, effectively clearing the stored value(s).

参数

key

The key serves as the name of the constant set being stored. This key is used to retrieve the stored constants in apc_load_constants().

constants

An associative array of constant_name => value pairs. The constant_name must follow the normal constant naming rules. value must evaluate to a scalar value.

case_sensitive

The default behaviour for constants is to be declared case-sensitive; i.e. CONSTANT and Constant represent different values. If this parameter evaluates to FALSE the constants will be declared as case-insensitive symbols.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

范例

例子 1. apc_define_constants() example

<?php
$constants = array(
    'ONE'   => 1,
    'TWO'   => 2,
    'THREE' => 3,
);
apc_define_constants('numbers', $constants);
apc_load_constants('numbers');
echo ONE, TWO, THREE;
?>

上例将输出:

123

apc_delete

(PECL)

apc_delete --  Removes a stored variable from the cache

说明

bool apc_delete ( string key )

参数

key

The key used to store the value (with apc_store()).

返回值

如果成功则返回 TRUE,失败则返回 FALSE

范例

例子 1. A apc_delete() example

<?php
$bar = 'BAR';
apc_store('foo', $bar);
apc_delete('foo'));
// this is obviously useless in this form
?>

apc_fetch

(PECL)

apc_fetch --  Fetch a stored variable from the cache

说明

mixed apc_fetch ( string key )

参数

key

The key used to store the value (with apc_store()).

返回值

The stored variable on success; FALSE on failure

范例

例子 1. A apc_fetch() example

<?php
$bar = 'BAR';
apc_store('foo', $bar);
var_dump(apc_fetch('foo'));
?>

上例将输出:

string(3) "BAR"

apc_load_constants

(PECL)

apc_load_constants --  Loads a set of constants from the cache

说明

bool apc_load_constants ( string key [, bool case_sensitive] )

参数

key

The name of the constant set (that was stored with apc_define_constants()) to be retrieved.

case_sensitive

The default behaviour for constants is to be declared case-sensitive; i.e. CONSTANT and Constant represent different values. If this parameter evaluates to FALSE the constants will be declared as case-insensitive symbols.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

范例

例子 1. apc_load_constants() example

<?php
$constants = array(
    'ONE'   => 1,
    'TWO'   => 2,
    'THREE' => 3,
);
apc_define_constants('numbers', $constants);
apc_load_constants('numbers');
echo ONE, TWO, THREE;
?>

上例将输出:

123

apc_sma_info

(PECL)

apc_sma_info --  Retrieves APC's Shared Memory Allocation information

说明

array apc_sma_info ( void )

返回值

Array of Shared Memory Allocation data; FALSE on failure.

范例

例子 1. A apc_sma_info() example

<?php
print_r(apc_sma_info());
?>

上例的输出类似于:

Array
(
    [num_seg] => 1
    [seg_size] => 31457280
    [avail_mem] => 31448408
    [block_lists] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [size] => 31448408
                            [offset] => 8864
                        )

                )

        )

)

apc_store

(PECL)

apc_store --  Cache a variable in the data store

说明

bool apc_store ( string key, mixed var [, int ttl] )

注: Unlike many other mechanisms in PHP, variables stored using apc_store() will persist between requests (until the value is removed from the cache).

参数

key

Store the variable using this name. keys are cache-unique, so storing a second value with the same key will overwrite the original value.

var

The variable to store

ttl

Time To Live; store var in the cache for ttl seconds. After the ttl has passed, the stored variable will be expunged from the cache (on the next request). If no ttl is supplied (or if the ttl is 0), the value will persist until it is removed from the cache manually, or otherwise fails to exist in the cache (clear, restart, etc.).

返回值

如果成功则返回 TRUE,失败则返回 FALSE

范例

例子 1. A apc_store() example

<?php
$bar = 'BAR';
apc_store('foo', $bar);
var_dump(apc_fetch('foo'));
?>

上例将输出:

string(3) "BAR"

IV. Apache 特有函数

简介

本类函数仅在 PHP 作为 Apache 的模块运行时可用。

注: 自 PHP 4.3.2 起,Apache 2 SAPI 中不再像和 Apache 1 中相反那样隐含设定 PATH_TRANSLATED,它将被设为 SCRIPT_FILENAME 服务器环境变量而不是由 Apache 产生。此修改是为了符合 CGI 规范,PATH_TRANSLATED 应仅在定义了 PATH_INFO 之时才有效。

Apache 2 用户可以在 httpd.conf 中使用 AcceptPathInfo = On 来定义 PATH_INFO


安装

PHP 在 Apache 中的安装见安装一章。


运行时配置

Apache 的 PHP 模块的行为受 php.ini 的设置影响。在 php.ini 中的设置可以被服务器配置文件或本地的 .htaccess 文件中的 php_flag 设置所覆盖。

例子 1. 用 .htaccess 禁用一个目录的 PHP 解析

php_flag engine off

表格 1. Apache 配置选项

名称默认值可修改范围更新记录
engine"1"PHP_INI_ALL自 PHP 4.0.5 起可用
child_terminate"0"PHP_INI_ALL自 PHP 4.0.5 起可用
last_modified"0"PHP_INI_ALL自 PHP 4.0.5 起可用
xbithack"0"PHP_INI_ALL自 PHP 4.0.5 起可用
有关 PHP_INI_* 常量进一步的细节与定义参见附录 G

以下是配置选项的简要解释。

engine boolean

打开或关闭 PHP 解析。本指令仅在使用 PHP 的 Apache 模块版本时才有用。可以基于目录或者虚拟主机来打开或者关闭 PHP。将 engine off 放到 httpd.conf 文件中适当的位置就可以激活或禁用 PHP。

child_terminate boolean

指定 PHP 脚本在请求结束后是否可以要求终止子进程。参见 apache_child_terminate()

last_modified boolean

在本次请求中发送一个头信息 Last-Modified:,显示 PHP 脚本最后被修改的日期。

xbithack boolean

不管文件结尾是什么,将文件作为 PHP 以可执行位组来解析。


资源类型

本扩展模块未定义任何资源类型。


预定义常量

本扩展模块未定义任何常量。

目录
apache_child_terminate -- 在本次请求结束后终止 apache 进程
apache_get_modules -- Get a list of loaded Apache modules
apache_get_version -- Fetch Apache version
apache_getenv -- Get an Apache subprocess_env variable
apache_lookup_uri -- 对指定的 URI 执行部分请求并返回所有有关信息
apache_note -- 取得或设置 apache 请求记录
apache_request_headers -- Fetch all HTTP request headers
apache_reset_timeout -- Reset the Apache write timer
apache_response_headers -- Fetch all HTTP response headers
apache_setenv -- Set an Apache subprocess_env variable
ascii2ebcdic -- Translate string from ASCII to EBCDIC
ebcdic2ascii -- Translate string from EBCDIC to ASCII
getallheaders -- Fetch all HTTP request headers
virtual -- Perform an Apache sub-request

apache_child_terminate

(PHP 4 >= 4.0.5, PHP 5)

apache_child_terminate -- 在本次请求结束后终止 apache 进程

说明

bool apache_child_terminate ( void )

apache_child_terminate() 将把运行当前 PHP 请求的 Apache 进程注册为终止状态,一旦结束 PHP 代码的运行此进程将终止。可以用在占用大量内存的脚本后面来终止该进程,因为通常内存只在内部释放而不会还给操作系统。

返回值

如果 PHP 以 Apache 1 模块方式运行,且 Apache 的版本是非多线程的,以及激活了 PHP 指令 child_terminate,则返回 TRUE。如果不满足上述条件则返回 FALSE 并生成一条 E_WARNING 级的错误信息。

注释

注: 本函数未在 Windows 平台下实现。

参见

exit()

apache_get_modules

(PHP 4 >= 4.3.2, PHP 5)

apache_get_modules -- Get a list of loaded Apache modules

说明

array apache_get_modules ( void )

Get a list of loaded Apache modules.

返回值

An array of loaded Apache modules.

更新日志

版本说明
5.0.0 Became available when using Apache 1, or the PHP Apache 2 filter API. Before this time, it was only available when using the Apache 2 handler API.

范例

例子 1. apache_get_modules() example

<?php
print_r(apache_get_modules());
?>

上例的输出类似于:

Array
(
    [0] => core
    [1] => http_core
    [2] => mod_so
    [3] => sapi_apache2
    [4] => mod_mime
    [5] => mod_rewrite
)

apache_get_version

(PHP 4 >= 4.3.2, PHP 5)

apache_get_version -- Fetch Apache version

说明

string apache_get_version ( void )

Fetch the Apache version.

返回值

Returns the Apache version on success, or FALSE on failure.

更新日志

版本说明
4.3.4 Became available with Apache 1.
5.0.0 Became available with the Apache 2 filter API.

范例

例子 1. apache_get_version() example

<?php
$version = apache_get_version();
echo "$version\n";
?>

上例的输出类似于:

Apache/1.3.29 (Unix) PHP/4.3.4

参见

phpinfo()

apache_getenv

(PHP 4 >= 4.3.0, PHP 5)

apache_getenv -- Get an Apache subprocess_env variable

说明

string apache_getenv ( string variable [, bool walk_to_top] )

Get an Apache environment variable as specified by variable.

This function requires Apache 2 otherwise it's undefined.

参数

variable

The Apache environment variable

walk_to_top

Whether to get the top-level variable available to all Apache layers.

返回值

The value of the Apache environment variable on success, or FALSE on failure

范例

例子 1. apache_getenv() example

The example above shows how to retrieve the value of the Apache environment variable SERVER_ADDR.

<?php
$ret = apache_getenv("SERVER_ADDR");
echo $ret;
?>

上例的输出类似于:

42.24.42.240

参见

apache_sentenv()
getenv()
Superglobals

apache_lookup_uri

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

apache_lookup_uri -- 对指定的 URI 执行部分请求并返回所有有关信息

说明

object apache_lookup_uri ( string filename )

本函数对一个 URL 执行部分请求。取得所有有关给定资源的重要信息后就停手。

此函数仅在 PHP 作为 Apache 模块安装时才可使用。

参数

filename

被请求的文件名(URI),失败时为 FALSE

返回值

一个有关 URI 信息的 object。此 object 的属性有:

status
the_request
status_line
method
content_type
handler
uri
filename
path_info
args
boundary
no_cache
no_local_copy
allowed
send_bodyct
bytes_sent
byterange
clength
unparsed_uri
mtime
request_time

范例

例子 1. apache_lookup_uri() 例子

<?php
$info = apache_lookup_uri('index.php?var=value');
print_r($info);

if (file_exists($info->filename)) {
    echo 'file exists!';
}
?>

上例的输出类似于:

stdClass Object
(
    [status] => 200
    [the_request] => GET /dir/file.php HTTP/1.1
    [method] => GET
    [mtime] => 0
    [clength] => 0
    [chunked] => 0
    [content_type] => application/x-httpd-php
    [no_cache] => 0
    [no_local_copy] => 1
    [unparsed_uri] => /dir/index.php?var=value
    [uri] => /dir/index.php
    [filename] => /home/htdocs/dir/index.php
    [args] => var=value
    [allowed] => 0
    [sent_bodyct] => 0
    [bytes_sent] => 0
    [request_time] => 1074282764
)
file exists!

apache_note

(PHP 3 >= 3.0.2, PHP 4, PHP 5)

apache_note -- 取得或设置 apache 请求记录

说明

string apache_note ( string note_name [, string note_value] )

apache_note() 是用于 Apache 的函数,可以取得或者设置请求 notes 表中的值。

参数

note_name

note 名。

note_value

note 值。

返回值

如果只有一个参数调用,则返回记录 note_name 的当前值。如果用两个参数调用,则将记录 note_name 的值设为 note_value 并返回记录 note_name 的前一个值。如果未能获取记录,则返回 FALSE

apache_request_headers

(PHP 4 >= 4.3.0, PHP 5)

apache_request_headers -- Fetch all HTTP request headers

说明

array apache_request_headers ( void )

Fetches all HTTP requests from the current request.

此函数仅在 PHP 作为 Apache 模块安装时才可使用。

返回值

An associative array of all the HTTP headers in the current request, or FALSE on failure.

范例

例子 1. apache_request_headers() example

<?php
$headers = apache_request_headers();

foreach ($headers as $header => $value) {
    echo "$header: $value <br />\n";
}
?>

上例的输出类似于:

Accept: */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0
Host: www.example.com
Connection: Keep-Alive

注释

注: Prior to PHP 4.3.0, apache_request_headers() was called getallheaders(). After PHP 4.3.0, getallheaders() is an alias for apache_request_headers().

注: You can also get at the value of the common CGI variables by reading them from the environment, which works whether or not you are using PHP as an Apache module. Use phpinfo() to see a list of all of the available environment variables.

注: 自 PHP 4.3.3 起也可以在 Netscape/iPlanet/SunONE 服务器的 NSAPI server module 中使用本函数。

apache_reset_timeout

(no version information, might be only in CVS)

apache_reset_timeout -- Reset the Apache write timer

说明

bool apache_reset_timeout ( void )

apache_reset_timeout() resets the Apache write timer, which defaults to 300 seconds. With set_time_limit(0); ignore_user_abort(true) and periodic apache_reset_timeout() calls, Apache can theoretically run forever.

This function requires Apache 1.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

注释

注: 本函数在安全模式下被禁用。

apache_response_headers

(PHP 4 >= 4.3.0, PHP 5)

apache_response_headers -- Fetch all HTTP response headers

说明

array apache_response_headers ( void )

Fetch all HTTP response headers.

返回值

An array of all Apache response headers on success, or FALSE on failure.

范例

例子 1. apache_response_headers() example

<?php
print_r(apache_response_headers());
?>

上例的输出类似于:

Array
(
    [Accept-Ranges] => bytes
    [X-Powered-By] => PHP/4.3.8
)

注释

注: 自 PHP 4.3.3 起也可以在 Netscape/iPlanet/SunONE 服务器的 NSAPI server module 中使用本函数。

apache_setenv

(PHP 4 >= 4.2.0, PHP 5)

apache_setenv -- Set an Apache subprocess_env variable

说明

bool apache_setenv ( string variable, string value [, bool walk_to_top] )

apache_setenv() sets the value of the Apache environment variable specified by variable.

注: When setting an Apache environment variable, the corresponding $_SERVER variable is not changed.

参数

variable

The environment variable that's being set.

value

The new variable value.

walk_to_top

Whether to set the top-level variable available to all Apache layers.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

范例

例子 1. Setting an Apache environment variable using apache_setenv()

<?php
apache_setenv("EXAMPLE_VAR", "Example Value");
?>

注释

注: apache_setenv() can be paired up with apache_getenv() across separate pages or for setting variables to pass to Server Side Includes (.shtml) that have been included in PHP scripts.

ascii2ebcdic

(PHP 3 >= 3.0.17)

ascii2ebcdic -- Translate string from ASCII to EBCDIC

说明

int ascii2ebcdic ( string ascii_str )

ascii2ebcdic() is an Apache-specific function which is available only on EBCDIC based operating systems (OS/390, BS2000). It translates the ASCII encoded string ascii_str to its equivalent EBCDIC representation (binary safe), and returns the result.

参数

ascii_str

The ASCII string that will be translated.

返回值

The EBCDIC representation of an ASCII string.

ebcdic2ascii

(PHP 3 >= 3.0.17)

ebcdic2ascii -- Translate string from EBCDIC to ASCII

说明

int ebcdic2ascii ( string ebcdic_str )

ebcdic2ascii() is an Apache-specific function which is available only on EBCDIC based operating systems (OS/390, BS2000). It translates the EBCDIC encoded string ebcdic_str to its equivalent ASCII representation (binary safe), and returns the result.

参数

ebcdic_str

The EBCDIC string that will be translated.

返回值

The ASCII representation of an EBCDIC string.

getallheaders

(PHP 3, PHP 4, PHP 5)

getallheaders -- Fetch all HTTP request headers

说明

array getallheaders ( void )

Fetches all HTTP requests from the current request.

This function is an alias for apache_request_headers(). Please read the apache_request_headers() documentation for more information on how this function works.

此函数仅在 PHP 作为 Apache 模块安装时才可使用。

返回值

An associative array of all the HTTP headers in the current request, or FALSE on failure.

更新日志

版本说明
4.3.0 Became an alias for apache_request_headers(). Essentially, it was renamed. This is because this function only works with Apache.

注释

注: 自 PHP 4.3.3 起也可以在 Netscape/iPlanet/SunONE 服务器的 NSAPI server module 中使用本函数。

virtual

(PHP 3, PHP 4, PHP 5)

virtual -- Perform an Apache sub-request

说明

bool virtual ( string filename )

virtual() is an Apache-specific function which is equivalent to <!--#include virtual...--> in mod_include. It performs an Apache sub-request. It is useful for including CGI scripts or .shtml files, or anything else that you would parse through Apache. Note that for a CGI script, the script must generate valid CGI headers. At the minimum that means it must generate a Content-type header.

To run the sub-request, all buffers are terminated and flushed to the browser, pending headers are sent too.

此函数仅在 PHP 作为 Apache 模块安装时才可使用。

参数

filename

The file that the virtual command will be performed on.

返回值

Performs the virtual command on success, or returns FALSE on failure.

更新日志

版本说明
4.0.6 This function may be used on PHP files. However, it is typically better to use include() or require() for PHP files.

注释

警告

The query string can be passed to the included file but $_GET is copied from the parent script and only $_SERVER['QUERY_STRING'] is filled with the passed query string. The query string may only be passed when using Apache 2. The requested file will not be listed in the Apache access log.

注: 自 PHP 4.3.3 起也可以在 Netscape/iPlanet/SunONE 服务器的 NSAPI server module 中使用本函数。

V. Array 数组函数

简介

本类函数允许用多种方法来操作数组和与之交互。数组的本质是储存,管理和操作一组变量。

PHP 支持一维和多维数组,可以是用户创建或由另一个函数创建。有一些特定的数据库处理函数可以从数据库查询中生成数组,还有一些函数返回数组。

参见手册中的数组一节关于 PHP 是怎样实现和使用数组的详细解释。参见数组运算符一节关于怎样操作数组的其它方法。


需求

要编译本扩展模块不需要外部库文件。


安装

本函数库作为 PHP 内核的一部分,不用安装就能使用。


运行时配置

本扩展模块在 php.ini 中未定义任何配置选项。


资源类型

本扩展模块未定义任何资源类型。


预定义常量

以下常量作为 PHP 核心的一部分一直有效。

CASE_LOWER (integer)

CASE_LOWER 用在 array_change_key_case() 中将数组的键名转换成小写字母。这也是 array_change_key_case() 的默认值。

CASE_UPPER (integer)

CASE_UPPER 用在 array_change_key_case() 中将数组的键名转换成大写字母。

排序顺序标识:

SORT_ASC (integer)

SORT_ASC 用在 array_multisort() 函数中,使其升序排列。

SORT_DESC (integer)

SORT_DESC 用在 array_multisort() 函数中,使其降序排列。

排序类型标识:用于各种排序函数

SORT_REGULAR (integer)

SORT_REGULAR 用于对对象进行通常比较。

SORT_NUMERIC (integer)

SORT_NUMERIC 用于对对象进行数值比较。

SORT_STRING (integer)

SORT_STRING 用于对对象进行字符串比较。

SORT_LOCALE_STRING (integer)

SORT_LOCALE_STRING 基于当前区域来对对象进行字符串比较。PHP 4.4.0 和 5.0.2 新加。

COUNT_NORMAL (integer)

COUNT_RECURSIVE (integer)

EXTR_OVERWRITE (integer)

EXTR_SKIP (integer)

EXTR_PREFIX_SAME (integer)

EXTR_PREFIX_ALL (integer)

EXTR_PREFIX_INVALID (integer)

EXTR_PREFIX_IF_EXISTS (integer)

EXTR_IF_EXISTS (integer)

EXTR_REFS (integer)


参见

参见 is_array()explode()implode()split()preg_split()unset()

【译者注】本章中出现的“关联数组”或“结合数组”指的是键名为字符串的数组,“索引”和“键名”指的是同一样东西。“索引”多指数组的数字形式的下标。

目录
array_change_key_case -- 返回字符串键名全为小写或大写的数组
array_chunk -- 将一个数组分割成多个
array_combine --  创建一个数组,用一个数组的值作为其键名,另一个数组的值作为其值
array_count_values -- 统计数组中所有的值出现的次数
array_diff_assoc -- 带索引检查计算数组的差集
array_diff_key -- 使用键名比较计算数组的差集
array_diff_uassoc -- 用用户提供的回调函数做索引检查来计算数组的差集
array_diff_ukey -- 用回调函数对键名比较计算数组的差集
array_diff -- 计算数组的差集
array_fill -- 用给定的值填充数组
array_filter --  用回调函数过滤数组中的单元
array_flip -- 交换数组中的键和值
array_intersect_assoc -- 带索引检查计算数组的交集
array_intersect_key -- 使用键名比较计算数组的交集
array_intersect_uassoc -- 带索引检查计算数组的交集,用回调函数比较索引
array_intersect_ukey -- 用回调函数比较键名来计算数组的交集
array_intersect -- 计算数组的交集
array_key_exists -- 检查给定的键名或索引是否存在于数组中
array_keys -- 返回数组中所有的键名
array_map --  将回调函数作用到给定数组的单元上
array_merge_recursive -- 递归地合并一个或多个数组
array_merge -- 合并一个或多个数组
array_multisort -- 对多个数组或多维数组进行排序
array_pad --  用值将数组填补到指定长度
array_pop -- 将数组最后一个单元弹出(出栈)
array_product -- 计算数组中所有值的乘积
array_push --  将一个或多个单元压入数组的末尾(入栈)
array_rand --  从数组中随机取出一个或多个单元
array_reduce -- 用回调函数迭代地将数组简化为单一的值
array_reverse --  返回一个单元顺序相反的数组
array_search --  在数组中搜索给定的值,如果成功则返回相应的键名
array_shift --  将数组开头的单元移出数组
array_slice -- 从数组中取出一段
array_splice --  把数组中的一部分去掉并用其它值取代
array_sum --  计算数组中所有值的和
array_udiff_assoc -- 带索引检查计算数组的差集,用回调函数比较数据
array_udiff_uassoc -- 带索引检查计算数组的差集,用回调函数比较数据和索引
array_udiff -- 用回调函数比较数据来计算数组的差集
array_uintersect_assoc -- 带索引检查计算数组的交集,用回调函数比较数据
array_uintersect_uassoc -- 带索引检查计算数组的交集,用回调函数比较数据和索引
array_uintersect -- 计算数组的交集,用回调函数比较数据
array_unique -- 移除数组中重复的值
array_unshift --  在数组开头插入一个或多个单元
array_values -- 返回数组中所有的值
array_walk_recursive -- 对数组中的每个成员递归地应用用户函数
array_walk -- 对数组中的每个成员应用用户函数
array --  新建一个数组
arsort --  对数组进行逆向排序并保持索引关系
asort -- 对数组进行排序并保持索引关系
compact --  建立一个数组,包括变量名和它们的值
count -- 计算数组中的单元数目或对象中的属性个数
current -- 返回数组中的当前单元
each --  返回数组中当前的键/值对并将数组指针向前移动一步
end --  将数组的内部指针指向最后一个单元
extract --  从数组中将变量导入到当前的符号表
in_array -- 检查数组中是否存在某个值
key -- 从关联数组中取得键名
krsort -- 对数组按照键名逆向排序
ksort -- 对数组按照键名排序
list --  把数组中的值赋给一些变量
natcasesort --  用“自然排序”算法对数组进行不区分大小写字母的排序
natsort --  用“自然排序”算法对数组排序
next --  将数组中的内部指针向前移动一位
pos -- current() 的别名
prev -- 将数组的内部指针倒回一位
range --  建立一个包含指定范围单元的数组
reset --  将数组的内部指针指向第一个单元
rsort -- 对数组逆向排序
shuffle -- 将数组打乱
sizeof -- count() 的别名
sort -- 对数组排序
uasort --  使用用户自定义的比较函数对数组中的值进行排序并保持索引关联
uksort --  使用用户自定义的比较函数对数组中的键名进行排序
usort --  使用用户自定义的比较函数对数组中的值进行排序

array_change_key_case

(PHP 4 >= 4.2.0, PHP 5)

array_change_key_case -- 返回字符串键名全为小写或大写的数组

说明

array array_change_key_case ( array input [, int case] )

array_change_key_case()input 数组中的所有键名改为全小写或大写。改变是根据后一个选项 case 参数来进行的。可以在这里用两个常量,CASE_UPPERCASE_LOWER。默认值是 CASE_LOWER。本函数不改变数字索引。

例子 1. array_change_key_case() 例子

<?php
$input_array = array("FirSt" => 1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));
?>

上例将输出:

Array
(
    [FIRST] => 1
    [SECOND] => 4
)

如果一个数组中的多个键名经过本函数后变成一样的话(例如 "keY" 和 "kEY"),最后一个值将覆盖其它的值。

array_chunk

(PHP 4 >= 4.2.0, PHP 5)

array_chunk -- 将一个数组分割成多个

说明

array array_chunk ( array input, int size [, bool preserve_keys] )

array_chunk() 将一个数组分割成多个数组,其中每个数组的单元数目由 size 决定。最后一个数组的单元数目可能会少几个。得到的数组是一个多维数组中的单元,其索引从零开始。

将可选参数 preserve_keys 设为 TRUE,可以使 PHP 保留输入数组中原来的键名。如果你指定了 FALSE,那每个结果数组将用从零开始的新数字索引。默认值是 FALSE

例子 1. array_chunk() 例子

<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, true));
?>

上例将输出:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [2] => c
            [3] => d
        )

    [2] => Array
        (
            [4] => e
        )

)

array_combine

(PHP 5)

array_combine --  创建一个数组,用一个数组的值作为其键名,另一个数组的值作为其值

说明

array array_combine ( array keys, array values )

返回一个 array,用来自 keys 数组的值作为键名,来自 values 数组的值作为相应的值。

如果两个数组的单元数不同或者数组为空时返回 FALSE

例子 1. 简单的 array_combine() 例子

<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?>

上例将输出:

Array
(
    [green]  => avocado
    [red]    => apple
    [yellow] => banana
)

参见 array_merge()array_walk()array_values()

array_count_values

(PHP 4, PHP 5)

array_count_values -- 统计数组中所有的值出现的次数

说明

array array_count_values ( array input )

array_count_values() 返回一个数组,该数组用 input 数组中的值作为键名,该值在 input 数组中出现的次数作为值。

例子 1. array_count_values() 例子

<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values ($array));
?>

上例将输出:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

参见 count()array_unique()array_values()count_chars()

array_diff_assoc

(PHP 4 >= 4.3.0, PHP 5)

array_diff_assoc -- 带索引检查计算数组的差集

说明

array array_diff_assoc ( array array1, array array2 [, array ...] )

array_diff_assoc() 返回一个数组,该数组包括了所有在 array1 中但是不在任何其它参数数组中的值。注意和 array_diff() 不同的是键名也用于比较。

例子 1. array_diff_assoc() 例子

<?php
$array1 = array ("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array ("a" => "green", "yellow", "red");
$result = array_diff_assoc($array1, $array2);
?>

上例将输出:

Array
(
    [b] => brown
    [c] => blue
    [0] => red
)

上面的例子中可以看到键值对 "a" => "green" 在两个数组中都有,因此不在本函数的输出中。与此不同,键值对 0 => "red" 出现在输出中是因为第二个参数中的 "red" 的键名是 1

键值对 key => value 中的两个值仅在 (string) $elem1 === (string) $elem2 时被认为相等。也就是说使用了严格检查,字符串的表达必须相同。

注: 注意本函数只检查了多维数组中的一维。当然可以用 array_diff_assoc($array1[0], $array2[0]); 检查更深的维度。

参见 array_diff()array_intersect()array_intersect_assoc()

array_diff_key

(PHP 5 >= 5.1.0RC1)

array_diff_key -- 使用键名比较计算数组的差集

说明

array array_diff_key ( array array1, array array2 [, array ...] )

array_diff_key() 返回一个数组,该数组包括了所有出现在 array1 中但是未出现在任何其它参数数组中的键名的值。注意关联关系保留不变。本函数和 array_diff() 相同只除了比较是根据键名而不是值来进行的。

例子 1. array_diff_key() 例子

<?php
$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_diff_key($array1, $array2));
?>

上例将输出:

array(2) {
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}

key => value 对中的两个键名仅在 (string) $key1 === (string) $key2 时被认为相等。换句话说,执行的是严格类型检查,因此字符串的表达必须完全一样。

注: 注意本函数只检查了多维数组中的一维。当然,可以用 array_diff_key($array1[0], $array2[0]); 来检查更深的维度。

参见 array_diff()array_udiff()array_diff_assoc()array_diff_uassoc()array_udiff_assoc()array_udiff_uassoc()array_diff_ukey()array_intersect()array_intersect_assoc()array_intersect_uassoc()array_intersect_key()array_intersect_ukey()

array_diff_uassoc

(PHP 5)

array_diff_uassoc -- 用用户提供的回调函数做索引检查来计算数组的差集

说明

array array_diff_uassoc ( array array1, array array2 [, array ..., callback key_compare_func] )

array_diff_uassoc() 返回一个数组,该数组包括了所有在 array1 中但是不在任何其它参数数组中的值。注意和 array_diff() 不同的是键名也用于比较。

此比较是通过用户提供的回调函数来进行的。如果认为第一个参数小于,等于,或大于第二个参数时必须分别返回一个小于零,等于零,或大于零的整数。这和 array_diff_assoc() 不同的是还使用了比较索引的内部函数。

例子 1. array_diff_uassoc() 例子

<?php
function key_compare_func($a, $b)
{
    if ($a === $b) {
        return 0;
    }
    return ($a > $b)? 1:-1;
}

$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_uassoc($array1, $array2, "key_compare_func");
print_r($result);
?>

上例将输出:

Array
(
    [b] => brown
    [c] => blue
    [0] => red
)

上面的例子中 "a" => "green" 出现在两个数组中因此不在函数的输出中。但是 0 => "red" 却在输出中,因为第二个参数中的 "red" 的键名是 1

两个索引是否相同是由用户提供的回调函数来检查的。

注: 注意本函数只检查了多维数组中的一维。当然可以用 array_diff_uassoc($array1[0], $array2[0], "key_compare_func"); 检查更深的维度。

参见 array_diff()array_diff_assoc()array_udiff()array_udiff_assoc()array_udiff_uassoc()array_intersect()array_intersect_assoc()array_uintersect()array_uintersect_assoc()array_uintersect_uassoc()

array_diff_ukey

(PHP 5 >= 5.1.0RC1)

array_diff_ukey -- 用回调函数对键名比较计算数组的差集

说明

array array_diff_ukey ( array array1, array array2 [, array ..., callback key_compare_func] )

array_diff_ukey() 返回一个数组,该数组包括了所有出现在 array1 中但是未出现在任何其它参数数组中的键名的值。注意关联关系保留不变。本函数和 array_diff() 相同只除了比较是根据键名而不是值来进行的。

此比较是通过用户提供的回调函数来进行的。如果认为第一个参数小于,等于,或大于第二个参数时必须分别返回一个小于零,等于零,或大于零的整数。

例子 1. array_diff_ukey() 例子

<?php
function key_compare_func($key1, $key2)
{
    if ($key1 == $key2)
        return 0;
    else if ($key1 > $key2)
        return 1;
    else
        return -1;
}

$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_diff_ukey($array1, $array2, 'key_compare_func'));
?>

上例将输出:

array(2) {
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}

注: 注意本函数只检查了多维数组中的一维。当然,可以用 array_diff_ukey($array1[0], $array2[0], 'callback_func'); 来检查更深的维度。

参见 array_diff()array_udiff()array_diff_assoc()array_diff_uassoc()array_udiff_assoc()array_udiff_uassoc()array_diff_key()array_intersect()array_intersect_assoc()array_intersect_uassoc()array_intersect_key()array_intersect_ukey()

array_diff

(PHP 4 >= 4.0.1, PHP 5)

array_diff -- 计算数组的差集

说明

array array_diff ( array array1, array array2 [, array ...] )

array_diff() 返回一个数组,该数组包括了所有在 array1 中但是不在任何其它参数数组中的值。注意键名保留不变。

例子 1. array_diff() 例子

<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);
?>

在 $array1 中多次出现的值一样处理,输出结果为:

Array
(
    [1] => blue
)

注: 两个单元仅在 (string) $elem1 === (string) $elem2 时被认为是相同的。也就是说,当字符串的表达是一样的时候。

注: 注意本函数只检查了多维数组中的一维。当然可以用 array_diff($array1[0], $array2[0]); 检查更深的维度。

警告

本函数在 PHP 4.0.4 中是坏的!

参见 array_diff_assoc()array_intersect()array_intersect_assoc()

array_fill

(PHP 4 >= 4.2.0, PHP 5)

array_fill -- 用给定的值填充数组

说明

array array_fill ( int start_index, int num, mixed value )

array_fill()value 参数的值将一个数组填充 num 个条目,键名由 start_index 参数指定的开始。注意 num 必须是一个大于零的数值,否则 PHP 会发出一条警告。

例子 1. array_fill() 例子

<?php
$a = array_fill(5, 6, 'banana');
print_r($a);
?>

$a 现在是:

Array
(
    [5]  => banana
    [6]  => banana
    [7]  => banana
    [8]  => banana
    [9]  => banana
    [10] => banana
)

参见 str_repeat()range()

array_filter

(PHP 4 >= 4.0.6, PHP 5)

array_filter --  用回调函数过滤数组中的单元

说明

array array_filter ( array input [, callback callback] )

array_filter() 依次将 input 数组中的每个值传递到 callback 函数。如果 callback 函数返回 TRUE,则 input 数组的当前值会被包含在返回的结果数组中。数组的键名保留不变。

例子 1. array_filter() 例子

<?php
function odd($var)
{
    return($var % 2 == 1);
}

function even($var)
{
    return($var % 2 == 0);
}

$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);

echo "Odd :\n";
print_r(array_filter($array1, "odd"));
echo "Even:\n";
print_r(array_filter($array2, "even"));
?>

上例将输出:

Odd :
Array
(
    [a] => 1
    [c] => 3
    [e] => 5
)
Even:
Array
(
    [0] => 6
    [2] => 8
    [4] => 10
    [6] => 12
)

用户不应在回调函数中修改数组本身。例如增加/删除单元或者对 array_filter() 正在作用的数组进行 unset。如果数组改变了,此函数的行为没有定义。

如果没有提供 callback 函数,array_filter() 将删除 input 中所有等值为 FALSE 的条目。更多信息见转换为布尔值

例子 2. array_filter()callback

<?php

$entry = array(
             0 => 'foo',
             1 => false,
             2 => -1,
             3 => null,
             4 => ''
          );

print_r(array_filter($entry));
?>

上例将输出:

Array
(
    [0] => foo
    [2] => -1
)

参见 array_map()array_reduce()array_walk()

array_flip

(PHP 4, PHP 5)

array_flip -- 交换数组中的键和值

说明

array array_flip ( array trans )

array_flip() 返回一个反转后的 array,例如 trans 中的键名变成了值,而 trans 中的值成了键名。

注意 trans 中的值需要能够作为合法的键名,例如需要是 integer 或者 string。如果值的类型不对将发出一个警告,并且有问题的键/值对将不会反转

如果同一个值出现了多次,则最后一个键名将作为它的值,所有其它的都丢失了。

array_flip() 如果失败返回 FALSE

例子 1. array_flip() 例子

<?php
$trans = array_flip($trans);
$original = strtr($str, $trans);
?>

例子 2. array_flip() 例子:冲突

<?php
$trans = array("a" => 1, "b" => 1, "c" => 2);
$trans = array_flip($trans);
print_r($trans);
?>

现在 $trans 变成了:

Array
(
    [1] => b
    [2] => c
)

参见 array_values()array_keys()array_reverse()

array_intersect_assoc

(PHP 4 >= 4.3.0, PHP 5)

array_intersect_assoc -- 带索引检查计算数组的交集

说明

array array_intersect_assoc ( array array1, array array2 [, array ...] )

array_intersect_assoc() 返回一个数组,该数组包含了所有在 array1 中也同时出现在所有其它参数数组中的值。注意和 array_intersect() 不同的是键名也用于比较。

例子 1. array_intersect_assoc() 例子

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result_array = array_intersect_assoc($array1, $array2);
?>

$result_array 将是:

Array
(
    [a] => green
)

上面例子中可以看到只有键值对 "a" => "green" 在两个数组中都存在从而被返回。值 "red" 没有被返回是因为在 $array1 中它的键名是 0 而在 $array2"red" 的键名是 1

键值对 key => value 中的两个值仅在 (string) $elem1 === (string) $elem2 时被认为相等。也就是说使用了严格检查,字符串的表达必须相同。

参见 array_intersect()array_uintersect_assoc()array_intersect_uassoc()array_uintersect_uassoc()array_diff()array_diff_assoc()

array_intersect_key

(PHP 5 >= 5.1.0RC1)

array_intersect_key -- 使用键名比较计算数组的交集

说明

array array_intersect_key ( array array1, array array2 [, array ...] )

array_intersect_key() 返回一个数组,该数组包含了所有出现在 array1 中并同时出现在所有其它参数数组中的键名的值。

例子 1. array_intersect_key() 例子

<?php
$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_intersect_key($array1, $array2));
?>

上例将输出:

array(2) {
  ["blue"]=>
  int(1)
  ["green"]=>
  int(3)
})

上例中可以看到只有 'blue''green' 两个键名出现在两个数组中,因此被返回。此外注意 'blue''green' 的值在两个数组中是不同的。但因为只检查键名,因此还是匹配。返回的值只是 array1 中的。

key => value 对中的两个键名仅在 (string) $key1 === (string) $key2 时被认为相等。换句话说,执行的是严格类型检查,因此字符串的表达必须完全一样。

参见 array_diff()array_udiff()array_diff_assoc()array_diff_uassoc()array_udiff_assoc()array_udiff_uassoc()array_diff_key()array_diff_ukey()array_intersect()array_intersect_assoc()array_intersect_uassoc()array_intersect_ukey()

array_intersect_uassoc

(PHP 5)

array_intersect_uassoc -- 带索引检查计算数组的交集,用回调函数比较索引

说明

array array_intersect_uassoc ( array array1, array array2 [, array ..., callback key_compare_func] )

array_intersect_uassoc() 返回一个数组,该数组包含了所有在 array1 中也同时出现在所有其它参数数组中的值。注意和 array_intersect() 不同的是键名也用于比较。

此比较是通过用户提供的回调函数来进行的。如果认为第一个参数小于,等于,或大于第二个参数时必须分别返回一个小于零,等于零,或大于零的整数。

例子 1. array_intersect_uassoc() 例子

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_intersect_uassoc($array1, $array2, "strcasecmp"));
?>

上例将输出:

Array
(
    [b] => brown
)

参见 array_intersect()array_intersect_assoc()array_uintersect_assoc()array_uintersect_uassoc()array_intersect_key()array_intersect_ukey()

array_intersect_ukey

(PHP 5 >= 5.1.0RC1)

array_intersect_ukey -- 用回调函数比较键名来计算数组的交集

说明

array array_intersect_ukey ( array array1, array array2 [, array ..., callback key_compare_func] )

array_intersect_ukey() 返回一个数组,该数组包含了所有出现在 array1 中并同时出现在所有其它参数数组中的键名的值。

此比较是通过用户提供的回调函数来进行的。如果认为第一个参数小于,等于,或大于第二个参数时必须分别返回一个小于零,等于零,或大于零的整数。

例子 1. array_intersect_ukey() 例子

<?php
function key_compare_func($key1, $key2)
{
    if ($key1 == $key2)
        return 0;
    else if ($key1 > $key2)
        return 1;
    else
        return -1;
}

$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_intersect_ukey($array1, $array2, 'key_compare_func'));
?>

上例将输出:

array(2) {
  ["blue"]=>
  int(1)
  ["green"]=>
  int(3)
})

上例中可以看到只有 'blue''green' 两个键名出现在两个数组中,因此被返回。此外注意 'blue''green' 的值在两个数组中是不同的。但因为只检查键名,因此还是匹配。返回的值只是 array1 中的。

参见 array_diff()array_udiff()array_diff_assoc()array_diff_uassoc()array_udiff_assoc()array_udiff_uassoc()array_diff_key()array_diff_ukey()array_intersect()array_intersect_assoc()array_intersect_uassoc()array_intersect_key()

array_intersect

(PHP 4 >= 4.0.1, PHP 5)

array_intersect -- 计算数组的交集

说明

array array_intersect ( array array1, array array2 [, array ...] )

array_intersect() 返回一个数组,该数组包含了所有在 array1 中也同时出现在所有其它参数数组中的值。注意键名保留不变。

例子 1. array_intersect() 例子

<?php
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
?>

这使得 $result 成为:

Array
(
    [a] => green
    [0] => red
)

注: 两个单元仅在 (string) $elem1 === (string) $elem2 时被认为是相同的。也就是说,当字符串的表达是一样的时候。

参见 array_intersect_assoc()array_diff()array_diff_assoc()

array_key_exists

(PHP 4 >= 4.1.0, PHP 5)

array_key_exists -- 检查给定的键名或索引是否存在于数组中

说明

bool array_key_exists ( mixed key, array search )

array_key_exists() 在给定的 key 存在于数组中时返回 TRUEkey 可以是任何能作为数组索引的值。array_key_exists() 也可用于对象。

例子 1. array_key_exists() 例子

<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array";
}
?>

注: 在 PHP 4.0.6 中本函数名为 key_exists()

例子 2. array_key_exists()isset() 对比

isset() 对于数组中为 NULL 的值不会返回 TRUE,而 array_key_exists() 会。

<?php
$search_array = array('first' => null, 'second' => 4);

// returns false
isset($search_array['first']);

// returns true
array_key_exists('first', $search_array);
?>

参见 isset()array_keys()in_array()

array_keys

(PHP 4, PHP 5)

array_keys -- 返回数组中所有的键名

说明

array array_keys ( array input [, mixed search_value [, bool strict]] )

array_keys() 返回 input 数组中的数字或者字符串的键名。

如果指定了可选参数 search_value,则只返回该值的键名。否则 input 数组中的所有键名都会被返回。自 PHP 5 起,可以用 strict 参数来进行全等比较(===)。

例子 1. array_keys() 例子

<?php
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));

$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));

$array = array("color" => array("blue", "red", "green"),
               "size"  => array("small", "medium", "large"));
print_r(array_keys($array));
?>

上例将输出:

Array
(
    [0] => 0
    [1] => color
)
Array
(
    [0] => 0
    [1] => 3
    [2] => 4
)
Array
(
    [0] => color
    [1] => size
)

参见 array_values()array_key_exists()

array_map

(PHP 4 >= 4.0.6, PHP 5)

array_map --  将回调函数作用到给定数组的单元上

说明

array array_map ( callback callback, array arr1 [, array ...] )

array_map() 返回一个数组,该数组包含了 arr1 中的所有单元经过 callback 作用过之后的单元。callback 接受的参数数目应该和传递给 array_map() 函数的数组数目一致。

例子 1. array_map() 例子

<?php
function cube($n)
{
    return($n * $n * $n);
}

$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
?>

这使得 $b 成为:

Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
)

例子 2. array_map() - 使用更多的数组

<?php
function show_Spanish($n, $m)
{
    return("The number $n is called $m in Spanish");
}

function map_Spanish($n, $m)
{
    return(array($n => $m));
}

$a = array(1, 2, 3, 4, 5);
$b = array("uno", "dos", "tres", "cuatro", "cinco");

$c = array_map("show_Spanish", $a, $b);
print_r($c);

$d = array_map("map_Spanish", $a , $b);
print_r($d);
?>

上例将输出:

// printout of $c
Array
(
    [0] => The number 1 is called uno in Spanish
    [1] => The number 2 is called dos in Spanish
    [2] => The number 3 is called tres in Spanish
    [3] => The number 4 is called cuatro in Spanish
    [4] => The number 5 is called cinco in Spanish
)

// printout of $d
Array
(
    [0] => Array
        (
            [1] => uno
        )

    [1] => Array
        (
            [2] => dos
        )

    [2] => Array
        (
            [3] => tres
        )

    [3] => Array
        (
            [4] => cuatro
        )

    [4] => Array
        (
            [5] => cinco
        )

)

通常使用了两个或更多数组时,它们的长度应该相同,因为回调函数是平行作用于相应的单元上的。如果数组的长度不同,则最短的一个将被用空的单元扩充。

本函数一个有趣的用法是构造一个数组的数组,这可以很容易的通过用 NULL 作为回调函数名来实现。

例子 3. 建立一个数组的数组

<?php
$a = array(1, 2, 3, 4, 5);
$b = array("one", "two", "three", "four", "five");
$c = array("uno", "dos", "tres", "cuatro", "cinco");

$d = array_map(null, $a, $b, $c);
print_r($d);
?>

上例将输出:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => one
            [2] => uno
        )

    [1] => Array
        (
            [0] => 2
            [1] => two
            [2] => dos
        )

    [2] => Array
        (
            [0] => 3
            [1] => three
            [2] => tres
        )

    [3] => Array
        (
            [0] => 4
            [1] => four
            [2] => cuatro
        )

    [4] => Array
        (
            [0] => 5
            [1] => five
            [2] => cinco
        )

)

参见 array_filter()array_reduce()array_walk() 和有关 callback 类型的信息。

array_merge_recursive

(PHP 4 >= 4.0.1, PHP 5)

array_merge_recursive -- 递归地合并一个或多个数组

说明

array array_merge_recursive ( array array1 [, array ...] )

array_merge_recursive() 将一个或多个数组的单元合并起来,一个数组中的值附加在前一个数组的后面。返回作为结果的数组。

如果输入的数组中有相同的字符串键名,则这些值会被合并到一个数组中去,这将递归下去,因此如果一个值本身是一个数组,本函数将按照相应的条目把它合并为另一个数组。然而,如果数组具有相同的数组键名,后一个值将不会覆盖原来的值,而是附加到后面。

例子 1. array_merge_recursive() 例子

<?php
$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
?>

$result 成为:

Array
(
    [color] => Array
        (
            [favorite] => Array
                (
                    [0] => red
                    [1] => green
                )

            [0] => blue
        )

    [0] => 5
    [1] => 10
)

参见 array_merge()

array_merge

(PHP 4, PHP 5)

array_merge -- 合并一个或多个数组

说明

array array_merge ( array array1 [, array array2 [, array ...]] )

array_merge() 将一个或多个数组的单元合并起来,一个数组中的值附加在前一个数组的后面。返回作为结果的数组。

如果输入的数组中有相同的字符串键名,则该键名后面的值将覆盖前一个值。然而,如果数组包含数字键名,后面的值将不会覆盖原来的值,而是附加到后面。

如果只给了一个数组并且该数组是数字索引的,则键名会以连续方式重新索引。

例子 1. array_merge() 例子

<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

上例将输出:

Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)

例子 2. 简单的 array_merge() 例子

<?php
$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);
?>

别忘了数字键名将会被重新编号!

Array
(
    [0] => data
)

如果你想完全保留原有数组并只想新的数组附加到后面,用 + 运算符:

<?php
$array1 = array();
$array2 = array(1 => "data");
$result = $array1 + $array2;
?>

数字键名将被保留从而原来的关联保持不变。

Array
(
    [1] => data
)

警告

array_merge() 的行为在 PHP 5 中被修改了。和 PHP 4 不同,array_merge() 现在只接受 array 类型的参数。不过可以用强制转换来合并其它类型。请看下面的例子。

例子 3. array_merge() PHP 5 例子

<?php
$beginning = 'foo';
$end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
print_r($result);
?>

上例将输出:

Array
(
    [0] => foo
    [1] => bar
)

参见 array_merge_recursive()array_combine()数组运算符

array_multisort

(PHP 4, PHP 5)

array_multisort -- 对多个数组或多维数组进行排序

说明

bool array_multisort ( array ar1 [, mixed arg [, mixed ... [, array ...]]] )

如果成功则返回 TRUE,失败则返回 FALSE

array_multisort() 可以用来一次对多个数组进行排序,或者根据某一维或多维对多维数组进行排序。

关联(string)键名保持不变,但数字键名会被重新索引。

输入数组被当成一个表的列并以行来排序――这类似于 SQL 的 ORDER BY 子句的功能。第一个数组是要排序的主要数组。数组中的行(值)比较为相同的话就按照下一个输入数组中相应值的大小来排序,依此类推。

本函数的参数结构有些不同寻常,但是非常灵活。第一个参数必须是一个数组。接下来的每个参数可以是数组或者是下面列出的排序标志。

排序顺序标志:

  • SORT_ASC - 按照上升顺序排序

  • SORT_DESC - 按照下降顺序排序

排序类型标志:

  • SORT_REGULAR - 将项目按照通常方法比较

  • SORT_NUMERIC - 将项目按照数值比较

  • SORT_STRING - 将项目按照字符串比较

每个数组之后不能指定两个同类的排序标志。每个数组后指定的排序标志仅对该数组有效 - 在此之前为默认值 SORT_ASCSORT_REGULAR

例子 1. 对多个数组排序

<?php
$ar1 = array("10", 100, 100, "a");
$ar2 = array(1, 3, "2", 1);
array_multisort($ar1, $ar2);

var_dump($ar1);
var_dump($ar2);
?>

本例中经过排序后,第一个数组将包含 "10","a",100,100。第二个数组将包含 1,1,"2",3。第二个数组中的项目顺序完全和第一个数组中相应的项目(100 和 100)顺序一致。

array(4) {
  [0]=> string(2) "10"
  [1]=> string(1) "a"
  [2]=> int(100)
  [3]=> int(100)
}
array(4) {
  [0]=> int(1)
  [1]=> int(1)
  [2]=> string(1) "2"
  [3]=> int(3)
}

例子 2. 对多维数组排序

<?php
$ar = array (array ("10", 100, 100, "a"), array (1, 3, "2", 1));
array_multisort ($ar[0], SORT_ASC, SORT_STRING,
                 $ar[1], SORT_NUMERIC, SORT_DESC);
?>

本例中经过排序后,第一个数组将包含 10,100,100,"a"(作为字符串上升排序),第二个数组将包含 1,3,"2",1(作为数值下降排序)。

例子 3. Sorting multi-dimensional array

<?php
$ar = array(
       array("10", 11, 100, 100, "a"),
       array(   1,  2, "2",   3,   1)
      );
array_multisort($ar[0], SORT_ASC, SORT_STRING,
                $ar[1], SORT_NUMERIC, SORT_DESC);
var_dump($ar);
?>

本例中在排序后,第一个数组将变成 "10",100,100,11,"a"(被当作字符串以升序排列)。第二个数组将包含 1, 3, "2", 2, 1(被当作数字以降序排列)。

array(2) {
  [0]=> array(5) {
    [0]=> string(2) "10"
    [1]=> int(100)
    [2]=> int(100)
    [3]=> int(11)
    [4]=> string(1) "a"
  }
  [1]=> array(5) {
    [0]=> int(1)
    [1]=> int(3)
    [2]=> string(1) "2"
    [3]=> int(2)
    [4]=> int(1)
  }
}

例子 4. 对数据库结果进行排序

本例中 data 数组中的每个单元表示一个表中的一行。这是典型的数据库记录的数据集合。

例子中的数据如下:

volume | edition
-------+--------
    67 |       2
    86 |       1
    85 |       6
    98 |       2
    86 |       6
    67 |       7

数据全都存放在名为 data 的数组中。这通常是通过循环从数据库取得的结果,例如 mysql_fetch_assoc()

<?php
$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);
?>

本例中将把 volume 降序排列,把 edition 升序排列。

现在有了包含有行的数组,但是 array_multisort() 需要一个包含列的数组,因此用以下代码来取得列,然后排序。

<?php
// 取得列的列表
foreach ($data as $key => $row) {
    $volume[$key]  = $row['volume'];
    $edition[$key] = $row['edition'];
}

// 将数据根据 volume 降序排列,根据 edition 升序排列
// 把 $data 作为最后一个参数,以通用键排序
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
?>

数据集合现在排好序了,结果如下:

volume | edition
-------+--------
    98 |       2
    86 |       1
    86 |       6
    85 |       6
    67 |       2
    67 |       7

例子 5. 不区分大小写字母排序

SORT_STRINGSORT_REGULAR 都是区分大小写字母的,大写字母会排在小写字母之前。

要进行不区分大小写的排序,就要按照原数组的小写字母拷贝来排序。

<?php
$array = array('Alpha', 'atomic', 'Beta', 'bank');
$array_lowercase = array_map('strtolower', $array);

array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $array);

print_r($array);
?>

上例将输出:

Array
(
    [0] => Alpha
    [1] => atomic
    [2] => bank
    [3] => Beta
)

【译者注】本函数相当有用,为有助于理解,请再看下面这个例子:

例子 6. 名次排列

<?php
$grade = array("score" => array(70, 95, 70.0, 60, "70"),
               "name" => array("Zhang San", "Li Si", "Wang Wu",
                               "Zhao Liu", "Liu Qi"));
array_multisort($grade["score"], SORT_NUMERIC, SORT_DESC,
                // 将分数作为数值,由高到低排序
                $grade["name"], SORT_STRING, SORT_ASC);
                // 将名字作为字符串,由小到大排序
var_dump($grade);
?>

上例将输出:

array(2) {
  ["score"]=>
  array(5) {
    [0]=>
    int(95)
    [1]=>
    string(2) "70"
    [2]=>
    float(70)
    [3]=>
    int(70)
    [4]=>
    int(60)
  }
  ["name"]=>
  array(5) {
    [0]=>
    string(5) "Li Si"
    [1]=>
    string(6) "Liu Qi"
    [2]=>
    string(7) "Wang Wu"
    [3]=>
    string(9) "Zhang San"
    [4]=>
    string(8) "Zhao Liu"
  }
}

本例中对包含成绩的数组 $grade 按照分数(score)由高到低进行排序,分数相同的人则按照名字(name)由小到大排序。排序后李四 95 分为第一名,赵六 60 分为第五名没有异议。张三、王五和刘七都是 70 分,他们的名次则由其姓名的字母顺序排列,Liu 在前,Wang 在后而 Zhang 在最后。为了区别,三个 70 分分别用了整数,浮点数和字符串来表示,可以在程序输出中清楚地看到它们排序的结果。

array_pad

(PHP 4, PHP 5)

array_pad --  用值将数组填补到指定长度

说明

array array_pad ( array input, int pad_size, mixed pad_value )

array_pad() 返回 input 的一个拷贝,并用 pad_value 将其填补到 pad_size 指定的长度。如果 pad_size 为正,则数组被填补到右侧,如果为负则从左侧开始填补。如果 pad_size 的绝对值小于或等于 input 数组的长度则没有任何填补。有可能一次最多填补 1048576 个单元。

例子 1. array_pad() 例子

<?php
$input = array(12, 10, 9);

$result = array_pad($input, 5, 0);
// result is array(12, 10, 9, 0, 0)

$result = array_pad($input, -7, -1);
// result is array(-1, -1, -1, -1, 12, 10, 9)

$result = array_pad($input, 2, "noop");
// not padded
?>

参见 array_fill()range()

array_pop

(PHP 4, PHP 5)

array_pop -- 将数组最后一个单元弹出(出栈)

说明

mixed array_pop ( array &array )

array_pop() 弹出并返回 array 数组的最后一个单元,并将数组 array 的长度减一。如果 array 为空(或者不是数组)将返回 NULL

注: 使用本函数后会重置(reset())数组指针。

例子 1. array_pop() 例子

<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack);
?>

经过此操作后,$stack 将只有 3 个单元:

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
)

并且 rasberry 将被赋给 $fruit

参见 array_push()array_shift()array_unshift()

array_product

(PHP 5 >= 5.1.0RC1)

array_product -- 计算数组中所有值的乘积

说明

number array_product ( array array )

array_product() 以整数或浮点数返回一个数组中所有值的乘积。

例子 1. array_product() 例子

<?php

$a = array(2, 4, 6, 8);
echo "product(a) = " . array_product($a) . "\n";

?>

上例将输出:

product(a) = 384

array_push

(PHP 4, PHP 5)

array_push --  将一个或多个单元压入数组的末尾(入栈)

说明

int array_push ( array &array, mixed var [, mixed ...] )

array_push()array 当成一个栈,并将传入的变量压入 array 的末尾。array 的长度将根据入栈变量的数目增加。和如下效果相同:
<?php
$array[] = $var;
?>
并对每个 var 重复以上动作。

返回数组新的单元总数。

例子 1. array_push() 例子

<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
?>

本例将使 $stack 具有如下单元:

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)

注: 如果用 array_push() 来给数组增加一个单元,还不如用 $array[] = ,因为这样没有调用函数的额外负担。

注: 如果第一个参数不是数组,array_push() 将发出一条警告。这和 $var[] 的行为不同,后者会新建一个数组。

参见 array_pop()array_shift()array_unshift()

array_rand

(PHP 4, PHP 5)

array_rand --  从数组中随机取出一个或多个单元

说明

mixed array_rand ( array input [, int num_req] )

array_rand() 在你想从数组中取出一个或多个随机的单元时相当有用。它接受 input 作为输入数组和一个可选的参数 num_req,指明了你想取出多少个单元 - 如果没有指定,默认为 1。

如果你只取出一个,array_rand() 返回一个随机单元的键名,否则就返回一个包含随机键名的数组。这样你就可以随机从数组中取出键名和值。

注: 自 PHP 4.2.0 起,不再需要用 srand()mt_srand() 函数给随机数发生器播种,现已自动完成。

例子 1. array_rand() 例子

<?php
srand((float) microtime() * 10000000);
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
print $input[$rand_keys[0]] . "\n";
print $input[$rand_keys[1]] . "\n";
?>

参见 shuffle()

array_reduce

(PHP 4 >= 4.0.5, PHP 5)

array_reduce -- 用回调函数迭代地将数组简化为单一的值

说明

mixed array_reduce ( array input, callback function [, int initial] )

array_reduce() 将回调函数 function 迭代地作用到 input 数组中的每一个单元中,从而将数组简化为单一的值。如果指定了可选参数 initial,该参数将被当成是数组中的第一个值来处理,或者如果数组为空的话就作为最终返回值。如果数组为空并且没有传递 initial 参数,array_reduce() 返回 NULL

例子 1. array_reduce() 例子

<?php
function rsum($v, $w)
{
    $v += $w;
    return $v;
}

function rmul($v, $w)
{
    $v *= $w;
    return $v;
}

$a = array(1, 2, 3, 4, 5);
$x = array();
$b = array_reduce($a, "rsum");
$c = array_reduce($a, "rmul", 10);
$d = array_reduce($x, "rsum", 1);
?>

这将使 $b 的值为 15$c 的值为 1200(= 10*1*2*3*4*5),以及 $d 的值为 1

参见 array_filter()array_map()array_unique()array_count_values()

array_reverse

(PHP 4, PHP 5)

array_reverse --  返回一个单元顺序相反的数组

说明

array array_reverse ( array array [, bool preserve_keys] )

array_reverse() 接受数组 array 作为输入并返回一个单元为相反顺序的新数组,如果 preserve_keysTRUE 则保留原来的键名。

例子 1. array_reverse() 例子

<?php
$input  = array("php", 4.0, array("green", "red"));
$result = array_reverse($input);
$result_keyed = array_reverse($input, TRUE);
?>

这将使 $result$result_keyed 具有相同的单元,但是注意键名的区别。$result$result_keyed 的打印输出显示分别为:

Array
(
    [0] => Array
        (
            [0] => green
            [1] => red
        )

    [1] => 4
    [2] => php
)
Array
(
    [2] => Array
        (
            [0] => green
            [1] => red
        )

    [1] => 4
    [0] => php
)

注: 第二个参数是 PHP 4.0.3 中新加的。

参见 array_flip()

array_search

(PHP 4 >= 4.0.5, PHP 5)

array_search --  在数组中搜索给定的值,如果成功则返回相应的键名

说明

mixed array_search ( mixed needle, array haystack [, bool strict] )

haystack 中搜索 needle 参数并在找到的情况下返回键名,否则返回 FALSE

注: 如果 needle 是字符串,则比较以区分大小写的方式进行。

注: 在 PHP 4.2.0 之前,array_search() 在失败时返回 NULL 而不是 FALSE

如果可选的第三个参数 strictTRUE,则 array_search() 还将在 haystack 中检查 needle 的类型。

如果 needlehaystack 中出现不止一次,则返回第一个匹配的键。要返回所有匹配值的键,应该用 array_keys() 加上可选参数 search_value 来代替。

例子 1. array_search() 例子

<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
?>

警告

本函数可能返回布尔值 FALSE,但也可能返回一个与 FALSE 等值的非布尔值,例如 0 或者 ""。请参阅布尔类型章节以获取更多信息。应使用 === 运算符来测试本函数的返回值。

参见 array_keys()array_values()array_key_exists()in_array()

array_shift

(PHP 4, PHP 5)

array_shift --  将数组开头的单元移出数组

说明

mixed array_shift ( array &array )

array_shift()array 的第一个单元移出并作为结果返回,将 array 的长度减一并将所有其它单元向前移动一位。所有的数字键名将改为从零开始计数,文字键名将不变。如果 array 为空(或者不是数组),则返回 NULL

注: 使用本函数后会重置(reset())数组指针。

例子 1. array_shift() 例子

<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);
?>

这将使 $stack 剩下 3 个单元:

Array
(
    [0] => banana
    [1] => apple
    [2] => raspberry
)

并且 orange 被赋给了 $fruit

参见 array_unshift()array_push()array_pop()

array_slice

(PHP 4, PHP 5)

array_slice -- 从数组中取出一段

说明

array array_slice ( array array, int offset [, int length [, bool preserve_keys]] )

array_slice() 返回根据 offsetlength 参数所指定的 array 数组中的一段序列。

如果 offset 非负,则序列将从 array 中的此偏移量开始。如果 offset 为负,则序列将从 array 中距离末端这么远的地方开始。

如果给出了 length 并且为正,则序列中将具有这么多的单元。如果给出了 length 并且为负,则序列将终止在距离数组末端这么远的地方。如果省略,则序列将从 offset 开始一直到 array 的末端。

注意 array_slice() 默认将重置数组的键。自 PHP 5.0.2 起,可以通过将 preserve_keys 设为 TRUE 来改变此行为。

例子 1. array_slice() 例子

<?php
$input = array("a", "b", "c", "d", "e");

$output = array_slice($input, 2);      // returns "c", "d", and "e"
$output = array_slice($input, -2, 1);  // returns "d"
$output = array_slice($input, 0, 3);   // returns "a", "b", and "c"

// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>

上例将输出:

Array
(
    [0] => c
    [1] => d
)
Array
(
    [2] => c
    [3] => d
)

参见 array_splice()unset()

array_splice

(PHP 4, PHP 5)

array_splice --  把数组中的一部分去掉并用其它值取代

说明

array array_splice ( array &input, int offset [, int length [, array replacement]] )

array_splice()input 数组中由 offsetlength 指定的单元去掉,如果提供了 replacement 参数,则用 replacement 数组中的单元取代。返回一个包含有被移除单元的数组。注意 input 中的数字键名不被保留。

如果 offset 为正,则从 input 数组中该值指定的偏移量开始移除。如果 offset 为负,则从 input 末尾倒数该值指定的偏移量开始移除。

如果省略 length,则移除数组中从 offset 到结尾的所有部分。如果指定了 length 并且为正值,则移除这么多单元。如果指定了 length 并且为负值,则移除从 offset 到数组末尾倒数 length 为止中间所有的单元。小窍门:当给出了 replacement 时要移除从 offset 到数组末尾所有单元时,用 count($input) 作为 length

如果给出了 replacement 数组,则被移除的单元被此数组中的单元替代。如果 offsetlength 的组合结果是不会移除任何值,则 replacement 数组中的单元将被插入到 offset 指定的位置。注意替换数组中的键名不保留。如果用来替换的值只是一个单元,那么不需要给它加上 array(),除非该单元本身就是一个数组。

以下表达式以同样方式修改了 $input

表格 1. array_splice() 等价表达式

array_push($input, $x, $y) array_splice($input, count($input), 0, array($x, $y))
array_pop($input) array_splice($input, -1)
array_shift($input) array_splice($input, 0, 1)
array_unshift($input, $x, $y) array_splice($input, 0, 0, array($x, $y))
$input[$x] = $y // 对于键名和偏移量等值的数组 array_splice($input, $x, 1, $y)

返回一个包含被移除单元的数组。

例子 1. array_splice() 例子

<?php
$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
// $input is now array("red", "green")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
// $input is now array("red", "yellow")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, count($input), "orange");
// $input is now array("red", "orange")

$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
// $input is now array("red", "green",
//          "blue", "black", "maroon")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 3, 0, "purple");
// $input is now array("red", "green",
//          "blue", "purple", "yellow");
?>

参见 array_slice()unset()array_merge()

array_sum

(PHP 4 >= 4.0.4, PHP 5)

array_sum --  计算数组中所有值的和

说明

number array_sum ( array array )

array_sum() 将数组中的所有值的和以整数或浮点数的结果返回。

例子 1. array_sum() 例子

<?php
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";

$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo "sum(b) = " . array_sum($b) . "\n";
?>

上例将输出:

sum(a) = 20
sum(b) = 6.9

注: PHP 4.2.1 之前的版本修改了传入的数组本身,将其中的字符串值转换成数值(大多数情况下都转换成了零,根据具体值而定)。

array_udiff_assoc

(PHP 5)

array_udiff_assoc -- 带索引检查计算数组的差集,用回调函数比较数据

说明

array array_udiff_assoc ( array array1, array array2 [, array ..., callback data_compare_func] )

array_udiff_assoc() 返回一个数组,该数组包括了所有在 array1 中但是不在任何其它参数数组中的值。注意和 array_diff()array_udiff() 不同的是键名也用于比较。数组数据的比较是用用户提供的回调函数进行的。在此方面和 array_diff_assoc() 的行为正好相反,后者是用内部函数进行比较的。

例子 1. array_udiff_assoc() 例子

<?php
class cr {
    private $priv_member;
    function cr($val)
    {
        $this->priv_member = $val;
    }

    function comp_func_cr($a, $b)
    {
        if ($a->priv_member === $b->priv_member) return 0;
        return ($a->priv_member > $b->priv_member)? 1:-1;
    }
}

$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff_assoc($a, $b, array("cr", "comp_func_cr"));
print_r($result);
?>

上例将输出:

Array
(
    [0.1] => cr Object
        (
            [priv_member:private] => 9
        )

    [0.5] => cr Object
        (
            [priv_member:private] => 12
        )

    [0] => cr Object
        (
            [priv_member:private] => 23
        )
)

上例中可以看到键值对 "1" => new cr(4) 同时出现在两个数组中因此不在本函数的输出中。

此比较是通过用户提供的回调函数来进行的。如果认为第一个参数小于,等于,或大于第二个参数时必须分别返回一个小于零,等于零,或大于零的整数。

注: 注意本函数只检查了多维数组中的一维。当然,可以用 array_udiff_assoc($array1[0], $array2[0], "some_comparison_func"); 来检查更深的维度。

参见 array_diff()array_diff_assoc()array_diff_uassoc()array_udiff()array_udiff_uassoc()array_intersect()array_intersect_assoc()array_uintersect()array_uintersect_assoc()array_uintersect_uassoc()

array_udiff_uassoc

(PHP 5)

array_udiff_uassoc -- 带索引检查计算数组的差集,用回调函数比较数据和索引

说明

array array_udiff_uassoc ( array array1, array array2 [, array ..., callback data_compare_func, callback key_compare_func] )

array_udiff_uassoc() 返回一个数组,该数组包括了所有在 array1 中但是不在任何其它参数数组中的值。注意和 array_diff()array_udiff() 不同的是键名也用于比较。数组数据的比较是用用户提供的回调函数 data_compare_func 进行的。在此方面和 array_diff_assoc() 的行为正好相反,后者是用内部函数进行比较的。对键名(索引)的检查也是由回调函数 key_compare_func 进行的。这和 array_udiff_assoc() 的行为不同,后者是用内部函数比较索引的。

例子 1. array_udiff_uassoc() 例子

<?php
class cr {
    private $priv_member;
    function cr($val)
    {
        $this->priv_member = $val;
    }

    function comp_func_cr($a, $b)
    {
        if ($a->priv_member === $b->priv_member) return 0;
        return ($a->priv_member > $b->priv_member)? 1:-1;
    }

    function comp_func_key($a, $b)
    {
        if ($a === $b) return 0;
        return ($a > $b)? 1:-1;
    }
}
$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff_uassoc($a, $b, array("cr", "comp_func_cr"), array("cr", "comp_func_key"));
print_r($result);
?>

上例将输出:

Array
(
    [0.1] => cr Object
        (
            [priv_member:private] => 9
        )

    [0.5] => cr Object
        (
            [priv_member:private] => 12
        )

    [0] => cr Object
        (
            [priv_member:private] => 23
        )
)

在上例中键值对 "1" => new cr(4) 同时出现在两个数组中,因此不在本函数的输出中。要记住必须提供两个回调函数。

此比较是通过用户提供的回调函数来进行的。如果认为第一个参数小于,等于,或大于第二个参数时必须分别返回一个小于零,等于零,或大于零的整数。

注: 注意本函数只检查了多维数组中的一维。当然,可以用 array_udiff_uassoc($array1[0], $array2[0], "data_compare_func", "key_compare_func"); 来检查更深的维度。

参见 array_diff()array_diff_assoc()array_diff_uassoc()array_udiff()array_udiff_assoc()array_intersect()array_intersect_assoc()array_uintersect()array_uintersect_assoc()array_uintersect_uassoc()

array_udiff

(PHP 5)

array_udiff -- 用回调函数比较数据来计算数组的差集

说明

array array_udiff ( array array1, array array2 [, array ..., callback data_compare_func] )

array_udiff() 返回一个数组,该数组包括了所有在 array1 中但是不在任何其它参数数组中的值。注意键名保持不变。数据的比较是用 data_compare_func 进行的。如果认为第一个参数小于,等于,或大于第二个参数时必须分别返回一个小于零,等于零,或大于零的整数。这和 array_diff() 不同,后者使用了内部函数来比较数据。

例子 1. array_udiff() 例子

<?php
class cr {
    private $priv_member;
    function cr($val)
    {
        $this->priv_member = $val;
    }

    function comp_func_cr($a, $b)
    {
        if ($a->priv_member === $b->priv_member) return 0;
        return ($a->priv_member > $b->priv_member)? 1:-1;
    }
}
$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff($a, $b, array("cr", "comp_func_cr"));
print_r($result);
?>

上例将输出:

Array
(
    [0.5] => cr Object
        (
            [priv_member:private] => 12
        )

    [0] => cr Object
        (
            [priv_member:private] => 23
        )

)

注: 注意本函数只检查了多维数组中的一维。当然,可以用 array_udiff($array1[0], $array2[0], "data_compare_func"); 来检查更深的维度。

参见 array_diff()array_diff_assoc()array_diff_uassoc()array_udiff_assoc()array_udiff_uassoc()array_intersect()array_intersect_assoc()array_uintersect()array_uintersect_assoc()array_uintersect_uassoc()

array_uintersect_assoc

(PHP 5)

array_uintersect_assoc -- 带索引检查计算数组的交集,用回调函数比较数据

说明

array array_uintersect_assoc ( array array1, array array2 [, array ..., callback data_compare_func] )

array_uintersect_assoc() 返回一个数组,该数组包含了所有在 array1 中也同时出现在所有其它参数数组中的值。注意和 array_uintersect() 不同的是键名也要比较。数据是用回调函数比较的。

例子 1. array_uintersect_assoc() 例子

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_uintersect_assoc($array1, $array2, "strcasecmp"));
?>

上例将输出:

Array
(
    [a] => green
)

此比较是通过用户提供的回调函数来进行的。如果认为第一个参数小于,等于,或大于第二个参数时必须分别返回一个小于零,等于零,或大于零的整数。

参见 array_uintersect()array_intersect_assoc()array_intersect_uassoc()array_uintersect_uassoc()

array_uintersect_uassoc

(PHP 5)

array_uintersect_uassoc -- 带索引检查计算数组的交集,用回调函数比较数据和索引

说明

array array_uintersect_uassoc ( array array1, array array2 [, array ..., callback data_compare_func, callback key_compare_func] )

array_uintersect_uassoc() 返回一个数组,该数组包含了所有在 array1 中也同时出现在所有其它参数数组中的值。注意和 array_uintersect() 不同的是键名也要比较。数据和索引都是用回调函数比较的。

例子 1. array_uintersect_uassoc() 例子

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_uintersect_uassoc($array1, $array2, "strcasecmp", "strcasecmp"));
?>

上例将输出:

Array
(
    [a] => green
    [b] => brown
)

此比较是通过用户提供的回调函数来进行的。如果认为第一个参数小于,等于,或大于第二个参数时必须分别返回一个小于零,等于零,或大于零的整数。

参见 array_uintersect()array_intersect_assoc()array_intersect_uassoc()array_uintersect_assoc()

array_uintersect

(PHP 5)

array_uintersect -- 计算数组的交集,用回调函数比较数据

说明

array array_uintersect ( array array1, array array2 [, array ..., callback data_compare_func] )

array_uintersect() 返回一个数组,该数组包含了所有在 array1 中也同时出现在所有其它参数数组中的值。数据比较是用回调函数进行的。

例子 1. array_uintersect() 例子

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_uintersect($array1, $array2, "strcasecmp"));
?>

上例将输出:

Array
(
    [a] => green
    [b] => brown
    [0] => red
)

此比较是通过用户提供的回调函数来进行的。如果认为第一个参数小于,等于,或大于第二个参数时必须分别返回一个小于零,等于零,或大于零的整数。

参见 array_intersect()array_uintersect_assoc()array_intersect_uassoc()array_uintersect_uassoc()

array_unique

(PHP 4 >= 4.0.1, PHP 5)

array_unique -- 移除数组中重复的值

说明

array array_unique ( array array )

array_unique() 接受 array 作为输入并返回没有重复值的新数组。

注意键名保留不变。array_unique() 先将值作为字符串排序,然后对每个值只保留第一个遇到的键名,接着忽略所有后面的键名。这并不意味着在未排序的 array 中同一个值的第一个出现的键名会被保留。

注: 当且仅当 (string) $elem1 === (string) $elem2 时两个单元被认为相同。就是说,当字符串的表达一样时。

第一个单元将被保留。

例子 1. array_unique() 例子

<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>

上例将输出:

Array
(
    [a] => green
    [0] => red
    [1] => blue
)

例子 2. array_unique() 和类型

<?php
$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);
?>

上例将输出:

array(2) {
  [0] => int(4)
  [2] => string(1) "3"
}

array_unshift

(PHP 4, PHP 5)

array_unshift --  在数组开头插入一个或多个单元

说明

int array_unshift ( array &array, mixed var [, mixed ...] )

array_unshift() 将传入的单元插入到 array 数组的开头。注意单元是作为整体被插入的,因此传入单元将保持同样的顺序。所有的数值键名将修改为从零开始重新计数,所有的文字键名保持不变。

返回 array 数组新的单元数目。

例子 1. array_unshift() 例子

<?php
$queue = array("orange", "banana");
array_unshift($queue, "apple", "raspberry");
?>

这将使 $queue 包含如下单元:

Array
(
    [0] => apple
    [1] => raspberry
    [2] => orange
    [3] => banana
)

参见 array_shift()array_push()array_pop()

array_values

(PHP 4, PHP 5)

array_values -- 返回数组中所有的值

说明

array array_values ( array input )

array_values() 返回 input 数组中所有的值并给其建立数字索引。

例子 1. array_values() 例子

<?php
$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array));
?>

上例将输出:

Array
(
    [0] => XL
    [1] => gold
)

参见 array_keys()

array_walk_recursive

(PHP 5)

array_walk_recursive -- 对数组中的每个成员递归地应用用户函数

说明

bool array_walk_recursive ( array &input, callback funcname [, mixed userdata] )

将用户自定义函数 funcname 应用到 array 数组中的每个单元。本函数会递归到更深层的数组中去。典型情况下 funcname 接受两个参数。input 参数的值作为第一个,键名作为第二个。如果提供了可选参数 userdata,将被作为第三个参数传递给 callback funcname

如果成功则返回 TRUE,失败则返回 FALSE

注: 如果 funcname 需要直接作用于数组中的值,则给 funcname 的第一个参数指定为引用。这样任何对这些单元的改变也将会改变原始数组本身。

例子 1. array_walk_recursive() 例子

<?php
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');

function test_print($item, $key)
{
    echo "$key holds $item\n";
}

array_walk_recursive($fruits, 'test_print');
?>

上例将输出:

a holds apple
b holds banana
sour holds lemon

注意上例中的键 'sweet' 并没有显示出来。任何其值为数组的键都不会被传递到回调函数中去。

参见 array_walk() 和有关 callback 类型的信息。

array_walk

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

array_walk -- 对数组中的每个成员应用用户函数

说明

bool array_walk ( array &array, callback funcname [, mixed userdata] )

如果成功则返回 TRUE,失败则返回 FALSE

将用户自定义函数 funcname 应用到 array 数组中的每个单元。典型情况下 funcname 接受两个参数。array 参数的值作为第一个,键名作为第二个。如果提供了可选参数 userdata,将被作为第三个参数传递给 callback funcname

如果 funcname 函数需要的参数比给出的多,则每次 array_walk() 调用 funcname 时都会产生一个 E_WARNING 级的错误。这些警告可以通过在 array_walk() 调用前加上 PHP 的错误操作符 @ 来抑制,或者用 error_reporting()

注: 如果 funcname 需要直接作用于数组中的值,则给 funcname 的第一个参数指定为引用。这样任何对这些单元的改变也将会改变原始数组本身。

注: 将键名和 userdata 传递到 funcname 中是 PHP 4.0 新增加的。

array_walk() 不会受到 array 内部数组指针的影响。array_walk() 会遍历整个数组而不管指针的位置。

用户不应在回调函数中改变该数组本身。例如增加/删除单元,unset 单元等等。如果 array_walk() 作用的数组改变了,则此函数的的行为未经定义,且不可预期。

例子 1. array_walk() 例子

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");

function test_alter(&$item1, $key, $prefix)
{
    $item1 = "$prefix: $item1";
}

function test_print($item2, $key)
{
    echo "$key. $item2<br />\n";
}

echo "Before ...:\n";
array_walk($fruits, 'test_print');

array_walk($fruits, 'test_alter', 'fruit');
echo "... and after:\n";

array_walk($fruits, 'test_print');
?>

上例将输出:

Before ...:
d. lemon
a. orange
b. banana
c. apple
... and after:
d. fruit: lemon
a. fruit: orange
b. fruit: banana
c. fruit: apple

参见 array_walk_recursive()create_function()list()foreacheach()call_user_func_array()array_map() 和有关 callback 类型的信息。

array

(PHP 3, PHP 4, PHP 5)

array --  新建一个数组

说明

array array ( [mixed ...] )

返回根据参数建立的数组。参数可以用 => 运算符给出索引。关于数组是什么的信息请阅读数组一节。

注: array() 是一个语言结构,用于字面上表示数组,不是常规的函数。

语法“index => values”,用逗号分开,定义了索引和值。索引可以是字符串或数字。如果省略了索引,会自动产生从 0 开始的整数索引。如果索引是整数,则下一个产生的索引将是目前最大的整数索引 + 1。注意如果定义了两个完全一样的索引,则后面一个会覆盖前一个。

在最后一个定义的数组项目之后加一个逗号虽然不常见,却是合法的语法。

下面的例子演示了怎样建立一个二维数组,怎样给相应的数组指定键名,以及怎样在普通数组中略过和继续数字索引。

例子 1. array() 例子

<?php
$fruits = array (
    "fruits"  => array("a" => "orange", "b" => "banana", "c" => "apple"),
    "numbers" => array(1, 2, 3, 4, 5, 6),
    "holes"   => array("first", 5 => "second", "third")
);
?>

例子 2. array() 的自动索引

<?php
$array = array(1, 1, 1, 1,  1, 8 => 1,  4 => 1, 19, 3 => 13);
print_r($array);
?>

上例将输出:

Array
(
    [0] => 1
    [1] => 1
    [2] => 1
    [3] => 13
    [4] => 1
    [8] => 1
    [9] => 19
)

注意索引 3 被定义了两次,保留了最后的值 13。索引 4 在 索引 8 之后定义,下一个自动生成的索引(值为 19 那个)为 9,因为最大的索引是 8。

本例建立了从 1 开始的数组。

例子 3. 从 1 开始索引的 array()

<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>

上例将输出:

Array
(
    [1] => January
    [2] => February
    [3] => March
)

在 Perl 中,可以访问在双引号内的数组的值。但在 PHP 中需要将数组用花括号括起来。

例子 4. 访问双引号内的数组

<?php

$foo = array('bar' => 'baz');
echo "Hello {$foo['bar']}!"; // Hello baz!

?>

参见 array_pad()list()count()foreachrange()

arsort

(PHP 3, PHP 4, PHP 5)

arsort --  对数组进行逆向排序并保持索引关系

说明

bool arsort ( array &array [, int sort_flags] )

本函数对数组进行排序,数组的索引保持和单元的关联。主要用于对那些单元顺序很重要的结合数组进行排序。

如果成功则返回 TRUE,失败则返回 FALSE

例子 1. arsort() 例子

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
arsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

上例将输出:

a = orange
d = lemon
b = banana
c = apple

fruits 被按照字母顺序逆向排序,并且单元的索引关系不变。

可以用可选的参数 sort_flags 改变排序的行为,详情见 sort()

参见 asort()rsort()ksort()sort()

asort

(PHP 3, PHP 4, PHP 5)

asort -- 对数组进行排序并保持索引关系

说明

bool asort ( array &array [, int sort_flags] )

本函数对数组进行排序,数组的索引保持和单元的关联。主要用于对那些单元顺序很重要的结合数组进行排序。

如果成功则返回 TRUE,失败则返回 FALSE

例子 1. asort() 例子

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
asort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

上例将输出:

c = apple
b = banana
d = lemon
a = orange

fruits 被按照字母顺序排序,并且单元的索引关系不变。

可以用可选的参数 sort_flags 改变排序的行为,详情见 sort()

参见 arsort()rsort()ksort()sort()

compact

(PHP 4, PHP 5)

compact --  建立一个数组,包括变量名和它们的值

说明

array compact ( mixed varname [, mixed ...] )

compact() 接受可变的参数数目。每个参数可以是一个包括变量名的字符串或者是一个包含变量名的数组,该数组中还可以包含其它单元内容为变量名的数组, compact() 可以递归处理。

对每个参数,compact() 在当前的符号表中查找该变量名并将它添加到输出的数组中,变量名成为键名而变量的内容成为该键的值。简单说,它做的事和 extract() 正好相反。返回将所有变量添加进去后的数组。

任何没有变量名与之对应的字符串都被略过。

Gotcha: 因为可变变量也许不能在函数内部用于 PHP 的超全局数组,此时不能将超全局数组传递入 compact() 中。

例子 1. compact() 例子

<?php
$city  = "San Francisco";
$state = "CA";
$event = "SIGGRAPH";

$location_vars = array("city", "state");

$result = compact("event", "nothing_here", $location_vars);
?>

经过处理后,$result 为:

Array
(
    [event] => SIGGRAPH
    [city] => San Francisco
    [state] => CA
)

参见 extract()

count

(PHP 3, PHP 4, PHP 5)

count -- 计算数组中的单元数目或对象中的属性个数

说明

int count ( mixed var [, int mode] )

返回 var 中的单元数目,通常是一个 array,任何其它类型都只有一个单元。

对于对象,如果安装了 SPL,可以通过实现 Countable 接口来调用 count()。该接口只有一个方法 count(),此方法返回 count() 函数的返回值。

如果 var 不是数组类型或者实现了 Countable 接口的对象,将返回 1,有一个例外,如果 varNULL 则结果是 0

注: 可选的 mode 参数自 PHP 4.2.0 起可用。

如果可选的 mode 参数设为 COUNT_RECURSIVE(或 1),count() 将递归地对数组计数。对计算多维数组的所有单元尤其有用。mode 的默认值是 0count() 识别不了无限递归。

注意

count() 对没有初始化的变量返回 0,但对于空的数组也会返回 0。用 isset() 来测试变量是否已经初始化。

请参考手册中数组一节中关于怎样在 PHP 中实现和使用数组的详细解释。

例子 1. count() 例子

<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count($a);
// $result == 3

$b[0] = 7;
$b[5] = 9;
$b[10] = 11;
$result = count($b);
// $result == 3;

$result = count(null);
// $result == 0

$result = count(false);
// $result == 1
?>

例子 2. count() 的递归例子(PHP >= 4.2.0)

<?php
$food = array('fruits'  => array('orange', 'banana', 'apple'),
              'veggie'  => array('carrot', 'collard','pea'));

// recursive count
echo count($food, COUNT_RECURSIVE);  // output 8

// normal count
echo count($food);                  // output 2
?>

参见 is_array()isset()strlen()

current

(PHP 3, PHP 4, PHP 5)

current -- 返回数组中的当前单元

说明

mixed current ( array &array )

每个数组中都有一个内部的指针指向它“当前的”单元,初始指向插入到数组中的第一个单元。

current() 函数返回当前被内部指针指向的数组单元的值,并不移动指针。如果内部指针指向超出了单元列表的末端,current() 返回 FALSE

警告

如果数组包含有空的单元(0 或者 "",空字符串)则本函数在碰到这个单元时也返回 FALSE。这使得用 current() 不可能判断是否到了此数组列表的末端。要正确遍历可能含有空单元的数组,用 each() 函数。

例子 1. current() 及相关函数的用法示例

<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport);    // $mode = 'bike';
$mode = current($transport); // $mode = 'bike';
$mode = prev($transport);    // $mode = 'foot';
$mode = end($transport);     // $mode = 'plane';
$mode = current($transport); // $mode = 'plane';
?>

参见 end()key()next()prev()reset()

each

(PHP 3, PHP 4, PHP 5)

each --  返回数组中当前的键/值对并将数组指针向前移动一步

说明

array each ( array &array )

返回 array 数组中当前指针位置的键/值对并向前移动数组指针。键值对被返回为四个单元的数组,键名为 01keyvalue。单元 0key 包含有数组单元的键名,1value 包含有数据。

如果内部指针越过了数组的末端,则 each() 返回 FALSE

例子 1. each() 例子

<?php
$foo = array("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bar = each($foo);
print_r($bar);
?>

$bar 现在包含有如下的键/值对:

Array
{
    [1] => bob
    [value] => bob
    [0] => 0
    [key] => 0
}

<?php
$foo = array("Robert" => "Bob", "Seppo" => "Sepi");
$bar = each($foo);
print_r($bar);
?>

$bar 现在包含有如下的键/值对:

Array
{
    [1] => Bob
    [value] => Bob
    [0] => Robert
    [key] => Robert
}

each() 经常和 list() 结合使用来遍历数组,例如:

例子 2. 用 each() 遍历数组

<?php
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');
reset($fruit);
while (list($key, $val) = each($fruit)) {
    echo "$key => $val\n";
}
?>

上例将输出:

a => apple
b => banana
c => cranberry

在执行 each() 之后,数组指针将停留在数组中的下一个单元或者当碰到数组结尾时停留在最后一个单元。如果要再用 each 遍历数组,必须使用 reset()

注意

因为将一个数组赋值给另一个数组时会重置原来的数组指针,因此在上边的例子中如果我们在循环内部将 $fruit 赋给了另一个变量的话将会导致无限循环。

参见 key()list()current()reset()next()prev()foreach

end

(PHP 3, PHP 4, PHP 5)

end --  将数组的内部指针指向最后一个单元

说明

mixed end ( array &array )

end()array 的内部指针移动到最后一个单元并返回其值。

例子 1. 简单的 end() 例子

<?php
$fruits = array('apple','banana','cranberry');
echo end($fruits); // cranberry
?>

参见 current()each()prev()next()reset()

extract

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

extract --  从数组中将变量导入到当前的符号表

说明

int extract ( array var_array [, int extract_type [, string prefix]] )

本函数用来将变量从数组中导入到当前的符号表中。接受结合数组 var_array 作为参数并将键名当作变量名,值作为变量的值。对每个键/值对都会在当前的符号表中建立变量,并受到 extract_typeprefix 参数的影响。

注: 自版本 4.0.5 起本函数返回被提取的变量数目。

注: EXTR_IF_EXISTSEXTR_PREFIX_IF_EXISTS 是版本 4.2.0 中引进的。

注: EXTR_REFS 是版本 4.3.0 中引进的。

extract() 检查每个键名看是否可以作为一个合法的变量名,同时也检查和符号表中已有的变量名的冲突。对待非法/数字和冲突的键名的方法将根据 extract_type 参数决定。可以是以下值之一:

EXTR_OVERWRITE

如果有冲突,覆盖已有的变量。

EXTR_SKIP

如果有冲突,不覆盖已有的变量。

EXTR_PREFIX_SAME

如果有冲突,在变量名前加上前缀 prefix

EXTR_PREFIX_ALL

给所有变量名加上前缀 prefix。自 PHP 4.0.5 起这也包括了对数字索引的处理。

EXTR_PREFIX_INVALID

仅在非法/数字的变量名前加上前缀 prefix。本标记是 PHP 4.0.5 新加的。

EXTR_IF_EXISTS

仅在当前符号表中已有同名变量时,覆盖它们的值。其它的都不处理。可以用在已经定义了一组合法的变量,然后要从一个数组例如 $_REQUEST 中提取值覆盖这些变量的场合。本标记是 PHP 4.2.0 新加的。

EXTR_PREFIX_IF_EXISTS

仅在当前符号表中已有同名变量时,建立附加了前缀的变量名,其它的都不处理。本标记是 PHP 4.2.0 新加的。

EXTR_REFS

将变量作为引用提取。这有力地表明了导入的变量仍然引用了 var_array 参数的值。可以单独使用这个标志或者在 extract_type 中用 OR 与其它任何标志结合使用。本标记是 PHP 4.3.0 新加的。

如果没有指定 extract_type,则被假定为 EXTR_OVERWRITE

注意 prefix 仅在 extract_type 的值是 EXTR_PREFIX_SAMEEXTR_PREFIX_ALLEXTR_PREFIX_INVALIDEXTR_PREFIX_IF_EXISTS 时需要。如果附加了前缀后的结果不是合法的变量名,将不会导入到符号表中。

extract() 返回成功导入到符号表中的变量数目。

警告

不要对不能信任的数据使用 extract(),例如用户的输入($_GET,...)。如果这样做,举例说,要临时运行依赖于 register_globals 的老代码,要确保使用不会覆盖的 extract_type 值,例如 EXTR_SKIP,并且要留意应该按照 php.ini 中由 variables_order 定义的顺序来提取。

extract() 的一种可能用法是将 wddx_deserialize() 返回的结合数组中的内容导入到符号表变量中去。

例子 1. extract() 例子

<?php

/* 假定 $var_array 是 wddx_deserialize 返回的数组*/

$size = "large";
$var_array = array("color" => "blue",
                   "size"  => "medium",
                   "shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "wddx");

echo "$color, $size, $shape, $wddx_size\n";

?>

上例将输出:

blue, large, sphere, medium

$size 没有被覆盖,因为指定了 EXTR_PREFIX_SAME,这使得 $wddx_size 被建立。如果指定了 EXTR_SKIP,则 $wddx_size 也不会被建立。EXTR_OVERWRITE 将使 $size 的值为“medium”,EXTR_PREFIX_ALL 将建立新变量 $wddx_color$wddx_size$wddx_shape

必须使用结合数组,数字索引的数组将不会产生结果,除非用了 EXTR_PREFIX_ALL 或者 EXTR_PREFIX_INVALID

参见 compact()

in_array

(PHP 4, PHP 5)

in_array -- 检查数组中是否存在某个值

说明

bool in_array ( mixed needle, array haystack [, bool strict] )

haystack 中搜索 needle,如果找到则返回 TRUE,否则返回 FALSE

如果第三个参数 strict 的值为 TRUEin_array() 函数还会检查 needle类型是否和 haystack 中的相同。

注: 如果 needle 是字符串,则比较是区分大小写的。

注: 在 PHP 版本 4.2.0 之前,needle 不允许是一个数组。

例子 1. in_array() 例子

<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
    echo "Got Irix";
}
if (in_array("mac", $os)) {
    echo "Got mac";
}
?>

第二个条件失败,因为 in_array() 是区分大小写的,所以以上程序显示为:

Got Irix

例子 2. in_array() 严格类型检查例子

<?php
$a = array('1.10', 12.4, 1.13);

if (in_array('12.4', $a, true)) {
    echo "'12.4' found with strict check\n";
}
if (in_array(1.13, $a, true)) {
    echo "1.13 found with strict check\n";
}
?>

上例将输出:

1.13 found with strict check

例子 3. in_array() 中用数组作为 needle

<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');

if (in_array(array('p', 'h'), $a)) {
    echo "'ph' was found\n";
}
if (in_array(array('f', 'i'), $a)) {
    echo "'fi' was found\n";
}
if (in_array('o', $a)) {
    echo "'o' was found\n";
}
?>

上例将输出:

'ph' was found
  'o' was found

参见 array_search()array_key_exists()isset()

key

(PHP 3, PHP 4, PHP 5)

key -- 从关联数组中取得键名

说明

mixed key ( array &array )

key() 返回数组中当前单元的键名。

例子 1. key() 例子

<?php
$array = array(
 'fruit1' => 'apple',
 'fruit2' => 'orange',
 'fruit3' => 'grape',
 'fruit4' => 'apple',
 'fruit5' => 'apple');

// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
    if ($fruit_name == 'apple') {
        echo key($array).'<br />';
    }
    next($array);
}
?>

参见 current()next()

krsort

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

krsort -- 对数组按照键名逆向排序

说明

bool krsort ( array &array [, int sort_flags] )

对数组按照键名逆向排序,保留键名到数据的关联。主要用于结合数组。

如果成功则返回 TRUE,失败则返回 FALSE

例子 1. krsort() 例子

<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
krsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

上例将输出:

d = lemon
c = apple
b = banana
a = orange

可以用可选参数 sort_flags 改变排序的行为,详情见 sort()

参见 asort()arsort()ksort()sort()natsort()rsort()

ksort

(PHP 3, PHP 4, PHP 5)

ksort -- 对数组按照键名排序

说明

bool ksort ( array &array [, int sort_flags] )

对数组按照键名排序,保留键名到数据的关联。本函数主要用于关联数组。

如果成功则返回 TRUE,失败则返回 FALSE

例子 1. ksort() 例子

<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

上例将输出:

a = orange
b = banana
c = apple
d = lemon

可以用可选参数 sort_flags 改变排序的行为,详情见 sort()

参见 asort()arsort()krsort()uksort()sort()natsort()rsort()

注: 第二个参数是 PHP 4 新加的。

list

(PHP 3, PHP 4, PHP 5)

list --  把数组中的值赋给一些变量

说明

void list ( mixed varname, mixed ... )

array() 一样,这不是真正的函数,而是语言结构。list() 用一步操作给一组变量进行赋值。

注: list() 仅能用于数字索引的数组并假定数字索引从 0 开始。

例子 1. list() 例子

<?php

$info = array('coffee', 'brown', 'caffeine');

// Listing all the variables
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.\n";

// Listing some of them
list($drink, , $power) = $info;
echo "$drink has $power.\n";

// Or let's skip to only the third one
list( , , $power) = $info;
echo "I need $power!\n";

?>

例子 2. 使用 list() 的例子

<table>
 <tr>
  <th>Employee name</th>
  <th>Salary</th>
 </tr>

<?php

$result = mysql_query("SELECT id, name, salary FROM employees",$conn);
while (list($id, $name, $salary) = mysql_fetch_row($result)) {
    echo " <tr>\n".
         "  <td><a href=\"info.php?id=$id\">$name</a></td>\n".
         "  <td>$salary</td>\n".
         " </tr>\n";
}

?>

</table>

警告

list() 从最右边一个参数开始赋值。如果你用单纯的变量,不用担心这一点。但是如果你用了具有索引的数组,通常你期望得到的结果和在 list() 中写的一样是从左到右的,但实际上不是。是以相反顺序赋值的。

例子 3. 在 list() 中使用数组索引

<?php
$info = array('coffee', 'brown', 'caffeine');
list($a[0], $a[1], $a[2]) = $info;
var_dump($a);
?>

产生如下输出(注意单元顺序和 list() 语法中所写的顺序的比较):

array(3) {
  [2]=>
  string(8) "caffeine"
  [1]=>
  string(5) "brown"
  [0]=>
  string(6) "coffee"
}

参见 each()array()extract()

natcasesort

(PHP 4, PHP 5)

natcasesort --  用“自然排序”算法对数组进行不区分大小写字母的排序

说明

bool natcasesort ( array &array )

本函数实现了一个和人们通常对字母数字字符串进行排序的方法一样的排序算法并保持原有键/值的关联,这被称为“自然排序”。

如果成功则返回 TRUE,失败则返回 FALSE

natcasesort()natsort() 函数的不区分大小写字母的版本。

例子 1. natcasesort() 例子

<?php
$array1 = $array2 = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png');

sort($array1);
echo "Standard sorting\n";
print_r($array1);

natcasesort($array2);
echo "\nNatural order sorting (case-insensitive)\n";
print_r($array2);
?>

上例将输出:

Standard sorting
Array
(
    [0] => IMG0.png
    [1] => IMG3.png
    [2] => img1.png
    [3] => img10.png
    [4] => img12.png
    [5] => img2.png
)

Natural order sorting (case-insensitive)
Array
(
    [0] => IMG0.png
    [4] => img1.png
    [3] => img2.png
    [5] => IMG3.png
    [2] => img10.png
    [1] => img12.png
)

更多信息见 Martin Pool 的 Natural Order String Comparison 页面。

参见 sort()natsort()strnatcmp()strnatcasecmp()

natsort

(PHP 4, PHP 5)

natsort --  用“自然排序”算法对数组排序

说明

bool natsort ( array &array )

本函数实现了一个和人们通常对字母数字字符串进行排序的方法一样的排序算法并保持原有键/值的关联,这被称为“自然排序”。本算法和通常的计算机字符串排序算法(用于 sort())的区别见下面示例。

如果成功则返回 TRUE,失败则返回 FALSE

例子 1. natsort() 例子

<?php
$array1 = $array2 = array("img12.png", "img10.png", "img2.png", "img1.png");

sort($array1);
echo "Standard sorting\n";
print_r($array1);

natsort($array2);
echo "\nNatural order sorting\n";
print_r($array2);
?>

上例将输出:

Standard sorting
Array
(
    [0] => img1.png
    [1] => img10.png
    [2] => img12.png
    [3] => img2.png
)

Natural order sorting
Array
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)

更多信息见 Martin Pool 的 Natural Order String Comparison 页面。

参见 natcasesort()strnatcmp()strnatcasecmp()

next

(PHP 3, PHP 4, PHP 5)

next --  将数组中的内部指针向前移动一位

说明

mixed next ( array &array )

返回数组内部指针指向的下一个单元的值,或当没有更多单元时返回 FALSE

next()current() 的行为类似,只有一点区别,在返回值之前将内部指针向前移动一位。这意味着它返回的是下一个数组单元的值并将数组指针向前移动了一位。如果移动指针的结果是超出了数组单元的末端,则 next() 返回 FALSE

警告

如果数组包含空的单元,或者单元的值是 0 则本函数碰到这些单元也返回 FALSE。要正确遍历可能含有空单元或者单元值为 0 的数组,参见 each() 函数。

例子 1. next() 及相关函数的用法示例

<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport);    // $mode = 'bike';
$mode = next($transport);    // $mode = 'car';
$mode = prev($transport);    // $mode = 'bike';
$mode = end($transport);     // $mode = 'plane';
?>

参见 current()end()prev()reset()

pos

(PHP 3, PHP 4, PHP 5)

pos -- current() 的别名

说明

本函数是该函数的别名:current()

prev

(PHP 3, PHP 4, PHP 5)

prev -- 将数组的内部指针倒回一位

说明

mixed prev ( array &array )

返回数组内部指针指向的前一个单元的值,或当没有更多单元时返回 FALSE

警告

如果数组包含空的单元,或者单元的值是 0 则本函数碰到这些单元也返回 FALSE。要正确遍历可能含有空单元或者单元值为 0 的数组,参见 each() 函数。

prev()next() 的行为类似,只除了它将内部指针倒回一位而不是前移一位。

例子 1. prev() 及相关函数用法示例

<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport);    // $mode = 'bike';
$mode = next($transport);    // $mode = 'car';
$mode = prev($transport);    // $mode = 'bike';
$mode = end($transport);     // $mode = 'plane';
?>

参见 current()end()next()reset()

range

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

range --  建立一个包含指定范围单元的数组

说明

array range ( mixed low, mixed high [, number step] )

range() 返回数组中从 lowhigh 的单元,包括它们本身。如果 low > high,则序列将从 high 到 low。

新参数: 可选的 step 参数是 PHP 5.0.0 新加的。

如果给出了 step 的值,它将被作为单元之间的步进值。step 应该为正值。如果未指定,step 则默认为 1。

例子 1. range() 例子

<?php
// array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
foreach (range(0, 12) as $number) {
    echo $number;
}

// The step parameter was introduced in 5.0.0
// array(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
foreach (range(0, 100, 10) as $number) {
    echo $number;
}

// Use of character sequences introduced in 4.1.0
// array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i');
foreach (range('a', 'i') as $letter) {
    echo $letter;
}
// array('c', 'b', 'a');
foreach (range('c', 'a') as $letter) {
    echo $letter;
}

注: 在版本 4.1.0 之前 range() 函数只产生递增的整数数组。对于字符序列和递减数组的支持是 4.1.0 加入的。字符序列值的长度限定为一。如果输入的长度超过一,则只使用第一个字符。

注意

在 PHP 版本 4.1.0 到 4.3.2 中,range() 将数字字符串看作字符串而不是整数,因此将会被作为字符序列使用。例如,"4242" 会被当作 "4" 来对待。

参见 shuffle()array_fill()foreach

reset

(PHP 3, PHP 4, PHP 5)

reset --  将数组的内部指针指向第一个单元

说明

mixed reset ( array &array )

reset()array 的内部指针倒回到第一个单元并返回第一个数组单元的值,如果数组为空则返回 FALSE

例子 1. reset() 例子

<?php

$array = array('step one', 'step two', 'step three', 'step four');

// by default, the pointer is on the first element
echo current($array) . "<br />\n"; // "step one"

// skip two steps
next($array);
next($array);
echo current($array) . "<br />\n"; // "step three"

// reset pointer, start again on step one
reset($array);
echo current($array) . "<br />\n"; // "step one"

?>

参见 current()each()next()prev()

rsort

(PHP 3, PHP 4, PHP 5)

rsort -- 对数组逆向排序

说明

bool rsort ( array &array [, int sort_flags] )

本函数对数组进行逆向排序(最高到最低)。

注: 本函数为 array 中的单元赋予新的键名。这将删除原有的键名而不仅是重新排序。

如果成功则返回 TRUE,失败则返回 FALSE

例子 1. rsort() 例子

<?php
$fruits = array("lemon", "orange", "banana", "apple");
rsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

上例将输出:

0 = orange
1 = lemon
2 = banana
3 = apple

fruits 被按照字母顺序逆向排序。

可以用可选参数 sort_flags 改变排序的行为,详情见 sort()

参见 arsort()asort()ksort()krsort()sort()usort()

shuffle

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

shuffle -- 将数组打乱

说明

bool shuffle ( array &array )

本函数打乱(随机排列单元的顺序)一个数组。

注: 本函数为 array 中的单元赋予新的键名。这将删除原有的键名而不仅是重新排序。

例子 1. shuffle() 例子

<?php
$numbers = range(1,20);
srand((float)microtime()*1000000);
shuffle($numbers);
foreach ($numbers as $number) {
    echo "$number ";
}
?>

注: 自 PHP 4.2.0 起,不再需要用 srand()mt_srand() 函数给随机数发生器播种,现已自动完成。

参见 arsort()asort()ksort()rsort()sort()usort()

sizeof

(PHP 3, PHP 4, PHP 5)

sizeof -- count() 的别名

说明

本函数是该函数的别名:count()

sort

(PHP 3, PHP 4, PHP 5)

sort -- 对数组排序

说明

bool sort ( array &array [, int sort_flags] )

本函数对数组进行排序。当本函数结束时数组单元将被从最低到最高重新安排。

注: 本函数为 array 中的单元赋予新的键名。这将删除原有的键名而不仅是重新排序。

如果成功则返回 TRUE,失败则返回 FALSE

例子 1. sort() 例子

<?php

$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
    echo "fruits[".$key."] = " . $val . "\n";
}

?>

上例将输出:

fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange

fruits 被按照字母顺序排序。

可选的第二个参数 sort_flags 可以用以下值改变排序的行为:

排序类型标记:

  • SORT_REGULAR - 正常比较单元(不改变类型)

  • SORT_NUMERIC - 单元被作为数字来比较

  • SORT_STRING - 单元被作为字符串来比较

  • SORT_LOCALE_STRING - 根据当前的 locale 设置来把单元当作字符串比较。PHP 4.4.0 和 5.0.2 新加

注: 第二个参数是 PHP 4 新加的。

警告

在对含有混合类型值的数组排序时要小心,因为 sort() 可能会产生不可预知的结果。

参见 arsort()asort()ksort()krsort()natsort()natcasesort()rsort()usort()array_multisort()uksort()

uasort

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

uasort --  使用用户自定义的比较函数对数组中的值进行排序并保持索引关联

说明

bool uasort ( array &array, callback cmp_function )

本函数对数组排序并保持索引和单元之间的关联。主要用于对那些单元顺序很重要的结合数组进行排序。比较函数是用户自定义的。

如果成功则返回 TRUE,失败则返回 FALSE

注: 用户自定义比较函数的例子请参考 usort()uksort()

参见 usort()uksort()sort()asort()arsort()ksort()rsort()

uksort

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

uksort --  使用用户自定义的比较函数对数组中的键名进行排序

说明

bool uksort ( array &array, callback cmp_function )

本函数将使用用户提供的比较函数对数组中的键名进行排序。如果要排序的数组需要用一种不寻常的标准进行排序,那么应该使用此函数。

cmp_function 函数应接受两个参数,该参数将被 array 中的一对键名填充。比较函数在第一个参数小于,等于,或大于第二个参数时必须分别返回一个小于零,等于零,或大于零的整数。

如果成功则返回 TRUE,失败则返回 FALSE

例子 1. uksort() 例子

<?php
function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a > $b) ? -1 : 1;
}

$a = array(4 => "four", 3 => "three", 20 => "twenty", 10 => "ten");

uksort($a, "cmp");

foreach ($a as $key => $value) {
    echo "$key: $value\n";
}
?>

上例将输出:

20: twenty
10: ten
4: four
3: three

参见 usort()uasort()sort()asort()arsort()ksort()natsort()rsort()

usort

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

usort --  使用用户自定义的比较函数对数组中的值进行排序

说明

bool usort ( array &array, callback cmp_function )

本函数将用用户自定义的比较函数对一个数组中的值进行排序。如果要排序的数组需要用一种不寻常的标准进行排序,那么应该使用此函数。

比较函数必须在第一个参数被认为小于,等于或大于第二个参数时分别返回一个小于,等于或大于零的整数。

注: 如果两个成员比较结果相同,则它们在排序后的数组中的顺序未经定义。到 PHP 4.0.6 之前,用户自定义函数将保留这些单元的原有顺序。但是由于在 4.1.0 中引进了新的排序算法,结果将不是这样了,因为对此没有一个有效的解决方案。

注: 本函数为 array 中的单元赋予新的键名。这将删除原有的键名而不仅是重新排序。

如果成功则返回 TRUE,失败则返回 FALSE

例子 1. usort() 例子

<?php
function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

$a = array(3, 2, 5, 6, 1);

usort($a, "cmp");

foreach ($a as $key => $value) {
    echo "$key: $value\n";
}
?>

上例将输出:

0: 1
1: 2
2: 3
3: 5
4: 6

注: 很明显在这个小例子中用 sort() 函数更合适。

例子 2. 使用多维数组的 usort() 例子

<?php
function cmp($a, $b)
{
    return strcmp($a["fruit"], $b["fruit"]);
}

$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";

usort($fruits, "cmp");

while (list($key, $value) = each($fruits)) {
    echo "\$fruits[$key]: " . $value["fruit"] . "\n";
}
?>

当排序多维数组时,$a$b 包含到数组第一个索引的引用。

上例将输出:

$fruits[0]: apples
$fruits[1]: grapes
$fruits[2]: lemons

例子 3. 使用对象的成员函数的 usort() 例子

<?php
class TestObj {
    var $name;

    function TestObj($name)
    {
        $this->name = $name;
    }

    /* This is the static comparing function: */
    function cmp_obj($a, $b)
    {
        $al = strtolower($a->name);
        $bl = strtolower($b->name);
        if ($al == $bl) {
            return 0;
        }
        return ($al > $bl) ? +1 : -1;
    }
}

$a[] = new TestObj("c");
$a[] = new TestObj("b");
$a[] = new TestObj("d");

usort($a, array("TestObj", "cmp_obj"));

foreach ($a as $item) {
    echo $item->name . "\n";
}
?>

上例将输出:

b
c
d

参见 uasort()uksort()sort()asort()arsort()ksort()natsort()rsort()

VI. Aspell 函数(已废弃)

简介

可以用 aspell() 函数对某个单词进行拼写检查并给出正确的拼写建议。

注: 该扩展已经被从 PHP 中删除,在 PHP 4.3.0 及以后的版本不再有效。如果想用 PHP 进行拼写检查,请使用 pspell。它使用 pspell 库,并且能够和更新版本的 aspell 一起工作。


需求

aspell 仅工作于非常旧(.27.* 及以前)版本的 aspell 库。无论是该模块,或是那些旧版本的 aspell 均不再被支持。如果需要 aspell 库,可以在 http://aspell.sourceforge.net/ 找到。


安装

在 PHP 4 中,本类函数仅在 PHP 编译时配置了 --with-aspell=[DIR] 时可用。


参见

参见 pspell

目录
aspell_check_raw --  Check a word without changing its case or trying to trim it [deprecated]
aspell_check -- Check a word [deprecated]
aspell_new -- Load a new dictionary [deprecated]
aspell_suggest -- Suggest spellings of a word [deprecated]

aspell_check_raw

(PHP 3 >= 3.0.7, PHP 4 <= 4.2.3)

aspell_check_raw --  Check a word without changing its case or trying to trim it [deprecated]

Description

bool aspell_check_raw ( int dictionary_link, string word )

aspell_check_raw() checks the spelling of a word, without changing its case or trying to trim it in any way and returns TRUE if the spelling is correct, FALSE if not.

例子 1. aspell_check_raw()

<?php

$aspell_link = aspell_new("english");

if (aspell_check_raw($aspell_link, "test")) {
    echo "This is a valid spelling";
} else {
    echo "Sorry, wrong spelling";
}

?>

aspell_check

(PHP 3 >= 3.0.7, PHP 4 <= 4.2.3)

aspell_check -- Check a word [deprecated]

Description

bool aspell_check ( int dictionary_link, string word )

aspell_check() checks the spelling of a word and returns TRUE if the spelling is correct, FALSE if not.

例子 1. aspell_check()

<?php

$aspell_link = aspell_new("english");

if (aspell_check($aspell_link, "testt")) {
    echo "This is a valid spelling";
} else {
    echo "Sorry, wrong spelling";
}

?>

aspell_new

(PHP 3 >= 3.0.7, PHP 4 <= 4.2.3)

aspell_new -- Load a new dictionary [deprecated]

Description

int aspell_new ( string master [, string personal] )

aspell_new() opens up a new dictionary and returns the dictionary link identifier for use in other aspell functions. Returns FALSE on error.

例子 1. aspell_new()

<?php
$aspell_link = aspell_new("english");
?>

aspell_suggest

(PHP 3 >= 3.0.7, PHP 4 <= 4.2.3)

aspell_suggest -- Suggest spellings of a word [deprecated]

Description

array aspell_suggest ( int dictionary_link, string word )

aspell_suggest() returns an array of possible spellings for the given word.

例子 1. aspell_suggest()

<?php

$aspell_link = aspell_new("english");

if (!aspell_check($aspell_link, "test")) {
    $suggestions = aspell_suggest($aspell_link, "test");

    foreach ($suggestions as $suggestion) {
        echo "Possible spelling: $suggestion<br />\n"; 
    }
}

?>

VII. BC math 高精度数学函数

简介

PHP 为任意精度数学计算提供了二进制计算器(Binary Calculator),它支持任意大小和精度的数字,以字符串形式描述。


需求

自 PHP 4.0.4 以来,libbcmath 都绑定在 PHP 内部。本扩展不需要其它外部库的支持。


安装

本类函数仅在 PHP 编译时配置了 --enable-bcmath 时可用。在 PHP 3 中,本类函数仅在 PHP 编译时没有配置 --disable-bcmath 时可用。

PHP 的 Windows 版本已经内置该扩展模块的支持。无需加载任何附加扩展库即可使用这些函数。


运行时配置

这些函数的行为受 php.ini 的影响。

表格 1. BC 数学库配置选项

名称默认值可修改范围更新记录
bcmath.scale"0"PHP_INI_ALL自 PHP 5.0.0 起可用。
有关 PHP_INI_* 常量进一步的细节与定义参见附录 G

以下是配置选项的简要解释。

bcmath.scale integer

所有 bcmath 函数中十进制数字的数目。参见 bcscale()


资源类型

本扩展模块未定义任何资源类型。


预定义常量

本扩展模块未定义任何常量。

目录
bcadd -- Add two arbitrary precision numbers
bccomp -- Compare two arbitrary precision numbers
bcdiv -- Divide two arbitrary precision numbers
bcmod --  Get modulus of an arbitrary precision number
bcmul -- Multiply two arbitrary precision number
bcpow --  Raise an arbitrary precision number to another
bcpowmod --  Raise an arbitrary precision number to another, reduced by a specified modulus
bcscale --  Set default scale parameter for all bc math functions
bcsqrt --  Get the square root of an arbitrary precision number
bcsub --  Subtract one arbitrary precision number from another

bcadd

(PHP 3, PHP 4, PHP 5)

bcadd -- Add two arbitrary precision numbers

Description

string bcadd ( string left_operand, string right_operand [, int scale] )

Adds the left_operand to the right_operand and returns the sum in a string. The optional scale parameter is used to set the number of digits after the decimal place in the result.

范例

例子 1. bcadd() example

<?php

$a = '1.234';
$b = '5';

echo bcadd($a, $b);     // 6
echo bcadd($a, $b, 4);  // 6.2340

?>

参见

bcsub().

bccomp

(PHP 3, PHP 4, PHP 5)

bccomp -- Compare two arbitrary precision numbers

Description

int bccomp ( string left_operand, string right_operand [, int scale] )

Compares the left_operand to the right_operand and returns the result as an integer. The optional scale parameter is used to set the number of digits after the decimal place which will be used in the comparison. The return value is 0 if the two operands are equal. If the left_operand is larger than the right_operand the return value is +1 and if the left_operand is less than the right_operand the return value is -1.

范例

例子 1. bccomp() example

<?php

echo bccomp('1', '2') . "\n";   // -1
echo bccomp('1.00001', '1', 3); // 0
echo bccomp('1.00001', '1', 5); // 1

?>

bcdiv

(PHP 3, PHP 4, PHP 5)

bcdiv -- Divide two arbitrary precision numbers

Description

string bcdiv ( string left_operand, string right_operand [, int scale] )

Divides the left_operand by the right_operand and returns the result. The optional scale sets the number of digits after the decimal place in the result, which defaults to 0.

范例

例子 1. bcdiv() example

<?php

echo bcdiv('105', '6.55957', 3);  // 16.007

?>

参见

bcmul().

bcmod

(PHP 3, PHP 4, PHP 5)

bcmod --  Get modulus of an arbitrary precision number

Description

string bcmod ( string left_operand, string modulus )

Get the modulus of the left_operand using modulus.

范例

例子 1. bcmod() example

<?php
echo bcmod('4', '2'); // 0
echo bcmod('2', '4'); // 2
?>

参见

bcdiv().

bcmul

(PHP 3, PHP 4, PHP 5)

bcmul -- Multiply two arbitrary precision number

Description

string bcmul ( string left_operand, string right_operand [, int scale] )

Multiply the left_operand by the right_operand and returns the result. The optional scale sets the number of digits after the decimal place in the result.

范例

例子 1. bcmul() example

<?php
echo bcmul('1.34747474747', '35', 3); // 47.162
echo bcmul('2', '4'); // 8
?>

参见

bcdiv().

bcpow

(PHP 3, PHP 4, PHP 5)

bcpow --  Raise an arbitrary precision number to another

Description

string bcpow ( string x, string y [, int scale] )

Raise x to the power y. The optional scale can be used to set the number of digits after the decimal place in the result.

范例

例子 1. bcpow() example

<?php

echo bcpow('4.2', '3', 2); // 74.08

?>

参见

bcpowmod()bcsqrt().

bcpowmod

(PHP 5)

bcpowmod --  Raise an arbitrary precision number to another, reduced by a specified modulus

Description

string bcpowmod ( string x, string y, string modulus [, int scale] )

Use the fast-exponentiation method to raise x to the power y with respect to the modulus modulus. The optional scale can be used to set the number of digits after the decimal place in the result.

注: Because this method uses the modulus operation, non-natural numbers may give unexpected results. A natural number is any positive non-zero integer.

范例

The following two statements are functionally identical. The bcpowmod() version however, executes in less time and can accept larger parameters.

<?php
$a = bcpowmod($x, $y, $mod);

$b = bcmod(bcpow($x, $y), $mod);

// $a and $b are equal to each other. 

?>

参见

bcpow()bcmod().

bcscale

(PHP 3, PHP 4, PHP 5)

bcscale --  Set default scale parameter for all bc math functions

Description

bool bcscale ( int scale )

This function sets the default scale parameter for all subsequent bc math functions that do not explicitly specify a scale parameter. 如果成功则返回 TRUE,失败则返回 FALSE

范例

例子 1. bcscale() example

<?php

// default scale : 3
bcscale(3);
echo bcdiv('105', '6.55957'); // 16.007

// this is the same without bcscale()
echo bcdiv('105', '6.55957', 3); // 16.007

?>

bcsqrt

(PHP 3, PHP 4, PHP 5)

bcsqrt --  Get the square root of an arbitrary precision number

Description

string bcsqrt ( string operand [, int scale] )

Return the square root of the operand. The optional scale parameter sets the number of digits after the decimal place in the result.

范例

例子 1. bcsqrt() example

<?php

echo bcsqrt('2', 3); // 1.414

?>

参见

bcpow().

bcsub

(PHP 3, PHP 4, PHP 5)

bcsub --  Subtract one arbitrary precision number from another

Description

string bcsub ( string left_operand, string right_operand [, int scale] )

Subtracts the right_operand from the left_operand and returns the result in a string. The optional scale parameter is used to set the number of digits after the decimal place in the result.

范例

例子 1. bcsub() example

<?php

$a = '1.234';
$b = '5';
 
echo bcsub($a, $b);     // -3
echo bcsub($a, $b, 4);  // -3.7660

?>

参见

bcadd().

VIII. Bzip2 压缩函数

简介

Bzip2 函数用来透明的读写 bzip2(.bz2)压缩文件。


需求

本模块使用 Julian Seward 写的 bzip2 库。此模块需要 bzip2/libbzip2 版本 >= 1.0.x。


安装

PHP 的 bzip2 支持默认未打开。编译 PHP 时需要 --with-bz2[=DIR] 配置选项来激活 bzip2 支持。


运行时配置

本扩展模块在 php.ini 中未定义任何配置选项。


资源类型

本扩展定义了一种资源类型:一个文件指针,指向正在被操作的 bz2 文件。


预定义常量

本扩展模块未定义任何常量。


范例

该例子打开一临时文件,并写入一测试字符串,然后打印文件内容。

例子 1. Bzip2 例子

<?php

$filename = "/tmp/testfile.bz2";
$str = "This is a test string.\n";

// 以写入方式打开文件
$bz = bzopen($filename, "w");

// 写入字符串到文件
bzwrite($bz, $str);

// 关闭文件
bzclose($bz);

// 以读取方式打开文件
$bz = bzopen($filename, "r");

// 读取 10 个字符
echo bzread($bz, 10);

// 输出直到文件结尾(或后续的 1024 字节)并关闭它。
echo bzread($bz);

bzclose($bz);

?>
目录
bzclose -- Close a bzip2 file
bzcompress -- Compress a string into bzip2 encoded data
bzdecompress -- Decompresses bzip2 encoded data
bzerrno -- Returns a bzip2 error number
bzerror --  Returns the bzip2 error number and error string in an array
bzerrstr -- Returns a bzip2 error string
bzflush -- Force a write of all buffered data
bzopen -- Opens a bzip2 compressed file
bzread -- Binary safe bzip2 file read
bzwrite -- Binary safe bzip2 file write

bzclose

(PHP 4 >= 4.3.3, PHP 5)

bzclose -- Close a bzip2 file

说明

int bzclose ( resource bz )

Closes the given bzip2 file pointer.

参数

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

返回值

如果成功则返回 TRUE,失败则返回 FALSE

参见

bzopen()

bzcompress

(PHP 4 >= 4.3.3, PHP 5)

bzcompress -- Compress a string into bzip2 encoded data

说明

mixed bzcompress ( string source [, int blocksize [, int workfactor]] )

bzcompress() compresses the given string and returns it as bzip2 encoded data.

参数

source

The string to compress.

blocksize

Specifies the blocksize used during compression and should be a number from 1 to 9 with 9 giving the best compression, but using more resources to do so. blocksize defaults to 4.

workfactor

Controls how the compression phase behaves when presented with worst case, highly repetitive, input data. The value can be between 0 and 250 with 0 being a special case and 30 being the default value.

Regardless of the workfactor, the generated output is the same.

返回值

The compressed string or number of error in case of error.

范例

例子 1. Compressing data

<?php
$str = "sample data";
$bzstr = bzcompress($str, 9);
echo $bzstr;
?>

bzdecompress

(PHP 4 >= 4.3.3, PHP 5)

bzdecompress -- Decompresses bzip2 encoded data

说明

mixed bzdecompress ( string source [, int small] )

bzdecompress() decompresses the given string containing bzip2 encoded data.

参数

source

The string to decompress.

small

If TRUE, an alternative decompression algorithm will be used which uses less memory (the maximum memory requirement drops to around 2300K) but works at roughly half the speed.

See the bzip2 documentation for more information about this feature.

返回值

The decompressed string or number of error in case of error.

范例

例子 1. Decompressing a String

<?php
$start_str = "This is not an honest face?";
$bzstr = bzcompress($start_str);

echo "Compressed String: ";
echo $bzstr;
echo "\n<br />\n";

$str = bzdecompress($bzstr);
echo "Decompressed String: ";
echo $str;
echo "\n<br />\n";
?>

参见

bzcompress()

bzerrno

(PHP 4 >= 4.3.3, PHP 5)

bzerrno -- Returns a bzip2 error number

说明

int bzerrno ( resource bz )

Returns the error number of any bzip2 error returned by the given file pointer.

参数

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

返回值

Returns the error number as an integer.

bzerror

(PHP 4 >= 4.3.3, PHP 5)

bzerror --  Returns the bzip2 error number and error string in an array

说明

array bzerror ( resource bz )

Returns the error number and error string of any bzip2 error returned by the given file pointer.

参数

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

返回值

Returns an associative array, with the error code in the errno entry, and the error message in the errstr entry.

范例

例子 1. bzerror() example

<?php
$error = bzerror($bz);

echo $error["errno"];
echo $error["errstr"];
?>

bzerrstr

(PHP 4 >= 4.3.3, PHP 5)

bzerrstr -- Returns a bzip2 error string

说明

string bzerrstr ( resource bz )

Gets the error string of any bzip2 error returned by the given file pointer.

参数

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

返回值

Returns a string containing the error message.

bzflush

(PHP 4 >= 4.3.3, PHP 5)

bzflush -- Force a write of all buffered data

说明

int bzflush ( resource bz )

Forces a write of all buffered bzip2 data for the file pointer bz.

参数

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

返回值

如果成功则返回 TRUE,失败则返回 FALSE

bzopen

(PHP 4 >= 4.3.3, PHP 5)

bzopen -- Opens a bzip2 compressed file

说明

resource bzopen ( string filename, string mode )

bzopen() opens a bzip2 (.bz2) file for reading or writing.

参数

filename

The name of the file to open.

mode

Similar to the fopen() function ('r' for read, 'w' for write, etc.).

返回值

If the open fails, bzopen() returns FALSE, otherwise it returns a pointer to the newly opened file.

范例

例子 1. bzopen() example

<?php

$file = "/tmp/foo.bz2";
$bz = bzopen($file, "r") or die("Couldn't open $file for reading");

bzclose($bz);

?>

参见

bzclose()

bzread

(PHP 4 >= 4.3.3, PHP 5)

bzread -- Binary safe bzip2 file read

说明

string bzread ( resource bz [, int length] )

bzread() reads from the given bzip2 file pointer.

Reading stops when length (uncompressed) bytes have been read or EOF is reached, whichever comes first.

参数

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

length

If not specified, bzread() will read 1024 (uncompressed) bytes at a time.

返回值

Returns the uncompressed data, or FALSE on error.

范例

例子 1. bzread() example

<?php

$file = "/tmp/foo.bz2";
$bz = bzopen($file, "r") or die("Couldn't open $file");

$decompressed_file = '';
while (!feof($bz)) {
  $decompressed_file .= bzread($bz, 4096);
}
bzclose($bz);

echo "The contents of $file are: <br />\n";
echo $decompressed_file;

?>

bzwrite

(PHP 4 >= 4.3.3, PHP 5)

bzwrite -- Binary safe bzip2 file write

说明

int bzwrite ( resource bz, string data [, int length] )

bzwrite() writes a string into the given bzip2 file stream.

参数

bz

The file pointer. It must be valid and must point to a file successfully opened by bzopen().

data

The written data.

length

If supplied, writing will stop after length (uncompressed) bytes have been written or the end of data is reached, whichever comes first.

返回值

Returns the number of bytes written, or FALSE on error.

范例

例子 1. bzwrite() example

<?php
$str = "uncompressed data";
$bz = bzopen("/tmp/foo.bz2", "w");
bzwrite($bz, $str, strlen($str));
bzclose($bz);
?>

IX. Calendar 日历函数

简介

日历扩展是由一系列简单的日历格式转换函数组成。媒介或标准是基于儒略日计数(Julian Day Count)。儒略日计数是从公元前 4713 年 1 月 1 日开始计算的。在不同的日历系统中转换,必须先将其转换为儒略日计数,然后转换为目标日历格式。儒略日计数与罗马儒略历(Julian Calendar)完全不同!更多关于儒略日计数的信息,请访问 http://www.hermetic.ch/cal_stud/jdn.htm。更多关于日历系统的信息,请访问 http://www.boogle.com/info/cal-overview.html。从此页面引用的信息包含了这些介绍,在引号之内。


安装

要使用本类函数,需要在编译 PHP 时加上 --enable-calendar

PHP 的 Windows 版本已经内置该扩展模块的支持。无需加载任何附加扩展库即可使用这些函数。


运行时配置

本扩展模块在 php.ini 中未定义任何配置选项。


资源类型

本扩展模块未定义任何资源类型。


预定义常量

以下常量由本扩展模块定义,因此只有在本扩展模块被编译到 PHP 中,或者在运行时被动态加载后才有效。

CAL_GREGORIAN (integer)

CAL_JULIAN (integer)

CAL_JEWISH (integer)

CAL_FRENCH (integer)

CAL_NUM_CALS (integer)

CAL_DOW_DAYNO (integer)

CAL_DOW_SHORT (integer)

CAL_DOW_LONG (integer)

CAL_MONTH_GREGORIAN_SHORT (integer)

CAL_MONTH_GREGORIAN_LONG (integer)

CAL_MONTH_JULIAN_SHORT (integer)

CAL_MONTH_JULIAN_LONG (integer)

CAL_MONTH_JEWISH (integer)

CAL_MONTH_FRENCH (integer)

以下常量自 PHP 4.3.0 起可用:

CAL_EASTER_DEFAULT (integer)

CAL_EASTER_ROMAN (integer)

CAL_EASTER_ALWAYS_GREGORIAN (integer)

CAL_EASTER_ALWAYS_JULIAN (integer)

以下常量自 PHP 5.0.0 起可用:

CAL_JEWISH_ADD_ALAFIM_GERESH (integer)

CAL_JEWISH_ADD_ALAFIM (integer)

CAL_JEWISH_ADD_GERESHAYIM (integer)

目录
cal_days_in_month -- Return the number of days in a month for a given year and calendar
cal_from_jd -- Converts from Julian Day Count to a supported calendar
cal_info -- Returns information about a particular calendar
cal_to_jd -- Converts from a supported calendar to Julian Day Count
easter_date --  Get Unix timestamp for midnight on Easter of a given year
easter_days --  Get number of days after March 21 on which Easter falls for a given year
FrenchToJD --  Converts a date from the French Republican Calendar to a Julian Day Count
GregorianToJD --  Converts a Gregorian date to Julian Day Count
JDDayOfWeek -- Returns the day of the week
JDMonthName -- Returns a month name
JDToFrench --  Converts a Julian Day Count to the French Republican Calendar
JDToGregorian -- Converts Julian Day Count to Gregorian date
jdtojewish --  Converts a Julian day count to a Jewish calendar date
JDToJulian --  Converts a Julian Day Count to a Julian Calendar Date
jdtounix -- Convert Julian Day to Unix timestamp
JewishToJD --  Converts a date in the Jewish Calendar to Julian Day Count
JulianToJD --  Converts a Julian Calendar date to Julian Day Count
unixtojd -- Convert Unix timestamp to Julian Day

cal_days_in_month

(PHP 4 >= 4.1.0, PHP 5)

cal_days_in_month -- Return the number of days in a month for a given year and calendar

Description

int cal_days_in_month ( int calendar, int month, int year )

This function will return the number of days in the month of year for the specified calendar.

例子 1. cal_days_in_month() example

<?php
$num = cal_days_in_month(CAL_GREGORIAN, 8, 2003); // 31
echo "There was $num days in August 2003";
?>

See also jdtounix().

cal_from_jd

(PHP 4 >= 4.1.0, PHP 5)

cal_from_jd -- Converts from Julian Day Count to a supported calendar

Description

array cal_from_jd ( int jd, int calendar )

cal_from_jd() converts the Julian day given in jd into a date of the specified calendar. Supported calendar values are CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH and CAL_FRENCH.

例子 1. cal_from_jd() example

<?php
$today = unixtojd(mktime(0, 0, 0, 8, 16, 2003));
print_r(cal_from_jd($today, CAL_GREGORIAN));
?>

上例将输出:

Array
(
    [date] => 8/16/2003
    [month] => 8
    [day] => 16
    [year] => 2003
    [dow] => 6
    [abbrevdayname] => Sat
    [dayname] => Saturday
    [abbrevmonth] => Aug
    [monthname] => August
)

See also cal_to_jd().

cal_info

(PHP 4 >= 4.1.0, PHP 5)

cal_info -- Returns information about a particular calendar

Description

array cal_info ( [int calendar] )

cal_info() returns information on the specified calendar.

Calendar information is returned as an array containing the elements calname, calsymbol, month, abbrevmonth and maxdaysinmonth. The names of the different calendars which can be used as calendar are as follows:

  • 0 or CAL_GREGORIAN - Gregorian Calendar

  • 1 or CAL_JULIAN - Julian Calendar

  • 2 or CAL_JEWISH - Jewish Calendar

  • 3 or CAL_FRENCH - French Revolutionary Calendar

If no calendar is specified information on all supported calendars is returned as an array. This functionality is available beginning with PHP 5.

例子 1. cal_info() example

<?php
$info = cal_info(0);
print_r($info);
?>

上例将输出:

Array
(
    [months] => Array
        (
            [1] => January
            [2] => February
            [3] => March
            [4] => April
            [5] => May
            [6] => June
            [7] => July
            [8] => August
            [9] => September
            [10] => October
            [11] => November
            [12] => December
        )

    [abbrevmonths] => Array
        (
            [1] => Jan
            [2] => Feb
            [3] => Mar
            [4] => Apr
            [5] => May
            [6] => Jun
            [7] => Jul
            [8] => Aug
            [9] => Sep
            [10] => Oct
            [11] => Nov
            [12] => Dec
        )

    [maxdaysinmonth] => 31
    [calname] => Gregorian
    [calsymbol] => CAL_GREGORIAN
)

cal_to_jd

(PHP 4 >= 4.1.0, PHP 5)

cal_to_jd -- Converts from a supported calendar to Julian Day Count

Description

int cal_to_jd ( int calendar, int month, int day, int year )

cal_to_jd() calculates the Julian day count for a date in the specified calendar. Supported calendars are CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH and CAL_FRENCH.

See also cal_from_jd().

easter_date

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

easter_date --  Get Unix timestamp for midnight on Easter of a given year

Description

int easter_date ( [int year] )

Returns the Unix timestamp corresponding to midnight on Easter of the given year.

Since PHP 4.3.0, the year parameter is optional and defaults to the current year according to the localtime if omitted.

例子 1. easter_date() example

<?php

echo date("M-d-Y", easter_date(1999));        // Apr-04-1999
echo date("M-d-Y", easter_date(2000));        // Apr-23-2000
echo date("M-d-Y", easter_date(2001));        // Apr-15-2001

?>

警告

This function will generate a warning if the year is outside of the range for Unix timestamps (i.e. before 1970 or after 2037).

The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.

(The code is based on a C program by Simon Kershaw, <webmaster at ely.anglican dot org>)

See easter_days() for calculating Easter before 1970 or after 2037.

easter_days

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

easter_days --  Get number of days after March 21 on which Easter falls for a given year

Description

int easter_days ( [int year [, int method]] )

Returns the number of days after March 21 on which Easter falls for a given year. If no year is specified, the current year is assumed.

Since PHP 4.3.0, the year parameter is optional and defaults to the current year according to the localtime if omitted.

The method parameter was also introduced in PHP 4.3.0 and allows to calculate easter dates based on the Gregorian calendar during the years 1582 - 1752 when set to CAL_EASTER_ROMAN. See the calendar constants for more valid constants.

This function can be used instead of easter_date() to calculate Easter for years which fall outside the range of Unix timestamps (i.e. before 1970 or after 2037).

例子 1. easter_days() example

<?php

echo easter_days(1999);        // 14, i.e. April 4
echo easter_days(1492);        // 32, i.e. April 22
echo easter_days(1913);        //  2, i.e. March 23

?>

The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.

(The code is based on a C program by Simon Kershaw, <webmaster at ely.anglican dot org>)

See also easter_date().

FrenchToJD

(PHP 3, PHP 4, PHP 5)

FrenchToJD --  Converts a date from the French Republican Calendar to a Julian Day Count

Description

int frenchtojd ( int month, int day, int year )

Converts a date from the French Republican Calendar to a Julian Day Count.

These routines only convert dates in years 1 through 14 (Gregorian dates 22 September 1792 through 22 September 1806). This more than covers the period when the calendar was in use.

GregorianToJD

(PHP 3, PHP 4, PHP 5)

GregorianToJD --  Converts a Gregorian date to Julian Day Count

Description

int gregoriantojd ( int month, int day, int year )

Valid Range for Gregorian Calendar 4714 B.C. to 9999 A.D.

Although this function can handle dates all the way back to 4714 B.C., such use may not be meaningful. The Gregorian calendar was not instituted until October 15, 1582 (or October 5, 1582 in the Julian calendar). Some countries did not accept it until much later. For example, Britain converted in 1752, The USSR in 1918 and Greece in 1923. Most European countries used the Julian calendar prior to the Gregorian.

例子 1. Calendar functions

<?php
$jd = GregorianToJD(10, 11, 1970);
echo "$jd\n";
$gregorian = JDToGregorian($jd);
echo "$gregorian\n";
?>

JDDayOfWeek

(PHP 3, PHP 4, PHP 5)

JDDayOfWeek -- Returns the day of the week

Description

mixed jddayofweek ( int julianday [, int mode] )

Returns the day of the week. Can return a string or an integer depending on the mode.

表格 1. Calendar week modes

ModeMeaning
0 (Default) Returns the day number as an int (0=Sunday, 1=Monday, etc)
1 Returns string containing the day of week (English-Gregorian)
2 Returns a string containing the abbreviated day of week (English-Gregorian)

JDMonthName

(PHP 3, PHP 4, PHP 5)

JDMonthName -- Returns a month name

Description

string jdmonthname ( int julianday, int mode )

Returns a string containing a month name. mode tells this function which calendar to convert the Julian Day Count to, and what type of month names are to be returned.

表格 1. Calendar modes

ModeMeaningValues
0Gregorian - abbreviatedJan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
1GregorianJanuary, February, March, April, May, June, July, August, September, October, November, December
2Julian - abbreviatedJan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
3JulianJanuary, February, March, April, May, June, July, August, September, October, November, December
4JewishTishri, Heshvan, Kislev, Tevet, Shevat, AdarI, AdarII, Nisan, Iyyar, Sivan, Tammuz, Av, Elul
5French RepublicanVendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose, Germinal, Floreal, Prairial, Messidor, Thermidor, Fructidor, Extra

JDToFrench

(PHP 3, PHP 4, PHP 5)

JDToFrench --  Converts a Julian Day Count to the French Republican Calendar

Description

string jdtofrench ( int juliandaycount )

Converts a Julian Day Count to the French Republican Calendar.

JDToGregorian

(PHP 3, PHP 4, PHP 5)

JDToGregorian -- Converts Julian Day Count to Gregorian date

Description

string jdtogregorian ( int julianday )

Converts Julian Day Count to a string containing the Gregorian date in the format of "month/day/year".

jdtojewish

(PHP 3, PHP 4, PHP 5)

jdtojewish --  Converts a Julian day count to a Jewish calendar date

Description

string jdtojewish ( int juliandaycount [, bool hebrew [, int fl]] )

Converts a Julian Day Count to the Jewish Calendar.

The optional hebrew and fl parameters became available in PHP 5.0.0

If the hebrew parameter is set to TRUE, the fl parameter is used for Hebrew, string based, output format. The available formats are: CAL_JEWISH_ADD_ALAFIM_GERESH, CAL_JEWISH_ADD_ALAFIM, CAL_JEWISH_ADD_GERESHAYIM.

例子 1. jdtojewish() Example

<?php
echo jdtojewish(gregoriantojd(10, 8, 2002), true,
       CAL_JEWISH_ADD_GERESHAYIM + CAL_JEWISH_ADD_ALAFIM + CAL_JEWISH_ADD_ALAFIM_GERESH); 
?>

JDToJulian

(PHP 3, PHP 4, PHP 5)

JDToJulian --  Converts a Julian Day Count to a Julian Calendar Date

Description

string jdtojulian ( int julianday )

Converts Julian Day Count to a string containing the Julian Calendar Date in the format of "month/day/year".

jdtounix

(PHP 4, PHP 5)

jdtounix -- Convert Julian Day to Unix timestamp

Description

int jdtounix ( int jday )

This function will return a Unix timestamp corresponding to the Julian Day given in jday or FALSE if jday is not inside the Unix epoch (Gregorian years between 1970 and 2037 or 2440588 <= jday <= 2465342 ). The time returned is localtime (and not GMT).

See also unixtojd().

JewishToJD

(PHP 3, PHP 4, PHP 5)

JewishToJD --  Converts a date in the Jewish Calendar to Julian Day Count

Description

int jewishtojd ( int month, int day, int year )

Although this function can handle dates all the way back to the year 1 (3761 B.C.), such use may not be meaningful. The Jewish calendar has been in use for several thousand years, but in the early days there was no formula to determine the start of a month. A new month was started when the new moon was first observed.

JulianToJD

(PHP 3, PHP 4, PHP 5)

JulianToJD --  Converts a Julian Calendar date to Julian Day Count

Description

int juliantojd ( int month, int day, int year )

Valid Range for Julian Calendar 4713 B.C. to 9999 A.D.

Although this function can handle dates all the way back to 4713 B.C., such use may not be meaningful. The calendar was created in 46 B.C., but the details did not stabilize until at least 8 A.D., and perhaps as late at the 4th century. Also, the beginning of a year varied from one culture to another - not all accepted January as the first month.

注意

Remember, the current calendar system being used worldwide is the Gregorian calendar. gregoriantojd() can be used to convert such dates to their Julian Day count.

unixtojd

(PHP 4, PHP 5)

unixtojd -- Convert Unix timestamp to Julian Day

Description

int unixtojd ( [int timestamp] )

Return the Julian Day for a Unix timestamp (seconds since 1.1.1970), or for the current day if no timestamp is given.

See also jdtounix().

X. CCVS API Functions [deprecated]

简介

These functions interface the CCVS API, allowing you to work directly with CCVS from your PHP scripts. CCVS is RedHat's solution to the "middle-man" in credit card processing. It lets you directly address the credit card clearing houses via your *nix box and a modem. Using the CCVS module for PHP, you can process credit cards directly through CCVS via your PHP Scripts. The following references will outline the process.

注: CCVS has been discontinued by Red Hat and there are no plans to issue further keys or support contracts. Those looking for a replacement can consider MCVE by Main Street Softworks as a potential replacement. It is similar in design and has documented PHP support!

This extension has been removed from PHP and is no longer available as of PHP 4.3.0. If you want to use credit card processing features you can use MCVE instead.


安装

To enable CCVS Support in PHP, first verify your CCVS installation directory. You will then need to configure PHP with the --with-ccvs option. If you use this option without specifying the path to your CCVS installation, PHP will attempt to look in the default CCVS Install location (/usr/local/ccvs). If CCVS is in a non-standard location, run configure with: --with-ccvs=[DIR], where DIR is the path to your CCVS installation. Please note that CCVS support requires that DIR/lib and DIR/include exist, and include cv_api.h under the include directory and libccvs.a under the lib directory.

Additionally, a ccvsd process will need to be running for the configurations you intend to use in your PHP scripts. You will also need to make sure the PHP Processes are running under the same user as your CCVS was installed as (e.g. if you installed CCVS as user 'ccvs', your PHP processes must run as 'ccvs' as well.)


参见

RedHat has discontinued support for CCVS; however, a slightly outdated manual is still available at http://www.redhat.com/docs/manuals/ccvs/.

目录
ccvs_add -- Add data to a transaction
ccvs_auth -- Perform credit authorization test on a transaction
ccvs_command --  Performs a command which is peculiar to a single protocol, and thus is not available in the general CCVS API
ccvs_count --  Find out how many transactions of a given type are stored in the system
ccvs_delete -- Delete a transaction
ccvs_done -- Terminate CCVS engine and do cleanup work
ccvs_init -- Initialize CCVS for use
ccvs_lookup --  Look up an item of a particular type in the database #
ccvs_new -- Create a new, blank transaction
ccvs_report -- Return the status of the background communication process
ccvs_return --  Transfer funds from the merchant to the credit card holder
ccvs_reverse --  Perform a full reversal on an already-processed authorization
ccvs_sale --  Transfer funds from the credit card holder to the merchant
ccvs_status -- Check the status of an invoice
ccvs_textvalue -- Get text return value for previous function call
ccvs_void --  Perform a full reversal on a completed transaction

ccvs_add

(4.0.2 - 4.2.3 only)

ccvs_add -- Add data to a transaction

Description

string ccvs_add ( string session, string invoice, string argtype, string argval )

警告

本函数暂无文档,仅有参数列表。

ccvs_auth

(4.0.2 - 4.2.3 only)

ccvs_auth -- Perform credit authorization test on a transaction

Description

string ccvs_auth ( string session, string invoice )

警告

本函数暂无文档,仅有参数列表。

ccvs_command

(4.0.2 - 4.2.3 only)

ccvs_command --  Performs a command which is peculiar to a single protocol, and thus is not available in the general CCVS API

Description

string ccvs_command ( string session, string type, string argval )

警告

本函数暂无文档,仅有参数列表。

ccvs_count

(4.0.2 - 4.2.3 only)

ccvs_count --  Find out how many transactions of a given type are stored in the system

Description

int ccvs_count ( string session, string type )

警告

本函数暂无文档,仅有参数列表。

ccvs_delete

(4.0.2 - 4.2.3 only)

ccvs_delete -- Delete a transaction

Description

string ccvs_delete ( string session, string invoice )

警告

本函数暂无文档,仅有参数列表。

ccvs_done

(4.0.2 - 4.2.3 only)

ccvs_done -- Terminate CCVS engine and do cleanup work

Description

string ccvs_done ( string sess )

警告

本函数暂无文档,仅有参数列表。

ccvs_init

(4.0.2 - 4.2.3 only)

ccvs_init -- Initialize CCVS for use

Description

string ccvs_init ( string name )

警告

本函数暂无文档,仅有参数列表。

ccvs_lookup

(4.0.2 - 4.2.3 only)

ccvs_lookup --  Look up an item of a particular type in the database #

Description

string ccvs_lookup ( string session, string invoice, int inum )

警告

本函数暂无文档,仅有参数列表。

ccvs_new

(4.0.2 - 4.2.3 only)

ccvs_new -- Create a new, blank transaction

Description

string ccvs_new ( string session, string invoice )

警告

本函数暂无文档,仅有参数列表。

ccvs_report

(4.0.2 - 4.2.3 only)

ccvs_report -- Return the status of the background communication process

Description

string ccvs_report ( string session, string type )

警告

本函数暂无文档,仅有参数列表。

ccvs_return

(4.0.2 - 4.2.3 only)

ccvs_return --  Transfer funds from the merchant to the credit card holder

Description

string ccvs_return ( string session, string invoice )

警告

本函数暂无文档,仅有参数列表。

ccvs_reverse

(4.0.2 - 4.2.3 only)

ccvs_reverse --  Perform a full reversal on an already-processed authorization

Description

string ccvs_reverse ( string session, string invoice )

警告

本函数暂无文档,仅有参数列表。

ccvs_sale

(4.0.2 - 4.2.3 only)

ccvs_sale --  Transfer funds from the credit card holder to the merchant

Description

string ccvs_sale ( string session, string invoice )

警告

本函数暂无文档,仅有参数列表。

ccvs_status

(4.0.2 - 4.2.3 only)

ccvs_status -- Check the status of an invoice

Description

string ccvs_status ( string session, string invoice )

警告

本函数暂无文档,仅有参数列表。

ccvs_textvalue

(4.0.2 - 4.2.3 only)

ccvs_textvalue -- Get text return value for previous function call

Description

string ccvs_textvalue ( string session )

警告

本函数暂无文档,仅有参数列表。

ccvs_void

(4.0.2 - 4.2.3 only)

ccvs_void --  Perform a full reversal on a completed transaction

Description

string ccvs_void ( string session, string invoice )

警告

本函数暂无文档,仅有参数列表。

XI. Character Type Functions

简介

The functions provided by this extension check whether a character or string falls into a certain character class according to the current locale (see also setlocale()).

When called with an integer argument these functions behave exactly like their C counterparts from ctype.h. It means that if you pass an integer smaller than 256 it will use the ASCII value of it to see if it fits in the specified range (digits are in 0x30-0x39). If the number is between -128 (inclusive) and 0 then 256 will be added and the check will be done on that.

When called with a string argument they will check every character in the string and will only return TRUE if every character in the string matches the requested criteria. When called with an empty string the result will always be TRUE.

Passing anything else but a string or integer will return FALSE immediately.

It should be noted that ctype functions are always preferred over regular expressions, and even to some equivalent str_* and is_* functions. This is because of the fact that ctype uses a native C library and thus processes significantly faster.


需求

None besides functions from the standard C library which are always available.


安装

Beginning with PHP 4.2.0 these functions are enabled by default. For older versions you have to configure and compile PHP with --enable-ctype. You can disable ctype support with --disable-ctype.

PHP 的 Windows 版本已经内置该扩展模块的支持。无需加载任何附加扩展库即可使用这些函数。

注: Builtin support for ctype is available with PHP 4.3.0.


运行时配置

本扩展模块在 php.ini 中未定义任何配置选项。


资源类型

本扩展模块未定义任何资源类型。


预定义常量

本扩展模块未定义任何常量。

目录
ctype_alnum -- Check for alphanumeric character(s)
ctype_alpha -- Check for alphabetic character(s)
ctype_cntrl -- Check for control character(s)
ctype_digit -- Check for numeric character(s)
ctype_graph -- Check for any printable character(s) except space
ctype_lower -- Check for lowercase character(s)
ctype_print -- Check for printable character(s)
ctype_punct --  Check for any printable character which is not whitespace or an alphanumeric character
ctype_space -- Check for whitespace character(s)
ctype_upper -- Check for uppercase character(s)
ctype_xdigit --  Check for character(s) representing a hexadecimal digit

ctype_alnum

(PHP 4 >= 4.0.4, PHP 5)

ctype_alnum -- Check for alphanumeric character(s)

说明

bool ctype_alnum ( string text )

Checks if all of the characters in the provided string, text, are alphanumeric. In the standard C locale letters are just [A-Za-z] and the function is equivalent to preg_match('/^[a-z0-9]*$/i', $text).

参数

text

The tested string.

返回值

Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise.

范例

例子 1. A ctype_alnum() example (using the default locale)

<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
    if (ctype_alnum($testcase)) {
        echo "The string $testcase consists of all letters or digits.\n";
    } else {
        echo "The string $testcase does not consist of all letters or digits.\n";
    }
}
?>

上例将输出:

The string AbCd1zyZ9 consists of all letters or digits.
The string foo!#$bar does not consists of all letters or digits.

ctype_alpha

(PHP 4 >= 4.0.4, PHP 5)

ctype_alpha -- Check for alphabetic character(s)

说明

bool ctype_alpha ( string text )

Checks if all of the characters in the provided string, text, are alphabetic. In the standard C locale letters are just [A-Za-z] and ctype_alpha() is equivalent to (ctype_upper($text) || ctype_lower($text)) if $text is just a single character, but other languages have letters that are considered neither upper nor lower case.

参数

text

The tested string.

返回值

Returns TRUE if every character in text is a letter from the current locale, FALSE otherwise.

范例

例子 1. A ctype_alpha() example (using the default locale)

<?php
$strings = array('KjgWZC', 'arf12');
foreach ($strings as $testcase) {
    if (ctype_alpha($testcase)) {
        echo "The string $testcase consists of all letters.\n";
    } else {
        echo "The string $testcase does not consist of all letters.\n";
    }
}
?>

上例将输出:

The string KjgWZC consists of all letters.
The string arf12 does not consists of all letters.

ctype_cntrl

(PHP 4 >= 4.0.4, PHP 5)

ctype_cntrl -- Check for control character(s)

说明

bool ctype_cntrl ( string text )

Checks if all of the characters in the provided string, text, are control characters. Control characters are e.g. line feed, tab, esc.

参数

text

The tested string.

返回值

Returns TRUE if every character in text is a letter from the current locale, FALSE otherwise.

范例

例子 1. A ctype_cntrl() example

<?php
$strings = array('string1' => "\n\r\t", 'string2' => 'arf12');
foreach ($strings as $name => $testcase) {
    if (ctype_cntrl($testcase)) {
        echo "The string '$name' consists of all control characters.\n";
    } else {
        echo "The string '$name' does not consist of all control characters.\n";
    }
}
?>

上例将输出:

The string 'string1' consists of all control characters.
The string 'string2' does not consists of all control characters.

ctype_digit

(PHP 4 >= 4.0.4, PHP 5)

ctype_digit -- Check for numeric character(s)

说明

bool ctype_digit ( string text )

Checks if all of the characters in the provided string, text, are numerical.

参数

text

The tested string.

返回值

Returns TRUE if every character in text is a decimal digit, FALSE otherwise.

范例

例子 1. A ctype_digit() example

<?php
$strings = array('1820.20', '10002', 'wsl!12');
foreach ($strings as $testcase) {
    if (ctype_digit($testcase)) {
        echo "The string $testcase consists of all digits.\n";
    } else {
        echo "The string $testcase does not consist of all digits.\n";
    }
}
?>

上例将输出:

The string 1820.20 does not consists of all digits.
The string 10002 consists of all digits.
The string wsl!12 does not consists of all digits.

ctype_graph

(PHP 4 >= 4.0.4, PHP 5)

ctype_graph -- Check for any printable character(s) except space

说明

bool ctype_graph ( string text )

Checks if all of the characters in the provided string, text, creates visible output.

参数

text

The tested string.

返回值

Returns TRUE if every character in text is printable and actually creates visible output (no white space), FALSE otherwise.

范例

例子 1. A ctype_graph() example

<?php
$strings = array('string1' => "asdf\n\r\t", 'string2' => 'arf12', 'string3' => 'LKA#@%.54');
foreach ($strings as $name => $testcase) {
    if (ctype_graph($testcase)) {
        echo "The string '$name' consists of all (visibly) printable characters.\n";
    } else {
        echo "The string '$name' does not consist of all (visibly) printable characters.\n";
    }
}
?>

上例将输出:

The string 'string1' does not consist of all (visibly) printable characters.
The string 'string2' consists of all (visibly) printable characters.
The string 'string3' consists of all (visibly) printable characters.

ctype_lower

(PHP 4 >= 4.0.4, PHP 5)

ctype_lower -- Check for lowercase character(s)

说明

bool ctype_lower ( string text )

Checks if all of the characters in the provided string, text, are lowercase letters.

参数

text

The tested string.

返回值

Returns TRUE if every character in text is a lowercase letter in the current locale.

范例

例子 1. A ctype_lower() example (using the default locale)

<?php
$strings = array('aac123', 'qiutoas', 'QASsdks');
foreach ($strings as $testcase) {
    if (ctype_lower($testcase)) {
        echo "The string $testcase consists of all lowercase letters.\n";
    } else {
        echo "The string $testcase does not consist of all lowercase letters.\n";
    }
}
?>

上例将输出:

The string aac123 does not consist of all lowercase letters.
The string qiutoas consists of all lowercase letters.
The string QASsdks does not consist of all lowercase letters.

ctype_print

(PHP 4 >= 4.0.4, PHP 5)

ctype_print -- Check for printable character(s)

说明

bool ctype_print ( string text )

Checks if all of the characters in the provided string, text, are printable.

参数

text

The tested string.

返回值

Returns TRUE if every character in text will actually create output (including blanks). Returns FALSE if text contains control characters or characters that do not have any output or control function at all.

范例

例子 1. A ctype_print() example

<?php
$strings = array('string1' => "asdf\n\r\t", 'string2' => 'arf12', 'string3' => 'LKA#@%.54');
foreach ($strings as $name => $testcase) {
    if (ctype_print($testcase)) {
        echo "The string '$name' consists of all printable characters.\n";
    } else {
        echo "The string '$name' does not consist of all printable characters.\n";
    }
}
?>

上例将输出:

The string 'string1' does not consist of all printable characters.
The string 'string2' consists of all printable characters.
The string 'string3' consists of all printable characters.

ctype_punct

(PHP 4 >= 4.0.4, PHP 5)

ctype_punct --  Check for any printable character which is not whitespace or an alphanumeric character

说明

bool ctype_punct ( string text )

Checks if all of the characters in the provided string, text, are punctuation character.

参数

text

The tested string.

返回值

Returns TRUE if every character in text is printable, but neither letter, digit or blank, FALSE otherwise.

范例

例子 1. A ctype_punct() example

<?php
$strings = array('ABasdk!@!$#', '!@ # $', '*&$()');
foreach ($strings as $testcase) {
    if (ctype_punct($testcase)) {
        echo "The string $testcase consists of all punctuation.\n";
    } else {
        echo "The string $testcase does not consist of all punctuation.\n";
    }
}
?>

上例将输出:

The string ABasdk!@!$# does not consist of all punctuation.
The string !@ # $ does not consist of all punctuation.
The string *&$() consists of all punctuation.

ctype_space

(PHP 4 >= 4.0.4, PHP 5)

ctype_space -- Check for whitespace character(s)

说明

bool ctype_space ( string text )

Checks if all of the characters in the provided string, text, creates whitespace.

参数

text

The tested string.

返回值

Returns TRUE if every character in text creates some sort of white space, FALSE otherwise. Besides the blank character this also includes tab, vertical tab, line feed, carriage return and form feed characters.

范例

例子 1. A ctype_space() example

<?php
$strings = array('string1' => "\n\r\t", 'string2' => "\narf12", 'string3' => '\n\r\t');
foreach ($strings as $name => $testcase) {
    if (ctype_space($testcase)) {
        echo "The string '$name' consists of all whitespace characters.\n";
    } else {
        echo "The string '$name' does not consist of all whitespace characters.\n";
    }
}
?>

上例将输出:

The string 'string1' consists of all whitespace characters.
The string 'string2' does not consist of all whitespace characters.
The string 'string3' does not consist of all whitespace characters.

ctype_upper

(PHP 4 >= 4.0.4, PHP 5)

ctype_upper -- Check for uppercase character(s)

说明

bool ctype_upper ( string text )

Checks if all of the characters in the provided string, text, are uppercase characters.

参数

text

The tested string.

返回值

Returns TRUE if every character in text is an uppercase letter in the current locale.

范例

例子 1. A ctype_upper() example (using the default locale)

<?php
$strings = array('AKLWC139', 'LMNSDO', 'akwSKWsm');
foreach ($strings as $testcase) {
    if (ctype_upper($testcase)) {
        echo "The string $testcase consists of all uppercase letters.\n";
    } else {
        echo "The string $testcase does not consist of all uppercase letters.\n";
    }
}
?>

上例将输出:

The string AKLWC139 does not consist of all uppercase letters.
The string LMNSDO consists of all uppercase letters.
The string akwSKWsm does not consist of all uppercase letters.

ctype_xdigit

(PHP 4 >= 4.0.4, PHP 5)

ctype_xdigit --  Check for character(s) representing a hexadecimal digit

说明

bool ctype_xdigit ( string text )

Checks if all of the characters in the provided string, text, are hexadecimal 'digits'.

参数

text

The tested string.

返回值

Returns TRUE if every character in text is a hexadecimal 'digit', that is a decimal digit or a character from [A-Fa-f] , FALSE otherwise.

范例

例子 1. A ctype_xdigit() example

<?php
$strings = array('AB10BC99', 'AR1012', 'ab12bc99');
foreach ($strings as $testcase) {
    if (ctype_xdigit($testcase)) {
        echo "The string $testcase consists of all hexadecimal digits.\n";
    } else {
        echo "The string $testcase does not consist of all hexadecimal digits.\n";
    }
}
?>

上例将输出:

The string AB10BC99 consists of all hexadecimal digits.
The string AR1012 does not consist of all hexadecimal digits.
The string ab12bc99 consists of all hexadecimal digits.

XII. Classes/Objects 类/对象函数

简介

本类函数允许获取类和对象实例的信息。可以取得对象所属的类的名字,以及它的成员属性和方法。通过使用这些函数,不仅可以弄清楚一个对象类的全体成员,而且可以知道它的起源(例如,该对象类是哪个类的扩展)。


需求

要编译本扩展模块不需要外部库文件。


安装

本函数库作为 PHP 内核的一部分,不用安装就能使用。


运行时配置

本扩展模块在 php.ini 中未定义任何配置选项。


资源类型

本扩展模块未定义任何资源类型。


预定义常量

本扩展模块未定义任何常量。


范例

在本例子中,先定义一个基础类和一个扩展类。基础类描述的是普通的蔬菜(Vegetable),它是否可食用(is_edible)以及它是什么颜色(what_color)。子类 Spinach 增加了“烹调”的方法(cook_it)和“获知它是否已被烹调了”的方法(is_cooked)。

例子 1. classes.inc

<?php

// 基类及其成员属性与方法
class Vegetable {

    var $edible;
    var $color;

    function Vegetable($edible, $color="green")
    {
        $this->edible = $edible;
        $this->color = $color;
    }

    function is_edible()
    {
        return $this->edible;
    }

    function what_color()
    {
        return $this->color;
    }

} // Vegetable 类定义结束

// 扩展基类
class Spinach extends Vegetable {

    var $cooked = false;

    function Spinach()
    {
        $this->Vegetable(true, "green");
    }

    function cook_it()
    {
        $this->cooked = true;
    }

    function is_cooked()
    {
        return $this->cooked;
    }

} // Spinach 类定义结束

?>

接着,从这些对象中创建两个对象实例,打印出它们的相关信息,包括它们的起源。还定义了一些实用函数,它们主要是为了让变量的输出好看些。

例子 2. test_script.php

<pre>
<?php

include "classes.inc";

// utility functions

function print_vars($obj)
{
    foreach (get_object_vars($obj) as $prop => $val) {
        echo "\t$prop = $val\n";
    }
}

function print_methods($obj)
{
    $arr = get_class_methods(get_class($obj));
    foreach ($arr as $method) {
        echo "\tfunction $method()\n";
    }
}

function class_parentage($obj, $class)
{
    if (is_subclass_of($GLOBALS[$obj], $class)) {
        echo "Object $obj belongs to class " . get_class($$obj);
        echo " a subclass of $class\n";
    } else {
        echo "Object $obj does not belong to a subclass of $class\n";
    }
}

// instantiate 2 objects

$veggie = new Vegetable(true, "blue");
$leafy = new Spinach();

// print out information about objects
echo "veggie: CLASS " . get_class($veggie) . "\n";
echo "leafy: CLASS " . get_class($leafy);
echo ", PARENT " . get_parent_class($leafy) . "\n";

// show veggie properties
echo "\nveggie: Properties\n";
print_vars($veggie);

// and leafy methods
echo "\nleafy: Methods\n";
print_methods($leafy);

echo "\nParentage:\n";
class_parentage("leafy", "Spinach");
class_parentage("leafy", "Vegetable");
?>
</pre>

上边例子中重点要注意的是对象 $leafySpinach 类的一个实例,而 Spinach 类是 Vegetable 类的一个子类,因此上边脚本的最后部分将会输出:

[...]
Parentage:
Object leafy does not belong to a subclass of Spinach
Object leafy belongs to class spinach a subclass of Vegetable

目录
call_user_method_array --  调用一个用户方法,同时传递参数数组[已停用]
call_user_method --  调用特定对象的用户方法[已停用]
class_exists -- 检查类是否已定义
get_class_methods -- 返回由类的方法名组成的数组
get_class_vars --  返回由类的默认属性组成的数组
get_class -- 返回对象的类名
get_declared_classes -- 返回由已定义类的名字所组成的数组
get_declared_interfaces --  Returns an array of all declared interfaces
get_object_vars -- 返回由对象属性组成的关联数组
get_parent_class -- 返回对象或类的父类名
interface_exists -- Checks if the interface has been defined
is_a --  如果对象属于该类或该类是此对象的父类则返回 TRUE
is_subclass_of --  如果此对象是该类的子类,则返回 TRUE
method_exists -- 检查类的方法是否存在
property_exists --  Checks if the object or class has a property

call_user_method_array

(PHP 4 >= 4.0.5, PHP 5)

call_user_method_array --  调用一个用户方法,同时传递参数数组[已停用]

描述

mixed call_user_method_array ( string method_name, object obj [, array paramarr] )

警告

call_user_method_array() 函数从 PHP 4.1.0 开始已经停用,使用 call_user_func_array() 函数和 array(&$obj, "method_name") 语法代替。

从用户定义的 obj 对象中调用 method_name 所指的方法,同时使用 paramarr 中的参数。

参见: call_user_func_array()call_user_func()call_user_method()

注: 此函数是在 PHP 4.0.4pl1 发行版之后加入到 CVS 代码中的

call_user_method

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

call_user_method --  调用特定对象的用户方法[已停用]

描述

mixed call_user_method ( string method_name, object obj [, mixed parameter [, mixed ...]] )

警告

call_user_method() 函数从 PHP 4.1.0 开始已经停用,使用 call_user_func() 函数和 array(&$obj, "method_name") 语法代替。

从用户定义的 obj 对象中调用 method_name 所指的方法。下边是用法示例,我们定义了一个类,接着创建了一个对象实例,然后使用 call_user_method() 间接调用它的 print_info 方法。

<?php
class Country {
    var $NAME;
    var $TLD;
    
    function Country($name, $tld) {
        $this->NAME = $name;
        $this->TLD = $tld;
    }

    function print_info($prestr="") {
        echo $prestr."Country: ".$this->NAME."\n";
        echo $prestr."Top Level Domain: ".$this->TLD."\n";
    }
}

$cntry = new Country("Peru","pe");

echo "* Calling the object method directly\n";
$cntry->print_info();

echo "\n* Calling the same method indirectly\n";
call_user_method ("print_info", $cntry, "\t");
?>

参见 call_user_func_array()call_user_func()call_user_method_array()

class_exists

(PHP 4, PHP 5)

class_exists -- 检查类是否已定义

描述

bool class_exists ( string class_name )

如果由 class_name 所指的类已经定义,此函数返回 TRUE,否则返回 FALSE

参见 get_declared_classes()

get_class_methods

(PHP 4, PHP 5)

get_class_methods -- 返回由类的方法名组成的数组

描述

array get_class_methods ( mixed class_name )

返回由 class_name 指定的类中定义的方法名所组成的数组。

注: 从 PHP 4.0.6 开始,可以指定对象本身来代替 class_name,例如:

$class_methods = get_class_methods($my_class); // see below the full example

例子 1. get_class_methods() 示例

<?php

class myclass {
    // constructor
    function myclass() {
        return(TRUE);
    }
    
    // method 1
    function myfunc1() {
        return(TRUE);
    }

    // method 2
    function myfunc2() {
        return(TRUE);
    }
}

$my_object = new myclass();

$class_methods = get_class_methods(get_class($my_object));

foreach ($class_methods as $method_name) {
    echo "$method_name\n";
}

?>

运行结果:

myclass
myfunc1
myfunc2

参见 get_class_vars()get_object_vars()

get_class_vars

(PHP 4, PHP 5)

get_class_vars --  返回由类的默认属性组成的数组

描述

array get_class_vars ( string class_name )

返回由类的默认属性组成的关联数组,此数组的元素以 varname => value 的形式存在。

注: 在 PHP 4.2.0 之前,get_class_vars() 不会包含未初始化的类变量。

例子 1. get_class_vars() 示例

<?php

class myclass {

    var $var1; // 此变量没有默认值……
    var $var2 = "xyz";
    var $var3 = 100;
    
    // constructor
    function myclass() {
        return(TRUE);
    }

}

$my_class = new myclass();

$class_vars = get_class_vars(get_class($my_class));

foreach ($class_vars as $name => $value) {
    echo "$name : $value\n";
}

?>

运行结果:

// 在 PHP 4.2.0 之前
var2 : xyz
var3 : 100

// 从 PHP 4.2.0 开始
var1 :
var2 : xyz
var3 : 100

参见 get_class_methods()get_object_vars()

get_class

(PHP 4, PHP 5)

get_class -- 返回对象的类名

描述

string get_class ( object obj )

返回对象实例 obj 所属类的名字。如果 obj 不是一个对象则返回 FALSE

注: get_class() 返回用户定义的类名的小写形式。在 PHP 扩展中定义的类则返回其原有的名字。

参见 get_parent_class()gettype()is_subclass_of()

get_declared_classes

(PHP 4, PHP 5)

get_declared_classes -- 返回由已定义类的名字所组成的数组

描述

array get_declared_classes ( void )

返回由当前脚本中已定义类的名字组成的数组。

注: 在 PHP 4.0.1pl2 中,有三个额外的类存在于返回的数组中:stdClass(在 Zend/zend.c 中定义)、OverloadedTestClass(在 ext/standard/basic_functions.c 中定义)和 Directory(在 ext/standard/dir.c 中定义)。

还需要注意的是额外类的出现依赖于你已编译到 PHP 中的库。这意味着你不能使用这些类名定义自己的类。在附录的 预定义类 部分有预定义类的列表。

参见 class_exists()

get_declared_interfaces

(PHP 5)

get_declared_interfaces --  Returns an array of all declared interfaces

Description

array get_declared_interfaces ( void )

This function returns an array of the names of the declared interfaces in the current script.

例子 1. get_declared_interfaces() example

<?php
print_r(get_declared_interfaces());
?>

上例的输出类似于:

Array
(
    [0] => Traversable
    [1] => IteratorAggregate
    [2] => Iterator
    [3] => ArrayAccess
    [4] => reflector
    [5] => RecursiveIterator
    [6] => SeekableIterator
)

See also get_declared_classes().

get_object_vars

(PHP 4, PHP 5)

get_object_vars -- 返回由对象属性组成的关联数组

描述

array get_object_vars ( object obj )

返回由 obj 指定的对象中定义的属性组成的关联数组。

注: 在 PHP 4.2.0 之前的版本中,如果在 obj 对象实例中声明的变量没有被赋值,则它们将不会在返回的数组中。而在 PHP 4.2.0 之后,这些变量作为键名将被赋予 NULL 值。

例子 1. 使用 get_object_vars()

<?php
class Point2D {
    var $x, $y;
    var $label;

    function Point2D($x, $y) {
        $this->x = $x;
        $this->y = $y;
    }

    function setLabel($label) {
        $this->label = $label;
    }

    function getPoint() {
        return array("x" => $this->x,
                     "y" => $this->y,
                     "label" => $this->label);
    }
}

// "$label" is declared but not defined
$p1 = new Point2D(1.233, 3.445);
print_r(get_object_vars($p1));

$p1->setLabel("point #1");
print_r(get_object_vars($p1));

?>
上边的程序将输出:
Array
 (
     [x] => 1.233
     [y] => 3.445
     [label] =>
 )

 Array
 (
     [x] => 1.233
     [y] => 3.445
     [label] => point #1
 )

参见 get_class_methods()get_class_vars()

get_parent_class

(PHP 4, PHP 5)

get_parent_class -- 返回对象或类的父类名

描述

string get_parent_class ( mixed obj )

如果 obj 是对象,则返回对象实例 obj 所属类的父类名。

如果 obj 是字符串,则返回以此字符串为名的类的父类名。此功能是在 PHP 4.0.5 中增加的。

参见 get_class()is_subclass_of()

interface_exists

(PHP 5 >= 5.0.2)

interface_exists -- Checks if the interface has been defined

Description

bool interface_exists ( string interface_name [, bool autoload] )

This function returns TRUE if the interface given by interface_name has been defined, FALSE otherwise.

例子 1. interface_exists() example

<?php
// Check the interface exists before trying to use it
if (interface_exists('MyInterface')) {
    class MyClass implements MyInterface
    {
        // Methods
    }
}

?>

interface_exists() will attempt to call __autoload by default, if you don't want interface_exists() to call __autoload, you can set the parameter autoload to FALSE.

See also class_exists().

is_a

(PHP 4 >= 4.2.0, PHP 5)

is_a --  如果对象属于该类或该类是此对象的父类则返回 TRUE

描述

bool is_a ( object object, string class_name )

如果对象是该类或该类是此对象的父类则返回 TRUE,否则返回 FALSE

参见 get_class()get_parent_class()is_subclass_of()

is_subclass_of

(PHP 4, PHP 5)

is_subclass_of --  如果此对象是该类的子类,则返回 TRUE

描述

bool is_subclass_of ( object object, string class_name )

如果对象 object 所属类是类 class_name 的子类,则返回 TRUE,否则返回 FALSE

参见 get_class()get_parent_class()is_a()

method_exists

(PHP 4, PHP 5)

method_exists -- 检查类的方法是否存在

描述

bool method_exists ( object object, string method_name )

如果 method_name 所指的方法在 object 所指的对象类中已定义,则返回 TRUE,否则返回 FALSE

property_exists

(PHP 5 >= 5.1.0RC1)

property_exists --  Checks if the object or class has a property

说明

bool property_exists ( mixed class, string property )

This function checks if the given property exists in the specified class (and if it was declared as public).

注: As opposed with isset(), property_exists() returns TRUE even if the property has the value NULL.

参数

class

A string with the class name or an object of the class to test for

property

The name of the property

返回值

Returns TRUE if the property exists or FALSE otherwise.

范例

例子 1. A property_exists() example

<?php

class myClass {
    public $mine;
    private $xpto;
}

var_dump(property_exists('myClass', 'mine'));   //true
var_dump(property_exists(new myClass, 'mine')); //true
var_dump(property_exists('myClass', 'xpto'));   //false, isn't public

?>

XIII. Classkit Functions

简介

These functions allow the dynamic manipulation of PHP classes, at runtime.

注: This extension has been replaced by runkit, which is not limited to class manipulation but has function manipulation, as well.


安装

PECL 扩展未绑定于 PHP 中。

进一步信息例如新版本,下载,源程序,维护者信息以及更新日志可以在此找到: http://pecl.php.net/package/classkit.

可以从 PHP 下载页面或者 http://snaps.php.net/ 下载此 PECL 扩展的 DLL 文件。


运行时配置

本扩展模块在 php.ini 中未定义任何配置选项。


资源类型

本扩展模块未定义任何资源类型。


预定义常量

以下常量由本扩展模块定义,因此只有在本扩展模块被编译到 PHP 中,或者在运行时被动态加载后才有效。

CLASSKIT_ACC_PRIVATE (int)

Marks the method private

CLASSKIT_ACC_PROTECTED (int)

Marks the method protected

CLASSKIT_ACC_PUBLIC (int)

Marks the method public

目录
classkit_import -- Import new class method definitions from a file
classkit_method_add -- Dynamically adds a new method to a given class
classkit_method_copy -- Copies a method from class to another
classkit_method_redefine -- Dynamically changes the code of the given method
classkit_method_remove -- Dynamically removes the given method
classkit_method_rename -- Dynamically changes the name of the given method

classkit_import

(PECL)

classkit_import -- Import new class method definitions from a file

说明

array classkit_import ( string filename )

注: 本函数不能用于操作当前正在运行(或运行链上)的方法。

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

参数

filename

The filename of the class method definitions to import

返回值

Associative array of imported methods

范例

例子 1. classkit_import() example

<?php
// file: newclass.php
class Example {
    function foo() {
        return "bar!\n";
    }
}
?>
<?php
// requires newclass.php (see above)
class Example {
    function foo() {
        return "foo!\n";
    }
}

$e = new Example();

// output original
echo $e->foo();

// import replacement method
classkit_import('newclass.php');

// output imported
echo $e->foo();

?>

上例将输出:

foo!
bar!

classkit_method_add

(PECL)

classkit_method_add -- Dynamically adds a new method to a given class

说明

bool classkit_method_add ( string classname, string methodname, string args, string code [, int flags] )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

参数

classname

The class to which this method will be added

methodname

The name of the method to add

args

Comma-delimited list of arguments for the newly-created method

code

The code to be evaluated when methodname is called

flags

The type of method to create, can be CLASSKIT_ACC_PUBLIC, CLASSKIT_ACC_PROTECTED or CLASSKIT_ACC_PRIVATE

注: This parameter is only used as of PHP 5, because, prior to this, all methods were public.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

范例

例子 1. classkit_method_add() example

<?php
class Example {
    function foo() {
        echo "foo!\n";
    }
}

// create an Example object
$e = new Example();

// Add a new public method
classkit_method_add(
    'Example',
    'add',
    '$num1, $num2',
    'return $num1 + $num2;',
    CLASSKIT_ACC_PUBLIC
);

// add 12 + 4
echo $e->add(12, 4);
?>

上例将输出:

16

classkit_method_copy

(PECL)

classkit_method_copy -- Copies a method from class to another

说明

bool classkit_method_copy ( string dClass, string dMethod, string sClass [, string sMethod] )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

参数

dClass

Destination class for copied method

dMethod

Destination method name

sClass

Source class of the method to copy

sMethod

Name of the method to copy from the source class. If this parameter is omitted, the value of dMethod is assumed.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

范例

例子 1. classkit_method_copy() example

<?php
class Foo {
    function example() {
        return "foo!\n";
    }
}

class Bar {
    // initially, no methods
}

// copy the example() method from the Foo class to the Bar class, as baz()
classkit_method_copy('Bar', 'baz', 'Foo', 'example');

// output copied function
echo Bar::baz();
?>

上例将输出:

foo!

classkit_method_redefine

(PECL)

classkit_method_redefine -- Dynamically changes the code of the given method

说明

bool classkit_method_redefine ( string classname, string methodname, string args, string code [, int flags] )

注: 本函数不能用于操作当前正在运行(或运行链上)的方法。

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

参数

classname

The class in which to redefine the method

methodname

The name of the method to redefine

args

Comma-delimited list of arguments for the redefined method

code

The new code to be evaluated when methodname is called

flags

The redefined method can be CLASSKIT_ACC_PUBLIC, CLASSKIT_ACC_PROTECTED or CLASSKIT_ACC_PRIVATE

注: This parameter is only used as of PHP 5, because, prior to this, all methods were public.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

范例

例子 1. classkit_method_redefine() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }
}

// create an Example object
$e = new Example();

// output Example::foo() (before redefine)
echo "Before: " . $e->foo();

// Redefine the 'foo' method
classkit_method_redefine(
    'Example',
    'foo',
    '',
    'return "bar!\n";',
    CLASSKIT_ACC_PUBLIC
);

// output Example::foo() (after redefine)
echo "After: " . $e->foo();
?>

上例将输出:

Before: foo!
After: bar!

classkit_method_remove

(PECL)

classkit_method_remove -- Dynamically removes the given method

说明

bool classkit_method_remove ( string classname, string methodname )

注: 本函数不能用于操作当前正在运行(或运行链上)的方法。

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

参数

classname

The class in which to remove the method

methodname

The name of the method to remove

返回值

如果成功则返回 TRUE,失败则返回 FALSE

范例

例子 1. classkit_method_remove() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }
    
    function bar() {
        return "bar!\n";
    }
}

// Remove the 'foo' method
classkit_method_remove(
    'Example',
    'foo'
);

echo implode(' ', get_class_methods('Example'));

?>

上例将输出:

bar

classkit_method_rename

(PECL)

classkit_method_rename -- Dynamically changes the name of the given method

说明

bool classkit_method_rename ( string classname, string methodname, string newname )

注: 本函数不能用于操作当前正在运行(或运行链上)的方法。

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

参数

classname

The class in which to rename the method

methodname

The name of the method to rename

newname

The new name to give to the renamed method

返回值

如果成功则返回 TRUE,失败则返回 FALSE

范例

例子 1. classkit_method_rename() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }
}

// Rename the 'foo' method to 'bar'
classkit_method_rename(
    'Example',
    'foo',
    'bar'
);

// output renamed function
echo Example::bar();
?>

上例将输出:

foo!

XIV. ClibPDF Functions

简介

ClibPDF lets you create PDF documents with PHP. ClibPDF functionality and API are similar to PDFlib. This documentation should be read alongside the ClibPDF manual since it explains the library in much greater detail.

Many functions in the native ClibPDF and the PHP module, as well as in PDFlib, have the same name. All functions except for cpdf_open() take the handle for the document as their first parameter.

Currently this handle is not used internally since ClibPDF does not support the creation of several PDF documents at the same time. Actually, you should not even try it, the results are unpredictable. I can't oversee what the consequences in a multi threaded environment are. According to the author of ClibPDF this will change in one of the next releases (current version when this was written is 1.10). If you need this functionality use the pdflib module.

A nice feature of ClibPDF (and PDFlib) is the ability to create the pdf document completely in memory without using temporary files. It also provides the ability to pass coordinates in a predefined unit length. (This feature can also be simulated by pdf_translate() when using the PDFlib functions.)

Another nice feature of ClibPDF is the fact that any page can be modified at any time even if a new page has been already opened. The function cpdf_set_current_page() allows to leave the current page and presume modifying an other page.

Most of the functions are fairly easy to use. The most difficult part is probably creating a very simple PDF document at all. The following example should help you to get started. It creates a document with one page. The page contains the text "Times-Roman" in an outlined 30pt font. The text is underlined.

注: 本扩展已被移动到 PECL 库中且自以下版本起不再被绑定到 PHP 中:5.1.0.

注: If you're interested in alternative free PDF generators that do not utilize external PDF libraries, see this related FAQ.


需求

In order to use the ClibPDF functions you need to install the ClibPDF package. It is available for download from FastIO, but requires that you purchase a license for commercial use. PHP requires that you use cpdflib >= 2.


安装

To get these functions to work, you have to compile PHP with --with-cpdflib[=DIR]. DIR is the cpdflib install directory, defaults to /usr. In addition you can specify the jpeg library and the tiff library for ClibPDF to use. To do so add to your configure line the options --with-jpeg-dir[=DIR] --with-tiff-dir[=DIR].


运行时配置

本扩展模块在 php.ini 中未定义任何配置选项。


预定义常量

以下常量由本扩展模块定义,因此只有在本扩展模块被编译到 PHP 中,或者在运行时被动态加载后才有效。

CPDF_PM_NONE (integer)

CPDF_PM_OUTLINES (integer)

CPDF_PM_THUMBS (integer)

CPDF_PM_FULLSCREEN (integer)

CPDF_PL_SINGLE (integer)

CPDF_PL_1COLUMN (integer)

CPDF_PL_2LCOLUMN (integer)

CPDF_PL_2RCOLUMN (integer)


范例

例子 1. Simple ClibPDF Example

<?php
$cpdf = cpdf_open(0);
cpdf_page_init($cpdf, 1, 0, 595, 842, 1.0);
cpdf_add_outline($cpdf, 0, 0, 0, 1, "Page 1");
cpdf_begin_text($cpdf);
cpdf_set_font($cpdf, "Times-Roman", 30, "WinAnsiEncoding");
cpdf_set_text_rendering($cpdf, 1);
cpdf_text($cpdf, "Times Roman outlined", 50, 50);
cpdf_end_text($cpdf);
cpdf_moveto($cpdf, 50, 50);
cpdf_lineto($cpdf, 740, 330);
cpdf_stroke($cpdf);
cpdf_finalize_page($cpdf, 1);
cpdf_finalize($cpdf);
Header("Content-type: application/pdf");
cpdf_output_buffer($cpdf);
cpdf_close($cpdf);
?>

The pdflib distribution contains a more complex example which creates a series of pages with an analog clock. Here is that example converted into PHP using the ClibPDF extension:

例子 2. pdfclock example from pdflib 2.0 distribution

<?php
$radius = 200;
$margin = 20;
$pagecount = 40;

$pdf = cpdf_open(0);
cpdf_set_creator($pdf, "pdf_clock.php");
cpdf_set_title($pdf, "Analog Clock");
  
while ($pagecount-- > 0) {
  cpdf_page_init($pdf, $pagecount+1, 0, 2 * ($radius + $margin), 2 * ($radius + $margin), 1.0);
  
  cpdf_set_page_animation($pdf, 4, 0.5, 0, 0, 0);  /* wipe */
  
  cpdf_translate($pdf, $radius + $margin, $radius + $margin);
  cpdf_save($pdf);
  cpdf_setrgbcolor($pdf, 0.0, 0.0, 1.0);
  
  /* minute strokes */
  cpdf_setlinewidth($pdf, 2.0);
  for ($alpha = 0; $alpha < 360; $alpha += 6) {
    cpdf_rotate($pdf, 6.0);
    cpdf_moveto($pdf, $radius, 0.0);
    cpdf_lineto($pdf, $radius-$margin/3, 0.0);
    cpdf_stroke($pdf);
  }
  
  cpdf_restore($pdf);
  cpdf_save($pdf);
 
  /* 5 minute strokes */
  cpdf_setlinewidth($pdf, 3.0);
  for ($alpha = 0; $alpha < 360; $alpha += 30) {
    cpdf_rotate($pdf, 30.0);
    cpdf_moveto($pdf, $radius, 0.0);
    cpdf_lineto($pdf, $radius-$margin, 0.0);
    cpdf_stroke($pdf);
  }

  $ltime = getdate();

  /* draw hour hand */
  cpdf_save($pdf);
  cpdf_rotate($pdf, -(($ltime['minutes']/60.0) + $ltime['hours'] - 3.0) * 30.0);
  cpdf_moveto($pdf, -$radius/10, -$radius/20);
  cpdf_lineto($pdf, $radius/2, 0.0);
  cpdf_lineto($pdf, -$radius/10, $radius/20);
  cpdf_closepath($pdf);
  cpdf_fill($pdf);
  cpdf_restore($pdf);

  /* draw minute hand */
  cpdf_save($pdf);
  cpdf_rotate($pdf, -(($ltime['seconds']/60.0) + $ltime['minutes'] - 15.0) * 6.0);
  cpdf_moveto($pdf, -$radius/10, -$radius/20);
  cpdf_lineto($pdf, $radius * 0.8, 0.0);
  cpdf_lineto($pdf, -$radius/10, $radius/20);
  cpdf_closepath($pdf);
  cpdf_fill($pdf);
  cpdf_restore($pdf);

  /* draw second hand */
  cpdf_setrgbcolor($pdf, 1.0, 0.0, 0.0);
  cpdf_setlinewidth($pdf, 2);
  cpdf_save($pdf);
  cpdf_rotate($pdf, -(($ltime['seconds'] - 15.0) * 6.0));
  cpdf_moveto($pdf, -$radius/5, 0.0);
  cpdf_lineto($pdf, $radius, 0.0);
  cpdf_stroke($pdf);
  cpdf_restore($pdf);

  /* draw little circle at center */
  cpdf_circle($pdf, 0, 0, $radius/30);
  cpdf_fill($pdf);

  cpdf_restore($pdf);

  cpdf_finalize_page($pdf, $pagecount+1);
}

cpdf_finalize($pdf);
Header("Content-type: application/pdf");
cpdf_output_buffer($pdf);
cpdf_close($pdf);
?>

参见

See also the PDFlib extension documentation.

目录
cpdf_add_annotation -- Adds annotation
cpdf_add_outline -- Adds bookmark for current page
cpdf_arc -- Draws an arc
cpdf_begin_text -- Starts text section
cpdf_circle -- Draw a circle
cpdf_clip -- Clips to current path
cpdf_close -- Closes the pdf document
cpdf_closepath_fill_stroke -- Close, fill and stroke current path
cpdf_closepath_stroke -- Close path and draw line along path
cpdf_closepath -- Close path
cpdf_continue_text -- Output text in next line
cpdf_curveto -- Draws a curve
cpdf_end_text -- Ends text section
cpdf_fill_stroke -- Fill and stroke current path
cpdf_fill -- Fill current path
cpdf_finalize_page -- Ends page
cpdf_finalize -- Ends document
cpdf_global_set_document_limits -- Sets document limits for any pdf document
cpdf_import_jpeg -- Opens a JPEG image
cpdf_lineto -- Draws a line
cpdf_moveto -- Sets current point
cpdf_newpath -- Starts a new path
cpdf_open -- Opens a new pdf document
cpdf_output_buffer -- Outputs the pdf document in memory buffer
cpdf_page_init -- Starts new page
cpdf_place_inline_image -- Places an image on the page
cpdf_rect -- Draw a rectangle
cpdf_restore -- Restores formerly saved environment
cpdf_rlineto -- Draws a line
cpdf_rmoveto -- Sets current point
cpdf_rotate_text --  Sets text rotation angle
cpdf_rotate -- Sets rotation
cpdf_save_to_file -- Writes the pdf document into a file
cpdf_save -- Saves current environment
cpdf_scale -- Sets scaling
cpdf_set_action_url --  Sets hyperlink
cpdf_set_char_spacing -- Sets character spacing
cpdf_set_creator -- Sets the creator field in the pdf document
cpdf_set_current_page -- Sets current page
cpdf_set_font_directories --  Sets directories to search when using external fonts
cpdf_set_font_map_file --  Sets fontname to filename translation map when using external fonts
cpdf_set_font -- Select the current font face and size
cpdf_set_horiz_scaling -- Sets horizontal scaling of text
cpdf_set_keywords -- Sets the keywords field of the pdf document
cpdf_set_leading -- Sets distance between text lines
cpdf_set_page_animation -- Sets duration between pages
cpdf_set_subject -- Sets the subject field of the pdf document
cpdf_set_text_matrix -- Sets the text matrix
cpdf_set_text_pos -- Sets text position
cpdf_set_text_rendering -- Determines how text is rendered
cpdf_set_text_rise -- Sets the text rise
cpdf_set_title -- Sets the title field of the pdf document
cpdf_set_viewer_preferences --  How to show the document in the viewer
cpdf_set_word_spacing -- Sets spacing between words
cpdf_setdash -- Sets dash pattern
cpdf_setflat -- Sets flatness
cpdf_setgray_fill -- Sets filling color to gray value
cpdf_setgray_stroke -- Sets drawing color to gray value
cpdf_setgray -- Sets drawing and filling color to gray value
cpdf_setlinecap -- Sets linecap parameter
cpdf_setlinejoin -- Sets linejoin parameter
cpdf_setlinewidth -- Sets line width
cpdf_setmiterlimit -- Sets miter limit
cpdf_setrgbcolor_fill -- Sets filling color to rgb color value
cpdf_setrgbcolor_stroke -- Sets drawing color to rgb color value
cpdf_setrgbcolor -- Sets drawing and filling color to rgb color value
cpdf_show_xy -- Output text at position
cpdf_show -- Output text at current position
cpdf_stringwidth -- Returns width of text in current font
cpdf_stroke -- Draw line along path
cpdf_text -- Output text with parameters
cpdf_translate -- Sets origin of coordinate system

cpdf_add_annotation

(PHP 3 >= 3.0.12, PHP 4, PHP 5 <= 5.0.4)

cpdf_add_annotation -- Adds annotation

Description

bool cpdf_add_annotation ( int pdf_document, float llx, float lly, float urx, float ury, string title, string content [, int mode] )

The cpdf_add_annotation() adds a note with the lower left corner at (llx, lly) and the upper right corner at (urx, ury). 如果成功则返回 TRUE,失败则返回 FALSE

可选参数 mode 决定单元的长度。如果为 0 或被省略则使用该页指定的默认单元。否则坐标忽略当前单元而使用 postscript 的点来度量。

cpdf_add_outline

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_add_outline -- Adds bookmark for current page

Description

int cpdf_add_outline ( int pdf_document, int lastoutline, int sublevel, int open, int pagenr, string text )

The cpdf_add_outline() function adds a bookmark with text text that points to the current page.

例子 1. Adding a page outline

<?php
$cpdf = cpdf_open(0);
cpdf_page_init($cpdf, 1, 0, 595, 842);
cpdf_add_outline($cpdf, 0, 0, 0, 1, "Page 1");
// ...
// some drawing
// ...
cpdf_finalize($cpdf);
Header("Content-type: application/pdf");
cpdf_output_buffer($cpdf);
cpdf_close($cpdf);
?>

cpdf_arc

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_arc -- Draws an arc

Description

bool cpdf_arc ( int pdf_document, float x_coor, float y_coor, float radius, float start, float end [, int mode] )

The cpdf_arc() function draws an arc with center at point (x_coor, y_coor) and radius radius, starting at angle start and ending at angle end. 如果成功则返回 TRUE,失败则返回 FALSE

可选参数 mode 决定单元的长度。如果为 0 或被省略则使用该页指定的默认单元。否则坐标忽略当前单元而使用 postscript 的点来度量。

See also cpdf_circle().

cpdf_begin_text

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_begin_text -- Starts text section

Description

bool cpdf_begin_text ( int pdf_document )

The cpdf_begin_text() function starts a text section. 如果成功则返回 TRUE,失败则返回 FALSE。 The created text section must be ended with cpdf_end_text().

例子 1. Text output

<?php
cpdf_begin_text($pdf);
cpdf_set_font($pdf, 16, "Helvetica", "WinAnsiEncoding");
cpdf_text($pdf, 100, 100, "Some text");
cpdf_end_text($pdf)
?>

See also cpdf_end_text().

cpdf_circle

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_circle -- Draw a circle

Description

bool cpdf_circle ( int pdf_document, float x_coor, float y_coor, float radius [, int mode] )

The cpdf_circle() function draws a circle with center at point (x_coor, y_coor) and radius radius. 如果成功则返回 TRUE,失败则返回 FALSE

可选参数 mode 决定单元的长度。如果为 0 或被省略则使用该页指定的默认单元。否则坐标忽略当前单元而使用 postscript 的点来度量。

See also cpdf_arc().

cpdf_clip

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_clip -- Clips to current path

Description

bool cpdf_clip ( int pdf_document )

The cpdf_clip() function clips all drawing to the current path. 如果成功则返回 TRUE,失败则返回 FALSE

cpdf_close

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_close -- Closes the pdf document

Description

bool cpdf_close ( int pdf_document )

The cpdf_close() function closes the pdf document. 如果成功则返回 TRUE,失败则返回 FALSE。 This should be the last function even after cpdf_finalize(), cpdf_output_buffer() and cpdf_save_to_file().

See also cpdf_open().

cpdf_closepath_fill_stroke

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_closepath_fill_stroke -- Close, fill and stroke current path

Description

bool cpdf_closepath_fill_stroke ( int pdf_document )

The cpdf_closepath_fill_stroke() function closes, fills the interior of the current path with the current fill color and draws current path. 如果成功则返回 TRUE,失败则返回 FALSE

See also cpdf_closepath(), cpdf_stroke(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill() and cpdf_setrgbcolor().

cpdf_closepath_stroke

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_closepath_stroke -- Close path and draw line along path

Description

bool cpdf_closepath_stroke ( int pdf_document )

The cpdf_closepath_stroke() function is a combination of cpdf_closepath() and cpdf_stroke(). Then clears the path. 如果成功则返回 TRUE,失败则返回 FALSE

See also cpdf_closepath() and cpdf_stroke().

cpdf_closepath

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_closepath -- Close path

Description

bool cpdf_closepath ( int pdf_document )

The cpdf_closepath() function closes the current path. 如果成功则返回 TRUE,失败则返回 FALSE

cpdf_continue_text

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_continue_text -- Output text in next line

Description

bool cpdf_continue_text ( int pdf_document, string text )

The cpdf_continue_text() function outputs the string in text in the next line. 如果成功则返回 TRUE,失败则返回 FALSE

See also cpdf_show_xy(), cpdf_text(), cpdf_set_leading() and cpdf_set_text_pos().

cpdf_curveto

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_curveto -- Draws a curve

Description

bool cpdf_curveto ( int pdf_document, float x1, float y1, float x2, float y2, float x3, float y3 [, int mode] )

The cpdf_curveto() function draws a Bezier curve from the current point to the point (x3, y3) using (x1, y1) and (x2, y2) as control points. 如果成功则返回 TRUE,失败则返回 FALSE

可选参数 mode 决定单元的长度。如果为 0 或被省略则使用该页指定的默认单元。否则坐标忽略当前单元而使用 postscript 的点来度量。

See also cpdf_moveto(), cpdf_rmoveto(), cpdf_rlineto() and cpdf_lineto().

cpdf_end_text

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_end_text -- Ends text section

Description

bool cpdf_end_text ( int pdf_document )

The cpdf_end_text() function ends a text section which was started with cpdf_begin_text(). 如果成功则返回 TRUE,失败则返回 FALSE

例子 1. Text output

<?php
cpdf_begin_text($pdf);
cpdf_set_font($pdf, 16, "Helvetica", "WinAnsiEncoding");
cpdf_text($pdf, 100, 100, "Some text");
cpdf_end_text($pdf)
?>

See also cpdf_begin_text().

cpdf_fill_stroke

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_fill_stroke -- Fill and stroke current path

Description

bool cpdf_fill_stroke ( int pdf_document )

The cpdf_fill_stroke() function fills the interior of the current path with the current fill color and draws current path. 如果成功则返回 TRUE,失败则返回 FALSE

See also cpdf_closepath(), cpdf_stroke(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill() and cpdf_setrgbcolor().

cpdf_fill

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_fill -- Fill current path

Description

bool cpdf_fill ( int pdf_document )

The cpdf_fill() function fills the interior of the current path with the current fill color. 如果成功则返回 TRUE,失败则返回 FALSE

See also cpdf_closepath(), cpdf_stroke(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill() and cpdf_setrgbcolor().

cpdf_finalize_page

(PHP 3 >= 3.0.10, PHP 4, PHP 5 <= 5.0.4)

cpdf_finalize_page -- Ends page

Description

bool cpdf_finalize_page ( int pdf_document, int page_number )

The cpdf_finalize_page() function ends the page with page number page_number. 如果成功则返回 TRUE,失败则返回 FALSE

This function is only for saving memory. A finalized page takes less memory but cannot be modified anymore.

See also cpdf_page_init().

cpdf_finalize

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_finalize -- Ends document

Description

bool cpdf_finalize ( int pdf_document )

The cpdf_finalize() function ends the document. You still have to call cpdf_close(). 如果成功则返回 TRUE,失败则返回 FALSE

See also cpdf_close().

cpdf_global_set_document_limits

(PHP 4, PHP 5 <= 5.0.4)

cpdf_global_set_document_limits -- Sets document limits for any pdf document

Description

bool cpdf_global_set_document_limits ( int maxpages, int maxfonts, int maximages, int maxannotations, int maxobjects )

The cpdf_global_set_document_limits() function sets several document limits. This function has to be called before cpdf_open() to take effect. It sets the limits for any document open afterwards. 如果成功则返回 TRUE,失败则返回 FALSE

See also cpdf_open().

cpdf_import_jpeg

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_import_jpeg -- Opens a JPEG image

Description

bool cpdf_import_jpeg ( int pdf_document, string file_name, float x_coor, float y_coor, float angle, float width, float height, float x_scale, float y_scale, int gsave [, int mode] )

The cpdf_import_jpeg() function opens an image stored in the file with the name file_name. The format of the image has to be jpeg. The image is placed on the current page at position (x_coor, y_coor). The image is rotated by angle degrees. gsave should be non-zero to allow this function to operate correctly.

可选参数 mode 决定单元的长度。如果为 0 或被省略则使用该页指定的默认单元。否则坐标忽略当前单元而使用 postscript 的点来度量。

See also cpdf_place_inline_image().

cpdf_lineto

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_lineto -- Draws a line

Description

bool cpdf_lineto ( int pdf_document, float x_coor, float y_coor [, int mode] )

The cpdf_lineto() function draws a line from the current point to the point with coordinates (x_coor, y_coor). 如果成功则返回 TRUE,失败则返回 FALSE

可选参数 mode 决定单元的长度。如果为 0 或被省略则使用该页指定的默认单元。否则坐标忽略当前单元而使用 postscript 的点来度量。

See also cpdf_moveto(), cpdf_rmoveto() and cpdf_curveto().

cpdf_moveto

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_moveto -- Sets current point

Description

bool cpdf_moveto ( int pdf_document, float x_coor, float y_coor [, int mode] )

The cpdf_moveto() function set the current point to the coordinates x_coor and y_coor. 如果成功则返回 TRUE,失败则返回 FALSE

可选参数 mode 决定单元的长度。如果为 0 或被省略则使用该页指定的默认单元。否则坐标忽略当前单元而使用 postscript 的点来度量。

cpdf_newpath

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_newpath -- Starts a new path

Description

bool cpdf_newpath ( int pdf_document )

The cpdf_newpath() starts a new path on the document given by the pdf_document parameter. 如果成功则返回 TRUE,失败则返回 FALSE

cpdf_open

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_open -- Opens a new pdf document

Description

int cpdf_open ( int compression [, string filename [, array doc_limits]] )

The cpdf_open() function opens a new pdf document. The first parameter turns document compression on if it is unequal to 0. The second optional parameter sets the file in which the document is written. If it is omitted the document is created in memory and can either be written into a file with the cpdf_save_to_file() or written to standard output with cpdf_output_buffer().

注: The return value will be needed in further versions of ClibPDF as the first parameter in all other functions which are writing to the pdf document.

The ClibPDF library takes the filename "-" as a synonym for stdout. If PHP is compiled as an apache module this will not work because the way ClibPDF outputs to stdout does not work with apache. You can solve this problem by skipping the filename and using cpdf_output_buffer() to output the pdf document.

See also cpdf_close() and cpdf_output_buffer().

cpdf_output_buffer

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_output_buffer -- Outputs the pdf document in memory buffer

Description

bool cpdf_output_buffer ( int pdf_document )

The cpdf_output_buffer() function outputs the pdf document to stdout. The document has to be created in memory which is the case if cpdf_open() has been called with no filename parameter. 如果成功则返回 TRUE,失败则返回 FALSE

See also cpdf_open().

cpdf_page_init

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_page_init -- Starts new page

Description

bool cpdf_page_init ( int pdf_document, int page_number, int orientation, float height, float width [, float unit] )

The cpdf_page_init() function starts a new page with height height and width width. 如果成功则返回 TRUE,失败则返回 FALSE。 The page has number page_number and orientation orientation. orientation can be 0 for portrait and 1 for landscape. The last optional parameter unit sets the unit for the coordinate system. The value should be the number of postscript points per unit. Since one inch is equal to 72 points, a value of 72 would set the unit to one inch. The default is also 72.

See also cpdf_set_current_page().

cpdf_place_inline_image

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_place_inline_image -- Places an image on the page

Description

bool cpdf_place_inline_image ( int pdf_document, int image, float x_coor, float y_coor, float angle, float width, float height, int gsave [, int mode] )

The cpdf_place_inline_image() function places an image created with the PHP image functions on the page at position (x_coor, y_coor). The image can be scaled at the same time. 如果成功则返回 TRUE,失败则返回 FALSE

可选参数 mode 决定单元的长度。如果为 0 或被省略则使用该页指定的默认单元。否则坐标忽略当前单元而使用 postscript 的点来度量。

注: This function is only available if PHP was compiled with the GD Graphics Library 1.3. See the GD extension installation instructions for further information.

See also cpdf_import_jpeg().

cpdf_rect

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_rect -- Draw a rectangle

Description

bool cpdf_rect ( int pdf_document, float x_coor, float y_coor, float width, float height [, int mode] )

The cpdf_rect() function draws a rectangle with its lower left corner at point (x_coor, y_coor). This width is set to width. This height is set to height. 如果成功则返回 TRUE,失败则返回 FALSE

可选参数 mode 决定单元的长度。如果为 0 或被省略则使用该页指定的默认单元。否则坐标忽略当前单元而使用 postscript 的点来度量。

例子 1. Drawing a rectangle

<?php

$cpdf = cpdf_open(0);
cpdf_page_init($cpdf, 1, 0, 595, 842, 1.0);

// set the fill color to red
cpdf_setrgbcolor($cpdf, 1, 0, 0);

// draw a (180 * 100) rectangle
cpdf_rect($cpdf, 645, 400, 180, 100);

// fill the rectangle
cpdf_fill($cpdf);

cpdf_finalize($cpdf);
Header("Content-type: application/pdf");
cpdf_output_buffer($cpdf);
cpdf_close($cpdf);

?>

cpdf_restore

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_restore -- Restores formerly saved environment

Description

bool cpdf_restore ( int pdf_document )

The cpdf_restore() function restores the environment saved with cpdf_save(). It works like the postscript command grestore. Very useful if you want to translate or rotate an object without effecting other objects. 如果成功则返回 TRUE,失败则返回 FALSE

例子 1. Save/Restore

<?php
cpdf_save($pdf);
// do all kinds of rotations, transformations, ...
cpdf_restore($pdf)
?>

See also cpdf_save().

cpdf_rlineto

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_rlineto -- Draws a line

Description

bool cpdf_rlineto ( int pdf_document, float x_coor, float y_coor [, int mode] )

The cpdf_rlineto() function draws a line from the current point to the relative point with coordinates (x_coor, y_coor). 如果成功则返回 TRUE,失败则返回 FALSE

可选参数 mode 决定单元的长度。如果为 0 或被省略则使用该页指定的默认单元。否则坐标忽略当前单元而使用 postscript 的点来度量。

See also cpdf_moveto(), cpdf_rmoveto() and cpdf_curveto().

cpdf_rmoveto

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_rmoveto -- Sets current point

Description

bool cpdf_rmoveto ( int pdf_document, float x_coor, float y_coor [, int mode] )

The cpdf_rmoveto() function set the current point relative to the coordinates x_coor and y_coor. 如果成功则返回 TRUE,失败则返回 FALSE

可选参数 mode 决定单元的长度。如果为 0 或被省略则使用该页指定的默认单元。否则坐标忽略当前单元而使用 postscript 的点来度量。

See also cpdf_moveto().

cpdf_rotate_text

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_rotate_text --  Sets text rotation angle

Description

bool cpdf_rotate_text ( int pdfdoc, float angle )

警告

本函数暂无文档,仅有参数列表。

cpdf_rotate

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_rotate -- Sets rotation

Description

bool cpdf_rotate ( int pdf_document, float angle )

The cpdf_rotate() function set the rotation in degrees to angle. 如果成功则返回 TRUE,失败则返回 FALSE

cpdf_save_to_file

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_save_to_file -- Writes the pdf document into a file

Description

bool cpdf_save_to_file ( int pdf_document, string filename )

The cpdf_save_to_file() function outputs the pdf document into a file if it has been created in memory. 如果成功则返回 TRUE,失败则返回 FALSE

This function is not needed if the pdf document has been open by specifying a filename as a parameter of cpdf_open().

See also cpdf_output_buffer() and cpdf_open().

cpdf_save

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_save -- Saves current environment

Description

bool cpdf_save ( int pdf_document )

The cpdf_save() function saves the current environment. It works like the postscript command gsave. Very useful if you want to translate or rotate an object without effecting other objects. 如果成功则返回 TRUE,失败则返回 FALSE

See also cpdf_restore().

cpdf_scale

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_scale -- Sets scaling

Description

bool cpdf_scale ( int pdf_document, float x_scale, float y_scale )

The cpdf_scale() function set the scaling factor in both directions. 如果成功则返回 TRUE,失败则返回 FALSE

cpdf_set_action_url

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_action_url --  Sets hyperlink

Description

bool cpdf_set_action_url ( int pdfdoc, float xll, float yll, float xur, float xur, string url [, int mode] )

警告

本函数暂无文档,仅有参数列表。

cpdf_set_char_spacing

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_char_spacing -- Sets character spacing

Description

bool cpdf_set_char_spacing ( int pdf_document, float space )

The cpdf_set_char_spacing() function sets the spacing between characters. 如果成功则返回 TRUE,失败则返回 FALSE

See also cpdf_set_word_spacing() and cpdf_set_leading().

cpdf_set_creator

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_creator -- Sets the creator field in the pdf document

Description

bool cpdf_set_creator ( int pdf_document, string creator )

The cpdf_set_creator() function sets the creator of a pdf document. 如果成功则返回 TRUE,失败则返回 FALSE

See also cpdf_set_subject(), cpdf_set_title() and cpdf_set_keywords().

cpdf_set_current_page

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_current_page -- Sets current page

Description

bool cpdf_set_current_page ( int pdf_document, int page_number )

The cpdf_set_current_page() function set the page on which all operations are performed. One can switch between pages until a page is finished with cpdf_finalize_page(). 如果成功则返回 TRUE,失败则返回 FALSE

See also cpdf_finalize_page().

cpdf_set_font_directories

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

cpdf_set_font_directories --  Sets directories to search when using external fonts

Description

bool cpdf_set_font_directories ( int pdfdoc, string pfmdir, string pfbdir )

警告

本函数暂无文档,仅有参数列表。

cpdf_set_font_map_file

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

cpdf_set_font_map_file --  Sets fontname to filename translation map when using external fonts

Description

bool cpdf_set_font_map_file ( int pdfdoc, string filename )

警告

本函数暂无文档,仅有参数列表。

cpdf_set_font

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_font -- Select the current font face and size

Description

bool cpdf_set_font ( int pdf_document, string font_name, float size, string encoding )

The cpdf_set_font() function sets the current font face, font size and encoding. Currently only the standard postscript fonts are supported. 如果成功则返回 TRUE,失败则返回 FALSE

The last parameter encoding can take the following values: "MacRomanEncoding", "MacExpertEncoding", "WinAnsiEncoding", and "NULL". "NULL" stands for the font's built-in encoding.

See the ClibPDF Manual for more information, especially how to support Asian fonts.

cpdf_set_horiz_scaling

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_horiz_scaling -- Sets horizontal scaling of text

Description

bool cpdf_set_horiz_scaling ( int pdf_document, float scale )

The cpdf_set_horiz_scaling() function sets the horizontal scaling to scale percent. 如果成功则返回 TRUE,失败则返回 FALSE

cpdf_set_keywords

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_keywords -- Sets the keywords field of the pdf document

Description

bool cpdf_set_keywords ( int pdf_document, string keywords )

The cpdf_set_keywords() function sets the keywords of a pdf document. 如果成功则返回 TRUE,失败则返回 FALSE

See also cpdf_set_title(), cpdf_set_creator() and cpdf_set_subject().

cpdf_set_leading

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_leading -- Sets distance between text lines

Description

bool cpdf_set_leading ( int pdf_document, float distance )

The cpdf_set_leading() function sets the distance between text lines. This will be used if text is output by cpdf_continue_text(). 如果成功则返回 TRUE,失败则返回 FALSE

See also cpdf_continue_text().

cpdf_set_page_animation

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_page_animation -- Sets duration between pages

Description

bool cpdf_set_page_animation ( int pdf_document, int transition, float duration, float direction, int orientation, int inout )

The cpdf_set_page_animation() function set the transition between following pages. 如果成功则返回 TRUE,失败则返回 FALSE

The value of transition can be

0 for none,
1 for two lines sweeping across the screen reveal the page,
2 for multiple lines sweeping across the screen reveal the page,
3 for a box reveals the page,
4 for a single line sweeping across the screen reveals the page,
5 for the old page dissolves to reveal the page,
6 for the dissolve effect moves from one screen edge to another,
7 for the old page is simply replaced by the new page (default)

The value of duration is the number of seconds between page flipping.

cpdf_set_subject

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_subject -- Sets the subject field of the pdf document

Description

bool cpdf_set_subject ( int pdf_document, string subject )

The cpdf_set_subject() function sets the subject of a pdf document. 如果成功则返回 TRUE,失败则返回 FALSE

See also cpdf_set_title(), cpdf_set_creator() and cpdf_set_keywords().

cpdf_set_text_matrix

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_text_matrix -- Sets the text matrix

Description

bool cpdf_set_text_matrix ( int pdf_document, array matrix )

The cpdf_set_text_matrix() function sets a matrix which describes a transformation applied on the current text font. 如果成功则返回 TRUE,失败则返回 FALSE

cpdf_set_text_pos

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_text_pos -- Sets text position

Description

bool cpdf_set_text_pos ( int pdf_document, float x_coor, float y_coor [, int mode] )

The cpdf_set_text_pos() function sets the position of text for the next cpdf_show() function call. 如果成功则返回 TRUE,失败则返回 FALSE

可选参数 mode 决定单元的长度。如果为 0 或被省略则使用该页指定的默认单元。否则坐标忽略当前单元而使用 postscript 的点来度量。

See also cpdf_show() and cpdf_text().

cpdf_set_text_rendering

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_text_rendering -- Determines how text is rendered

Description

bool cpdf_set_text_rendering ( int pdf_document, int rendermode )

The cpdf_set_text_rendering() function determines how text is rendered. 如果成功则返回 TRUE,失败则返回 FALSE

The possible values for rendermode are 0=fill text, 1=stroke text, 2=fill and stroke text, 3=invisible, 4=fill text and add it to clipping path, 5=stroke text and add it to clipping path, 6=fill and stroke text and add it to clipping path, 7=add it to clipping path.

cpdf_set_text_rise

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_text_rise -- Sets the text rise

Description

bool cpdf_set_text_rise ( int pdf_document, float value )

The cpdf_set_text_rise() function sets the text rising to value units. 如果成功则返回 TRUE,失败则返回 FALSE

cpdf_set_title

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_title -- Sets the title field of the pdf document

Description

bool cpdf_set_title ( int pdf_document, string title )

The cpdf_set_title() function sets the title of a pdf document. 如果成功则返回 TRUE,失败则返回 FALSE

See also cpdf_set_subject(), cpdf_set_creator() and cpdf_set_keywords().

cpdf_set_viewer_preferences

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_viewer_preferences --  How to show the document in the viewer

Description

bool cpdf_set_viewer_preferences ( int pdfdoc, array preferences )

警告

本函数暂无文档,仅有参数列表。

cpdf_set_word_spacing

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_word_spacing -- Sets spacing between words

Description

bool cpdf_set_word_spacing ( int pdf_document, float space )

The cpdf_set_word_spacing() function sets the spacing between words. 如果成功则返回 TRUE,失败则返回 FALSE

See also cpdf_set_char_spacing() and cpdf_set_leading().

cpdf_setdash

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setdash -- Sets dash pattern

Description

bool cpdf_setdash ( int pdf_document, float white, float black )

The cpdf_setdash() function set the dash pattern white white units and black black units. If both are 0 a solid line is set. 如果成功则返回 TRUE,失败则返回 FALSE

cpdf_setflat

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setflat -- Sets flatness

Description

bool cpdf_setflat ( int pdf_document, float value )

The cpdf_setflat() function set the flatness to a value between 0 and 100. 如果成功则返回 TRUE,失败则返回 FALSE

cpdf_setgray_fill

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setgray_fill -- Sets filling color to gray value

Description

bool cpdf_setgray_fill ( int pdf_document, float value )

The cpdf_setgray_fill() function sets the current gray value to fill a path. 如果成功则返回 TRUE,失败则返回 FALSE

See also cpdf_setrgbcolor_fill().

cpdf_setgray_stroke

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setgray_stroke -- Sets drawing color to gray value

Description

bool cpdf_setgray_stroke ( int pdf_document, float gray_value )

The cpdf_setgray_stroke() function sets the current drawing color to the given gray value. 如果成功则返回 TRUE,失败则返回 FALSE

See also cpdf_setrgbcolor_stroke().

cpdf_setgray

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setgray -- Sets drawing and filling color to gray value

Description

bool cpdf_setgray ( int pdf_document, float gray_value )

The cpdf_setgray() function sets the current drawing and filling color to the given gray value. 如果成功则返回 TRUE,失败则返回 FALSE

See also cpdf_setrgbcolor_stroke() and cpdf_setrgbcolor_fill().

cpdf_setlinecap

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setlinecap -- Sets linecap parameter

Description

bool cpdf_setlinecap ( int pdf_document, int value )

The cpdf_setlinecap() function set the linecap parameter between a value of 0 and 2. 0 = butt end, 1 = round, 2 = projecting square. 如果成功则返回 TRUE,失败则返回 FALSE

cpdf_setlinejoin

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setlinejoin -- Sets linejoin parameter

Description

bool cpdf_setlinejoin ( int pdf_document, int value )

The cpdf_setlinejoin() function set the linejoin parameter between a value of 0 and 2. 0 = miter, 1 = round, 2 = bevel. 如果成功则返回 TRUE,失败则返回 FALSE

cpdf_setlinewidth

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setlinewidth -- Sets line width

Description

bool cpdf_setlinewidth ( int pdf_document, float width )

The cpdf_setlinewidth() function set the line width to width. 如果成功则返回 TRUE,失败则返回 FALSE

cpdf_setmiterlimit

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setmiterlimit -- Sets miter limit

Description

bool cpdf_setmiterlimit ( int pdf_document, float value )

The cpdf_setmiterlimit() function set the miter limit to a value greater or equal than 1. 如果成功则返回 TRUE,失败则返回 FALSE

cpdf_setrgbcolor_fill

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setrgbcolor_fill -- Sets filling color to rgb color value

Description

bool cpdf_setrgbcolor_fill ( int pdf_document, float red_value, float green_value, float blue_value )

The cpdf_setrgbcolor_fill() function sets the current rgb color value to fill a path. 如果成功则返回 TRUE,失败则返回 FALSE

注: The values are expected to be floating point values between 0.0 and 1.0. (i.e black is (0.0, 0.0, 0.0) and white is (1.0, 1.0, 1.0)).

See also cpdf_setrgbcolor_stroke() and cpdf_setrgbcolor().

cpdf_setrgbcolor_stroke

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setrgbcolor_stroke -- Sets drawing color to rgb color value

Description

bool cpdf_setrgbcolor_stroke ( int pdf_document, float red_value, float green_value, float blue_value )

The cpdf_setrgbcolor_stroke() function sets the current drawing color to the given rgb color value. 如果成功则返回 TRUE,失败则返回 FALSE

注: The values are expected to be floating point values between 0.0 and 1.0. (i.e black is (0.0, 0.0, 0.0) and white is (1.0, 1.0, 1.0)).

See also cpdf_setrgbcolor_fill() and cpdf_setrgbcolor().

cpdf_setrgbcolor

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setrgbcolor -- Sets drawing and filling color to rgb color value

Description

bool cpdf_setrgbcolor ( int pdf_document, float red_value, float green_value, float blue_value )

The cpdf_setrgbcolor() function sets the current drawing and filling color to the given rgb color value. 如果成功则返回 TRUE,失败则返回 FALSE

注: The values are expected to be floating point values between 0.0 and 1.0. (i.e black is (0.0, 0.0, 0.0) and white is (1.0, 1.0, 1.0)).

See also cpdf_setrgbcolor_stroke() and cpdf_setrgbcolor_fill().

cpdf_show_xy

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_show_xy -- Output text at position

Description

bool cpdf_show_xy ( int pdf_document, string text, float x_coor, float y_coor [, int mode] )

The cpdf_show_xy() function outputs the string text at position with coordinates (x_coor, y_coor). 如果成功则返回 TRUE,失败则返回 FALSE

可选参数 mode 决定单元的长度。如果为 0 或被省略则使用该页指定的默认单元。否则坐标忽略当前单元而使用 postscript 的点来度量。

注: The function cpdf_show_xy() is identical to cpdf_text() without the optional parameters.

See also cpdf_text().

cpdf_show

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_show -- Output text at current position

Description

bool cpdf_show ( int pdf_document, string text )

The cpdf_show() function outputs the string in text at the current position. 如果成功则返回 TRUE,失败则返回 FALSE

See also cpdf_text(), cpdf_begin_text() and cpdf_end_text().

cpdf_stringwidth

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_stringwidth -- Returns width of text in current font

Description

float cpdf_stringwidth ( int pdf_document, string text )

The cpdf_stringwidth() function returns the width of the string in text. It requires a font to be set before.

See also cpdf_set_font().

cpdf_stroke

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_stroke -- Draw line along path

Description

bool cpdf_stroke ( int pdf_document )

The cpdf_stroke() function draws a line along current path. 如果成功则返回 TRUE,失败则返回 FALSE

See also cpdf_closepath() and cpdf_closepath_stroke().

cpdf_text

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_text -- Output text with parameters

Description

bool cpdf_text ( int pdf_document, string text [, float x_coor, float y_coor [, int mode [, float orientation [, int alignmode]]]] )

The cpdf_text() function outputs the string text at position with coordinates (x_coor, y_coor). 如果成功则返回 TRUE,失败则返回 FALSE

可选参数 mode 决定单元的长度。如果为 0 或被省略则使用该页指定的默认单元。否则坐标忽略当前单元而使用 postscript 的点来度量。

The optional parameter orientation is the rotation of the text in degree.

The optional parameter alignmode determines how the text is aligned.

See the ClibPDF documentation for possible values.

See also cpdf_show_xy().

cpdf_translate

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_translate -- Sets origin of coordinate system

Description

bool cpdf_translate ( int pdf_document, float x_coor, float y_coor )

The cpdf_translate() function set the origin of coordinate system to the point (x_coor, y_coor). 如果成功则返回 TRUE,失败则返回 FALSE

可选参数 mode 决定单元的长度。如果为 0 或被省略则使用该页指定的默认单元。否则坐标忽略当前单元而使用 postscript 的点来度量。

XV. COM 和 .Net(Windows)函数

简介

COM is an acronym for Component Object Model; it is an object orientated layer (and associated services) on top of DCE RPC (an open standard) and defines a common calling convention that enables code written in any language to call and interoperate with code written in any other language (provided those languages are COM aware). Not only can the code be written in any language, but it need not even be part of the same executable; the code can be loaded from a DLL, be found in another process running on the same machine, or, with DCOM (Distributed COM), be found in another process on a remote machine, all without your code even needing to know where a component resides.

There is a subset of COM known as OLE Automation which comprises a set of COM interfaces that allow loose binding to COM objects, so that they can be introspected and called at run-time without compile-time knowledge of how the object works. The PHP COM extension utilizes the OLE Automation interfaces to allow you to create and call compatible objects from your scripts. Technically speaking, this should really be called the "OLE Automation Extension for PHP", since not all COM objects are OLE compatible.

Now, why would or should you use COM? COM is one of the main ways to glue applications and components together on the Windows platform; using COM you can launch Microsoft Word, fill in a document template and save the result as a Word document and send it to a visitor of your web site. You can also use COM to perform administrative tasks for your network and to configure your IIS; these are just the most common uses; you can do much more with COM.

Starting with PHP 5, this extension (and this documentation) was rewritten from scratch and much of the old confusing and bogus cruft has be removed. Additionally, we support the instantiation and creation of .Net assemblies using the COM interoperability layer provided by Microsoft.

Please read this article for an overview of the changes in this extension in PHP 5.


需求

COM functions are only available for the Windows version of PHP.

.Net support requires PHP 5 and the .Net runtime.


安装

本函数库作为 PHP 内核的一部分,不用安装就能使用。

PHP 的 Windows 版本已经内置该扩展模块的支持。无需加载任何附加扩展库即可使用这些函数。

You are responsible for installing support for the various COM objects that you intend to use (such as MS Word); we don't and can't bundle all of those with PHP.


For Each

Starting with PHP 5, you may use PHP's own the 节 called foreach 在 µÚ 16 章 statement to iterate over the contents of a standard COM/OLE IEnumVariant. In laymans terms, this means that you can use foreach in places where you would have used For Each in VB/ASP code.

例子 1. For Each in ASP

<%
Set domainObject = GetObject("WinNT://Domain")
For Each obj in domainObject
  Response.Write obj.Name & "<br />"
Next
%>

例子 2. while() ... Next() in PHP 4

<?php
$domainObject = new COM("WinNT://Domain");
while ($obj = $domainObject->Next()) {
   echo $obj->Name . "<br />";
}
?>

例子 3. foreach in PHP 5

<?php
$domainObject = new COM("WinNT://Domain");
foreach ($domainObject as $obj) {
   echo $obj->Name . "<br />";
}
?>


Arrays and Array-style COM properties

Many COM objects expose their properties as arrays, or using array-style access. In PHP 4, you may use PHP array syntax to read/write such a property, but only a single dimension is allowed. If you want to read a multi-dimensional property, you could instead make the property access into a function call, with each parameter representing each dimension of the array access, but there is no way to write to such a property.

PHP 5 introduces the following new features to make your life easier:

  • Access multi-dimensional arrays, or COM properties that require multiple parameters using PHP array syntax. You can also write or set properties using this technique.

  • Iterate SafeArrays ("true" arrays) using the the 节 called foreach 在 µÚ 16 章 control structure. This works because SafeArrays include information about their size. If an array-style property implements IEnumVariant then you can also use foreach for that property too; take a look at the 节 called For Each for more information on this topic.


Exceptions (PHP 5)

This extension will throw instances of the class com_exception whenever there is a potentially fatal error reported by COM. All COM exceptions have a well-defined code property that corresponds to the HRESULT return value from the various COM operations. You may use this code to make programmatic decisions on how to handle the exception.


运行时配置

这些函数的行为受 php.ini 的影响。

表格 1. COM 配置选项

名称默认值可修改范围更新记录
com.allow_dcom"0"PHP_INI_SYSTEM自 PHP 4.0.5 起可用
com.autoregister_typelib"0"PHP_INI_ALL在 PHP 4 中是 PHP_INI_SYSTEM。自 PHP 4.1.0 起可用
com.autoregister_verbose"0"PHP_INI_ALL在 PHP 4 中是 PHP_INI_SYSTEM。自 PHP 4.1.0 起可用
com.autoregister_casesensitive"1"PHP_INI_ALL在 PHP 4 中是 PHP_INI_SYSTEM。自 PHP 4.1.0 起可用
com.code_page""PHP_INI_ALL自 PHP 5.0.0 起可用
com.typelib_file""PHP_INI_SYSTEM自 PHP 4.0.5 起可用
有关 PHP_INI_* 常量进一步的细节与定义参见附录 G

以下是配置选项的简要解释。

com.allow_dcom

如果打开此选项,PHP 将被允许以一个 D-COM(Distributed COM)客户方式操作并允许 PHP 脚本在远程服务器上实例化 COM 对象。

com.autoregister_typelib

When this is turned on, PHP will attempt to register constants from the typelibrary of objects that it instantiates, if those objects implement the interfaces required to obtain that information. The case sensitivity of the constants it registers is controlled by the com.autoregister_casesensitive configuration directive.

com.autoregister_verbose

When this is turned on, any problems with loading a typelibrary during object instantiation will be reported using the PHP error mechanism. The default is off, which does not emit any indication if there was an error finding or loading the type library.

com.autoregister_casesensitive

When this is turned on (the default), constants found in auto-loaded type libraries will be registered case sensitively. See com_load_typelib() for more details.

com.code_page

It controls the default character set code-page to use when passing strings to and from COM objects. If set to an empty string, PHP will assume that you want CP_ACP, which is the default system ANSI code page.

If the text in your scripts is encoded using a different encoding/character set by default, setting this directive will save you from having to pass the code page as a parameter to the COM class constructor. Please note that by using this directive (as with any PHP configuration directive), your PHP script becomes less portable; you should use the COM constructor parameter whenever possible.

注: This configuration directive was introduced with PHP 5.

com.typelib_file

When set, this should hold the path to a file that contains a list of typelibraries that should be loaded on startup. Each line of the file will be treated as the type library name and loaded as though you had called com_load_typelib(). The constants will be registered persistently, so that the library only needs to be loaded once. If a type library name ends with the string #cis or #case_insensitive, then the constants from that library will be registered case insensitively.


预定义常量

以下常量由本扩展模块定义,因此只有在本扩展模块被编译到 PHP 中,或者在运行时被动态加载后才有效。

CLSCTX_INPROC_SERVER (integer)

CLSCTX_INPROC_HANDLER (integer)

CLSCTX_LOCAL_SERVER (integer)

CLSCTX_REMOTE_SERVER (integer)

CLSCTX_SERVER (integer)

CLSCTX_ALL (integer)

VT_NULL (integer)

VT_EMPTY (integer)

VT_UI1 (integer)

VT_I2 (integer)

VT_I4 (integer)

VT_R4 (integer)

VT_R8 (integer)

VT_BOOL (integer)

VT_ERROR (integer)

VT_CY (integer)

VT_DATE (integer)

VT_BSTR (integer)

VT_DECIMAL (integer)

VT_UNKNOWN (integer)

VT_DISPATCH (integer)

VT_VARIANT (integer)

VT_I1 (integer)

VT_UI2 (integer)

VT_UI4 (integer)

VT_INT (integer)

VT_UINT (integer)

VT_ARRAY (integer)

VT_BYREF (integer)

CP_ACP (integer)

CP_MACCP (integer)

CP_OEMCP (integer)

CP_UTF7 (integer)

CP_UTF8 (integer)

CP_SYMBOL (integer)

CP_THREAD_ACP (integer)

VARCMP_LT (integer)

VARCMP_EQ (integer)

VARCMP_GT (integer)

VARCMP_NULL (integer)

NORM_IGNORECASE (integer)

NORM_IGNORENONSPACE (integer)

NORM_IGNORESYMBOLS (integer)

NORM_IGNOREWIDTH (integer)

NORM_IGNOREKANATYPE (integer)

NORM_IGNOREKASHIDA (integer)

DISP_E_DIVBYZERO (integer)

DISP_E_OVERFLOW (integer)

MK_E_UNAVAILABLE (integer)


参见

For further information on COM read the COM specification or perhaps take a look at Don Box's Yet Another COM Library (YACL). You might find some additional useful information in our FAQ for µÚ 55 章. If you're thinking of using MS Office applications on the server side, you should read the information here: Considerations for Server-Side Automation of Office.

目录
COM -- COM 类
DOTNET -- DOTNET class
VARIANT -- VARIANT 类
com_addref --  增加组件引用计数。[被废弃]
com_create_guid --  Generate a globally unique identifier (GUID)
com_event_sink --  Connect events from a COM object to a PHP object
com_get_active_object --  Returns a handle to an already running instance of a COM object
com_get --  获取 COM 组件的属性值 [被废弃]
com_invoke --  调用 COM 组件的方法。
com_isenum -- 获取一个 IEnumVariant
com_load_typelib -- 装载一个 Typelib
com_load --  创建新的 COM 组件的引用
com_message_pump --  Process COM messages, sleeping for up to timeoutms milliseconds
com_print_typeinfo --  Print out a PHP class definition for a dispatchable interface
com_propget -- com_get() 的别名
com_propput -- com_set() 的别名
com_propset -- com_set() 的别名
com_release --  减少组件引用计数。[被废弃]
com_set --  给 COM 组件的属性赋值
variant_abs --  Returns the absolute value of a variant
variant_add --  "Adds" two variant values together and returns the result
variant_and --  performs a bitwise AND operation between two variants and returns the result
variant_cast --  Convert a variant into a new variant object of another type
variant_cat --  concatenates two variant values together and returns the result
variant_cmp --  Compares two variants
variant_date_from_timestamp --  Returns a variant date representation of a unix timestamp
variant_date_to_timestamp --  Converts a variant date/time value to unix timestamp
variant_div --  Returns the result from dividing two variants
variant_eqv --  Performs a bitwise equivalence on two variants
variant_fix --  Returns the integer portion ? of a variant
variant_get_type -- Returns the type of a variant object
variant_idiv --  Converts variants to integers and then returns the result from dividing them
variant_imp --  Performs a bitwise implication on two variants
variant_int --  Returns the integer portion of a variant
variant_mod --  Divides two variants and returns only the remainder
variant_mul --  multiplies the values of the two variants and returns the result
variant_neg --  Performs logical negation on a variant
variant_not --  Performs bitwise not negation on a variant
variant_or --  Performs a logical disjunction on two variants
variant_pow --  Returns the result of performing the power function with two variants
variant_round --  Rounds a variant to the specified number of decimal places
variant_set_type --  Convert a variant into another type "in-place"
variant_set --  Assigns a new value for a variant object
variant_sub --  subtracts the value of the right variant from the left variant value and returns the result
variant_xor --  Performs a logical exclusion on two variants

COM

(no version information, might be only in CVS)

COM -- COM 类

大纲

$obj = new COM("server.object")

描述

COM 类提供了一个将 (D)COM 组件整合到 PHP 脚本中的框架。

方法

string COM::COM ( string module_name [, string server_name [, int codepage]] )

COM 类构造函数。参数:

module_name

被请求组件的名字或 class-id。

server_name

DCOM 服务器的名字,组件在此服务器上被取用。如果是 NULL,则假定是 localhost。想要允许 DCOM,必须将 php.ini 中的 com.allow_dcom 设为 TRUE

codepage

指定用于将 PHP 字符串(php-strings)转换成 UNICODE 字符串(unicode-strings)的代码页,反之亦然。可用的值为 CP_ACPCP_MACCPCP_OEMCPCP_SYMBOLCP_THREAD_ACP, CP_UTF7CP_UTF8

例子 1. COM 示例 (1)

// 启动 word
$word = new COM("word.application") or die("Unable to instanciate Word");
print "Loaded Word, version {$word->Version}\n";

//将其置前
$word->Visible = 1;

//打开一个空文档
$word->Documents->Add();

//随便做些事情
$word->Selection->TypeText("This is a test...");
$word->Documents[1]->SaveAs("Useless test.doc");

//关闭 word
$word->Quit();

//释放对象
$word->Release();
$word = null;

例子 2. COM 示例 (2)

$conn = new COM("ADODB.Connection") or die("Cannot start ADO");
$conn->Open("Provider=SQLOLEDB; Data Source=localhost;
Initial Catalog=database; User ID=user; Password=password");

$rs = $conn->Execute("SELECT * FROM sometable");    // 记录集

$num_columns = $rs->Fields->Count();
echo $num_columns . "\n";

for ($i=0; $i < $num_columns; $i++)
{
    $fld[$i] = $rs->Fields($i);
}

$rowcount = 0;
while (!$rs->EOF)
{
    for ($i=0; $i < $num_columns; $i++)
    {
        echo $fld[$i]->value . "\t";
    }
    echo "\n";
    $rowcount++;            // rowcount 自增
    $rs->MoveNext();
}

$rs->Close();
$conn->Close();

$rs->Release();
$conn->Release();

$rs = null;
$conn = null;

DOTNET

(no version information, might be only in CVS)

DOTNET -- DOTNET class

大纲

$obj = new DOTNET("assembly", "classname")

Description

The DOTNET class allows you to instantiate a class from a .Net assembly and call its methods and access its properties.

Methods

string DOTNET::DOTNET ( string assembly_name, string class_name [, int codepage] )

DOTNET class constructor. assembly_name specifies which assembly should be loaded, and class_name specifices which class in that assembly to instantiate. You may optionally specify a codepage to use for unicode string transformations; see the COM class for more details on code pages.

The returned object is an overloaded object, which means that PHP does not see any fixed methods as it does with regular classes; instead, any property or method accesses are passed through to COM and from there to DOTNET. In other words, the .Net object is mapped through the COM interoperability layer provided by the .Net runtime.

Once you have created a DOTNET object, PHP treats it identically to any other COM object; all the same rules apply.

例子 1. DOTNET example

<?php
  $stack = new DOTNET("mscorlib", "System.Collections.Stack"); 
  $stack->Push(".Net"); 
  $stack->Push("Hello "); 
  echo $stack->Pop() . $stack->Pop(); 
?>

注: You need to install the .Net runtime on your web server to take advantage of this feature.

VARIANT

(no version information, might be only in CVS)

VARIANT -- VARIANT 类

大纲

$vVar = new VARIANT($var)

描述

用于将变量封装进 VARIANT 结构中的简单容器。

方法

string VARIANT::VARIANT ( [mixed value [, int type [, int codepage]]] )

VARIANT 类构造函数。参数:

value

初始值。若省略则创建一个 VT_EMPTY 对象。

type

指定 VARIANT 对象的内容类型。可用的值为 VT_UI1VT_UI2VT_UI4VT_I1VT_I2VT_I4VT_R4VT_R8VT_INTVT_UINTVT_BOOLVT_ERRORVT_CYVT_DATEVT_BSTRVT_DECIMALVT_UNKNOWNVT_DISPATCHVT_VARIANT。这些值相互排斥,但是可以使用 VT_BYREF 将它们联合起来指定为一个值。若省略,则使用参数 value 的类型。额外信息请查阅 msdn 库。

codepage

指定用于将 PHP 字符串(php-strings)转换成 UNICODE 字符串(unicode-strings)的代码页,反之亦然。可用的值为 CP_ACPCP_MACCPCP_OEMCPCP_SYMBOLCP_THREAD_ACP, CP_UTF7CP_UTF8

com_addref

(PHP 4 >= 4.1.0)

com_addref --  增加组件引用计数。[被废弃]

描述

void com_addref ( void )

增加组件引用计数。

警告

你应当不再需要使用该函数。

注: 该函数已经在 PHP 5 取消。

com_create_guid

(PHP 5)

com_create_guid --  Generate a globally unique identifier (GUID)

Description

string com_create_guid ( void )

Generates a Globally Unique Identifier (GUID) and returns it as a string. A GUID is generated in the same way as DCE UUID's, except that the Microsoft convention is to enclose a GUID in curly braces.

See also uuid_create() in the PECL uuid extension.

com_event_sink

(PHP 4 >= 4.2.3, PHP 5)

com_event_sink --  Connect events from a COM object to a PHP object

Description

bool com_event_sink ( variant comobject, object sinkobject [, mixed sinkinterface] )

Instructs COM to sink events generated by comobject into the PHP object sinkobject. PHP will attempt to use the default dispinterface type specified by the typelibrary associated with comobject, but you may override this choice by setting sinkinterface to the name of the dispinterface that you want to use.

sinkobject should be an instance of a class with methods named after those of the desired dispinterface; you may use com_print_typeinfo() to help generate a template class for this purpose.

Be careful how you use this feature; if you are doing something similar to the example below, then it doesn't really make sense to run it in a web server context.

例子 1. COM event sink example

<?php
class IEEventSinker {
  var $terminated = false;

  function ProgressChange($progress, $progressmax) {
    echo "Download progress: $progress / $progressmax\n";
  }

  function DocumentComplete(&$dom, $url) {
    echo "Document $url complete\n";
  }

  function OnQuit() {
    echo "Quit!\n";
    $this->terminated = true;
  }
}
$ie = new COM("InternetExplorer.Application");
// note that you don't need the & for PHP 5!
$sink =& new IEEventSinker();
com_event_sink($ie, $sink, "DWebBrowserEvents2");
$ie->Visible = true;
$ie->Navigate("http://www.php.net");
while(!$sink->terminated) {
  com_message_pump(4000);
}
$ie = null;
?>

See also com_print_typeinfo(), com_message_pump().

com_get_active_object

(PHP 5)

com_get_active_object --  Returns a handle to an already running instance of a COM object

Description

variant com_get_active_object ( string progid [, int code_page] )

com_get_active_object() is similar to creating a new instance of a COM object, except that it will only return an object to your script if the object is already running. OLE applications use something known as the Running Object Table to allow well-known applications to be launched only once; this function exposes the COM library function GetActiveObject() to get a handle on a running instance.

progid must be either the ProgID or CLSID for the object that you want to access (for example Word.Application). code_page acts in precisely the same way that it does for the COM class.

If the requested object is running, it will be returned to your script just like any other COM object. Otherwise a com_exception will be raised. There are a variety of reasons why this function might fail, the most common being that the object is not already running. In that situation, the exception error code will be MK_E_UNAVAILABLE; you can use the getCode method of the exception object to check the exception code.

警告

Using com_get_active_object() in a web server context is not always a smart idea. Most COM/OLE applications are not designed to handle more than one client concurrently, even (or especially!) Microsoft Office. You should read Considerations for Server-Side Automation of Office for more information on the general issues involved.

com_get

(PHP 3 >= 3.0.3, PHP 4)

com_get --  获取 COM 组件的属性值 [被废弃]

描述

mixed com_get ( resource com_object, string property )

返回由 com_object 所引用的 COM 对象的 property 属性值,出错则返回 FALSE

例子 1. 不要使用 com_get() ,使用 OO 语法代替

<?php
// do this
$var = $obj->property;
// instead of this:
$var = com_get($obj, 'property');
?>

注: 本函数在 PHP 5 中不存在,应该使用常规的并更自然的面向对象语法来访问属性或调用方法。

com_invoke

(PHP 4)

com_invoke --  调用 COM 组件的方法。

描述

mixed com_invoke ( resource com_object, string function_name [, mixed function parameters, ...] )

com_invoke() 调用由 com_object 所引用的对象的方法。出错返回 FALSE,成功则返回 function_name 的返回值。

com_isenum

(PHP 4 >= 4.1.0)

com_isenum -- 获取一个 IEnumVariant

描述

void com_isenum ( object com_module )

警告

本函数暂无文档,仅有参数列表。

com_load_typelib

(PHP 4 >= 4.1.0, PHP 5)

com_load_typelib -- 装载一个 Typelib

描述

void com_load_typelib ( string typelib_name [, int case_insensitive] )

警告

本函数暂无文档,仅有参数列表。

com_load

(PHP 4)

com_load --  创建新的 COM 组件的引用

描述

string com_load ( string module_name [, string server_name [, int codepage]] )

com_load() 创建新的 COM 组件同时返回此组件的引用。失败则返回 FALSEcodepage 可用的值为:CP_ACPCP_MACCPCP_OEMCPCP_SYMBOLCP_THREAD_ACP, CP_UTF7CP_UTF8

com_message_pump

(PHP 4 >= 4.2.3, PHP 5)

com_message_pump --  Process COM messages, sleeping for up to timeoutms milliseconds

Description

bool com_message_pump ( [int timeoutms] )

This function will sleep for up to timeoutms milliseconds, or until a message arrives in the queue. If a message or messages arrives before the timeout, they will be dispatched, and the function will return TRUE. If the timeout occurs and no messages were processed, the return value will be FALSE. If you do not specify a value for timeoutms, then 0 will be assumed. A 0 value means that no waiting will be performed; if there are messages pending they will be dispatched as before; if there are no messages pending, the function will return FALSE immediately without sleeping.

The purpose of this function is to route COM calls between apartments and handle various synchronization issues. This allows your script to wait efficiently for events to be triggered, while still handling other events or running other code in the background. You should use it in a loop, as demonstrated by the example in the com_event_sink() function, until you are finished using event bound COM objects.

com_print_typeinfo

(PHP 4 >= 4.2.3, PHP 5)

com_print_typeinfo --  Print out a PHP class definition for a dispatchable interface

Description

bool com_print_typeinfo ( object comobject [, string dispinterface [, bool wantsink]] )

The purpose of this function is to help generate a skeleton class for use as an event sink. You may also use it to generate a dump of any COM object, provided that it supports enough of the introspection interfaces, and that you know the name of the interface you want to display.

comobject should be either an instance of a COM object, or be the name of a typelibrary (which will be resolved according to the rules set out in com_load_typelib()). dispinterface is the name of an IDispatch descendant interface that you want to display. If wantsink is TRUE, the corresponding sink interface will be displayed instead.

See also com_event_sink(), com_load_typelib().

com_propget

(PHP 3 >= 3.0.3, PHP 4)

com_propget -- com_get() 的别名

描述

此函数是 com_get() 的别名。

com_propput

(PHP 3 >= 3.0.3, PHP 4)

com_propput -- com_set() 的别名

描述

此函数是 com_set() 的别名。

com_propset

(PHP 3 >= 3.0.3, PHP 4)

com_propset -- com_set() 的别名

描述

此函数是 com_set() 的别名。

com_release

(PHP 4 >= 4.1.0)

com_release --  减少组件引用计数。[被废弃]

描述

void com_release ( void )

减少组件引用计数。

警告

你应当不再需要使用该函数。

注: 该函数已经在 PHP 5 取消。

com_set

(PHP 3 >= 3.0.3, PHP 4)

com_set --  给 COM 组件的属性赋值

描述

void com_set ( resource com_object, string property, mixed value )

设置由 com_object 所引用的对象的 property 属性值。成功则返回新设置的值,出错则返回 FALSE

例子 1. 不要使用 com_set() ,使用 OO 语法代替

<?php
   // do this
   $obj->property = $value;
   // instead of this:
   com_set($obj, 'property', $value);
   ?>

注: 本函数在 PHP 5 中不存在,应该使用常规的并更自然的面向对象语法来访问属性或调用方法。

variant_abs

(PHP 5)

variant_abs --  Returns the absolute value of a variant

Description

mixed variant_abs ( mixed val )

Returns the absolute value of val.

See also abs().

注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。

变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

variant_add

(PHP 5)

variant_add --  "Adds" two variant values together and returns the result

Description

mixed variant_add ( mixed left, mixed right )

Adds left to right using the following rules (taken from the MSDN library), which correspond to those of Visual Basic:

表格 1. Variant Addition Rules

IfThen
Both expressions are of the string typeConcatenation
One expression is a string type and the other a characterAddition
One expression is numeric and the other is a stringAddition
Both expressions are numericAddition
Either expression is NULLNULL is returned
Both expressions are emptyInteger subtype is returned

See also variant_sub().

注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。

变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

variant_and

(PHP 5)

variant_and --  performs a bitwise AND operation between two variants and returns the result

Description

mixed variant_and ( mixed left, mixed right )

Performs a bitwise AND operation, according to the following truth table; note that this is slightly different from a regular AND operation.

表格 1. Variant AND Rules

If left isIf right isthen the result is
TRUETRUETRUE
TRUEFALSEFALSE
TRUENULLNULL
FALSETRUEFALSE
FALSEFALSEFALSE
FALSENULLFALSE
NULLTRUENULL
NULLFALSEFALSE
NULLNULLNULL

See also variant_or().

注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。

变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

variant_cast

(PHP 5)

variant_cast --  Convert a variant into a new variant object of another type

Description

variant variant_cast ( variant variant, int type )

This function makes a copy of variant and then performs a variant cast operation to force the copy to have the type given by type. type should be one of the VT_XXX constants.

This function wraps VariantChangeType() in the COM library; consult MSDN for more information.

See also variant_set_type().

variant_cat

(PHP 5)

variant_cat --  concatenates two variant values together and returns the result

Description

mixed variant_cat ( mixed left, mixed right )

Concatenates left with right and returns the result.

See also the 节 called 字符串运算符 在 µÚ 15 章 for the string concatenation operator; this function is notionally equivalent to $left . $right.

注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。

变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

variant_cmp

(PHP 5)

variant_cmp --  Compares two variants

Description

int variant_cmp ( mixed left, mixed right [, int lcid [, int flags]] )

Compares left with right and returns one of the following values:

表格 1. Variant Comparision Results

valuemeaning
VARCMP_LTleft is less than right
VARCMP_EQleft is equal to right
VARCMP_GTleft is greater than right
VARCMP_NULLEither left, right or both are NULL

This function will only compare scalar values, not arrays or variant records.

lcid is a valid Locale Identifier to use when comparing strings (this affects string collation). flags can be one or more of the following values OR'd together, and affects string comparisons:

表格 2. Variant Comparision Flags

valuemeaning
NORM_IGNORECASECompare case insensitively
NORM_IGNORENONSPACEIgnore nonspacing characters
NORM_IGNORESYMBOLSIgnore symbols
NORM_IGNOREWIDTHIgnore string width
NORM_IGNOREKANATYPEIgnore Kana type
NORM_IGNOREKASHIDAIgnore Arabic kashida characters

注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。

变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

variant_date_from_timestamp

(PHP 5)

variant_date_from_timestamp --  Returns a variant date representation of a unix timestamp

Description

variant variant_date_from_timestamp ( int timestamp )

Converts timestamp from a unix timestamp value into a variant of type VT_DATE. This allows easier interopability between the unix-ish parts of PHP and COM.

See also variant_date_to_timestamp() for the inverse of this operation, mktime(), time().

variant_date_to_timestamp

(PHP 5)

variant_date_to_timestamp --  Converts a variant date/time value to unix timestamp

Description

int variant_date_to_timestamp ( variant variant )

Converts variant from a VT_DATE (or similar) value into a unix timestamp. This allows easier interopability between the unix-ish parts of PHP and COM.

See also variant_date_from_timestamp() for the inverse of this operation, date(), strftime().

variant_div

(PHP 5)

variant_div --  Returns the result from dividing two variants

Description

mixed variant_div ( mixed left, mixed right )

Divides left by right and returns the result, subject to the following rules:

表格 1. Variant Division Rules

IfThen
Both expressions are of the string, date, character, boolean typeDouble is returned
One expression is a string type and the other a characterDivision and a double is returned
One expression is numeric and the other is a stringDivision and a double is returned.
Both expressions are numericDivision and a double is returned
Either expression is NULLNULL is returned
right is empty and left is anything but emptyA com_exception with code DISP_E_DIVBYZERO is thrown
left is empty and right is anything but empty.0 as type double is returned
Both expressions are emptyA com_exception with code DISP_E_OVERFLOW is thrown

注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。

变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

variant_eqv

(PHP 5)

variant_eqv --  Performs a bitwise equivalence on two variants

Description

mixed variant_eqv ( mixed left, mixed right )

If each bit in left is equal to the corresponding bit in right then TRUE is returned, otherwise FALSE is returned.

注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。

变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

variant_fix

(PHP 5)

variant_fix --  Returns the integer portion ? of a variant

Description

mixed variant_fix ( mixed variant )

If variant is negative, then the first negative integer greater than or equal to the variant is returned, otherwise returns the integer portion of the value of variant.

See also variant_int(), variant_round(), floor(), ceil(), round().

警告

This documentation is based on the MSDN documentation; it appears that this function is either the same as variant_int(), or that there is an error in the MSDN documentation.

注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。

变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

variant_get_type

(PHP 5)

variant_get_type -- Returns the type of a variant object

Description

int variant_get_type ( variant variant )

This function returns an integer value that indicates the type of variant, which can be an instance of COM, DOTNET or VARIANT classes. The return value can be compared to one of the VT_XXX constants.

The return value for COM and DOTNET objects will usually be VT_DISPATCH; the only reason this function works for those classes is because COM and DOTNET are descendants of VARIANT.

In PHP versions prior to 5, you could obtain this information from instances of the VARIANT class ONLY, by reading a fake type property. See the VARIANT class for more information on this.

variant_idiv

(PHP 5)

variant_idiv --  Converts variants to integers and then returns the result from dividing them

Description

mixed variant_idiv ( mixed left, mixed right )

Converts left and right to integer values, and then performs integer division according the following rules:

表格 1. Variant Integer Division Rules

IfThen
Both expressions are of the string, date, character, boolean typeDivision and integer is returned
One expression is a string type and the other a characterDivision
One expression is numeric and the other is a stringDivision
Both expressions are numericDivision
Either expression is NULLNULL is returned
Both expressions are emptyA com_exception with code DISP_E_DIVBYZERO is thrown

See also variant_div().

注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。

变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

variant_imp

(PHP 5)

variant_imp --  Performs a bitwise implication on two variants

Description

mixed variant_imp ( mixed left, mixed right )

Performs a bitwise implication operation, according to the following truth table:

表格 1. Variant Implication Table

If left isIf right isthen the result is
TRUETRUETRUE
TRUEFALSETRUE
TRUENULLTRUE
FALSETRUETRUE
FALSEFALSETRUE
FALSENULLTRUE
NULLTRUETRUE
NULLFALSENULL
NULLNULLNULL

注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。

变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

variant_int

(PHP 5)

variant_int --  Returns the integer portion of a variant

Description

mixed variant_int ( mixed variant )

If variant is negative, then the first negative integer greater than or equal to the variant is returned, otherwise returns the integer portion of the value of variant.

See also variant_fix(), variant_round(), floor(), ceil(), round().

注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。

变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

variant_mod

(PHP 5)

variant_mod --  Divides two variants and returns only the remainder

Description

mixed variant_mod ( mixed left, mixed right )

Divides left by right and returns the remainder.

See also variant_div(), variant_idiv().

注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。

变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

variant_mul

(PHP 5)

variant_mul --  multiplies the values of the two variants and returns the result

Description

mixed variant_mul ( mixed left, mixed right )

Multiplies left by right and returns the result, subject to the following rules:

表格 1. Variant Multiplication Rules

IfThen
Both expressions are of the string, date, character, boolean typeMultiplication
One expression is a string type and the other a characterMultiplication
One expression is numeric and the other is a stringMultiplication
Both expressions are numericMultiplication
Either expression is NULLNULL is returned
Both expressions are emptyEmpty string is returned

Boolean values are converted to -1 for FALSE and 0 for TRUE.

See also variant_div(), variant_idiv().

注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。

变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

variant_neg

(PHP 5)

variant_neg --  Performs logical negation on a variant

Description

mixed variant_neg ( mixed variant )

Performs logical negation of variant and returns the result.

注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。

变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

variant_not

(PHP 5)

variant_not --  Performs bitwise not negation on a variant

Description

mixed variant_not ( mixed variant )

Performs bitwise not negation on variant and returns the result. If variant is NULL, the result will also be NULL.

注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。

变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

variant_or

(PHP 5)

variant_or --  Performs a logical disjunction on two variants

Description

mixed variant_or ( mixed left, mixed right )

Performs a bitwise OR operation, according to the following truth table; note that this is slightly different from a regular OR operation.

表格 1. Variant OR Rules

If left isIf right isthen the result is
TRUETRUETRUE
TRUEFALSETRUE
TRUENULLTRUE
FALSETRUETRUE
FALSEFALSEFALSE
FALSENULLNULL
NULLTRUETRUE
NULLFALSENULL
NULLNULLNULL

See also variant_and(), variant_xor().

注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。

变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

variant_pow

(PHP 5)

variant_pow --  Returns the result of performing the power function with two variants

Description

mixed variant_pow ( mixed left, mixed right )

Returns the result of left to the power of right.

See also pow().

注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。

变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

variant_round

(PHP 5)

variant_round --  Rounds a variant to the specified number of decimal places

Description

mixed variant_round ( mixed variant, int decimals )

Returns the value of variant rounded to decimals decimal places.

See also round().

注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。

变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

variant_set_type

(PHP 5)

variant_set_type --  Convert a variant into another type "in-place"

Description

void variant_set_type ( variant variant, int type )

This function is similar to variant_cast() except that the variant is modified "in-place"; no new variant is created. The parameters for this function have identical meaning to those of variant_cast().

See also variant_cast().

variant_set

(PHP 5)

variant_set --  Assigns a new value for a variant object

Description

void variant_set ( variant variant, mixed value )

Converts value to a variant and assigns it to the variant object; no new variant object is created, and the old value of variant is freed/released.

variant_sub

(PHP 5)

variant_sub --  subtracts the value of the right variant from the left variant value and returns the result

Description

mixed variant_sub ( mixed left, mixed right )

Subtracts right from left using the following rules:

表格 1. Variant Subtraction Rules

IfThen
Both expressions are of the string typeSubtraction
One expression is a string type and the other a characterSubtraction
One expression is numeric and the other is a stringSubtraction.
Both expressions are numericSubtraction
Either expression is NULLNULL is returned
Both expressions are emptyEmpty string is returned

See also variant_add().

注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。

变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

variant_xor

(PHP 5)

variant_xor --  Performs a logical exclusion on two variants

Description

mixed variant_xor ( mixed left, mixed right )

Performs a logical exclusion, according to the following truth table:

表格 1. Variant XOR Rules

If left isIf right isthen the result is
TRUETRUEFALSE
TRUEFALSETRUE
FALSETRUETRUE
FALSEFALSEFALSE
NULLNULLNULL

See also variant_and(), variant_or().

注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。

变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

XVI. Crack Functions

简介

These functions allow you to use the CrackLib library to test the 'strength' of a password. The 'strength' of a password is tested by that checks length, use of upper and lower case and checked against the specified CrackLib dictionary. CrackLib will also give helpful diagnostic messages that will help 'strengthen' the password.

注: 本扩展已被移动到 PECL 库中且自以下版本起不再被绑定到 PHP 中:5.0.0.


需求

More information regarding CrackLib along with the library can be found at http://www.crypticide.com/users/alecm/.


安装

PECL 扩展未绑定于 PHP 中。 进一步信息例如新版本,下载,源程序,维护者信息以及更新日志可以在此找到: http://pecl.php.net/package/crack.

在 PHP 4 中本 PECL 扩展的源程序位于 PHP 源程序中的 ext/ 目录下或者在上面的 PECL 连接中。 In order to use these functions you must compile PHP with Crack support by using the --with-crack[=DIR] configuration option.

Windows users will enable php_crack.dll inside of php.ini in order to use these functions. 在 PHP 4 中本 DLL 位于 PHP Windows 执行包中的 extensions/ 目录下。 可以从 PHP 下载页面或者 http://snaps.php.net/ 下载此 PECL 扩展的 DLL 文件。


运行时配置

这些函数的行为受 php.ini 的影响。

表格 1. Crack configuration options

NameDefaultChangeableChangelog
crack.default_dictionaryNULLPHP_INI_SYSTEMAvailable since PHP 4.0.5.
有关 PHP_INI_* 常量进一步的细节与定义参见附录 G


资源类型

本扩展模块未定义任何资源类型。


预定义常量

本扩展模块未定义任何常量。


范例

This example shows how to open a CrackLib dictionary, test a given password, retrieve any diagnostic messages, and close the dictionary.

例子 1. CrackLib example

<?php
// Open CrackLib Dictionary
$dictionary = crack_opendict('/usr/local/lib/pw_dict')
     or die('Unable to open CrackLib dictionary');

// Perform password check
$check = crack_check($dictionary, 'gx9A2s0x');

// Retrieve messages
$diag = crack_getlastmessage();
echo $diag; // 'strong password'

// Close dictionary
crack_closedict($dictionary);
?>

注: If crack_check() returns TRUE, crack_getlastmessage() will return 'strong password'.

目录
crack_check -- Performs an obscure check with the given password
crack_closedict -- Closes an open CrackLib dictionary
crack_getlastmessage -- Returns the message from the last obscure check
crack_opendict -- Opens a new CrackLib dictionary

crack_check

(PHP 4 >= 4.0.5, PECL)

crack_check -- Performs an obscure check with the given password

说明

bool crack_check ( resource dictionary, string password )

bool crack_check ( string password )

Performs an obscure check with the given password on the specified dictionary.

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

参数

dictionary

The crack lib dictionary. If not specified, the last opened dictionary is used.

password

The tested password.

返回值

Returns TRUE if password is strong, or FALSE otherwise.

crack_closedict

(PHP 4 >= 4.0.5, PECL)

crack_closedict -- Closes an open CrackLib dictionary

说明

bool crack_closedict ( [resource dictionary] )

crack_closedict() closes the specified dictionary identifier.

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

参数

dictionary

The dictionary to close. If not specified, the current directory is closed.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

crack_getlastmessage

(PHP 4 >= 4.0.5, PECL)

crack_getlastmessage -- Returns the message from the last obscure check

说明

string crack_getlastmessage ( void )

crack_getlastmessage() returns the message from the last obscure check.

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

返回值

The message from the last obscure check.

crack_opendict

(PHP 4 >= 4.0.5, PECL)

crack_opendict -- Opens a new CrackLib dictionary

说明

resource crack_opendict ( string dictionary )

crack_opendict() opens the specified CrackLib dictionary for use with crack_check().

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

注: Only one dictionary may be open at a time.

参数

dictionary

The path to the Cracklib dictionary.

返回值

Returns a dictionary resource identifier on success, or FALSE on failure.

XVII. Credit Mutuel CyberMUT functions

简介

This extension allows you to process credit cards transactions using Credit Mutuel CyberMUT system.

CyberMUT is a popular Web Payment Service in France, provided by the Credit Mutuel bank. If you are foreign in France, these functions will not be useful for you.

The use of these functions is almost identical to the original functions, except for the parameters of return for CreerFormulaireCM and CreerReponseCM, which are returned directly by functions PHP, whereas they had passed in reference in the original functions.

注: 本扩展模块在 Windows 平台下不可用。

注: 本扩展已被移动到 PECL 库中且自以下版本起不再被绑定到 PHP 中:4.3.0


需求

You will require the appropriate SDK for your platform, which may be sent to you after your CyberMUT's subscription (contact them via Web, or go to the nearest Credit Mutuel).

注: These functions only provide a link to CyberMUT SDK. Be sure to read the CyberMUT Developers Guide for full details of the required parameters.

目录
cybermut_creerformulairecm -- Generate HTML form of request for payment
cybermut_creerreponsecm -- Generate the delivery's acknowledgement of the payment's confirmation
cybermut_testmac -- Make sure that there was no data diddling contained in the received message of confirmation

cybermut_creerformulairecm

(4.0.5 - 4.2.3 only, PECL)

cybermut_creerformulairecm -- Generate HTML form of request for payment

说明

string cybermut_creerformulairecm ( string url_cm, string version, string tpe, string price, string ref_command, string text_free, string url_return, string url_return_ok, string url_return_err, string language, string code_company, string text_button )

cybermut_creerformulairecm() is used to generate the HTML form of request for payment.

cybermut_creerreponsecm

(4.0.5 - 4.2.3 only, PECL)

cybermut_creerreponsecm -- Generate the delivery's acknowledgement of the payment's confirmation

说明

string cybermut_creerreponsecm ( string sentence )

The parameter is "OK" if the message of confirmation of the payment were correctly authenticated by cybermut_testmac(). Any other chain is regarded as an error message.

返回值

Returns a string containing the message of acknowledgement of delivery.

cybermut_testmac

(4.0.5 - 4.2.3 only, PECL)

cybermut_testmac -- Make sure that there was no data diddling contained in the received message of confirmation

说明

bool cybermut_testmac ( string code_mac, string version, string tpe, string cdate, string price, string ref_command, string text_free, string code_return )

cybermut_testmac() is used to make sure that there was no data diddling contained in the received message of confirmation. Pay attention to parameters code_return and text_free, which cannot be evaluated as is, because of the dash.

XVIII. CURL, Client URL Library Functions

简介

PHP supports libcurl, a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.

These functions have been added in PHP 4.0.2.


需求

In order to use the CURL functions you need to install the CURL package. PHP requires that you use CURL 7.0.2-beta or higher. In PHP 4.2.3, you will need CURL version 7.9.0 or higher. From PHP 4.3.0, you will need a CURL version that's 7.9.8 or higher. PHP 5.0.0 requires a CURL version 7.10.5 or greater.


安装

To use PHP's CURL support you must also compile PHP --with-curl[=DIR] where DIR is the location of the directory containing the lib and include directories. In the "include" directory there should be a folder named "curl" which should contain the easy.h and curl.h files. There should be a file named libcurl.a located in the "lib" directory. Beginning with PHP 4.3.0 you can configure PHP to use CURL for URL streams --with-curlwrappers.

Note to Win32 Users: In order to enable this module on a Windows environment, you must copy libeay32.dll and ssleay32.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM folder of your Windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM)


预定义常量

以下常量由本扩展模块定义,因此只有在本扩展模块被编译到 PHP 中,或者在运行时被动态加载后才有效。

CURLOPT_AUTOREFERER (integer)

Available since PHP 5.1.0

CURLOPT_COOKIESESSION (integer)

Available since PHP 5.1.0

CURLOPT_DNS_USE_GLOBAL_CACHE (integer)

CURLOPT_DNS_CACHE_TIMEOUT (integer)

CURLOPT_FTPSSLAUTH (integer)

Available since PHP 5.1.0

CURLOPT_PORT (integer)

CURLOPT_FILE (integer)

CURLOPT_INFILE (integer)

CURLOPT_INFILESIZE (integer)

CURLOPT_URL (integer)

CURLOPT_PROXY (integer)

CURLOPT_VERBOSE (integer)

CURLOPT_HEADER (integer)

CURLOPT_HTTPHEADER (integer)

CURLOPT_NOPROGRESS (integer)

CURLOPT_NOBODY (integer)

CURLOPT_FAILONERROR (integer)

CURLOPT_UPLOAD (integer)

CURLOPT_POST (integer)

CURLOPT_FTPLISTONLY (integer)

CURLOPT_FTPAPPEND (integer)

CURLOPT_NETRC (integer)

CURLOPT_FOLLOWLOCATION (integer)

CURLOPT_FTPASCII (integer)

CURLOPT_PUT (integer)

CURLOPT_MUTE (integer)

CURLOPT_USERPWD (integer)

CURLOPT_PROXYUSERPWD (integer)

CURLOPT_RANGE (integer)

CURLOPT_TIMEOUT (integer)

CURLOPT_POSTFIELDS (integer)

CURLOPT_REFERER (integer)

CURLOPT_USERAGENT (integer)

CURLOPT_FTPPORT (integer)

CURLOPT_FTP_USE_EPSV (integer)

CURLOPT_LOW_SPEED_LIMIT (integer)

CURLOPT_LOW_SPEED_TIME (integer)

CURLOPT_RESUME_FROM (integer)

CURLOPT_COOKIE (integer)

CURLOPT_SSLCERT (integer)

CURLOPT_SSLCERTPASSWD (integer)

CURLOPT_WRITEHEADER (integer)

CURLOPT_SSL_VERIFYHOST (integer)

CURLOPT_COOKIEFILE (integer)

CURLOPT_SSLVERSION (integer)

CURLOPT_TIMECONDITION (integer)

CURLOPT_TIMEVALUE (integer)

CURLOPT_CUSTOMREQUEST (integer)

CURLOPT_STDERR (integer)

CURLOPT_TRANSFERTEXT (integer)

CURLOPT_RETURNTRANSFER (integer)

CURLOPT_QUOTE (integer)

CURLOPT_POSTQUOTE (integer)

CURLOPT_INTERFACE (integer)

CURLOPT_KRB4LEVEL (integer)

CURLOPT_HTTPPROXYTUNNEL (integer)

CURLOPT_FILETIME (integer)

CURLOPT_WRITEFUNCTION (integer)

CURLOPT_READFUNCTION (integer)

CURLOPT_PASSWDFUNCTION (integer)

CURLOPT_HEADERFUNCTION (integer)

CURLOPT_MAXREDIRS (integer)

CURLOPT_MAXCONNECTS (integer)

CURLOPT_CLOSEPOLICY (integer)

CURLOPT_FRESH_CONNECT (integer)

CURLOPT_FORBID_REUSE (integer)

CURLOPT_RANDOM_FILE (integer)

CURLOPT_EGDSOCKET (integer)

CURLOPT_CONNECTTIMEOUT (integer)

CURLOPT_SSL_VERIFYPEER (integer)

CURLOPT_CAINFO (integer)

CURLOPT_CAPATH (integer)

CURLOPT_COOKIEJAR (integer)

CURLOPT_SSL_CIPHER_LIST (integer)

CURLOPT_BINARYTRANSFER (integer)

CURLOPT_NOSIGNAL (integer)

CURLOPT_PROXYTYPE (integer)

CURLOPT_BUFFERSIZE (integer)

CURLOPT_HTTPGET (integer)

CURLOPT_HTTP_VERSION (integer)

CURLOPT_SSLKEY (integer)

CURLOPT_SSLKEYTYPE (integer)

CURLOPT_SSLKEYPASSWD (integer)

CURLOPT_SSLENGINE (integer)

CURLOPT_SSLENGINE_DEFAULT (integer)

CURLOPT_SSLCERTTYPE (integer)

CURLOPT_CRLF (integer)

CURLOPT_ENCODING (integer)

CURLOPT_PROXYPORT (integer)

CURLOPT_UNRESTRICTED_AUTH (integer)

CURLOPT_FTP_USE_EPRT (integer)

CURLOPT_HTTP200ALIASES (integer)

CURLOPT_HTTPAUTH (integer)

CURLAUTH_BASIC (integer)

CURLAUTH_DIGEST (integer)

CURLAUTH_GSSNEGOTIATE (integer)

CURLAUTH_NTLM (integer)

CURLAUTH_ANY (integer)

CURLAUTH_ANYSAFE (integer)

CURLOPT_PROXYAUTH (integer)

CURLCLOSEPOLICY_LEAST_RECENTLY_USED (integer)

CURLCLOSEPOLICY_LEAST_TRAFFIC (integer)

CURLCLOSEPOLICY_SLOWEST (integer)

CURLCLOSEPOLICY_CALLBACK (integer)

CURLCLOSEPOLICY_OLDEST (integer)

CURLINFO_EFFECTIVE_URL (integer)

CURLINFO_HTTP_CODE (integer)

CURLINFO_HEADER_SIZE (integer)

CURLINFO_REQUEST_SIZE (integer)

CURLINFO_TOTAL_TIME (integer)

CURLINFO_NAMELOOKUP_TIME (integer)

CURLINFO_CONNECT_TIME (integer)

CURLINFO_PRETRANSFER_TIME (integer)

CURLINFO_SIZE_UPLOAD (integer)

CURLINFO_SIZE_DOWNLOAD (integer)

CURLINFO_SPEED_DOWNLOAD (integer)

CURLINFO_SPEED_UPLOAD (integer)

CURLINFO_FILETIME (integer)

CURLINFO_SSL_VERIFYRESULT (integer)

CURLINFO_CONTENT_LENGTH_DOWNLOAD (integer)

CURLINFO_CONTENT_LENGTH_UPLOAD (integer)

CURLINFO_STARTTRANSFER_TIME (integer)

CURLINFO_CONTENT_TYPE (integer)

CURLINFO_REDIRECT_TIME (integer)

CURLINFO_REDIRECT_COUNT (integer)

CURL_VERSION_IPV6 (integer)

CURL_VERSION_KERBEROS4 (integer)

CURL_VERSION_SSL (integer)

CURL_VERSION_LIBZ (integer)

CURLVERSION_NOW (integer)

CURLE_OK (integer)

CURLE_UNSUPPORTED_PROTOCOL (integer)

CURLE_FAILED_INIT (integer)

CURLE_URL_MALFORMAT (integer)

CURLE_URL_MALFORMAT_USER (integer)

CURLE_COULDNT_RESOLVE_PROXY (integer)

CURLE_COULDNT_RESOLVE_HOST (integer)

CURLE_COULDNT_CONNECT (integer)

CURLE_FTP_WEIRD_SERVER_REPLY (integer)

CURLE_FTP_ACCESS_DENIED (integer)

CURLE_FTP_USER_PASSWORD_INCORRECT (integer)

CURLE_FTP_WEIRD_PASS_REPLY (integer)

CURLE_FTP_WEIRD_USER_REPLY (integer)

CURLE_FTP_WEIRD_PASV_REPLY (integer)

CURLE_FTP_WEIRD_227_FORMAT (integer)

CURLE_FTP_CANT_GET_HOST (integer)

CURLE_FTP_CANT_RECONNECT (integer)

CURLE_FTP_COULDNT_SET_BINARY (integer)

CURLE_PARTIAL_FILE (integer)

CURLE_FTP_COULDNT_RETR_FILE (integer)

CURLE_FTP_WRITE_ERROR (integer)

CURLE_FTP_QUOTE_ERROR (integer)

CURLE_HTTP_NOT_FOUND (integer)

CURLE_WRITE_ERROR (integer)

CURLE_MALFORMAT_USER (integer)

CURLE_FTP_COULDNT_STOR_FILE (integer)

CURLE_READ_ERROR (integer)

CURLE_OUT_OF_MEMORY (integer)

CURLE_OPERATION_TIMEOUTED (integer)

CURLE_FTP_COULDNT_SET_ASCII (integer)

CURLE_FTP_PORT_FAILED (integer)

CURLE_FTP_COULDNT_USE_REST (integer)

CURLE_FTP_COULDNT_GET_SIZE (integer)

CURLE_HTTP_RANGE_ERROR (integer)

CURLE_HTTP_POST_ERROR (integer)

CURLE_SSL_CONNECT_ERROR (integer)

CURLE_FTP_BAD_DOWNLOAD_RESUME (integer)

CURLE_FILE_COULDNT_READ_FILE (integer)

CURLE_LDAP_CANNOT_BIND (integer)

CURLE_LDAP_SEARCH_FAILED (integer)

CURLE_LIBRARY_NOT_FOUND (integer)

CURLE_FUNCTION_NOT_FOUND (integer)

CURLE_ABORTED_BY_CALLBACK (integer)

CURLE_BAD_FUNCTION_ARGUMENT (integer)

CURLE_BAD_CALLING_ORDER (integer)

CURLE_HTTP_PORT_FAILED (integer)

CURLE_BAD_PASSWORD_ENTERED (integer)

CURLE_TOO_MANY_REDIRECTS (integer)

CURLE_UNKNOWN_TELNET_OPTION (integer)

CURLE_TELNET_OPTION_SYNTAX (integer)

CURLE_OBSOLETE (integer)

CURLE_SSL_PEER_CERTIFICATE (integer)

CURLE_GOT_NOTHING (integer)

CURLE_SSL_ENGINE_NOTFOUND (integer)

CURLE_SSL_ENGINE_SETFAILED (integer)

CURLE_SEND_ERROR (integer)

CURLE_RECV_ERROR (integer)

CURLE_SHARE_IN_USE (integer)

CURLE_SSL_CERTPROBLEM (integer)

CURLE_SSL_CIPHER (integer)

CURLE_SSL_CACERT (integer)

CURLE_BAD_CONTENT_ENCODING (integer)

CURLE_LDAP_INVALID_URL (integer)

CURLE_FILESIZE_EXCEEDED (integer)

CURLE_FTP_SSL_FAILED (integer)

CURLFTPAUTH_DEFAULT (integer)

Available since PHP 5.1.0

CURLFTPAUTH_SSL (integer)

Available since PHP 5.1.0

CURLFTPAUTH_TLS (integer)

Available since PHP 5.1.0

CURLPROXY_HTTP (integer)

CURLPROXY_SOCKS5 (integer)

CURL_NETRC_OPTIONAL (integer)

CURL_NETRC_IGNORED (integer)

CURL_NETRC_REQUIRED (integer)

CURL_HTTP_VERSION_NONE (integer)

CURL_HTTP_VERSION_1_0 (integer)

CURL_HTTP_VERSION_1_1 (integer)

CURLM_CALL_MULTI_PERFORM (integer)

CURLM_OK (integer)

CURLM_BAD_HANDLE (integer)

CURLM_BAD_EASY_HANDLE (integer)

CURLM_OUT_OF_MEMORY (integer)

CURLM_INTERNAL_ERROR (integer)

CURLMSG_DONE (integer)


范例

Once you've compiled PHP with CURL support, you can begin using the CURL functions. The basic idea behind the CURL functions is that you initialize a CURL session using the curl_init(), then you can set all your options for the transfer via the curl_setopt(), then you can execute the session with the curl_exec() and then you finish off your session using the curl_close(). Here is an example that uses the CURL functions to fetch the example.com homepage into a file:

例子 1. Using PHP's CURL module to fetch the example.com homepage

<?php

$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

目录
curl_close -- Close a CURL session
curl_copy_handle --  Copy a cURL handle along with all of its preferences
curl_errno -- Return the last error number
curl_error --  Return a string containing the last error for the current session
curl_exec -- Perform a CURL session
curl_getinfo --  Get information regarding a specific transfer
curl_init -- Initialize a CURL session
curl_multi_add_handle --  Add a normal cURL handle to a cURL multi handle
curl_multi_close --  Close a set of cURL handles
curl_multi_exec --  Run the sub-connections of the current cURL handle
curl_multi_getcontent --  Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set
curl_multi_info_read --  Get information about the current transfers
curl_multi_init --  Returns a new cURL multi handle
curl_multi_remove_handle --  Remove a multi handle from a set of cURL handles
curl_multi_select --  Get all the sockets associated with the cURL extension, which can then be "selected"
curl_setopt -- Set an option for a CURL transfer
curl_version -- Return the current CURL version

curl_close

(PHP 4 >= 4.0.2, PHP 5)

curl_close -- Close a CURL session

Description

void curl_close ( resource ch )

This function closes a CURL session and frees all resources. The CURL handle, ch, is also deleted.

例子 1. Initializing a new CURL session and fetching a webpage

<?php
// create a new curl resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);

// close curl resource, and free up system resources
curl_close($ch);
?>

See also: curl_init().

curl_copy_handle

(PHP 5)

curl_copy_handle --  Copy a cURL handle along with all of its preferences

Description

resource curl_copy_handle ( resource ch )

This function copies a cURL handle, returning a new cURL handle with the same preferences.

例子 1. Copying a cURL handle.

<?php
// create a new curl resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/');
curl_setopt($ch, CURLOPT_HEADER, 0);

// copy the handle
$ch2 = curl_copy_handle($ch);

// grab URL (http://www.example.com/) and pass it to the browser
curl_exec($ch2);

// close curl resources, and free up system resources
curl_close($ch2);
curl_close($ch);
?>

curl_errno

(PHP 4 >= 4.0.3, PHP 5)

curl_errno -- Return the last error number

Description

int curl_errno ( resource ch )

Returns the error number for the last cURL operation on the resource ch, or 0 (zero) if no error occurred.

See also curl_error() and Curl error codes.

curl_error

(PHP 4 >= 4.0.3, PHP 5)

curl_error --  Return a string containing the last error for the current session

Description

string curl_error ( resource ch )

Returns a clear text error message for the last cURL operation on the resource ch, or '' (the empty string) if no error occurred.

See also curl_errno() and Curl error codes.

curl_exec

(PHP 4 >= 4.0.2, PHP 5)

curl_exec -- Perform a CURL session

Description

mixed curl_exec ( resource ch )

This function should be called after you initialize a CURL session and all the options for the session are set. Its purpose is simply to execute the predefined CURL session (given by the ch).

例子 1. Initializing a new CURL session and fetching a webpage

<?php
// create a new curl resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);

// close curl resource, and free up system resources
curl_close($ch);
?>

注: If you want to have the result returned instead of it being printed to the browser directly, use the CURLOPT_RETURNTRANSFER option of curl_setopt().

curl_getinfo

(PHP 4 >= 4.0.4, PHP 5)

curl_getinfo --  Get information regarding a specific transfer

Description

mixed curl_getinfo ( resource ch [, int opt] )

Returns information about the last transfer, opt may be one of the following:

  • "CURLINFO_EFFECTIVE_URL" - Last effective URL

  • "CURLINFO_HTTP_CODE" - Last received HTTP code

  • "CURLINFO_FILETIME" - Remote time of the retrieved document, if -1 is returned the time of the document is unknown

  • "CURLINFO_TOTAL_TIME" - Total transaction time in seconds for last transfer

  • "CURLINFO_NAMELOOKUP_TIME" - Time in seconds until name resolving was complete

  • "CURLINFO_CONNECT_TIME" - Time in seconds it took to establish the connection

  • "CURLINFO_PRETRANSFER_TIME" - Time in seconds from start until just before file transfer begins

  • "CURLINFO_STARTTRANSFER_TIME" - Time in seconds until the first byte is about to be transferred

  • "CURLINFO_REDIRECT_TIME" - Time in seconds of all redirection steps before final transaction was started

  • "CURLINFO_SIZE_UPLOAD" - Total number of bytes uploaded

  • "CURLINFO_SIZE_DOWNLOAD" - Total number of bytes downloaded

  • "CURLINFO_SPEED_DOWNLOAD" - Average download speed

  • "CURLINFO_SPEED_UPLOAD" - Average upload speed

  • "CURLINFO_HEADER_SIZE" - Total size of all headers received

  • "CURLINFO_REQUEST_SIZE" - Total size of issued requests, currently only for HTTP requests

  • "CURLINFO_SSL_VERIFYRESULT" - Result of SSL certification verification requested by setting CURLOPT_SSL_VERIFYPEER

  • "CURLINFO_CONTENT_LENGTH_DOWNLOAD" - content-length of download, read from Content-Length: field

  • "CURLINFO_CONTENT_LENGTH_UPLOAD" - Specified size of upload

  • "CURLINFO_CONTENT_TYPE" - Content-type of downloaded object, NULL indicates server did not send valid Content-Type: header

If called without the optional parameter opt an associative array is returned with the following array elements which correspond to opt options:

  • "url"

  • "content_type"

  • "http_code"

  • "header_size"

  • "request_size"

  • "filetime"

  • "ssl_verify_result"

  • "redirect_count"

  • "total_time"

  • "namelookup_time"

  • "connect_time"

  • "pretransfer_time"

  • "size_upload"

  • "size_download"

  • "speed_download"

  • "speed_upload"

  • "download_content_length"

  • "upload_content_length"

  • "starttransfer_time"

  • "redirect_time"

curl_init

(PHP 4 >= 4.0.2, PHP 5)

curl_init -- Initialize a CURL session

Description

resource curl_init ( [string url] )

The curl_init() will initialize a new session and return a CURL handle for use with the curl_setopt(), curl_exec(), and curl_close() functions. If the optional url parameter is supplied then the CURLOPT_URL option will be set to the value of the parameter. You can manually set this using the curl_setopt() function.

例子 1. Initializing a new CURL session and fetching a webpage

<?php
// create a new curl resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);

// close curl resource, and free up system resources
curl_close($ch);
?>

See also: curl_close(), curl_setopt()

curl_multi_add_handle

(PHP 5)

curl_multi_add_handle --  Add a normal cURL handle to a cURL multi handle

Description

int curl_multi_add_handle ( resource mh, resource ch )

警告

本函数暂无文档,仅有参数列表。

See also curl_multi_init(), curl_init(), and curl_multi_remove_handle().

curl_multi_close

(PHP 5)

curl_multi_close --  Close a set of cURL handles

Description

void curl_multi_close ( resource mh )

警告

本函数暂无文档,仅有参数列表。

See also curl_multi_init() and curl_close().

curl_multi_exec

(PHP 5)

curl_multi_exec --  Run the sub-connections of the current cURL handle

Description

int curl_multi_exec ( resource mh, int &still_running )

警告

本函数暂无文档,仅有参数列表。

See also curl_multi_init() and curl_exec().

curl_multi_getcontent

(PHP 5)

curl_multi_getcontent --  Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set

Description

string curl_multi_getcontent ( resource ch )

警告

本函数暂无文档,仅有参数列表。

See also curl_multi_init().

curl_multi_info_read

(PHP 5)

curl_multi_info_read --  Get information about the current transfers

Description

array curl_multi_info_read ( resource mh )

警告

本函数暂无文档,仅有参数列表。

See also curl_multi_init().

curl_multi_init

(PHP 5)

curl_multi_init --  Returns a new cURL multi handle

Description

resource curl_multi_init ( void )

警告

本函数暂无文档,仅有参数列表。

See also curl_init() and curl_multi_close().

curl_multi_remove_handle

(PHP 5)

curl_multi_remove_handle --  Remove a multi handle from a set of cURL handles

Description

int curl_multi_remove_handle ( resource mh, resource ch )

警告

本函数暂无文档,仅有参数列表。

See also curl_multi_init(), curl_init(), and curl_multi_add_handle().

curl_multi_select

(PHP 5)

curl_multi_select --  Get all the sockets associated with the cURL extension, which can then be "selected"

Description

int curl_multi_select ( resource mh [, float timeout] )

警告

本函数暂无文档,仅有参数列表。

See also curl_multi_init().

curl_setopt

(PHP 4 >= 4.0.2, PHP 5)

curl_setopt -- Set an option for a CURL transfer

Description

bool curl_setopt ( resource ch, int option, mixed value )

Set an option for a CURL session identified by the ch parameter. option specifies which option to set, and value specifies the value for the option given.

value should be a bool for the following values of the option parameter:

OptionSet value toNotes
CURLOPT_AUTOREFERER TRUE to automatically set the Referer: field in requests where it follows a Location: redirect. Available since PHP 5.1.0.
CURLOPT_BINARYTRANSFER TRUE to return the raw output when CURLOPT_RETURNTRANSFER is used.  
CURLOPT_COOKIESESSION TRUE to mark this as a new cookie "session". It will force libcurl to ignore all cookies it is about to load that are "session cookies" from the previous session. By default, libcurl always stores and loads all cookies, independent if they are session cookies are not. Session cookies are cookies without expiry date and they are meant to be alive and existing for this "session" only. Available since PHP 5.1.0.
CURLOPT_CRLF TRUE to convert Unix newlines to CRLF newlines on transfers.  
CURLOPT_DNS_USE_GLOBAL_CACHE TRUE to use a global DNS cache. This option is not thread-safe and is enabled by default.  
CURLOPT_FAILONERROR TRUE to fail silently if the HTTP code returned is greater than 300. The default behavior is to return the page normally, ignoring the code.  
CURLOPT_FILETIME TRUE to attempt to retrieve the modification date of the remote document. You can then retrieve this value using the CURLINFO_FILETIME option with curl_getinfo().  
CURLOPT_FOLLOWLOCATION TRUE to follow any "Location: " header that the server sends as part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent, unless CURLOPT_MAXREDIRS is set).  
CURLOPT_FORBID_REUSE TRUE to force the connection to explicitly close when it has finished processing, and not be pooled for reuse.  
CURLOPT_FRESH_CONNECT TRUE to force the use of a new connection instead of a cached one.  
CURLOPT_FTP_USE_EPRT TRUE to use EPRT (and LPRT) when doing active FTP downloads. Use FALSE to disable EPRT and LPRT and use PORT only. Added in PHP 5.0.0.
CURLOPT_FTP_USE_EPSV TRUE to first try an EPSV command for FTP transfers before reverting back to PASV. Set to FALSE to disable EPSV.  
CURLOPT_FTPAPPEND TRUE to append to the remote file instead of overwriting it.  
CURLOPT_FTPASCII An alias of CURLOPT_TRANSFERTEXT. Use that instead.  
CURLOPT_FTPLISTONLY TRUE to only list the names of an FTP directory.  
CURLOPT_HEADER TRUE to include the header in the output.  
CURLOPT_HTTPGET TRUE to reset the HTTP request method to GET. Since GET is the default, this is only necessary if the request method has been changed.  
CURLOPT_HTTPPROXYTUNNEL TRUE to tunnel through a given HTTP proxy.  
CURLOPT_MUTE TRUE to be completely silent with regards to the CURL functions.  
CURLOPT_NETRC TRUE to scan your ~/.netrc file to find your username and password for the remote site that you're establishing a connection with.  
CURLOPT_NOBODY TRUE to exclude the body from the output.  
CURLOPT_NOPROGRESS TRUE to disable the progress meter for CURL transfers.

注: PHP automatically sets this option to TRUE, this should only be changed for debugging purposes.

 
CURLOPT_NOSIGNAL TRUE to ignore any CURL function that causes a signal to be sent to the PHP process. This is turned on by default in multi-threaded SAPIs so timeout options can still be used. Added in CURL 7.10 and PHP 5.0.0.
CURLOPT_POST TRUE to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.  
CURLOPT_PUT TRUE to HTTP PUT a file. The file to PUT must be set with CURLOPT_INFILE and CURLOPT_INFILESIZE.  
CURLOPT_RETURNTRANSFER TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.  
CURLOPT_SSL_VERIFYPEER FALSE to stop CURL from verifying the peer's certificate. Alternate certificates to verify against can be specified with the CURLOPT_CAINFO option or a certificate directory can be specified with the CURLOPT_CAPATH option. CURLOPT_SSL_VERIFYHOST may also need to be TRUE or FALSE if CURLOPT_SSL_VERIFYPEER is disabled (it defaults to 2). TRUE by default as of CURL 7.10. Default bundle installed as of CURL 7.10.
CURLOPT_TRANSFERTEXT TRUE to use ASCII mode for FTP transfers. For LDAP, it retrieves data in plain text instead of HTML. On Windows systems, it will not set STDOUT to binary mode.  
CURLOPT_UNRESTRICTED_AUTH TRUE to keep sending the username and password when following locations (using CURLOPT_FOLLOWLOCATION), even when the hostname has changed. Added in PHP 5.0.0.
CURLOPT_UPLOAD TRUE to prepare for an upload.  
CURLOPT_VERBOSE TRUE to output verbose information. Writes output to STDERR, or the file specified using CURLOPT_STDERR.  

value should be an integer for the following values of the option parameter:

OptionSet value toNotes
CURLOPT_BUFFERSIZE The size of the buffer to use for each read. There is no guarantee this request will be fulfilled, however. Added in CURL 7.10 and PHP 5.0.0.
CURLOPT_CLOSEPOLICY Either CURLCLOSEPOLICY_LEAST_RECENTLY_USED or CURLCLOSEPOLICY_OLDEST. There are three other CURLCLOSEPOLICY_ constants, but CURL does not support them yet.  
CURLOPT_CONNECTTIMEOUT The number of seconds to wait whilst trying to connect. Use 0 to wait indefinitely.  
CURLOPT_DNS_CACHE_TIMEOUT The number of seconds to keep DNS entries in memory. This option is set to 120 (2 minutes) by default.  
CURLOPT_FTPSSLAUTH The FTP authentication method (when is activated): CURLFTPAUTH_SSL (try SSL first), CURLFTPAUTH_TLS (try TLS first), or CURLFTPAUTH_DEFAULT (let CURL decide). Added in CURL 7.12.2 and PHP 5.1.0.
CURLOPT_HTTP_VERSION CURL_HTTP_VERSION_NONE (default, lets CURL decide which version to use), CURL_HTTP_VERSION_1_0 (forces HTTP/1.0), or CURL_HTTP_VERSION_1_1 (forces HTTP/1.1).  
CURLOPT_HTTPAUTH

The HTTP authentication method(s) to use. The options are: CURLAUTH_BASIC, CURLAUTH_DIGEST, CURLAUTH_GSSNEGOTIATE, CURLAUTH_NTLM, CURLAUTH_ANY, and CURLAUTH_ANYSAFE.

You can use the bitwise | (or) operator to combine more than one method. If you do this, CURL will poll the server to see what methods it supports and pick the best one.

CURLAUTH_ANY is an alias for CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM.

CURLAUTH_ANYSAFE is an alias for CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM.

Added in PHP 5.0.0.
CURLOPT_INFILESIZE The expected size, in bytes, of the file when uploading a file to a remote site.  
CURLOPT_LOW_SPEED_LIMIT The transfer speed, in bytes per second, that the transfer should be below during CURLOPT_LOW_SPEED_TIME seconds for PHP to consider the transfer too slow and abort.  
CURLOPT_LOW_SPEED_TIME The number of seconds the transfer should be below CURLOPT_LOW_SPEED_LIMIT for PHP to consider the transfer too slow and abort.  
CURLOPT_MAXCONNECTS The maximum amount of persistent connections that are allowed. When the limit is reached, CURLOPT_CLOSEPOLICY is used to determine which connection to close.  
CURLOPT_MAXREDIRS The maximum amount of HTTP redirections to follow. Use this option alongside CURLOPT_FOLLOWLOCATION.  
CURLOPT_PORT An alternative port number to connect to.  
CURLOPT_PROXYAUTH The HTTP authentication method(s) to use for the proxy connection. Use the same bitmasks as described in CURLOPT_HTTPAUTH. For proxy authentication, only CURLAUTH_BASIC and CURLAUTH_NTLM are currently supported. Added in CURL 7.10.7 and PHP 5.1.0.
CURLOPT_PROXYPORT The port number of the proxy to connect to. This port number can also be set in CURLOPT_PROXY. Added in PHP 5.0.0.
CURLOPT_PROXYTYPE Either CURLPROXY_HTTP (default) or CURLPROXY_SOCKS5. Added in CURL 7.10 and PHP 5.0.0.
CURLOPT_RESUME_FROM The offset, in bytes, to resume a transfer from.  
CURLOPT_SSL_VERIFYHOST 1 to check the existence of a common name in the SSL peer certificate. 2 to check the existence of a common name and also verify that it matches the hostname provided.  
CURLOPT_SSLVERSION The SSL version (2 or 3) to use. By default PHP will try to determine this itself, although in some cases you must set this manually.  
CURLOPT_TIMECONDITION How CURLOPT_TIMEVALUE is treated. Use CURL_TIMECOND_IFMODSINCE to return the page only if it has been modified since the time specified in CURLOPT_TIMEVALUE. If it hasn't been modified, a "304 Not Modified" header will be returned assuming CURLOPT_HEADER is TRUE. Use CURL_TIMECOND_ISUNMODSINCE for the reverse effect. CURL_TIMECOND_IFMODSINCE is the default. Added in PHP 5.1.0.
CURLOPT_TIMEOUT The maximum number of seconds to allow CURL functions to execute.  
CURLOPT_TIMEVALUE The time in seconds since January 1st, 1970. The time will be used by CURLOPT_TIMECONDITION. By default, CURL_TIMECOND_IFMODSINCE is used.  

value should be a string for the following values of the option parameter:

OptionSet value toNotes
CURLOPT_CAINFO The name of a file holding one or more certificates to verify the peer with. This only makes sense when used in combination with CURLOPT_SSL_VERIFYPEER.  
CURLOPT_CAPATH A directory that holds multiple CA certificates. Use this option alongside CURLOPT_SSL_VERIFYPEER.  
CURLOPT_COOKIE The contents of the "Set-Cookie: " header to be used in the HTTP request.  
CURLOPT_COOKIEFILE The name of the file containing the cookie data. The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file.  
CURLOPT_COOKIEJAR The name of a file to save all internal cookies to when the connection closes.  
CURLOPT_CUSTOMREQUEST A custom request method to use instead of "GET" or "HEAD" when doing a HTTP request. This is useful for doing "DELETE" or other, more obscure HTTP requests. Valid values are things like "GET", "POST", "CONNECT" and so on; i.e. Do not enter a whole HTTP request line here. For instance, entering "GET /index.html HTTP/1.0\r\n\r\n" would be incorrect.

注: Don't do this without making sure your server supports the custom request method first.

 
CURLOPT_EGBSOCKET Like CURLOPT_RANDOM_FILE, except a filename to an Entropy Gathering Daemon socket.  
CURLOPT_ENCODING The contents of the "Accept-Encoding: " header. This enables decoding of the response. Supported encodings are "identity", "deflate", and "gzip". If an empty string, "", is set, a header containing all supported encoding types is sent. Added in CURL 7.10.
CURLOPT_FTPPORT The value which will be used to get the IP address to use for the FTP "POST" instruction. The "POST" instruction tells the remote server to connect to our specified IP address. The string may be a plain IP address, a hostname, a network interface name (under Unix), or just a plain '-' to use the systems default IP address.  
CURLOPT_INTERFACE The name of the outgoing network interface to use. This can be an interface name, an IP address or a host name.  
CURLOPT_KRB4LEVEL The KRB4 (Kerberos 4) security level. Any of the following values (in order from least to most powerful) are valid: "clear", "safe", "confidential", "private".. If the string does not match one of these, "private" is used. Setting this option to NULL will disable KRB4 security. Currently KRB4 security only works with FTP transactions.  
CURLOPT_POSTFIELDS The full data to post in a HTTP "POST" operation.  
CURLOPT_PROXY The HTTP proxy to tunnel requests through.  
CURLOPT_PROXYUSERPWD A username and password formatted as "[username]:[password]" to use for the connection to the proxy.  
CURLOPT_RANDOM_FILE A filename to be used to seed the random number generator for SSL.  
CURLOPT_RANGE Range(s) of data to retrieve in the format "X-Y" where X or Y are optional. HTTP transfers also support several intervals, separated with commas in the format "X-Y,N-M".  
CURLOPT_REFERER The contents of the "Referer: " header to be used in a HTTP request.  
CURLOPT_SSL_CIPHER_LIST A list of ciphers to use for SSL. For example, RC4-SHA and TLSv1 are valid cipher lists.  
CURLOPT_SSLCERT The name of a file containing a PEM formatted certificate.  
CURLOPT_SSLCERTPASSWD The password required to use the CURLOPT_SSLCERT certificate.  
CURLOPT_SSLCERTTYPE The format of the certificate. Supported formats are "PEM" (default), "DER", and "ENG". Added in CURL 7.9.3 and PHP 5.0.0.
CURLOPT_SSLENGINE The identifier for the crypto engine of the private SSL key specified in CURLOPT_SSLKEY.  
CURLOPT_SSLENGINE_DEFAULT The identifier for the crypto engine used for asymmetric crypto operations.  
CURLOPT_SSLKEY The name of a file containing a private SSL key.  
CURLOPT_SSLKEYPASSWD The secret password needed to use the private SSL key specified in CURLOPT_SSLKEY.

注: Since this option contains a sensitive password, remember to keep the PHP script it is contained within safe.

 
CURLOPT_SSLKEYTYPE The key type of the private SSL key specified in CURLOPT_SSLKEY. Supported key types are "PEM" (default), "DER", and "ENG".  
CURLOPT_URL The URL to fetch. You can also set this when initializing a session with curl_init().  
CURLOPT_USERAGENT The contents of the "User-Agent: " header to be used in a HTTP request.  
CURLOPT_USERPWD A username and password formatted as "[username]:[password]" to use for the connection.  

value should be an array for the following values of the option parameter:

OptionSet value toNotes
CURLOPT_HTTP200ALIASES An array of HTTP 200 responses that will be treated as valid responses and not as errors. Added in CURL 7.10.3 and PHP 5.0.0.
CURLOPT_HTTPHEADER An array of HTTP header fields to set.  
CURLOPT_POSTQUOTE An array of FTP commands to execute on the server after the FTP request has been performed.  
CURLOPT_QUOTE An array of FTP commands to execute on the server prior to the FTP request.  

value should be a stream resource (using fopen(), for example) for the following values of the option parameter:

OptionSet value toNotes
CURLOPT_FILE The file that the transfer should be written to. The default is STDOUT (the browser window).  
CURLOPT_INFILE The file that the transfer should be read from when uploading.  
CURLOPT_STDERR An alternative location to output errors to instead of STDERR.  
CURLOPT_WRITEHEADER The file that the header part of the transfer is written to.  

value should be a string that is the name of a valid callback function for the following values of the option parameter:

OptionSet value toNotes
CURLOPT_HEADERFUNCTION The name of a callback function where the callback function takes two parameters. The first is the CURL resource, the second is a string with the header data to be written. Using this callback function, it becomes your responsibility to write the header data. Return the number of bytes written.  
CURLOPT_PASSWDFUNCTION The name of a callback function where the callback function takes three parameters. The first is the CURL resource, the second is a string containing a password prompt, and the third is the maximum password length. Return the string containing the password.  
CURLOPT_READFUNCTION The name of a callback function where the callback function takes two parameters. The first is the CURL resource, and the second is a string with the data to be read. Using this callback function, it becomes your responsibility to read the data. Return the number of bytes read. Return 0 to signal EOF.  
CURLOPT_WRITEFUNCTION The name of a callback function where the callback function takes two parameters. The first is the CURL resource, and the second is a string with the data to be written. Using this callback function, it becomes your responsibility to write the data. Must return the exact number of bytes written or this will fail.  

例子 1. Initializing a new CURL session and fetching a webpage

<?php
// create a new CURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, false);

// grab URL and pass it to the browser
curl_exec($ch);

// close CURL resource, and free up system resources
curl_close($ch);
?>

curl_version

(PHP 4 >= 4.0.2, PHP 5)

curl_version -- Return the current CURL version

Description

array curl_version ( [int version] )

The curl_version() function returns a string containing the current CURL version.

XIX. Cybercash Payment Functions

安装

These functions are only available if the interpreter has been compiled with the --with-cybercash=[DIR].

This extension has been moved from PHP as of PHP 4.3.0 and now CyberCash lives in PECL.

If you have questions as to the latest status of CyberCash then the following CyberCash Faq will be helpful. In short, CyberCash was bought out by VeriSign and although the CyberCash service continues to exist, VeriSign encourages users to switch. See the above faq and PECL link for details.

目录
cybercash_base64_decode -- base64 decode data for Cybercash
cybercash_base64_encode -- base64 encode data for Cybercash
cybercash_decr -- Cybercash decrypt
cybercash_encr -- Cybercash encrypt

cybercash_base64_decode

(PHP 4 <= 4.2.3, PECL)

cybercash_base64_decode -- base64 decode data for Cybercash

Description

string cybercash_base64_decode ( string inbuff )

cybercash_base64_encode

(PHP 4 <= 4.2.3, PECL)

cybercash_base64_encode -- base64 encode data for Cybercash

Description

string cybercash_base64_encode ( string inbuff )

cybercash_decr

(PHP 4 <= 4.2.3, PECL)

cybercash_decr -- Cybercash decrypt

Description

array cybercash_decr ( string wmk, string sk, string inbuff )

The function returns an associative array with the elements "errcode" and, if "errcode" is FALSE, "outbuff" (string), "outLth" (long) and "macbuff" (string).

cybercash_encr

(PHP 4 <= 4.2.3, PECL)

cybercash_encr -- Cybercash encrypt

Description

array cybercash_encr ( string wmk, string sk, string inbuff )

The function returns an associative array with the elements "errcode" and, if "errcode" is FALSE, "outbuff" (string), "outLth" (long) and "macbuff" (string).

XX. Cyrus IMAP administration Functions

简介

警告

本函数暂无文档,仅有参数列表。

注: 本扩展模块在 Windows 平台下不可用。


安装

To enable Cyrus IMAP support and to use these functions you have to compile PHP with the --with-cyrus option.

警告

IMAP 扩展模块不能和 recode 扩展模块,YAZ 扩展模块以及 Cyrus 扩展模块同时使用。因为它们使用了相同的内部符号。


预定义常量

以下常量由本扩展模块定义,因此只有在本扩展模块被编译到 PHP 中,或者在运行时被动态加载后才有效。

CYRUS_CONN_NONSYNCLITERAL (integer)

CYRUS_CONN_INITIALRESPONSE (integer)

CYRUS_CALLBACK_NUMBERED (integer)

CYRUS_CALLBACK_NOLITERAL (integer)

目录
cyrus_authenticate -- Authenticate against a Cyrus IMAP server
cyrus_bind -- Bind callbacks to a Cyrus IMAP connection
cyrus_close -- Close connection to a Cyrus IMAP server
cyrus_connect -- Connect to a Cyrus IMAP server
cyrus_query -- Send a query to a Cyrus IMAP server
cyrus_unbind -- Unbind ...

cyrus_authenticate

(PHP 4 >= 4.1.0, PECL)

cyrus_authenticate -- Authenticate against a Cyrus IMAP server

Description

void cyrus_authenticate ( resource connection [, string mechlist [, string service [, string user [, int minssf [, int maxssf [, string authname [, string password]]]]]]] )

警告

本函数暂无文档,仅有参数列表。

cyrus_bind

(PHP 4 >= 4.1.0, PECL)

cyrus_bind -- Bind callbacks to a Cyrus IMAP connection

Description

bool cyrus_bind ( resource connection, array callbacks )

警告

本函数暂无文档,仅有参数列表。

cyrus_close

(PHP 4 >= 4.1.0, PECL)

cyrus_close -- Close connection to a Cyrus IMAP server

Description

bool cyrus_close ( resource connection )

警告

本函数暂无文档,仅有参数列表。

cyrus_connect

(PHP 4 >= 4.1.0, PECL)

cyrus_connect -- Connect to a Cyrus IMAP server

Description

resource cyrus_connect ( [string host [, string port [, int flags]]] )

警告

本函数暂无文档,仅有参数列表。

cyrus_query

(PHP 4 >= 4.1.0, PECL)

cyrus_query -- Send a query to a Cyrus IMAP server

Description

array cyrus_query ( resource connection, string query )

警告

本函数暂无文档,仅有参数列表。

cyrus_unbind

(PHP 4 >= 4.1.0, PECL)

cyrus_unbind -- Unbind ...

Description

bool cyrus_unbind ( resource connection, string trigger_name )

警告

本函数暂无文档,仅有参数列表。

XXI. Database (dbm-style) Abstraction Layer Functions

简介

These functions build the foundation for accessing Berkeley DB style databases.

This is a general abstraction layer for several file-based databases. As such, functionality is limited to a common subset of features supported by modern databases such as Sleepycat Software's DB2. (This is not to be confused with IBM's DB2 software, which is supported through the ODBC functions.)


需求

The behaviour of various aspects depends on the implementation of the underlying database. Functions such as dba_optimize() and dba_sync() will do what they promise for one database and will do nothing for others. You have to download and install supported dba-Handlers.

表格 1. List of DBA handlers

HandlerNotes
dbm Dbm is the oldest (original) type of Berkeley DB style databases. You should avoid it, if possible. We do not support the compatibility functions built into DB2 and gdbm, because they are only compatible on the source code level, but cannot handle the original dbm format.
ndbm Ndbm is a newer type and more flexible than dbm. It still has most of the arbitrary limits of dbm (therefore it is deprecated).
gdbm Gdbm is the GNU database manager.
db2 DB2 is Sleepycat Software's DB2. It is described as "a programmatic toolkit that provides high-performance built-in database support for both standalone and client/server applications.
db3 DB3 is Sleepycat Software's DB3.
db4 DB4 is Sleepycat Software's DB4. This is available since PHP 4.3.2.
cdb Cdb is "a fast, reliable, lightweight package for creating and reading constant databases." It is from the author of qmail and can be found at http://cr.yp.to/cdb.html. Since it is constant, we support only reading operations. And since PHP 4.3.0 we support writing (not updating) through the internal cdb library.
cdb_make Since PHP 4.3.0 we support creation (not updating) of cdb files when the bundled cdb library is used.
flatfile This is available since PHP 4.3.0 for compatibility with the deprecated dbm extension only and should be avoided. However you may use this where files were created in this format. That happens when configure could not find any external library.
inifile This is available since PHP 4.3.3 to be able to modify php.ini files from within PHP scripts. When working with ini files you can pass arrays of the form array(0=>group,1=>value_name) or strings of the form "[group]value_name" where group is optional. As the functions dba_firstkey() and dba_nextkey() return string representations of the key there is a new function dba_key_split() available since PHP 5 which allows to convert the string keys into array keys without loosing FALSE.
qdbm This is available since PHP 5.0.0. The qdbm library can be loaded from http://qdbm.sourceforge.net.

When invoking the dba_open() or dba_popen() functions, one of the handler names must be supplied as an argument. The actually available list of handlers is displayed by invoking phpinfo() or dba_handlers().


安装

By using the --enable-dba=shared configuration option you can build a dynamic loadable module to enable PHP for basic support of dbm-style databases. You also have to add support for at least one of the following handlers by specifying the --with-XXXX configure switch to your PHP configure line.

警告

After configuring and compiling PHP you must execute the following test from commandline: php run-tests.php ext/dba. This shows whether your combination of handlers works. Most problematic are dbm and ndbm which conflict with many installations. The reason for this is that on several systems these libraries are part of more than one other library. The configuration test only prevents you from configuring malfaunctioning single handlers but not combinations.

表格 2. Supported DBA handlers

HandlerConfigure Switch
dbm To enable support for dbm add --with-dbm[=DIR].

注: dbm normally is a wrapper which often results in failures. This means you should only use dbm if you are sure it works and if you really need this format.

ndbm To enable support for ndbm add --with-ndbm[=DIR].

注: ndbm normally is a wrapper which often results in failures. This means you should only use ndbm if you are sure it works and if you really need this format.

gdbm To enable support for gdbm add --with-gdbm[=DIR].
db2 To enable support for db2 add --with-db2[=DIR].

注: db2 conflicts with db3 and db4.

db3 To enable support for db3 add --with-db3[=DIR].

注: db3 conflicts with db2 and db4.

db4 To enable support for db4 add --with-db4[=DIR].

注: db4 conflicts with db2 and db3.

注: This was added in PHP 4.3.2. In earlier versions of PHP you need to use --with-db3=DIR with DIR being the path to db4 library. It is not possible to use db versions starting from 4.1 with PHP prior to version 4.3.0. Also, the db libraries with versions 4.1 through 4.1.24 cannot be used in any PHP version.

cdb To enable support for cdb add --with-cdb[=DIR].

注: Since PHP 4.3.0 you can omit DIR to use the bundled cdb library that adds the cdb_make handler which allows creation of cdb files and allows to access cdb files on the network using PHP's streams.

flatfile To enable support for flatfile add --with-flatfile.

注: This was added in PHP 4.3.0 to add compatibility with deprecated dbm extension. Use this handler only when you cannot install one of the libraries required by the other handlers and when you cannot use bundled cdb handler.

inifile To enable support for inifile add --with-inifile.

注: This was added in PHP 5.0.0 and allows to read and set microsoft style .ini files (like the php.ini file).

qdbm To enable support for qdbm add --with-qdbm[=DIR].

注: qdbm conflicts with dbm and gdbm.

注: This was added in PHP 5.0.0. The qdbm library can be loaded from http://qdbm.sourceforge.net.

注: Up to PHP 4.3.0 you are able to add both db2 and db3 handler but only one of them can be used internally. That means that you cannot have both file formats. Starting with PHP 5.0.0 there is a configuration check avoid such misconfigurations.


运行时配置

本扩展模块在 php.ini 中未定义任何配置选项。


资源类型

The functions dba_open() and dba_popen() return a handle to the specified database file to access which is used by all other dba-function calls.


预定义常量

本扩展模块未定义任何常量。


范例

例子 1. DBA example

<?php

$id = dba_open("/tmp/test.db", "n", "db2");

if (!$id) {
    echo "dba_open failed\n";
    exit;
}

dba_replace("key", "This is an example!", $id);

if (dba_exists("key", $id)) {
    echo dba_fetch("key", $id);
    dba_delete("key", $id);
}

dba_close($id);
?>

DBA is binary safe and does not have any arbitrary limits. However, it inherits all limits set by the underlying database implementation.

All file-based databases must provide a way of setting the file mode of a new created database, if that is possible at all. The file mode is commonly passed as the fourth argument to dba_open() or dba_popen().

You can access all entries of a database in a linear way by using the dba_firstkey() and dba_nextkey() functions. You may not change the database while traversing it.

例子 2. Traversing a database

<?php

// ...open database...

$key = dba_firstkey($id);

while ($key != false) {
    if (true) {          // remember the key to perform some action later
        $handle_later[] = $key;
    }
    $key = dba_nextkey($id);
}

foreach ($handle_later as $val) {
    dba_delete($val, $id);
}

?>

目录
dba_close -- Close a DBA database
dba_delete -- Delete DBA entry specified by key
dba_exists -- Check whether key exists
dba_fetch -- Fetch data specified by key
dba_firstkey -- Fetch first key
dba_handlers -- List all the handlers available
dba_insert -- Insert entry
dba_key_split --  Splits a key in string representation into array representation
dba_list -- List all open database files
dba_nextkey -- Fetch next key
dba_open -- Open database
dba_optimize -- Optimize database
dba_popen -- Open database persistently
dba_replace -- Replace or insert entry
dba_sync -- Synchronize database

dba_close

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

dba_close -- Close a DBA database

说明

void dba_close ( resource handle )

dba_close() closes the established database and frees all resources of the specified database handle.

参数

handle

The database handler, returned by dba_open() or dba_popen().

返回值

无返回值。

dba_delete

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

dba_delete -- Delete DBA entry specified by key

说明

bool dba_delete ( string key, resource handle )

dba_delete() deletes the specified entry from the database.

参数

key

The key of the entry which is deleted.

handle

The database handler, returned by dba_open() or dba_popen().

返回值

如果成功则返回 TRUE,失败则返回 FALSE

dba_exists

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

dba_exists -- Check whether key exists

说明

bool dba_exists ( string key, resource handle )

dba_exists() checks whether the specified key exists in the database.

参数

key

The key the check is performed for.

handle

The database handler, returned by dba_open() or dba_popen().

返回值

Returns TRUE if the key exists, FALSE otherwise.

dba_fetch

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

dba_fetch -- Fetch data specified by key

说明

string dba_fetch ( string key, resource handle )

string dba_fetch ( string key, int skip, resource handle )

dba_fetch() fetches the data specified by key from the database specified with handle.

参数

key

The key the data is specified by.

注: When working with inifiles this function accepts arrays as keys where index 0 is the group and index 1 is the value name. See: dba_key_split().

skip

The number of key-value pairs to ignore when using cdb databases. This value is ignored for all other databases which do not support multiple keys with the same name.

handle

The database handler, returned by dba_open() or dba_popen().

返回值

Returns the associated string if the key/data pair is found, FALSE otherwise.

更新日志

版本说明
4.3 The skip parameter is available to support cdb's capability of multiple keys having the same name.

dba_firstkey

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

dba_firstkey -- Fetch first key

说明

string dba_firstkey ( resource handle )

dba_firstkey() returns the first key of the database and resets the internal key pointer. This permits a linear search through the whole database.

参数

handle

The database handler, returned by dba_open() or dba_popen().

返回值

Returns the key on success, or FALSE on failure.

dba_handlers

(PHP 4 >= 4.3.0, PHP 5)

dba_handlers -- List all the handlers available

说明

array dba_handlers ( [bool full_info] )

dba_handlers() list all the handlers supported by this extension.

参数

full_info

Turns on/off full information display in the result. The default is FALSE.

返回值

Returns an array of database handlers. If full_info is set to TRUE, the array will be associative with the handlers names as keys, and their version information as value. Otherwise, the result will be an indexed array of handlers names.

注: When the internal cdb library is used you will see cdb and cdb_make.

范例

例子 1. dba_handlers() Example

<?php

echo "Available DBA handlers:\n";
foreach (dba_handlers(true) as $handler_name => $handler_version) {
  // clean the versions
  $handler_version = str_replace('$', '', $handler_version);
  echo " - $handler_name: $handler_version\n";
}

?>

上例的输出类似于:

Available DBA handlers:
 - cdb: 0.75, Revision: 1.3.2.3 
 - cdb_make: 0.75, Revision: 1.2.2.4 
 - db2: Sleepycat Software: Berkeley DB 2.7.7: (08/20/99)
 - inifile: 1.0, Revision: 1.6.2.3 
 - flatfile: 1.0, Revision: 1.5.2.4

dba_insert

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

dba_insert -- Insert entry

说明

bool dba_insert ( string key, string value, resource handle )

dba_insert() inserts the entry described with key and value into the database.

参数

key

The key of the entry to be inserted. If this key already exist in the database, this function will fail. Use dba_replace() if you need to replace an existent key.

value

The value to be inserted.

handle

The database handler, returned by dba_open() or dba_popen().

返回值

如果成功则返回 TRUE,失败则返回 FALSE

dba_key_split

(PHP 5)

dba_key_split --  Splits a key in string representation into array representation

说明

mixed dba_key_split ( mixed key )

dba_key_split() splits a key (string representation) into an array representation.

参数

key

The key in string representation.

返回值

Returns an array of the form array(0 => group, 1 => value_name). This function will return FALSE if key is NULL or FALSE.

dba_list

(PHP 4 >= 4.3.0, PHP 5)

dba_list -- List all open database files

说明

array dba_list ( void )

dba_list() list all open database files.

返回值

An associative array, in the form resourceid => filename.

dba_nextkey

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

dba_nextkey -- Fetch next key

说明

string dba_nextkey ( resource handle )

dba_nextkey() returns the next key of the database and advances the internal key pointer.

参数

handle

The database handler, returned by dba_open() or dba_popen().

返回值

Returns the key on success, or FALSE on failure.

dba_open

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

dba_open -- Open database

说明

resource dba_open ( string path, string mode [, string handler [, mixed ...]] )

dba_open() establishes a database instance for path with mode using handler.

参数

path

Commonly a regular path in your filesystem.

mode

It is r for read access, w for read/write access to an already existing database, c for read/write access and database creation if it doesn't currently exist, and n for create, truncate and read/write access.

Additionally you can set the database lock method with the next char. Use l to lock the database with a .lck file or d to lock the databasefile itself. It is important that all of your applications do this consistently.

If you want to test the access and do not want to wait for the lock you can add t as third character. When you are absolutely sure that you do not require database locking you can do so by using - instead of l or d. When none of d, l or - is used, dba will lock on the database file as it would with d.

注: There can only be one writer for one database file. When you use dba on a webserver and more than one request requires write operations they can only be done one after another. Also read during write is not allowed. The dba extension uses locks to prevent this. See the following table:

表格 1. DBA locking

already openmode = "rl"mode = "rlt"mode = "wl"mode = "wlt"mode = "rd"mode = "rdt"mode = "wd"mode = "wdt"
not openokokokokokokokok
mode = "rl"okokwaitfalseillegalillegalillegalillegal
mode = "wl"waitfalsewaitfalseillegalillegalillegalillegal
mode = "rd"illegalillegalillegalillegalokokwaitfalse
mode = "wd"illegalillegalillegalillegalwaitfalsewaitfalse

ok: the second call will be successfull.
wait: the second call waits until dba_close() is called for the first.
false: the second call returns false.
illegal: you must not mix "l" and "d" modifiers for mode parameter.

handler

The name of the handler which shall be used for accessing path. It is passed all optional parameters given to dba_open() and can act on behalf of them.

返回值

Returns a positive handle on success, or FALSE on failure.

更新日志

版本说明
4.3.0 It's possible to open database files over network connection. However in cases a socket connection will be used (as with http or ftp) the connection will be locked instead of the resource itself. This is important to know since in such cases locking is simply ignored on the resource and other solutions have to be found.
4.3.0 Locking and the mode modifiers "l", "d", "-" and "t" were added. In previous PHP versions, you must use semaphores to guard against simultaneous database access for any database handler with the exception of GDBM. See System V semaphore support.
before 4.3.5 open mode 'c' is broken for several internal handlers and truncates the database instead of appending data to an existent database. Also dbm and ndbm fail on mode 'c' in typical configurations (this cannot be fixed).

dba_optimize

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

dba_optimize -- Optimize database

说明

bool dba_optimize ( resource handle )

dba_optimize() optimizes the underlying database.

参数

handle

The database handler, returned by dba_open() or dba_popen().

返回值

如果成功则返回 TRUE,失败则返回 FALSE

参见

dba_sync()

dba_popen

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

dba_popen -- Open database persistently

说明

resource dba_popen ( string path, string mode [, string handler [, mixed ...]] )

dba_popen() establishes a persistent database instance for path with mode using handler.

参数

path

Commonly a regular path in your filesystem.

mode

It is r for read access, w for read/write access to an already existing database, c for read/write access and database creation if it doesn't currently exist, and n for create, truncate and read/write access.

handler

The name of the handler which shall be used for accessing path. It is passed all optional parameters given to dba_popen() and can act on behalf of them.

返回值

Returns a positive handle on success, or FALSE on failure.

dba_replace

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

dba_replace -- Replace or insert entry

说明

bool dba_replace ( string key, string value, resource handle )

dba_replace() replaces or inserts the entry described with key and value into the database specified by handle.

参数

key

The key of the entry to be replaced.

value

The value to be replaced.

handle

The database handler, returned by dba_open() or dba_popen().

返回值

如果成功则返回 TRUE,失败则返回 FALSE

dba_sync

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

dba_sync -- Synchronize database

说明

bool dba_sync ( resource handle )

dba_sync() synchronizes the database. This will probably trigger a physical write to the disk, if supported.

参数

handle

The database handler, returned by dba_open() or dba_popen().

返回值

如果成功则返回 TRUE,失败则返回 FALSE

XXII. Date/Time 日期/时间函数

简介

可以用这些函数得到 PHP 所运行的服务器的日期和时间。可以用这些函数将日期和时间以很多不同方式格式化输出。

注: 请留意这些函数依赖于服务器的地区设置。确认在使用这些函数时考虑到了夏令时的设置(例如使用 $date = strtotime('+7 days', $date) 而不是 $date += 7*24*60*60)和闰年。


需求

要编译本扩展模块不需要外部库文件。


安装

本函数库作为 PHP 内核的一部分,不用安装就能使用。


运行时配置

本扩展模块在 php.ini 中未定义任何配置选项。


运行时配置

这些函数的行为受 php.ini 的影响。

表格 1. 日期/时间配置选项

名称默认值可修改范围更新记录
date.default_latitude"31.7667"PHP_INI_ALL自 PHP 5.0.0 起可用
date.default_longitude"35.2333"PHP_INI_ALL自 PHP 5.0.0 起可用
date.sunrise_zenith"90.83"PHP_INI_ALL自 PHP 5.0.0 起可用
date.sunset_zenith"90.83"PHP_INI_ALL自 PHP 5.0.0 起可用
date.timezone""PHP_INI_ALL自 PHP 5.0.0 起可用
有关 PHP_INI_* 常量进一步的细节与定义参见附录 G

以下是配置选项的简要解释。

date.default_latitude float

默认纬度。

date.default_longitude float

默认经度。

date.sunrise_zenith float

默认日出天顶。

date.sunset_zenith float

默认日落天顶。

date.timezone string

在未设定 TZ 环境变量时用于所有日期/时间函数的默认时区。优先顺序在 date_default_timezone_get() 页面中有说明。

注: 前四个配置选项目前仅用于 date_sunrise()date_sunset()


资源类型

本扩展模块未定义任何资源类型。


预定义常量

自 PHP 5.1.0 起定义有以下常量来提供标准日期表达方法,可以用于日期格式函数(例如 date())。

DATE_ATOMstring

原子钟格式(如:2005-08-15T15:52:01+0000)

DATE_COOKIEstring

HTTP Cookies 格式(如:Mon, 15 Aug 2005 15:52:01 UTC)

DATE_ISO8601string

ISO-8601(如:2005-08-15T15:52:01+0000)

DATE_RFC822string

RFC 822(如:Mon, 15 Aug 2005 15:52:01 UTC)

DATE_RFC850string

RFC 850(如:Monday, 15-Aug-05 15:52:01 UTC)

DATE_RFC1036string

RFC 1036(如:Monday, 15-Aug-05 15:52:01 UTC)

DATE_RFC1123string

RFC 1123(如:Mon, 15 Aug 2005 15:52:01 UTC)

DATE_RFC2822string

RFC 2822(如:Mon, 15 Aug 2005 15:52:01 +0000)

DATE_RSSstring

RSS(如:Mon, 15 Aug 2005 15:52:01 UTC)

DATE_W3Cstring

World Wide Web Consortium(如:2005-08-15T15:52:01+0000)

目录
checkdate -- 验证一个格里高里日期
date_default_timezone_get -- 取得一个脚本中所有日期时间函数所使用的默认时区
date_default_timezone_set -- 设定用于一个脚本中所有日期时间函数的默认时区
date_sunrise -- 返回给定的日期与地点的日出时间
date_sunset -- 返回给定的日期与地点的日落时间
date -- 格式化一个本地时间/日期
getdate -- 取得日期/时间信息
gettimeofday -- 取得当前时间
gmdate -- 格式化一个 GMT/UTC 日期/时间
gmmktime -- 取得 GMT 日期的 UNIX 时间戳
gmstrftime --  根据区域设置格式化 GMT/UTC 时间/日期
idate -- 将本地时间日期格式化为整数
localtime -- 取得本地时间
microtime -- 返回当前 Unix 时间戳和微秒数
mktime -- 取得一个日期的 Unix 时间戳
strftime -- 根据区域设置格式化本地时间/日期
strptime -- 解析由 strftime() 生成的日期/时间
strtotime -- 将任何英文文本的日期时间描述解析为 Unix 时间戳
time -- 返回当前的 Unix 时间戳

checkdate

(PHP 3, PHP 4, PHP 5)

checkdate -- 验证一个格里高里日期

说明

bool checkdate ( int month, int day, int year )

如果给出的日期有效则返回 TRUE,否则返回 FALSE。检查由参数构成的日期的合法性。日期在以下情况下被认为有效:

  • year 的值是从 1 到 32767

  • month 的值是从 1 到 12

  • Day 的值在给定的 month 所应该具有的天数范围之内,闰年已经考虑进去了。

例子 1. checkdate() 例子

<?php
var_dump(checkdate(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));
?>

上例将输出:

bool(true)
bool(false)

参见 mktime()strtotime()

date_default_timezone_get

(PHP 5 >= 5.1.0RC1)

date_default_timezone_get -- 取得一个脚本中所有日期时间函数所使用的默认时区

说明

string date_default_timezone_get ( void )

本函数返回默认时区,使用如下“假定”的顺序:

  • date_default_timezone_set() 函数设定的时区(如果设定了的话)

  • TZ 环境变量(如果非空)

  • date.timezone 配置选项(如果设定了的话)

  • 自己推测(如果操作系统支持)

  • 如果以上选择都不成功,则返回 UTC

返回值

返回一个 string

date_default_timezone_set

(PHP 5 >= 5.1.0RC1)

date_default_timezone_set -- 设定用于一个脚本中所有日期时间函数的默认时区

说明

bool date_default_timezone_set ( string timezone_identifier )

date_default_timezone_set() 设定用于所有日期时间函数的默认时区。

注: 自 PHP 5.1.0 起(此版本日期时间函数被重写了),如果时区不合法则每个对日期时间函数的调用都会产生一条 E_NOTICE 级别的错误信息。

参数

timezone_identifier

时区标识符,例如 UTCEurope/Lisbon

返回值

本函数永远返回 TRUE(即使 timezone_identifier 参数不合法)。

date_sunrise

(PHP 5)

date_sunrise -- 返回给定的日期与地点的日出时间

说明

mixed date_sunrise ( int timestamp [, int format [, float latitude [, float longitude [, float zenith [, float gmt_offset]]]]] )

date_sunrise() 返回给定的日期(以 timestamp 指定)与地点的日出时间。latitudelongitudezenith 参数默认值分别为配置选项中的 date.default_latitudedate.default_longitudedate.sunrise_zenith

latitude 默认是指北纬。因此如果要指定南纬,必须传递一个负值。同样规则也适用于 longitude,其默认是指东经。

gmt_offset 参数的单位是小时。

表格 1. format 常量

常量说明取值举例
SUNFUNCS_RET_STRINGstring 格式返回结果16:46
SUNFUNCS_RET_DOUBLEfloat 格式返回结果16.78243132
SUNFUNCS_RET_TIMESTAMPinteger 格式(时间戳)返回结果1095034606

例子 1. date_sunrise() 例子

<?php

/* 计算葡萄牙里斯本的日出时间
Latitude:  北纬 38.4 度
Longitude: 西经 9 度
Zenith ~= 90
offset: +1 GMT
*/

echo date("D M d Y"). ', sunrise time : ' .date_sunrise(time(), SUNFUNCS_RET_STRING, 38.4, -9, 90, 1);

?>

上例的输出类似于:

Mon Dec 20 2004, sunrise time : 08:54

参见 date_sunset()

date_sunset

(PHP 5)

date_sunset -- 返回给定的日期与地点的日落时间

说明

mixed date_sunset ( int timestamp [, int format [, float latitude [, float longitude [, float zenith [, float gmt_offset]]]]] )

date_sunset() 返回给定的日期(以 timestamp 指定)与地点的日落时间。latitudelongitudezenith 参数默认值分别为配置选项中的 date.default_latitudedate.default_longitudedate.sunrise_zenith

latitude 默认是指北纬。因此如果要指定南纬,必须传递一个负值。同样规则也适用于 longitude,其默认是指东经。

gmt_offset 参数的单位是小时。

表格 1. format 常量

常量说明取值举例
SUNFUNCS_RET_STRINGstring 格式返回结果16:46
SUNFUNCS_RET_DOUBLEfloat 格式返回结果16.78243132
SUNFUNCS_RET_TIMESTAMPinteger 格式(时间戳)返回结果1095034606

例子 1. date_sunset() 例子

<?php

/* 计算葡萄牙里斯本的日落时间
Latitude:  北纬 38.4 度
Longitude: 西经 9 度
Zenith ~= 90
offset: +1 GMT
*/

echo date("D M d Y"). ', sunset time : ' .date_sunset(time(), SUNFUNCS_RET_STRING, 38.4, -9, 90, 1);

?>

上例的输出类似于:

Mon Dec 20 2004, sunset time : 18:13

参见 date_sunrise()

date

(PHP 3, PHP 4, PHP 5)

date -- 格式化一个本地时间/日期

说明

string date ( string format [, int timestamp] )

返回将整数 timestamp 按照给定的格式字串而产生的字符串。如果没有给出时间戳则使用本地当前时间。换句话说,timestamp 是可选的,默认值为 time()

提示: 自 PHP 5.1.0 起有几个有用的常量可用作标准的日期/时间格式来指定 format 参数。

注: 有效的时间戳典型范围是格林威治时间 1901 年 12 月 13 日 20:45:54 到 2038 年 1 月 19 日 03:14:07。(此范围符合 32 位有符号整数的最小值和最大值)。不过在 PHP 5.1 之前此范围在某些系统(如 Windows)中限制为从 1970 年 1 月 1 日到 2038 年 1 月 19 日。

注: 要将字符串表达的时间转换成时间戳,应该使用 strtotime()。此外一些数据库有一些函数将其时间格式转换成时间戳(例如 MySQL 的 UNIX_TIMESTAMP 函数)。

表格 1. 格式字串可以识别以下 format 参数的字符串

format 字符说明返回值例子
------
d月份中的第几天,有前导零的 2 位数字0131
D星期中的第几天,文本表示,3 个字母MonSun
j月份中的第几天,没有前导零131
l(“L”的小写字母)星期几,完整的文本格式SundaySaturday
NISO-8601 格式数字表示的星期中的第几天(PHP 5.1.0 新加)1(表示星期一)到 7(表示星期天)
S每月天数后面的英文后缀,2 个字符stndrd 或者 th。可以和 j 一起用
w星期中的第几天,数字表示0(表示星期天)到 6(表示星期六)
z年份中的第几天0366
星期------
WISO-8601 格式年份中的第几周,每周从星期一开始(PHP 4.1.0 新加的)例如:42(当年的第 42 周)
------
F月份,完整的文本格式,例如 January 或者 MarchJanuaryDecember
m数字表示的月份,有前导零0112
M三个字母缩写表示的月份JanDec
n数字表示的月份,没有前导零112
t给定月份所应有的天数2831
------
L是否为闰年如果是闰年为 1,否则为 0
oISO-8601 格式年份数字。这和 Y 的值相同,只除了如果 ISO 的星期数(W)属于前一年或下一年,则用那一年。(PHP 5.1.0 新加)Examples: 1999 or 2003
Y4 位数字完整表示的年份例如:19992003
y2 位数字表示的年份例如:9903
时间------
a小写的上午和下午值ampm
A大写的上午和下午值AMPM
BSwatch Internet 标准时000999
g小时,12 小时格式,没有前导零112
G小时,24 小时格式,没有前导零023
h小时,12 小时格式,有前导零0112
H小时,24 小时格式,有前导零0023
i有前导零的分钟数0059>
s秒数,有前导零0059>
时区------
e时区标识(PHP 5.1.0 新加)例如:UTCGMTAtlantic/Azores
I是否为夏令时如果是夏令时为 1,否则为 0
O与格林威治时间相差的小时数例如:+0200
T本机所在的时区例如:ESTMDT(【译者注】在 Windows 下为完整文本格式,例如“Eastern Standard Time”,中文版会显示“中国标准时间”)。
Z时差偏移量的秒数。UTC 西边的时区偏移量总是负的,UTC 东边的时区偏移量总是正的。-4320043200
完整的日期/时间------
cISO 8601 格式的日期(PHP 5 新加)2004-02-12T15:19:21+00:00
rRFC 822 格式的日期例如:Thu, 21 Dec 2000 16:01:07 +0200
U从 Unix 纪元(January 1 1970 00:00:00 GMT)开始至今的秒数参见 time()

格式字串中不能被识别的字符将原样显示。Z 格式在使用 gmdate() 时总是返回 0

例子 1. date() 例子

<?php
// 设定要用的默认时区。自 PHP 5.1 可用
date_default_timezone_set('UTC');


// 输出类似:Monday
echo date("l");

// 输出类似:Monday 15th of August 2005 03:12:46 PM
echo date('l dS \of F Y h:i:s A');

// 输出:July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));

/* 在格式参数中使用常量 */
// 输出类似:Mon, 15 Aug 2005 15:12:46 UTC
echo date(DATE_RFC822);

// 输出类似:2000-07-01T00:00:00+0000
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));
?>

在格式字串中的字符前加上反斜线来转义可以避免它被按照上表解释。如果加上反斜线后的字符本身就是一个特殊序列,那还要转义反斜线。

例子 2. 在 date() 中转义字符

<?php
// prints something like: Wednesday the 15th
echo date("l \\t\h\e jS");
?>

可以把 date()mktime() 结合使用来得到未来或过去的日期。

例子 3. date()mktime() 例子

<?php
$tomorrow  = mktime(0, 0, 0, date("m")  , date("d")+1, date("Y"));
$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"),   date("Y"));
$nextyear  = mktime(0, 0, 0, date("m"),   date("d"),   date("Y")+1);
?>

注: 由于夏令时的缘故,这种方法比简单地在时间戳上加减一天或者一个月的秒数更可靠。

一些使用 date() 格式化日期的例子。注意要转义所有其它的字符,因为目前有特殊含义的字符会产生不需要的结果,而其余字符在 PHP 将来的版本中可能会被用上。当转义时,注意用单引号以避免类似 \n 的字符变成了换行符。

例子 4. date() 格式举例

<?php
// 假定今天是:March 10th, 2001, 5:16:18 pm
$today = date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
$today = date("m.d.y");                         // 03.10.01
$today = date("j, n, Y");                       // 10, 3, 2001
$today = date("Ymd");                           // 20010310
$today = date('h-i-s, j-m-y, it is w Day z ');  // 05-16-17, 10-03-01, 1631 1618 6 Fripm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.');   // It is the 10th day.
$today = date("D M j G:i:s T Y");               // Sat Mar 10 15:16:08 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:17 m is month
$today = date("H:i:s");                         // 17:16:17
?>

要格式化其它语种的日期,应该用 setlocale()strftime() 函数。

参见 getlastmod()gmdate()mktime()strftime()time()

getdate

(PHP 3, PHP 4, PHP 5)

getdate -- 取得日期/时间信息

说明

array getdate ( [int timestamp] )

返回一个根据 timestamp 得出的包含有日期信息的结合数组。如果没有给出时间戳则认为是当前本地时间。数组中的单元如下:

表格 1. 返回的关联数组中的键名单元

键名说明返回值例子
"seconds"秒的数字表示059
"minutes"分钟的数字表示059
"hours"小时的数字表示023
"mday"月份中第几天的数字表示131
"wday"星期中第几天的数字表示0(表示星期天)到 6(表示星期六)
"mon"月份的数字表示112
"year"4 位数字表示的完整年份例如:19992003
"yday"一年中第几天的数字表示0365
"weekday"星期几的完整文本表示SundaySaturday
"month"月份的完整文本表示January>December
0 自从 Unix 纪元开始至今的秒数,和 time() 的返回值以及用于 date() 的值类似。 系统相关,典型值为从 -21474836482147483647

例子 1. getdate() 例子

<?php
$today = getdate();
print_r($today);
?>

上例的输出类似于:

Array
(
    [seconds] => 40
    [minutes] => 58
    [hours]   => 21
    [mday]    => 17
    [wday]    => 2
    [mon]     => 6
    [year]    => 2003
    [yday]    => 167
    [weekday] => Tuesday
    [month]   => June
    [0]       => 1055901520
)

参见 date()time()setlocale()

gettimeofday

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

gettimeofday -- 取得当前时间

说明

mixed gettimeofday ( [bool return_float] )

本函数是 gettimeofday(2) 的接口。返回一个关联数组,包含有系统调用返回的数据。

自 PHP 5.1.0 起有个可选参数 return_float,当其设为 TRUE 时,gettimeofday() 会返回一个浮点数。

数组中的键为:

  • "sec" - 自 Unix 纪元起的秒数

  • "usec" - 微秒数

  • "minuteswest" - 格林威治向西的分钟数

  • "dsttime" - 夏令时修正的类型

例子 1. gettimeofday() example

<?php
print_r(gettimeofday());

echo gettimeofday(true);
?>

上例的输出类似于:

Array
(
    [sec] => 1073504408
    [usec] => 238215
    [minuteswest] => 0
    [dsttime] => 1
)

1073504408.23910

gmdate

(PHP 3, PHP 4, PHP 5)

gmdate -- 格式化一个 GMT/UTC 日期/时间

说明

string gmdate ( string format [, int timestamp] )

date() 函数完全一样,只除了返回的时间是格林威治标准时(GMT)。例如当在中国(GMT +0800)运行以下程序时,第一行显示“Jan 01 2000 00:00:00”而第二行显示“Dec 31 1999 16:00:00”。

例子 1. gmdate() 例子

<?php
echo date("M d Y H:i:s", mktime (0,0,0,1,1,2000));
echo gmdate("M d Y H:i:s", mktime (0,0,0,1,1,2000));
?>

注: 在 PHP 5.1.0 之前,负的时间戳(1970 年之前的日期)在某些系统下(例如 Windows)不能工作。

参见 date()mktime()gmmktime()strftime()

gmmktime

(PHP 3, PHP 4, PHP 5)

gmmktime -- 取得 GMT 日期的 UNIX 时间戳

说明

int gmmktime ( [int hour [, int minute [, int second [, int month [, int day [, int year [, int is_dst]]]]]]] )

mktime() 完全一样,只除了返回值是格林威治标准时的时间戳。

参数总是表示 GMT 日期,因此 is_dst 对结果没有影响。

mktime() 一样,参数可以从右到左依次空着,空着的参数会被设为相应的当前 GMT 值。

注: 自 5.1.0 起,is_dst 参数被废弃。因此应该用新的时区处理特性。

注: gmmktime() 内部使用了 mktime(),因此只有转换成本地时间也合法的时间才能用在其中。 so only times valid in derived local time can be used.

例子 1. gmmktime() 在 Windows 中的边界

<?php
gmmktime(0, 0, 0, 1, 1, 1970); // 在 GMT 和西方合法,在东方不合法
?>

参见 mktime()date()time()

gmstrftime

(PHP 3 >= 3.0.12, PHP 4, PHP 5)

gmstrftime --  根据区域设置格式化 GMT/UTC 时间/日期

说明

string gmstrftime ( string format [, int timestamp] )

strftime() 的行为相同,只除了返回时间是格林威治标准时(GMT)。例如,当在东部标准时(EST,GMT -500)运行时,下面第一行显示“Dec 31 1998 20:00:00”,而第二行显示“Jan 01 1999 01:00:00”。

例子 1. gmstrftime() 例子

<?php
setlocale(LC_TIME, 'en_US');
echo strftime("%b %d %Y %H:%M:%S", mktime (20,0,0,12,31,98))."\n";
echo gmstrftime("%b %d %Y %H:%M:%S", mktime (20,0,0,12,31,98))."\n";
?>

参见 strftime()

idate

(PHP 5)

idate -- 将本地时间日期格式化为整数

说明

int idate ( string format [, int timestamp] )

根据给定的格式字符对 timestamp 格式化并返回数字结果。timestamp 为可选项,默认值为本地当前时间,即 time() 的值。

date() 不同,idate() 只接受一个字符作为 format 参数。

表格 1. format 参数可识别以下字符

format 字符说明
BSwatch Beat/Internet Time
d月份中的第几天
h小时(12 小时格式)
H小时(24 小时格式)
i分钟
I如果启用夏时制则返回 1,否则返回 0
L如果是闰年则返回 1,否则返回 0
m月份的数字
s秒数
t本月的总天数
U自 Unix 纪元(January 1 1970 00:00:00 GMT)起的秒数――这和 time() 作用相同
w星期中的第几天(星期天是 0
WISO-8601 格式年份中的第几个星期,每星期从星期一开始
y年份(1 或 2 位数字――见下面说明)
Y年份(4 位数字)
z年份中的第几天
Z以秒为单位的时区偏移量

注: 因为 idate() 总是返回 integer,不能以“0”开头,因此 idate() 可能会返回比用户期望中要少的数字。见下面例子:

<?php
$timestamp = strtotime('1st January 2004'); //1072915200

// 下面以两位数字格式显示年份,但是因为
// 以“0”打头,因此只会显示“4”
echo idate('y', $timestamp);
?>

参见 date()time()

localtime

(PHP 4, PHP 5)

localtime -- 取得本地时间

说明

array localtime ( [int timestamp [, bool is_associative]] )

localtime() 函数返回一个数组,其结构和 C 函数调用返回的完全一样。localtime() 的第一个参数是时间戳,如果没有给出则使用从 time() 返回的当前时间。第二个参数是 is_associative,如果设为 FALSE 或未提供则返回的是普通的数字索引数组。如果该参数设为 TRUElocaltime() 函数返回包含有所有从 C 的 localtime 函数调用所返回的不同单元的关联数组。关联数组中不同的键名为:

  • "tm_sec" - 秒数

  • "tm_min" - 分钟数

  • "tm_hour" - 小时

  • "tm_mday" - 月份中的第几日

  • "tm_mon" - 年份中的第几个月,从 0 开始表示一月

  • "tm_year" - 年份,从 1900 开始

  • "tm_wday" - 星期中的第几天

  • "tm_yday" - 一年中的第几天

  • "tm_isdst" - 夏令时当前是否生效

注: 月份从 0(一月)到 11(十二月),星期数从 0(星期天)到 6(星期六)。

例子 1. time() 例子

<?php
$localtime = localtime();
$localtime_assoc = localtime(time(), true);
print_r($localtime);
print_r($localtime_assoc);
?>

上例的输出类似于:

Array
(
    [0] => 24
    [1] => 3
    [2] => 19
    [3] => 3
    [4] => 3
    [5] => 105
    [6] => 0
    [7] => 92
    [9] => 1
)

Array
(
    [tm_sec] => 24
    [tm_min] => 3
    [tm_hour] => 19
    [tm_mday] => 3
    [tm_mon] => 3
    [tm_year] => 105
    [tm_wday] => 0
    [tm_yday] => 92
    [tm_isdst] => 1
)

microtime

(PHP 3, PHP 4, PHP 5)

microtime -- 返回当前 Unix 时间戳和微秒数

说明

mixed microtime ( [bool get_as_float] )

microtime() 当前 Unix 时间戳以及微秒数。本函数仅在支持 gettimeofday() 系统调用的操作系统下可用。

如果调用时不带可选参数,本函数以 "msec sec" 的格式返回一个字符串,其中 sec 是自 Unix 纪元(0:00:00 January 1, 1970 GMT)起到现在的秒数,msec 是微秒部分。字符串的两部分都是以秒为单位返回的。

如果给出了 get_as_float 参数并且其值等价于 TRUEmicrotime() 将返回一个浮点数。

注: get_as_float 参数是 PHP 5.0.0 新加的。

例子 1. 用 microtime() 对脚本的运行计时

<?php
/**
 * Simple function to replicate PHP 5 behaviour
 */
function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

$time_start = microtime_float();

// Sleep for a while
usleep(100);

$time_end = microtime_float();
$time = $time_end - $time_start;

echo "Did nothing in $time seconds\n";
?>

参见 time()

mktime

(PHP 3, PHP 4, PHP 5)

mktime -- 取得一个日期的 Unix 时间戳

说明

int mktime ( [int hour [, int minute [, int second [, int month [, int day [, int year [, int is_dst]]]]]]] )

根据给出的参数返回 Unix 时间戳。时间戳是一个长整数,包含了从 Unix 纪元(January 1 1970 00:00:00 GMT)到给定时间的秒数。

参数可以从右向左省略,任何省略的参数会被设置成本地日期和时间的当前值。

参数

hour

小时数。

minute

分钟数。

second

秒数(一分钟之内)。

month

月份数。

day

天数。

year

年份数,可以是两位或四位数字,0-69 对应于 2000-2069,70-100 对应于 1970-2000。在如今系统中普遍把 time_t 作为一个 32 位有符号整数的情况下,year 的合法范围是 1901 到 2038 之间,不过此限制自 PHP 5.1.0 起已被克服了。

is_dst

本参数可以设为 1,表示正处于夏时制时间(DST),0 表示不是夏时制,或者 -1(默认值)表示不知道是否是夏时制。如果未知,PHP 会尝试自己搞明白。这可能产生不可预知(但并非不正确)的结果。如果 PHP 运行的系统中启用了 DST 或者 is_dst 设为 1,某些时间是无效的。例如 DST 自 2:00 生效,则所有处于 2:00 到 3:00 之间的时间都无效,mktime() 会返回一个未定义(通常为负)的值。某些系统(例如 Solaris 8)的 DST 在午夜生效,则 DST 生效当天的 0:30 会被计算为前一天的 23:30。

注: 自 PHP 5.1.0 起,本参数已被废弃。应该使用新的时区处理特性来替代。

返回值

mktime() 根据给出的参数返回 Unix 时间戳。如果参数非法(例如年,月,日都是零),本函数返回 FALSE(在 PHP 5.1 之前返回 -1)。

更新日志

版本说明
3.0.10加入了 is_dst 参数
5.1.0 is_dst 参数被废弃。出错时函数返回 FALSE 而不再是 -1

范例

例子 1. mktime() 例子

mktime() 在做日期计算和验证方面很有用,它会自动计算超出范围的输入的正确值。例如下面例子中每一行都会产生字符串 "Jan-01-1998"。

<?php
echo date("M-d-Y", mktime(0, 0, 0, 12, 32, 1997));
echo date("M-d-Y", mktime(0, 0, 0, 13, 1, 1997));
echo date("M-d-Y", mktime(0, 0, 0, 1, 1, 1998));
echo date("M-d-Y", mktime(0, 0, 0, 1, 1, 98));
?>

例子 2. 下个月的最后一天

任何给定月份的最后一天都可以被表示为下个月的第 "0" 天,而不是 -1 天。下面两个例子都会产生字符串 "The last day in Feb 2000 is: 29"。

<?php
$lastday = mktime(0, 0, 0, 3, 0, 2000);
echo strftime("Last day in Feb 2000 is: %d", $lastday);
$lastday = mktime(0, 0, 0, 4, -31, 2000);
echo strftime("Last day in Feb 2000 is: %d", $lastday);
?>

注释

注意

在 PHP 5.1.0 之前,在任何已知 Windows 版本以及一些其它系统下不支持负的时间戳。因此年份的有效范围限制为 1970 到 2038。

strftime

(PHP 3, PHP 4, PHP 5)

strftime -- 根据区域设置格式化本地时间/日期

说明

string strftime ( string format [, int timestamp] )

返回用给定的格式字串对给出的 timestamp 进行格式输出后的字符串。如果没有给出时间戳则用当前的本地时间。月份和星期几以及其它和语言有关的字符串写法和用 setlocale() 设定的当前的区域有关。

格式字串能识别下列转换标记:

  • %a - 当前区域星期几的简写

  • %A - 当前区域星期几的全称

  • %b - 当前区域月份的简写

  • %B - 当前区域月份的全称

  • %c - 当前区域首选的日期时间表达

  • %C - 世纪值(年份除以 100 后取整,范围从 00 到 99)

  • %d - 月份中的第几天,十进制数字(范围从 01 到 31)

  • %D - 和 %m/%d/%y 一样

  • %e - 月份中的第几天,十进制数字,一位的数字前会加上一个空格(范围从 ' 1' 到 '31')

  • %g - 和 %G 一样,但是没有世纪

  • %G - 4 位数的年份,符合 ISO 星期数(参见 %V)。和 %V 的格式和值一样,只除了如果 ISO 星期数属于前一年或者后一年,则使用那一年。

  • %h - 和 %b 一样

  • %H - 24 小时制的十进制小时数(范围从 00 到 23)

  • %I - 12 小时制的十进制小时数(范围从 00 到 12)

  • %j - 年份中的第几天,十进制数(范围从 001 到 366)

  • %m - 十进制月份(范围从 01 到 12)

  • %M - 十进制分钟数

  • %n - 换行符

  • %p - 根据给定的时间值为 `am' 或 `pm',或者当前区域设置中的相应字符串

  • %r - 用 a.m. 和 p.m. 符号的时间

  • %R - 24 小时符号的时间

  • %S - 十进制秒数

  • %t - 制表符

  • %T - 当前时间,和 %H:%M:%S 一样

  • %u - 星期几的十进制数表达 [1,7],1 表示星期一

    警告

    尽管 ISO 9889:1999(当前的 C 标准)明确指出一周从星期一开始,但是 Sun Solaris 的一周似乎从星期天开始并作为 1。

  • %U - 本年的第几周,从第一周的第一个星期天作为第一天开始

  • %V - 本年第几周的 ISO 8601:1988 格式,范围从 01 到 53,第 1 周是本年第一个至少还有 4 天的星期,星期一作为每周的第一天。(用 %G 或者 %g 作为指定时间戳相应周数的年份组成。)

  • %W - 本年的第几周数,从第一周的第一个星期一作为第一天开始

  • %w - 星期中的第几天,星期天为 0

  • %x - 当前区域首选的时间表示法,不包括时间

  • %X - 当前区域首选的时间表示法,不包括日期

  • %y - 没有世纪数的十进制年份(范围从 00 到 99)

  • %Y - 包括世纪数的十进制年份

  • %Z 或 %z - 时区名或缩写

  • %% - 文字上的 `%' 字符

注: 可能不是所有的转换标记都被 C 库文件支持,这种情况下 PHP 的 strftime() 也不支持。此外,不是所有的平台都支持负的时间戳,因此日期的范围可能限定在不早于 Unix 纪元。这意味着例如 %e, %T,%R 和 %D(可能更多)以及早于 Jan 1, 1970 的时间在 Windows,一些 Linux 发行版本,以及其它几个操作系统中无效。对于 Windows 系统,所支持的转换标记可在 MSDN 网站找到。

例子 1. strftime() 区域的例子

<?php
setlocale(LC_TIME, "C");
echo strftime("%A");
setlocale(LC_TIME, "fi_FI");
echo strftime(" in Finnish is %A,");
setlocale(LC_TIME, "fr_FR");
echo strftime(" in French %A and");
setlocale(LC_TIME, "de_DE");
echo strftime(" in German %A.\n");
?>
本例在你的系统中安装有各自的区域设置后才能工作。

注: %G 和 %V,如果数字编号系统未能充分理解,基于 ISO 8601:1988 的星期数可能得出未预期的结果。见上面的 %V 和以下的例子。

例子 2. ISO 8601:1988 week number example

<?php
/*     December 2002 / January 2003
ISOWk  M   Tu  W   Thu F   Sa  Su
----- ----------------------------
51     16  17  18  19  20  21  22
52     23  24  25  26  27  28  29
1      30  31   1   2   3   4   5
2       6   7   8   9  10  11  12
3      13  14  15  16  17  18  19   */

// Outputs: 12/28/2002 - %V,%G,%Y = 52,2002,2002
echo "12/28/2002 - %V,%G,%Y = " . strftime("%V,%G,%Y", strtotime("12/28/2002")) . "\n";

// Outputs: 12/30/2002 - %V,%G,%Y = 1,2003,2002
echo "12/30/2002 - %V,%G,%Y = " . strftime("%V,%G,%Y", strtotime("12/30/2002")) . "\n";

// Outputs: 1/3/2003 - %V,%G,%Y = 1,2003,2003
echo "1/3/2003 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/3/2003")) . "\n";

// Outputs: 1/10/2003 - %V,%G,%Y = 2,2003,2003
echo "1/10/2003 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/10/2003")) . "\n";



/*     December 2004 / January 2005
ISOWk  M   Tu  W   Thu F   Sa  Su
----- ----------------------------
51     13  14  15  16  17  18  19
52     20  21  22  23  24  25  26
53     27  28  29  30  31   1   2
1       3   4   5   6   7   8   9
2      10  11  12  13  14  15  16   */

// Outputs: 12/23/2004 - %V,%G,%Y = 52,2004,2004
echo "12/23/2004 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("12/23/2004")) . "\n";

// Outputs: 12/31/2004 - %V,%G,%Y = 53,2004,2004
echo "12/31/2004 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("12/31/2004")) . "\n";

// Outputs: 1/2/2005 - %V,%G,%Y = 53,2004,2005
echo "1/2/2005 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/2/2005")) . "\n";

// Outputs: 1/3/2005 - %V,%G,%Y = 1,2005,2005
echo "1/3/2005 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/3/2005")) . "\n";

?>

参见 setlocale()mktime()strptime() 以及 Open Group specification of strftime()

strptime

(PHP 5 >= 5.1.0RC1)

strptime -- 解析由 strftime() 生成的日期/时间

说明

array strptime ( string date, string format )

strptime() 返回一个将 date 解析后的数组,如果出错返回 FALSE

月份和星期几的名字以及其它与语种有关的字符串对应于 setlocale()设定的当前区域(LC_TIME)。

参数

datestring

被解析的字符串(例如从 strftime() 返回的)

formatstring

date 所使用的格式(例如同 strftime() 中所使用的相同)。

更多有关格式选项的信息见 strftime() 页面。

返回值

返回一个数组,失败则返回 FALSE

表格 1. 数组中包含以下单元

键名说明
tm_sec当前分钟内的秒数(0-61)
tm_min当前小时内的分钟数(0-59)
tm_hour午夜起的小时数(0-23)
tm_mday月份中的第几天(1-31)
tm_mon自一月起过了几个月(0-11)
tm_year自 1900 年起过了几年
tm_wday自星期天起过了几天(0-6)
tm_yday本年自一月一日起过了多少天(0-365)
unparseddate 中未能通过指定的 format 识别的部分

范例

例子 1. strptime() 例子

<?php
$format = '%d/%m/%Y %H:%M:%S';
$strf = strftime($format);

echo "$strf\n";

print_r(strptime($strf, $format));
?>

上例的输出类似于:

03/10/2004 15:54:19

Array
(
    [tm_sec] => 19
    [tm_min] => 54
    [tm_hour] => 15
    [tm_mday] => 3
    [tm_mon] => 9
    [tm_year] => 104
    [tm_wday] => 0
    [tm_yday] => 276
    [unparsed] =>
)

参见

strftime()

strtotime

(PHP 3 >= 3.0.12, PHP 4, PHP 5)

strtotime -- 将任何英文文本的日期时间描述解析为 Unix 时间戳

说明

int strtotime ( string time [, int now] )

本函数预期接受一个包含美国英语日期格式的字符串并尝试将其解析为 Unix 时间戳(自 January 1 1970 00:00:00 GMT 起的秒数),其值相对于 now 参数给出的时间,如果没有提供此参数则用系统当前时间。

本函数将使用 TZ 环境变量(如果有的话)来计算时间戳。自 PHP 5.1.0 起有更容易的方法来定义时区用于所有的日期/时间函数。此过程在 date_default_timezone_get() 函数页面中有说明。

注: 如果给定的年份是两位数字的格式,则其值 0-69 表示 2000-2069,70-100 表示 1970-2000。

参数

time

被解析的字符串,格式根据 GNU Date Input Formats 语法

now

用来计算返回值的时间戳

返回值

成功则返回时间戳,否则返回 FALSE。在 PHP 5.1.0 之前本函数在失败时返回 -1

更新日志

版本说明
5.1.0 失败时返回 FALSE,不再是 -1

范例

例子 1. strtotime() 例子

<?php
echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";
?>

例子 2. 失败检查

<?php
$str = 'Not Good';

// previous to PHP 5.1.0 you would compare with -1, instead of false
if (($timestamp = strtotime($str)) === false) {
    echo "The string ($str) is bogus";
} else {
    echo "$str == " . date('l dS of F Y h:i:s A', $timestamp);
}
?>

注释

警告

在 PHP 5 中到 5.0.2 之前,"now" 和其它相对时间从今天午夜起错误计算了。这和正确从当前时间起计算的其它版本不同。

注: 有效的时间戳通常从 Fri, 13 Dec 1901 20:45:54 GMT 到 Tue, 19 Jan 2038 03:14:07 GMT(对应于 32 位有符号整数的最小值和最大值)。不是所有的平台都支持负的时间戳,那么日记范围就被限制为不能早于 Unix 纪元。这意味着在 1970 年 1 月 1 日之前的日期将不能用在 Windows,一些 Linux 版本,以及几个其它的操作系统中。不过 PHP 5.1.0 及更新的版本克服了此限制。

参见

strptime()

time

(PHP 3, PHP 4, PHP 5)

time -- 返回当前的 Unix 时间戳

说明

int time ( void )

返回自从 Unix 纪元(格林威治时间 1970 年 1 月 1 日 00:00:00)到当前时间的秒数。

例子 1. time() 例子

<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
                   // 7 days; 24 hours; 60 mins; 60secs
echo 'Now:       '. date('Y-m-d') ."\n";
echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";
?>

上例的输出类似于:

Now:       2005-03-30
Next Week: 2005-04-07

参见 date()microtime()

XXIII. DB++ Functions

警告

本扩展模块是实验性的。本模块的行为,包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本扩展模块风险自担。


简介

db++, made by the German company Concept asa, is a relational database system with high performance and low memory and disk usage in mind. While providing SQL as an additional language interface, it is not really a SQL database in the first place but provides its own AQL query language which is much more influenced by the relational algebra then SQL is.

Concept asa always had an interest in supporting open source languages, db++ has had Perl and Tcl call interfaces for years now and uses Tcl as its internal stored procedure language.


需求

This extension relies on external client libraries so you have to have a db++ client installed on the system you want to use this extension on.

Concept asa provides db++ Demo versions and documentation for Linux, some other Unix versions. There is also a Windows version of db++, but this extension doesn't support it (yet).


安装

In order to build this extension yourself you need the db++ client libraries and header files to be installed on your system (these are included in the db++ installation archives by default). You have to run configure with option --with-dbplus to build this extension.

configure looks for the client libraries and header files under the default paths /usr/dbplus, /usr/local/dbplus and /opt/dblus. If you have installed db++ in a different place you have add the installation path to the configure option like this: --with-dbplus=/your/installation/path.


运行时配置

本扩展模块在 php.ini 中未定义任何配置选项。


资源类型

dbplus_relation

Most db++ functions operate on or return dbplus_relation resources. A dbplus_relation is a handle to a stored relation or a relation generated as the result of a query.


预定义常量

以下常量由本扩展模块定义,因此只有在本扩展模块被编译到 PHP 中,或者在运行时被动态加载后才有效。


db++ error codes

表格 1. DB++ Error Codes

PHP Constantdb++ constantmeaning
DBPLUS_ERR_NOERR (integer) ERR_NOERRNull error condition
DBPLUS_ERR_DUPLICATE (integer) ERR_DUPLICATETried to insert a duplicate tuple
DBPLUS_ERR_EOSCAN (integer) ERR_EOSCANEnd of scan from rget()
DBPLUS_ERR_EMPTY (integer) ERR_EMPTYRelation is empty (server)
DBPLUS_ERR_CLOSE (integer) ERR_CLOSEThe server can't close
DBPLUS_ERR_WLOCKED (integer) ERR_WLOCKEDThe record is write locked
DBPLUS_ERR_LOCKED (integer) ERR_LOCKEDRelation was already locked
DBPLUS_ERR_NOLOCK (integer) ERR_NOLOCKRelation cannot be locked
DBPLUS_ERR_READ (integer) ERR_READRead error on relation
DBPLUS_ERR_WRITE (integer) ERR_WRITEWrite error on relation
DBPLUS_ERR_CREATE (integer) ERR_CREATECreate() system call failed
DBPLUS_ERR_LSEEK (integer) ERR_LSEEKLseek() system call failed
DBPLUS_ERR_LENGTH (integer) ERR_LENGTHTuple exceeds maximum length
DBPLUS_ERR_OPEN (integer) ERR_OPENOpen() system call failed
DBPLUS_ERR_WOPEN (integer) ERR_WOPENRelation already opened for writing
DBPLUS_ERR_MAGIC (integer) ERR_MAGICFile is not a relation
DBPLUS_ERR_VERSION (integer) ERR_VERSIONFile is a very old relation
DBPLUS_ERR_PGSIZE (integer) ERR_PGSIZERelation uses a different page size
DBPLUS_ERR_CRC (integer) ERR_CRCInvalid crc in the superpage
DBPLUS_ERR_PIPE (integer) ERR_PIPEPiped relation requires lseek()
DBPLUS_ERR_NIDX (integer) ERR_NIDXToo many secondary indices
DBPLUS_ERR_MALLOC (integer) ERR_MALLOCMalloc() call failed
DBPLUS_ERR_NUSERS (integer) ERR_NUSERSError use of max users
DBPLUS_ERR_PREEXIT (integer) ERR_PREEXITCaused by invalid usage
DBPLUS_ERR_ONTRAP (integer) ERR_ONTRAPCaused by a signal
DBPLUS_ERR_PREPROC (integer) ERR_PREPROCError in the preprocessor
DBPLUS_ERR_DBPARSE (integer) ERR_DBPARSEError in the parser
DBPLUS_ERR_DBRUNERR (integer) ERR_DBRUNERRRun error in db
DBPLUS_ERR_DBPREEXIT (integer) ERR_DBPREEXITExit condition caused by prexit() * procedure
DBPLUS_ERR_WAIT (integer) ERR_WAITWait a little (Simple only)
DBPLUS_ERR_CORRUPT_TUPLE (integer) ERR_CORRUPT_TUPLEA client sent a corrupt tuple
DBPLUS_ERR_WARNING0 (integer) ERR_WARNING0 The Simple routines encountered a non fatal error which was corrected
DBPLUS_ERR_PANIC (integer) ERR_PANIC The server should not really die but after a disaster send ERR_PANIC to all its clients
DBPLUS_ERR_FIFO (integer) ERR_FIFOCan't create a fifo
DBPLUS_ERR_PERM (integer) ERR_PERMPermission denied
DBPLUS_ERR_TCL (integer) ERR_TCLTCL_error
DBPLUS_ERR_RESTRICTED (integer) ERR_RESTRICTEDOnly two users
DBPLUS_ERR_USER (integer) ERR_USER An error in the use of the library by an application programmer
DBPLUS_ERR_UNKNOWN (integer) ERR_UNKNOWN 

目录
dbplus_add -- Add a tuple to a relation
dbplus_aql -- Perform AQL query
dbplus_chdir -- Get/Set database virtual current directory
dbplus_close -- Close a relation
dbplus_curr -- Get current tuple from relation
dbplus_errcode --  Get error string for given errorcode or last error
dbplus_errno -- Get error code for last operation
dbplus_find -- Set a constraint on a relation
dbplus_first -- Get first tuple from relation
dbplus_flush -- Flush all changes made on a relation
dbplus_freealllocks -- Free all locks held by this client
dbplus_freelock -- Release write lock on tuple
dbplus_freerlocks -- Free all tuple locks on given relation
dbplus_getlock -- Get a write lock on a tuple
dbplus_getunique -- Get an id number unique to a relation
dbplus_info -- Get information about a relation
dbplus_last -- Get last tuple from relation
dbplus_lockrel -- Request write lock on relation
dbplus_next -- Get next tuple from relation
dbplus_open -- Open relation file
dbplus_prev -- Get previous tuple from relation
dbplus_rchperm -- Change relation permissions
dbplus_rcreate -- Creates a new DB++ relation
dbplus_rcrtexact -- Creates an exact but empty copy of a relation including indices
dbplus_rcrtlike -- Creates an empty copy of a relation with default indices
dbplus_resolve -- Resolve host information for relation
dbplus_restorepos -- Restore position
dbplus_rkeys -- Specify new primary key for a relation
dbplus_ropen -- Open relation file local
dbplus_rquery -- Perform local (raw) AQL query
dbplus_rrename -- Rename a relation
dbplus_rsecindex --  Create a new secondary index for a relation
dbplus_runlink -- Remove relation from filesystem
dbplus_rzap -- Remove all tuples from relation
dbplus_savepos -- Save position
dbplus_setindex -- Set index
dbplus_setindexbynumber -- Set index by number
dbplus_sql -- Perform SQL query
dbplus_tcl -- Execute TCL code on server side
dbplus_tremove -- Remove tuple and return new current tuple
dbplus_undo -- Undo
dbplus_undoprepare -- Prepare undo
dbplus_unlockrel -- Give up write lock on relation
dbplus_unselect -- Remove a constraint from relation
dbplus_update -- Update specified tuple in relation
dbplus_xlockrel -- Request exclusive lock on relation
dbplus_xunlockrel -- Free exclusive lock on relation

dbplus_add

(4.1.0 - 4.2.3 only, PECL)

dbplus_add -- Add a tuple to a relation

Description

int dbplus_add ( resource relation, array tuple )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

This function will add a tuple to a relation. The tuple data is an array of attribute/value pairs to be inserted into the given relation. After successful execution the tuple array will contain the complete data of the newly created tuple, including all implicitly set domain fields like sequences.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

dbplus_aql

(4.1.0 - 4.2.3 only, PECL)

dbplus_aql -- Perform AQL query

Description

resource dbplus_aql ( string query [, string server [, string dbpath]] )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_aql() will execute an AQL query on the given server and dbpath.

On success it will return a relation handle. The result data may be fetched from this relation by calling dbplus_next() and dbplus_current(). Other relation access functions will not work on a result relation.

Further information on the AQL A... Query Language is provided in the original db++ manual.

dbplus_chdir

(4.1.0 - 4.2.3 only, PECL)

dbplus_chdir -- Get/Set database virtual current directory

Description

string dbplus_chdir ( [string newdir] )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_chdir() will change the virtual current directory where relation files will be looked for by dbplus_open(). dbplus_chdir() will return the absolute path of the current directory. Calling dbplus_chdir() without giving any newdir may be used to query the current working directory.

dbplus_close

(4.1.0 - 4.2.3 only, PECL)

dbplus_close -- Close a relation

Description

mixed dbplus_close ( resource relation )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

Calling dbplus_close() will close a relation previously opened by dbplus_open().

Returns TRUE on success or DBPLUS_ERR_UNKNOWN on failure.

dbplus_curr

(4.1.0 - 4.2.3 only, PECL)

dbplus_curr -- Get current tuple from relation

Description

int dbplus_curr ( resource relation, array &tuple )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_curr() will read the data for the current tuple for the given relation and will pass it back as an associative array in tuple.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_first(), dbplus_prev(), dbplus_next(), and dbplus_last().

dbplus_errcode

(4.1.0 - 4.2.3 only, PECL)

dbplus_errcode --  Get error string for given errorcode or last error

Description

string dbplus_errcode ( [int errno] )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_errcode() returns a cleartext error string for the error code passed as errno of for the result code of the last db++ operation if no parameter is given.

dbplus_errno

(4.1.0 - 4.2.3 only, PECL)

dbplus_errno -- Get error code for last operation

Description

int dbplus_errno ( void )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_errno() will return the error code returned by the last db++ operation.

See also dbplus_errcode().

dbplus_find

(4.1.0 - 4.2.3 only, PECL)

dbplus_find -- Set a constraint on a relation

Description

int dbplus_find ( resource relation, array constraints, mixed tuple )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_find() will place a constraint on the given relation. Further calls to functions like dbplus_curr() or dbplus_next() will only return tuples matching the given constraints.

Constraints are triplets of strings containing of a domain name, a comparison operator and a comparison value. The constraints parameter array may consist of a collection of string arrays, each of which contains a domain, an operator and a value, or of a single string array containing a multiple of three elements.

The comparison operator may be one of the following strings: '==', '>', '>=', '<', '<=', '!=', '~' for a regular expression match and 'BAND' or 'BOR' for bitwise operations.

See also dbplus_unselect().

dbplus_first

(4.1.0 - 4.2.3 only, PECL)

dbplus_first -- Get first tuple from relation

Description

int dbplus_first ( resource relation, array &tuple )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_curr() will read the data for the first tuple for the given relation, make it the current tuple and pass it back as an associative array in tuple.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_curr(), dbplus_prev(), dbplus_next(), and dbplus_last().

dbplus_flush

(4.1.0 - 4.2.3 only, PECL)

dbplus_flush -- Flush all changes made on a relation

Description

int dbplus_flush ( resource relation )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_flush() will write all changes applied to relation since the last flush to disk.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

dbplus_freealllocks

(4.1.0 - 4.2.3 only, PECL)

dbplus_freealllocks -- Free all locks held by this client

Description

int dbplus_freealllocks ( void )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_freealllocks() will free all tuple locks held by this client.

See also dbplus_getlock(), dbplus_freelock(), and dbplus_freerlocks().

dbplus_freelock

(4.1.0 - 4.2.3 only, PECL)

dbplus_freelock -- Release write lock on tuple

Description

int dbplus_freelock ( resource relation, string tname )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_freelock() will release a write lock on the given tuple previously obtained by dbplus_getlock().

See also dbplus_getlock(), dbplus_freerlocks(), and dbplus_freealllocks().

dbplus_freerlocks

(4.1.0 - 4.2.3 only, PECL)

dbplus_freerlocks -- Free all tuple locks on given relation

Description

int dbplus_freerlocks ( resource relation )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_freerlocks() will free all tuple locks held on the given relation.

See also dbplus_getlock(), dbplus_freelock(), and dbplus_freealllocks().

dbplus_getlock

(4.1.0 - 4.2.3 only, PECL)

dbplus_getlock -- Get a write lock on a tuple

Description

int dbplus_getlock ( resource relation, string tname )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_getlock() will request a write lock on the specified tuple. It will return zero on success or a non-zero error code, especially DBPLUS_ERR_WLOCKED, on failure.

See also dbplus_freelock(), dbplus_freerlocks(), and dbplus_freealllocks().

dbplus_getunique

(4.1.0 - 4.2.3 only, PECL)

dbplus_getunique -- Get an id number unique to a relation

Description

int dbplus_getunique ( resource relation, int uniqueid )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_getunique() will obtain a number guaranteed to be unique for the given relation and will pass it back in the variable given as uniqueid.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

dbplus_info

(4.1.0 - 4.2.3 only, PECL)

dbplus_info -- Get information about a relation

Description

int dbplus_info ( resource relation, string key, array &result )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

警告

本函数暂无文档,仅有参数列表。

dbplus_last

(4.1.0 - 4.2.3 only, PECL)

dbplus_last -- Get last tuple from relation

Description

int dbplus_last ( resource relation, array &tuple )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_curr() will read the data for the last tuple for the given relation, make it the current tuple and pass it back as an associative array in tuple.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_first(), dbplus_curr(), dbplus_prev(), and dbplus_next().

dbplus_lockrel

(no version information, might be only in CVS)

dbplus_lockrel -- Request write lock on relation

Description

int dbplus_lockrel ( resource relation )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_lockrel() will request a write lock on the given relation. Other clients may still query the relation, but can't alter it while it is locked.

dbplus_next

(4.1.0 - 4.2.3 only, PECL)

dbplus_next -- Get next tuple from relation

Description

int dbplus_next ( resource relation, array &tuple )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_curr() will read the data for the next tuple for the given relation, will make it the current tuple and will pass it back as an associative array in tuple.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_first(), dbplus_curr(), dbplus_prev(), and dbplus_last().

dbplus_open

(4.1.0 - 4.2.3 only, PECL)

dbplus_open -- Open relation file

Description

resource dbplus_open ( string name )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

The relation file name will be opened. name can be either a file name or a relative or absolute path name. This will be mapped in any case to an absolute relation file path on a specific host machine and server.

On success a relation file resource (cursor) is returned which must be used in any subsequent commands referencing the relation. Failure leads to a zero return value, the actual error code may be asked for by calling dbplus_errno().

dbplus_prev

(4.1.0 - 4.2.3 only, PECL)

dbplus_prev -- Get previous tuple from relation

Description

int dbplus_prev ( resource relation, array &tuple )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_curr() will read the data for the previous tuple for the given relation, will make it the current tuple and will pass it back as an associative array in tuple.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_first(), dbplus_curr(), dbplus_next(), and dbplus_last().

dbplus_rchperm

(4.1.0 - 4.2.3 only, PECL)

dbplus_rchperm -- Change relation permissions

Description

int dbplus_rchperm ( resource relation, int mask, string user, string group )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_rchperm() will change access permissions as specified by mask, user and group. The values for these are operating system specific.

dbplus_rcreate

(4.1.0 - 4.2.3 only, PECL)

dbplus_rcreate -- Creates a new DB++ relation

Description

resource dbplus_rcreate ( string name, mixed domlist [, bool overwrite] )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_rcreate() will create a new relation named name. An existing relation by the same name will only be overwritten if the relation is currently not in use and overwrite is set to TRUE.

domlist should contain the domain specification for the new relation within an array of domain description strings. ( dbplus_rcreate() will also accept a string with space delimited domain description strings, but it is recommended to use an array). A domain description string consists of a domain name unique to this relation, a slash and a type specification character. See the db++ documentation, especially the dbcreate(1) manpage, for a description of available type specifiers and their meanings.

dbplus_rcrtexact

(4.1.0 - 4.2.3 only, PECL)

dbplus_rcrtexact -- Creates an exact but empty copy of a relation including indices

Description

mixed dbplus_rcrtexact ( string name, resource relation [, bool overwrite] )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_rcrtexact() will create an exact but empty copy of the given relation under a new name. An existing relation by the same name will only be overwritten if overwrite is TRUE and no other process is currently using the relation.

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

dbplus_rcrtlike

(4.1.0 - 4.2.3 only, PECL)

dbplus_rcrtlike -- Creates an empty copy of a relation with default indices

Description

mixed dbplus_rcrtlike ( string name, resource relation [, int overwrite] )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_rcrtexact() will create an empty copy of the given relation under a new name, but with default indices. An existing relation by the same name will only be overwritten if overwrite is TRUE and no other process is currently using the relation.

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

dbplus_resolve

(4.1.0 - 4.2.3 only, PECL)

dbplus_resolve -- Resolve host information for relation

Description

array dbplus_resolve ( string relation_name )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_resolve() will try to resolve the given relation_name and find out internal server id, real hostname and the database path on this host. The function will return an array containing these values under the keys 'sid', 'host' and 'host_path' or FALSE on error.

See also dbplus_tcl().

dbplus_restorepos

(4.1.0 - 4.2.3 only, PECL)

dbplus_restorepos -- Restore position

Description

int dbplus_restorepos ( resource relation, array tuple )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

警告

本函数暂无文档,仅有参数列表。

dbplus_rkeys

(4.1.0 - 4.2.3 only, PECL)

dbplus_rkeys -- Specify new primary key for a relation

Description

mixed dbplus_rkeys ( resource relation, mixed domlist )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_rkeys() will replace the current primary key for relation with the combination of domains specified by domlist.

domlist may be passed as a single domain name string or as an array of domain names.

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

dbplus_ropen

(4.1.0 - 4.2.3 only, PECL)

dbplus_ropen -- Open relation file local

Description

resource dbplus_ropen ( string name )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_ropen() will open the relation file locally for quick access without any client/server overhead. Access is read only and only dbplus_current() and dbplus_next() may be applied to the returned relation.

dbplus_rquery

(4.1.0 - 4.2.3 only, PECL)

dbplus_rquery -- Perform local (raw) AQL query

Description

resource dbplus_rquery ( string query [, string dbpath] )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_rquery() performs a local (raw) AQL query using an AQL interpreter embedded into the db++ client library. dbplus_rquery() is faster than dbplus_aql() but will work on local data only.

dbplus_rrename

(4.1.0 - 4.2.3 only, PECL)

dbplus_rrename -- Rename a relation

Description

int dbplus_rrename ( resource relation, string name )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_rrename() will change the name of relation to name.

dbplus_rsecindex

(4.1.0 - 4.2.3 only, PECL)

dbplus_rsecindex --  Create a new secondary index for a relation

Description

mixed dbplus_rsecindex ( resource relation, mixed domlist, int type )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_rsecindex() will create a new secondary index for relation with consists of the domains specified by domlist and is of type type

domlist may be passed as a single domain name string or as an array of domain names.

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

dbplus_runlink

(4.1.0 - 4.2.3 only, PECL)

dbplus_runlink -- Remove relation from filesystem

Description

int dbplus_runlink ( resource relation )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_unlink() will close and remove the relation.

dbplus_rzap

(4.1.0 - 4.2.3 only, PECL)

dbplus_rzap -- Remove all tuples from relation

Description

int dbplus_rzap ( resource relation )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_rzap() will remove all tuples from relation.

dbplus_savepos

(4.1.0 - 4.2.3 only, PECL)

dbplus_savepos -- Save position

Description

int dbplus_savepos ( resource relation )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

警告

本函数暂无文档,仅有参数列表。

dbplus_setindex

(4.1.0 - 4.2.3 only, PECL)

dbplus_setindex -- Set index

Description

int dbplus_setindex ( resource relation, string idx_name )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

警告

本函数暂无文档,仅有参数列表。

dbplus_setindexbynumber

(4.1.0 - 4.2.3 only, PECL)

dbplus_setindexbynumber -- Set index by number

Description

int dbplus_setindexbynumber ( resource relation, int idx_number )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

警告

本函数暂无文档,仅有参数列表。

dbplus_sql

(4.1.0 - 4.2.3 only, PECL)

dbplus_sql -- Perform SQL query

Description

resource dbplus_sql ( string query [, string server [, string dbpath]] )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

警告

本函数暂无文档,仅有参数列表。

dbplus_tcl

(4.1.0 - 4.2.3 only, PECL)

dbplus_tcl -- Execute TCL code on server side

Description

string dbplus_tcl ( int sid, string script )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

A db++ server will prepare a TCL interpreter for each client connection. This interpreter will enable the server to execute TCL code provided by the client as a sort of stored procedures to improve the performance of database operations by avoiding client/server data transfers and context switches.

dbplus_tcl() needs to pass the client connection id the TCL script code should be executed by. dbplus_resolve() will provide this connection id. The function will return whatever the TCL code returns or a TCL error message if the TCL code fails.

See also dbplus_resolve().

dbplus_tremove

(4.1.0 - 4.2.3 only, PECL)

dbplus_tremove -- Remove tuple and return new current tuple

Description

int dbplus_tremove ( resource relation, array tuple [, array &current] )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_tremove() removes tuple from relation if it perfectly matches a tuple within the relation. current, if given, will contain the data of the new current tuple after calling dbplus_tremove().

dbplus_undo

(4.1.0 - 4.2.3 only, PECL)

dbplus_undo -- Undo

Description

int dbplus_undo ( resource relation )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

警告

本函数暂无文档,仅有参数列表。

dbplus_undoprepare

(4.1.0 - 4.2.3 only, PECL)

dbplus_undoprepare -- Prepare undo

Description

int dbplus_undoprepare ( resource relation )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

警告

本函数暂无文档,仅有参数列表。

dbplus_unlockrel

(4.1.0 - 4.2.3 only, PECL)

dbplus_unlockrel -- Give up write lock on relation

Description

int dbplus_unlockrel ( resource relation )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_unlockrel() will release a write lock previously obtained by dbplus_lockrel().

dbplus_unselect

(4.1.0 - 4.2.3 only, PECL)

dbplus_unselect -- Remove a constraint from relation

Description

int dbplus_unselect ( resource relation )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

Calling dbplus_unselect() will remove a constraint previously set by dbplus_find() on relation.

dbplus_update

(4.1.0 - 4.2.3 only, PECL)

dbplus_update -- Update specified tuple in relation

Description

int dbplus_update ( resource relation, array old, array new )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_update() replaces the tuple given by old with the data from new if and only if old completely matches a tuple within relation.

dbplus_xlockrel

(4.1.0 - 4.2.3 only, PECL)

dbplus_xlockrel -- Request exclusive lock on relation

Description

int dbplus_xlockrel ( resource relation )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_xlockrel() will request an exclusive lock on relation preventing even read access from other clients.

See also dbplus_xunlockrel().

dbplus_xunlockrel

(4.1.0 - 4.2.3 only, PECL)

dbplus_xunlockrel -- Free exclusive lock on relation

Description

int dbplus_xunlockrel ( resource relation )

警告

本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。

dbplus_xunlockrel() will release an exclusive lock on relation previously obtained by dbplus_xlockrel().

XXIV. dBase Functions

简介

These functions allow you to access records stored in dBase-format (dbf) databases.

dBase files are simple sequential files of fixed length records. Records are appended to the end of the file and delete records are kept until you call dbase_pack().

The types of dBase fields available are:

表格 1. Available types of fields

FielddBase TypeFormatAdditional informations
MMemon/aThis type is not supported by PHP, such field will be ignored
DDateYYYYMMDDThe field length is limited to 8
NNumberA number You must declare a length and a precision (the number of digits after the decimal point)
CStringA stringYou must declare a length. When retrieving data, the string will be right-padded with spaces to fit the declared length.
LBooleanT or Y for TRUE, F or N for FALSEStored and returned as an integer (1 or 0)

警告

There is no support for indexes or memo fields. There is no support for locking, too. Two concurrent webserver processes modifying the same dBase file will very likely ruin your database.

We recommend that you do not use dBase files as your production database. Choose any real SQL server instead; MySQL or Postgres are common choices with PHP. dBase support is here to allow you to import and export data to and from your web database, because the file format is commonly understood by Windows spreadsheets and organizers.


安装

In order to enable the bundled dbase library and to use these functions, you must compile PHP with the --enable-dbase option.


运行时配置

本扩展模块在 php.ini 中未定义任何配置选项。


资源类型

本扩展模块未定义任何资源类型。


范例

Many examples in this reference require a dBase database. We will use /tmp/test.dbf that will be created in the example of dbase_create().


预定义常量

本扩展模块未定义任何常量。

目录
dbase_add_record -- Adds a record to a database
dbase_close -- Closes a database
dbase_create -- Creates a database
dbase_delete_record -- Deletes a record from a database
dbase_get_header_info -- Gets the header info of a database
dbase_get_record_with_names --  Gets a record from a database as an associative array
dbase_get_record --  Gets a record from a database as an indexed array
dbase_numfields -- Gets the number of fields of a database
dbase_numrecords -- Gets the number of records in a database
dbase_open -- Opens a database
dbase_pack -- Packs a database
dbase_replace_record -- Replaces a record in a database

dbase_add_record

(PHP 3, PHP 4, PHP 5)

dbase_add_record -- Adds a record to a database

说明

bool dbase_add_record ( int dbase_identifier, array record )

Adds the given data to the database.

参数

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record

An indexed array of data. The number of items must be equal to the number of fields in the database, otherwise dbase_add_record() will fail.

注: If you're using dbase_get_record() return value for this parameter, remember to reset the key named deleted.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

范例

例子 1. Inserting a record in a dBase database

<?php

// open in read-write mode
$db = dbase_open('/tmp/test.dbf', 2);

if ($db) {
  dbase_add_record($db, array(
      date('Ymd'), 
      'Maxim Topolov', 
      '23', 
      'max@example.com',
      'T'));   
  dbase_close($db);
}

?>

dbase_close

(PHP 3, PHP 4, PHP 5)

dbase_close -- Closes a database

说明

bool dbase_close ( int dbase_identifier )

Closes the given database link identifier.

参数

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

返回值

如果成功则返回 TRUE,失败则返回 FALSE

范例

例子 1. Closing a dBase database file

<?php

// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);

if ($db) {
  // read some data ..
  
  dbase_close($db);
}

?>

dbase_create

(PHP 3, PHP 4, PHP 5)

dbase_create -- Creates a database

说明

int dbase_create ( string filename, array fields )

dbase_create() creates a dBase database with the given definition.

注: 安全模式被激活时,PHP 将检查被操作的文件或者目录是否与正在执行的脚本有相同的 UID(所有者)。

注: 本函数受 open_basedir 的影响。

参数

filename

The name of the database. It can be a relative or absolute path to the file where dBase will store your data.

fields

An array of arrays, each array describing the format of one field of the database. Each field consists of a name, a character indicating the field type, and optionally, a length, and a precision.

注: The fieldnames are limited in length and must not exceed 10 chars.

返回值

Returns a database link identifier if the database is successfully created, or FALSE if an error occurred.

范例

例子 1. Creating a dBase database file

<?php

// database "definition"
$def = array(
  array("date",     "D"),
  array("name",     "C",  50),
  array("age",      "N",   3, 0),
  array("email",    "C", 128),
  array("ismember", "L")
);

// creation
if (!dbase_create('/tmp/test.dbf', $def)) {
  echo "Error, can't create the database\n";
}

?>

dbase_delete_record

(PHP 3, PHP 4, PHP 5)

dbase_delete_record -- Deletes a record from a database

说明

bool dbase_delete_record ( int dbase_identifier, int record_number )

Marks the given record to be deleted from the database.

注: To actually remove the record from the database, you must also call dbase_pack().

参数

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record_number

An integer which spans from 1 to the number of records in the database (as returned by dbase_numrecords()).

返回值

如果成功则返回 TRUE,失败则返回 FALSE

dbase_get_header_info

(PHP 5)

dbase_get_header_info -- Gets the header info of a database

说明

array dbase_get_header_info ( int dbase_identifier )

Returns information on the column structure of the given database link identifier.

参数

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

返回值

An indexed array with an entry for each column in the database. The array index starts at 0.

Each array element contains an associative array of column information, as described here:

name

The name of the column

type

The human-readable name for the dbase type of the column (i.e. date, boolean, etc.)

length

The number of bytes this column can hold

precision

The number of digits of decimal precision for the column

format

A suggested printf() format specifier for the column

offset

The byte offset of the column from the start of the row

If the database header information cannot be read, FALSE is returned.

范例

例子 1. Showing header information for a dBase database file

<?php
// Path to dbase file
$db_path = "/tmp/test.dbf";

// Open dbase file
$dbh = dbase_open($db_path, 0)
  or die("Error! Could not open dbase database file '$db_path'.");

// Get column information
$column_info = dbase_get_header_info($dbh);

// Display information
print_r($column_info);
?>

dbase_get_record_with_names

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

dbase_get_record_with_names --  Gets a record from a database as an associative array

说明

array dbase_get_record_with_names ( int dbase_identifier, int record_number )

Gets a record from a dBase database as an associative array.

参数

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record_number

The index of the record.

返回值

An associative array with the record. This will also include a key named deleted which is set to 1 if the record has been marked for deletion (see dbase_delete_record()).

Each field is converted to the appropriate PHP type, except:

  • Dates are left as strings.

  • Integers that would have caused an overflow (> 32 bits) are returned as strings.

On error, dbase_get_record_with_names() will return FALSE.

范例

例子 1. Listing all the registered members in the database

<?php
// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);

if ($db) {
  $record_numbers = dbase_numrecords($db);
  for ($i = 1; $i <= $record_numbers; $i++) {
      $row = dbase_get_record_with_names($db, $i);
      if ($row['ismember'] == 1) {
          echo "Member #$i: " . trim($row['name']) . "\n";
      }
  }
}
?>

dbase_get_record

(PHP 3, PHP 4, PHP 5)

dbase_get_record --  Gets a record from a database as an indexed array

说明

array dbase_get_record ( int dbase_identifier, int record_number )

Gets a record from a database as an indexed array.

参数

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record_number

The index of the record.

返回值

An indexed array with the record. This array will also include an associative key named deleted which is set to 1 if the record has been marked for deletion (see dbase_delete_record()).

Each field is converted to the appropriate PHP type, except:

  • Dates are left as strings.

  • Integers that would have caused an overflow (> 32 bits) are returned as strings.

On error, dbase_get_record() will return FALSE.

dbase_numfields

(PHP 3, PHP 4, PHP 5)

dbase_numfields -- Gets the number of fields of a database

说明

int dbase_numfields ( int dbase_identifier )

Gets the number of fields (columns) in the specified database.

注: Field numbers are between 0 and dbase_numfields($db)-1, while record numbers are between 1 and dbase_numrecords($db).

参数

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

返回值

The number of fields in the database, or FALSE if an error occurs.

范例

例子 1. dbase_numfields() Example

<?php

$rec = dbase_get_record($db, $recno);
$nf  = dbase_numfields($db);
for ($i = 0; $i < $nf; $i++) {
  echo $rec[$i], "\n";
}

?>

dbase_numrecords

(PHP 3, PHP 4, PHP 5)

dbase_numrecords -- Gets the number of records in a database

说明

int dbase_numrecords ( int dbase_identifier )

Gets the number of records (rows) in the specified database.

注: Record numbers are between 1 and dbase_numrecords($db), while field numbers are between 0 and dbase_numfields($db)-1.

参数

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

返回值

The number of records in the database, or FALSE if an error occurs.

范例

例子 1. Looping over all the records of the database

<?php

// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);

if ($db) {
  $record_numbers = dbase_numrecords($db);
  for ($i = 1; $i <= $record_numbers; $i++) {
      // do something here, for each record
  }
}

?>

参见

dbase_num_fields()

dbase_open

(PHP 3, PHP 4, PHP 5)

dbase_open -- Opens a database

说明

int dbase_open ( string filename, int mode )

dbase_open() opens a dBase database with the given access mode.

注: 安全模式被激活时,PHP 将检查被操作的文件或者目录是否与正在执行的脚本有相同的 UID(所有者)。

注: 本函数受 open_basedir 的影响。

参数

filename

The name of the database. It can be a relative or absolute path to the file where dBase will store your data.

mode

An integer which correspond to those for the open() system call (Typically 0 means read-only, 1 means write-only, and 2 means read and write).

注: You can't open a dBase file in write-only mode as the function will fail to read the headers information and thus you can't use 1 as mode.

范例

例子 1. Opening a dBase database file

<?php

// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);

if ($db) {
  // read some data ..
  
  dbase_close($db);
}

?>

返回值

Returns a database link identifier if the database is successfully opened, or FALSE if an error occurred.

dbase_pack

(PHP 3, PHP 4, PHP 5)

dbase_pack -- Packs a database

说明

bool dbase_pack ( int dbase_identifier )

Packs the specified database by permanently deleting all records marked for deletion using dbase_delete_record().

参数

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

返回值

如果成功则返回 TRUE,失败则返回 FALSE

范例

例子 1. Emptying a dBase database

<?php

// open in read-write mode
$db = dbase_open('/tmp/test.dbf', 2);

if ($db) {
  $record_numbers = dbase_numrecords($db);
  for ($i = 1; $i <= $record_numbers; $i++) {
      dbase_delete_record($db, $i);
  }
  // expunge the database
  dbase_pack($db);
}

?>

dbase_replace_record

(PHP 3 >= 3.0.11, PHP 4, PHP 5)

dbase_replace_record -- Replaces a record in a database

说明

bool dbase_replace_record ( int dbase_identifier, array record, int record_number )

Replaces the given record in the database with the given data.

参数

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record

An indexed array of data. The number of items must be equal to the number of fields in the database, otherwise dbase_add_record() will fail.

注: If you're using dbase_get_record() return value for this parameter, remember to reset the key named deleted.

record_number

An integer which spans from 1 to the number of records in the database (as returned by dbase_numrecords()).

返回值

如果成功则返回 TRUE,失败则返回 FALSE

范例

例子 1. Updating a record in the database

<?php

// open in read-write mode
$db = dbase_open('/tmp/test.dbf', 2);

if ($db) {
  // gets the old row
  $row = dbase_get_record_with_names($db, 1);
  
  // remove the 'deleted' entry
  unset($row['deleted']);
  
  // Update the date field with the current timestamp
  $row['date'] = date('Ymd');
  
  // Replace the record
  dbase_replace_record($db, $row, 1);
  dbase_close($db);
}

?>

XXV. DBM Functions [deprecated]

简介

These functions allow you to store records stored in a dbm-style database. This type of database (supported by the Berkeley DB, GDBM, and some system libraries, as well as a built-in flatfile library) stores key/value pairs (as opposed to the full-blown records supported by relational databases).

注: However, dbm support is deprecated and you are encouraged to use the Database (dbm-style) abstraction layer functions instead.


需求

To use this functions you have to compile PHP with support for an underlying database. See the list of supported Databases.


安装

In order to use these functions, you must compile PHP with dbm support by using the --with-db option. In addition you must ensure support for an underlying database or you can use some system libraries.


运行时配置

本扩展模块在 php.ini 中未定义任何配置选项。


资源类型

The function dbmopen() returns an database identifier which is used by the other dbm-functions.


预定义常量

本扩展模块未定义任何常量。


范例

例子 1. DBM example

<?php

$dbm = dbmopen("lastseen", "w");
if (dbmexists($dbm, $userid)) {
    $last_seen = dbmfetch($dbm, $userid);
} else {
    dbminsert($dbm, $userid, time());
}
do_stuff();
dbmreplace($dbm, $userid, time());
dbmclose($dbm);

?>

目录
dblist --  Describes the DBM-compatible library being used
dbmclose -- Closes a dbm database
dbmdelete --  Deletes the value for a key from a DBM database
dbmexists --  Tells if a value exists for a key in a DBM database
dbmfetch --  Fetches a value for a key from a DBM database
dbmfirstkey --  Retrieves the first key from a DBM database
dbminsert --  Inserts a value for a key in a DBM database
dbmnextkey --  Retrieves the next key from a DBM database
dbmopen -- Opens a DBM database
dbmreplace --  Replaces the value for a key in a DBM database

dblist

(PHP 3, PHP 4, PECL)

dblist --  Describes the DBM-compatible library being used

Description

string dblist ( void )

例子 1. Getting the information on the command line

[marcus@zaphod marcus]$ php -r 'echo dblist();'
This is GDBM version 1.8.0, as of May 19, 1999.

dbmclose

(PHP 3, PHP 4, PECL)

dbmclose -- Closes a dbm database

Description

bool dbmclose ( resource dbm_identifier )

Unlocks and closes the specified database.

dbmdelete

(PHP 3, PHP 4, PECL)

dbmdelete --  Deletes the value for a key from a DBM database

Description

bool dbmdelete ( resource dbm_identifier, string key )

Deletes the value for key in the database.

Returns FALSE if the key didn't exist in the database.

dbmexists

(PHP 3, PHP 4, PECL)

dbmexists --  Tells if a value exists for a key in a DBM database

Description

bool dbmexists ( resource dbm_identifier, string key )

Returns TRUE if there is a value associated with the key.

dbmfetch

(PHP 3, PHP 4, PECL)

dbmfetch --  Fetches a value for a key from a DBM database

Description

string dbmfetch ( resource dbm_identifier, string key )

Returns the value associated with key.

dbmfirstkey

(PHP 3, PHP 4, PECL)

dbmfirstkey --  Retrieves the first key from a DBM database

Description

string dbmfirstkey ( resource dbm_identifier )

Returns the first key in the database. Note that no particular order is guaranteed since the database may be built using a hash-table, which doesn't guarantee any ordering.

dbminsert

(PHP 3, PHP 4, PECL)

dbminsert --  Inserts a value for a key in a DBM database

Description

int dbminsert ( resource dbm_identifier, string key, string value )

Adds the value to the database with the specified key.

Returns -1 if the database was opened read-only, 0 if the insert was successful, and 1 if the specified key already exists. (To replace the value, use dbmreplace().)

dbmnextkey

(PHP 3, PHP 4, PECL)

dbmnextkey --  Retrieves the next key from a DBM database

Description

string dbmnextkey ( resource dbm_identifier, string key )

Returns the next key after key. By calling dbmfirstkey() followed by successive calls to dbmnextkey() it is possible to visit every key/value pair in the dbm database. For example:

例子 1. Visiting every key/value pair in a DBM database

<?php

$key = dbmfirstkey($dbm_id);
while ($key) {
    echo "$key = " . dbmfetch($dbm_id, $key) . "\n";
    $key = dbmnextkey($dbm_id, $key);
}

?>

dbmopen

(PHP 3, PHP 4, PECL)

dbmopen -- Opens a DBM database

Description

resource dbmopen ( string filename, string flags )

The first argument is the full-path filename of the DBM file to be opened and the second is the file open mode which is one of "r", "n", "c" or "w" for read-only, new (implies read-write, and most likely will truncate an already-existing database of the same name), create (implies read-write, and will not truncate an already-existing database of the same name) and read-write respectively.

Returns an identifier to be passed to the other DBM functions on success, or FALSE on failure.

If NDBM support is used, NDBM will actually create filename.dir and filename.pag files. GDBM only uses one file, as does the internal flat-file support, and Berkeley DB creates a filename.db file. Note that PHP does its own file locking in addition to any file locking that may be done by the DBM library itself. PHP does not delete the .lck files it creates. It uses these files simply as fixed inodes on which to do the file locking. For more information on DBM files, see your Unix man pages, or obtain GNU's GDBM.

注: 安全模式被激活时,PHP 将检查被操作的文件或者目录是否与正在执行的脚本有相同的 UID(所有者)。

dbmreplace

(PHP 3, PHP 4, PECL)

dbmreplace --  Replaces the value for a key in a DBM database

Description

int dbmreplace ( resource dbm_identifier, string key, string value )

Replaces the value for the specified key in the database.

This will also add the key to the database if it didn't already exist.

XXVI. dbx Functions

简介

The dbx module is a database abstraction layer (db 'X', where 'X' is a supported database). The dbx functions allow you to access all supported databases using a single calling convention. The dbx-functions themselves do not interface directly to the databases, but interface to the modules that are used to support these databases.

注: 本扩展已被移动到 PECL 库中且自以下版本起不再被绑定到 PHP 中:5.1.0.


需求

To be able to use a database with the dbx-module, the module must be either linked or loaded into PHP, and the database module must be supported by the dbx-module. Currently, the following databases are supported, but others will follow:

Documentation for adding additional database support to dbx can be found at http://www.guidance.nl/php/dbx/doc/.


安装

In order to have these functions available, you must compile PHP with dbx support by using the --enable-dbx option and all options for the databases that will be used, e.g. for MySQL you must also specify --with-mysql=[DIR]. To get other supported databases to work with the dbx-module refer to their specific documentation.


运行时配置

这些函数的行为受 php.ini 的影响。

表格 1. DBX Configuration Options

NameDefaultChangeableChangelog
dbx.colnames_case"unchanged"PHP_INI_SYSTEMAvailable since PHP 4.3.0.
有关 PHP_INI_* 常量进一步的细节与定义参见附录 G

以下是配置选项的简要解释。

dbx.colnames_case string

Columns names can be returned "unchanged" or converted to "uppercase" or "lowercase". This directive can be overridden with a flag to dbx_query().


资源类型

There are two resource types used in the dbx module. The first one is the link-object for a database connection, the second a result-object which holds the result of a query.


预定义常量

以下常量由本扩展模块定义,因此只有在本扩展模块被编译到 PHP 中,或者在运行时被动态加载后才有效。

DBX_MYSQL (integer)

DBX_ODBC (integer)

DBX_PGSQL (integer)

DBX_MSSQL (integer)

DBX_FBSQL (integer)

DBX_OCI8 (integer) (available from PHP 4.3.0)

DBX_SYBASECT (integer)

DBX_SQLITE (integer) (PHP 5)

DBX_PERSISTENT (integer)

DBX_RESULT_INFO (integer)

DBX_RESULT_INDEX (integer)

DBX_RESULT_ASSOC (integer)

DBX_RESULT_UNBUFFERED (integer) (PHP 5)

DBX_COLNAMES_UNCHANGED (integer) (available from PHP 4.3.0)

DBX_COLNAMES_UPPERCASE (integer) (available from PHP 4.3.0)

DBX_COLNAMES_LOWERCASE (integer) (available from PHP 4.3.0)

DBX_CMP_NATIVE (integer)

DBX_CMP_TEXT (integer)

DBX_CMP_NUMBER (integer)

DBX_CMP_ASC (integer)

DBX_CMP_DESC (integer)

目录
dbx_close -- Close an open connection/database
dbx_compare -- Compare two rows for sorting purposes
dbx_connect -- Open a connection/database
dbx_error --  Report the error message of the latest function call in the module (not just in the connection)
dbx_escape_string --  Escape a string so it can safely be used in an sql-statement
dbx_fetch_row -- Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set
dbx_query -- Send a query and fetch all results (if any)
dbx_sort --  Sort a result from a dbx_query by a custom sort function

dbx_close

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

dbx_close -- Close an open connection/database

Description

bool dbx_close ( object link_identifier )

如果成功则返回 TRUE,失败则返回 FALSE

例子 1. dbx_close() example

<?php
$link = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die("Could not connect");

echo "Connected successfully";
dbx_close($link);
?>

注: Always refer to the module-specific documentation as well.

See also dbx_connect().

dbx_compare

(PHP 4 >= 4.1.0, PHP 5 <= 5.0.4)

dbx_compare -- Compare two rows for sorting purposes

Description

int dbx_compare ( array row_a, array row_b, string column_key [, int flags] )

dbx_compare() returns 0 if the row_a[$column_key] is equal to row_b[$column_key], and 1 or -1 if the former is greater or is smaller than the latter one, respectively, or vice versa if the flag is set to DBX_CMP_DESC. dbx_compare() is a helper function for dbx_sort() to ease the make and use of the custom sorting function.

The flags can be set to specify comparison direction:

  • DBX_CMP_ASC - ascending order

  • DBX_CMP_DESC - descending order

and the preferred comparison type:

  • DBX_CMP_NATIVE - no type conversion

  • DBX_CMP_TEXT - compare items as strings

  • DBX_CMP_NUMBER - compare items numerically

One of the direction and one of the type constant can be combined with bitwise OR operator (|). The default value for the flags parameter is DBX_CMP_ASC | DBX_CMP_NATIVE.

例子 1. dbx_compare() example

<?php
function user_re_order($a, $b) 
{
    $rv = dbx_compare($a, $b, "parentid", DBX_CMP_DESC);
    if (!$rv) {
        $rv = dbx_compare($a, $b, "id", DBX_CMP_NUMBER);
    }
    return $rv;
}

$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, "SELECT id, parentid, description FROM table ORDER BY id");
    // data in $result is now ordered by id

dbx_sort($result, "user_re_order");
    // date in $result is now ordered by parentid (descending), then by id

dbx_close($link);
?>

See also dbx_sort().

dbx_connect

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

dbx_connect -- Open a connection/database

Description

object dbx_connect ( mixed module, string host, string database, string username, string password [, int persistent] )

dbx_connect() returns an object on success, FALSE on error. If a connection has been made but the database could not be selected, the connection is closed and FALSE is returned. The persistent parameter can be set to DBX_PERSISTENT, if so, a persistent connection will be created.

The module parameter can be either a string or a constant, though the latter form is preferred. The possible values are given below, but keep in mind that they only work if the module is actually loaded.

  • DBX_MYSQL or "mysql"

  • DBX_ODBC or "odbc"

  • DBX_PGSQL or "pgsql"

  • DBX_MSSQL or "mssql"

  • DBX_FBSQL or "fbsql" (available from PHP 4.1.0)

  • DBX_SYBASECT or "sybase_ct" (available from PHP 4.2.0)

  • DBX_OCI8 or "oci8" (available from PHP 4.3.0)

  • DBX_SQLITE or "sqlite" (PHP 5)

The host, database, username and password parameters are expected, but not always used depending on the connect functions for the abstracted module.

The returned object has three properties:

database

It is the name of the currently selected database.

handle

It is a valid handle for the connected database, and as such it can be used in module-specific functions (if required).

<?php
$link = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password");
mysql_close($link->handle); // dbx_close($link) would be better here
?>

module

It is used internally by dbx only, and is actually the module number mentioned above.

例子 1. dbx_connect() example

<?php
$link = dbx_connect(DBX_ODBC, "", "db", "username", "password", DBX_PERSISTENT)
    or die("Could not connect");

echo "Connected successfully";
dbx_close($link);
?>

注: Always refer to the module-specific documentation as well.

See also dbx_close().

dbx_error

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

dbx_error --  Report the error message of the latest function call in the module (not just in the connection)

Description

string dbx_error ( object link_identifier )

dbx_error() returns a string containing the error message from the last function call of the abstracted module (e.g. mysql module). If there are multiple connections in the same module, just the last error is given. If there are connections on different modules, the latest error is returned for the module specified by the link_identifier parameter.

例子 1. dbx_error() example

<?php
$link   = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, "select id from non_existing_table");
if ($result == 0) {
    echo dbx_error($link);
}
dbx_close($link);
?>

注: Always refer to the module-specific documentation as well.

The error message for Microsoft SQL Server is actually the result of the mssql_get_last_message() function.

The error message for Oracle (oci8) is not implemented (yet).

dbx_escape_string

(PHP 4 >= 4.3.0, PHP 5 <= 5.0.4)

dbx_escape_string --  Escape a string so it can safely be used in an sql-statement

Description

string dbx_escape_string ( object link_identifier, string text )

dbx_escape_string() returns the text, escaped where necessary (such as quotes, backslashes etc). It returns NULL on error.

例子 1. dbx_escape_string() example

<?php
$link   = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die("Could not connect");

$text = dbx_escape_string($link, "It\'s quoted and backslashed (\\).");
$result = dbx_query($link, "insert into tbl (txt) values ('" . $text . "')");
if ($result == 0) {
    echo dbx_error($link);
}
dbx_close($link);
?>

See also dbx_query().

dbx_fetch_row

(PHP 5 <= 5.0.4)

dbx_fetch_row -- Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set

Description

mixed dbx_fetch_row ( object result_identifier )

dbx_fetch_row() returns a row on success, and 0 on failure (e.g. when no more rows are available). When the DBX_RESULT_UNBUFFERED is not set in the query, dbx_fetch_row() will fail as all rows have already been fetched into the results data property.

As a side effect, the rows property of the query-result object is incremented for each successful call to dbx_fetch_row().

例子 1. How to handle the returned value

<?php
$result = dbx_query($link, 'SELECT id, parentid, description FROM table', DBX_RESULT_UNBUFFERED);

echo "<table>\n";
while ($row = dbx_fetch_row($result)) {
    echo "<tr>\n";
    foreach ($row as $field) {
        echo "<td>$field</td>";
    }
    echo "</tr>\n";
}
echo "</table>\n";
?>

The result_identifier parameter is the result object returned by a call to dbx_query().

The returned object contains the same information as any row would have in the dbx_query result data property, including columns accessible by index or fieldname when the flags for dbx_guery were set that way.

See also dbx_query().

dbx_query

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

dbx_query -- Send a query and fetch all results (if any)

Description

mixed dbx_query ( object link_identifier, string sql_statement [, int flags] )

dbx_query() returns an object or 1 on success, and 0 on failure. The result object is returned only if the query given in sql_statement produces a result set (i.e. a SELECT query, even if the result set is empty).

例子 1. How to handle the returned value

<?php
$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, 'SELECT id, parentid, description FROM table');

if (is_object($result) ) {
    // ... do some stuff here, see detailed examples below ...
    // first, print out field names and types 
    // then, draw a table filled with the returned field values
} else {
    exit("Query failed");
}

dbx_close($link);
?>

The flags parameter is used to control the amount of information that is returned. It may be any combination of the following constants with the bitwise OR operator (|). The DBX_COLNAMES_* flags override the dbx.colnames_case setting from php.ini.

DBX_RESULT_INDEX

It is always set, that is, the returned object has a data property which is a 2 dimensional array indexed numerically. For example, in the expression data[2][3] 2 stands for the row (or record) number and 3 stands for the column (or field) number. The first row and column are indexed at 0.

If DBX_RESULT_ASSOC is also specified, the returning object contains the information related to DBX_RESULT_INFO too, even if it was not specified.

DBX_RESULT_INFO

It provides info about columns, such as field names and field types.

DBX_RESULT_ASSOC

It effects that the field values can be accessed with the respective column names used as keys to the returned object's data property.

Associated results are actually references to the numerically indexed data, so modifying data[0][0] causes that data[0]['field_name_for_first_column'] is modified as well.

DBX_RESULT_UNBUFFERED (PHP 5)

This flag will not create the data property, and the rows property will initially be 0. Use this flag for large datasets, and use dbx_fetch_row() to retrieve the results row by row.

The dbx_fetch_row() function will return rows that are conformant to the flags set with this query. Incidentally, it will also update the rows each time it is called.

DBX_COLNAMES_UNCHANGED (available from PHP 4.3.0)

The case of the returned column names will not be changed.

DBX_COLNAMES_UPPERCASE (available from PHP 4.3.0)

The case of the returned column names will be changed to uppercase.

DBX_COLNAMES_LOWERCASE (available from PHP 4.3.0)

The case of the returned column names will be changed to lowercase.

Note that DBX_RESULT_INDEX is always used, regardless of the actual value of flags parameter. This means that only the following combinations are effective:

  • DBX_RESULT_INDEX

  • DBX_RESULT_INDEX | DBX_RESULT_INFO

  • DBX_RESULT_INDEX | DBX_RESULT_INFO | DBX_RESULT_ASSOC - this is the default, if flags is not specified.

The returned object has four or five properties depending on flags:

handle

It is a valid handle for the connected database, and as such it can be used in module specific functions (if required).

<?php
$result = dbx_query($link, "SELECT id FROM table");
mysql_field_len($result->handle, 0);
?>

cols and rows

These contain the number of columns (or fields) and rows (or records) respectively.

<?php
$result = dbx_query($link, 'SELECT id FROM table');
echo $result->rows; // number of records
echo $result->cols; // number of fields 
?>

info (optional)

It is returned only if either DBX_RESULT_INFO or DBX_RESULT_ASSOC is specified in the flags parameter. It is a 2 dimensional array, that has two named rows (name and type) to retrieve column information.

例子 2. lists each field's name and type

<?php
$result = dbx_query($link, 'SELECT id FROM table',
                     DBX_RESULT_INDEX | DBX_RESULT_INFO);

for ($i = 0; $i < $result->cols; $i++ ) {
    echo $result->info['name'][$i] . "\n";
    echo $result->info['type'][$i] . "\n";  
}
?>
data

This property contains the actual resulting data, possibly associated with column names as well depending on flags. If DBX_RESULT_ASSOC is set, it is possible to use $result->data[2]["field_name"].

例子 3. outputs the content of data property into HTML table

<?php
$result = dbx_query($link, 'SELECT id, parentid, description FROM table');

echo "<table>\n";
foreach ($result->data as $row) {
    echo "<tr>\n";
    foreach ($row as $field) {
        echo "<td>$field</td>";
    }
    echo "</tr>\n";
}
echo "</table>\n";
?>

例子 4. How to handle UNBUFFERED queries

<?php

$result = dbx_query ($link, 'SELECT id, parentid, description FROM table', DBX_RESULT_UNBUFFERED);

echo "<table>\n";
while ($row = dbx_fetch_row($result)) {
    echo "<tr>\n";
    foreach ($row as $field) {
        echo "<td>$field</td>";
    }
    echo "</tr>\n";
}
echo "</table>\n";

?>

注: Always refer to the module-specific documentation as well.

Column names for queries on an Oracle database are returned in lowercase.

See also dbx_escape_string(), dbx_fetch_row() and dbx_connect().

dbx_sort

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

dbx_sort --  Sort a result from a dbx_query by a custom sort function

Description

bool dbx_sort ( object result, string user_compare_function )

如果成功则返回 TRUE,失败则返回 FALSE

注: It is always better to use ORDER BY SQL clause instead of dbx_sort(), if possible.

例子 1. dbx_sort() example

<?php
function user_re_order($a, $b) 
{
    $rv = dbx_compare($a, $b, "parentid", DBX_CMP_DESC);
    if (!$rv) {
        $rv = dbx_compare($a, $b, "id", DBX_CMP_NUMBER);
    }
    return $rv;
}

$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, "SELECT id, parentid, description FROM tbl ORDER BY id");
    // data in $result is now ordered by id

dbx_sort($result, "user_re_order");
    // data in $result is now ordered by parentid (descending), then by id

dbx_close($link);
?>

See also dbx_compare().

XXVII. Direct IO Functions

简介

PHP supports the direct io functions as described in the Posix Standard (Section 6) for performing I/O functions at a lower level than the C-Language stream I/O functions (fopen(), fread(),..). The use of the DIO functions should be considered only when direct control of a device is needed. In all other cases, the standard filesystem functions are more than adequate.

注: 本扩展已被移动到 PECL 库中且自以下版本起不再被绑定到 PHP 中:5.1.0.

This extension is only available on Windows Platforms as of PHP 5.0.0


需求

要编译本扩展模块不需要外部库文件。


安装

To get these functions to work, you have to configure PHP with --enable-dio.


预定义常量

以下常量由本扩展模块定义,因此只有在本扩展模块被编译到 PHP 中,或者在运行时被动态加载后才有效。

c (integer)

F_DUPFD (integer)

F_GETFD (integer)

F_GETFL (integer)

F_GETLK (integer)

F_GETOWN (integer)

F_RDLCK (integer)

F_SETFL (integer)

F_SETLK (integer)

F_SETLKW (integer)

F_SETOWN (integer)

F_UNLCK (integer)

F_WRLCK (integer)

O_APPEND (integer)

O_ASYNC (integer)

O_CREAT (integer)

O_EXCL (integer)

O_NDELAY (integer)

O_NOCTTY (integer)

O_NONBLOCK (integer)

O_RDONLY (integer)

O_RDWR (integer)

O_SYNC (integer)

O_TRUNC (integer)

O_WRONLY (integer)

S_IRGRP (integer)

S_IROTH (integer)

S_IRUSR (integer)

S_IRWXG (integer)

S_IRWXO (integer)

S_IRWXU (integer)

S_IWGRP (integer)

S_IWOTH (integer)

S_IWUSR (integer)

S_IXGRP (integer)

S_IXOTH (integer)

S_IXUSR (integer)


运行时配置

本扩展模块在 php.ini 中未定义任何配置选项。


资源类型

One resource type is defined by this extension: a file descriptor returned by dio_open().

目录
dio_close -- Closes the file descriptor given by fd
dio_fcntl -- Performs a c library fcntl on fd
dio_open --  Opens a new filename with specified permissions of flags and creation permissions of mode
dio_read -- Reads bytes from a file descriptor
dio_seek -- Seeks to pos on fd from whence
dio_stat --  Gets stat information about the file descriptor fd
dio_tcsetattr --  Sets terminal attributes and baud rate for a serial port
dio_truncate --  Truncates file descriptor fd to offset bytes
dio_write --  Writes data to fd with optional truncation at length

dio_close

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

dio_close -- Closes the file descriptor given by fd

说明

void dio_close ( resource fd )

The function dio_close() closes the file descriptor fd.

参数

fd

The file descriptor returned by dio_open().

返回值

无返回值。

范例

例子 1. Closing an open file descriptor

<?php
$fd = dio_open('/dev/ttyS0', O_RDWR);

dio_close($fd);
?>

参见

dio_open()

dio_fcntl

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

dio_fcntl -- Performs a c library fcntl on fd

说明

mixed dio_fcntl ( resource fd, int cmd [, mixed args] )

The dio_fcntl() function performs the operation specified by cmd on the file descriptor fd. Some commands require additional arguments args to be supplied.

注: 本函数未在 Windows 平台下实现。

参数

fd

The file descriptor returned by dio_open().

cmd

Can be one of the following operations:

  • F_SETLK - Lock is set or cleared. If the lock is held by someone else dio_fcntl() returns -1.

  • F_SETLKW - like F_SETLK, but in case the lock is held by someone else, dio_fcntl() waits until the lock is released.

  • F_GETLK - dio_fcntl() returns an associative array (as described above) if someone else prevents lock. If there is no obstruction key "type" will set to F_UNLCK.

  • F_DUPFD - finds the lowest numbered available file descriptor greater than or equal to args and returns them.

  • F_SETFL - Sets the file descriptors flags to the value specified by args, which can be O_APPEND, O_NONBLOCK or O_ASYNC. To use O_ASYNC you will need to use the PCNTL extension.

args

args is an associative array, when cmd is F_SETLK or F_SETLLW, with the following keys:

  • "start" - offset where lock begins

  • "length" - size of locked area. zero means to end of file

  • "wenth" - Where l_start is relative to: can be SEEK_SET, SEEK_END and SEEK_CUR

  • "type" - type of lock: can be F_RDLCK (read lock), F_WRLCK (write lock) or F_UNLCK (unlock)

返回值

Returns the result of the C call.

范例

例子 1. Setting and clearing a lock

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR);

if (dio_fcntl($fd, F_SETLK, Array("type"=>F_WRLCK)) == -1) {
   // the file descriptor appears locked
   echo "The lock can not be cleared. It is held by someone else.";
} else {
   echo "Lock succesfully set/cleared";
}

dio_close($fd);
?>

dio_open

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

dio_open --  Opens a new filename with specified permissions of flags and creation permissions of mode

说明

resource dio_open ( string filename, int flags [, int mode] )

dio_open() opens a file and returns a new file descriptor for it.

参数

filename

The opened file.

flags

The flags parameter can also include any combination of the following flags:

  • O_CREAT - creates the file, if it doesn't already exist.

  • O_EXCL - if both, O_CREAT and O_EXCL are set, dio_open() fails, if the file already exists.

  • O_TRUNC - if the file exists, and its opened for write access, the file will be truncated to zero length.

  • O_APPEND - write operations write data at the end of the file.

  • O_NONBLOCK - sets non blocking mode.

mode

If flags is O_CREAT, mode will set the mode of the file (creation permissions).

  • O_RDONLY - opens the file for read access.

  • O_WRONLY - opens the file for write access.

  • O_RDWR - opens the file for both reading and writing.

返回值

A file descriptor or FALSE on error.

范例

例子 1. Opening a file descriptor

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK);

dio_close($fd);
?>

参见

dio_close()

dio_read

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

dio_read -- Reads bytes from a file descriptor

说明

string dio_read ( resource fd [, int len] )

The function dio_read() reads and returns len bytes from file with descriptor fd.

参数

fd

The file descriptor returned by dio_open().

len

The number of bytes to read. If not specified, dio_read() reads 1K sized block.

返回值

The bytes read from fd.

参见

dio_write()

dio_seek

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

dio_seek -- Seeks to pos on fd from whence

说明

int dio_seek ( resource fd, int pos [, int whence] )

The function dio_seek() is used to change the file position of the given file descriptor.

参数

fd

The file descriptor returned by dio_open().

pos

The new position.

whence

Specifies how the position pos should be interpreted:

  • SEEK_SET (default) - specifies that pos is specified from the beginning of the file.

  • SEEK_CUR - Specifies that pos is a count of characters from the current file position. This count may be positive or negative.

  • SEEK_END - Specifies that pos is a count of characters from the end of the file. A negative count specifies a position within the current extent of the file; a positive count specifies a position past the current end. If you set the position past the current end, and actually write data, you will extend the file with zeros up to that position.

返回值

范例

例子 1. Positioning in a file

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR);

dio_seek($fd, 10, SEEK_SET);
// position is now at 10 characters from the start of the file

dio_seek($fd, -2, SEEK_CUR);
// position is now at 8 characters from the start of the file

dio_seek($fd, -5, SEEK_END);
// position is now at 5 characters from the end of the file

dio_seek($fd, 10, SEEK_END);
// position is now at 10 characters past the end of the file. 
// The 10 characters between the end of the file and the current
// position are filled with zeros.

dio_close($fd);
?>

dio_stat

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

dio_stat --  Gets stat information about the file descriptor fd

说明

array dio_stat ( resource fd )

dio_stat() returns information about the given file descriptor.

参数

fd

The file descriptor returned by dio_open().

返回值

Returns an associative array with the following keys:

  • "device" - device

  • "inode" - inode

  • "mode" - mode

  • "nlink" - number of hard links

  • "uid" - user id

  • "gid" - group id

  • "device_type" - device type (if inode device)

  • "size" - total size in bytes

  • "blocksize" - blocksize

  • "blocks" - number of blocks allocated

  • "atime" - time of last access

  • "mtime" - time of last modification

  • "ctime" - time of last change

On error dio_stat() returns NULL.

dio_tcsetattr

(PHP 4 >= 4.3.0, PHP 5 <= 5.0.4)

dio_tcsetattr --  Sets terminal attributes and baud rate for a serial port

说明

bool dio_tcsetattr ( resource fd, array options )

dio_tcsetattr() sets the terminal attributes and baud rate of the open fd.

注: 本函数未在 Windows 平台下实现。

参数

fd

The file descriptor returned by dio_open().

options

The currently available options are:

  • 'baud' - baud rate of the port - can be 38400,19200,9600,4800,2400,1800, 1200,600,300,200,150,134,110,75 or 50, default value is 9600.

  • 'bits' - data bits - can be 8,7,6 or 5. Default value is 8.

  • 'stop' - stop bits - can be 1 or 2. Default value is 1.

  • 'parity' - can be 0,1 or 2. Default value is 0.

返回值

无返回值。

范例

例子 1. Setting the baud rate on a serial port

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK);

dio_fcntl($fd, F_SETFL, O_SYNC);

dio_tcsetattr($fd, array(
  'baud' => 9600,
  'bits' => 8,
  'stop'  => 1,
  'parity' => 0
)); 

while (1) {

  $data = dio_read($fd, 256);

  if ($data) {
      echo $data;
  }
} 

?>

dio_truncate

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

dio_truncate --  Truncates file descriptor fd to offset bytes

说明

bool dio_truncate ( resource fd, int offset )

dio_truncate() truncates a file to at most offset bytes in size.

If the file previously was larger than this size, the extra data is lost. If the file previously was shorter, it is unspecified whether the file is left unchanged or is extended. In the latter case the extended part reads as zero bytes.

注: 本函数未在 Windows 平台下实现。

参数

fd

The file descriptor returned by dio_open().

offset

The offset in bytes.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

dio_write

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

dio_write --  Writes data to fd with optional truncation at length

说明

int dio_write ( resource fd, string data [, int len] )

dio_write() writes up to len bytes from data to file fd.

参数

fd

The file descriptor returned by dio_open().

data

The written data.

len

The length of data to write in bytes. If not specified, the function writes all the data to the specified file.

返回值

Returns the number of bytes written to fd.

参见

dio_read()

XXVIII. Directory 目录函数


需求

要编译本扩展模块不需要外部库文件。


安装

本函数库作为 PHP 内核的一部分,不用安装就能使用。


运行时配置

本扩展模块在 php.ini 中未定义任何配置选项。


预定义常量

以下常量由本扩展模块定义,因此只有在本扩展模块被编译到 PHP 中,或者在运行时被动态加载后才有效。

DIRECTORY_SEPARATOR (string)

PATH_SEPARATOR (string)

注: PATH_SEPARATOR 是在 PHP 4.3.0-RC2 中引入。


参见

相关函数例如 dirname()is_dir()mkdir()rmdir(),见文件系统函数一章。

目录
chdir -- 改变目录
chroot -- 改变根目录
dir -- directory 类
closedir -- 关闭目录句柄
getcwd -- 取得当前工作目录
opendir -- 打开目录句柄
readdir -- 从目录句柄中读取条目
rewinddir -- 倒回目录句柄
scandir -- 列出指定路径中的文件和目录

chdir

(PHP 3, PHP 4, PHP 5)

chdir -- 改变目录

说明

bool chdir ( string directory )

将 PHP 的当前目录改为 directory

参数

directory

新的当前目录

返回值

如果成功则返回 TRUE,失败则返回 FALSE

范例

例子 1. chdir() 例子

<?php

// current directory
echo getcwd() . "\n";

chdir('public_html');

// current directory
echo getcwd() . "\n";

?>

上例的输出类似于:

/home/vincent
/home/vincent/public_html

注释

注: 安全模式被激活时,PHP 将检查被操作的目录是否和正在执行的脚本有相同的 UID(所有者)。

参见

getcwd()

chroot

(PHP 4 >= 4.0.5, PHP 5)

chroot -- 改变根目录

说明

bool chroot ( string directory )

将当前进程的根目录改变为 directory

本函数仅在系统支持且运行于 CLI,CGI 或嵌入 SAPI 版本时才能正确工作。此外本函数还需要 root 权限。

参数

directory

新目录

返回值

如果成功则返回 TRUE,失败则返回 FALSE

注释

注: 本函数未在 Windows 平台下实现。

dir

(PHP 3, PHP 4, PHP 5)

dir -- directory 类

说明

class dir {

dir ( string directory )

string path

resource handle

string read ( void )

void rewind ( void )

void close ( void )

}

这是个仿冒面向对象的机制来读取一个目录。给定的 directory 被打开。一旦目录被打开,有两个属性可用。handle 属性可以用在其它目录函数例如 readdir()rewinddir()closedir() 中。path 属性被设为被打开的目录路径。有三个方法可用:read,rewind 和 close。

范例

例子 1. dir() 例子

请留意下面例子中检查 dir() 返回值的风格。我们明确地测试返回值是否全等于(值和类型都相同 - 更多信息参见比较运算符FALSE,否则任何目录项的名称求值为 FALSE 的都会导致循环停止。

<?php
$d = dir("/etc/php5");
echo "Handle: " . $d->handle . "\n";
echo "Path: " . $d->path . "\n";
while (false !== ($entry = $d->read())) {
   echo $entry."\n";
}
$d->close();
?>

上例的输出类似于:

Handle: Resource id #2
Path: /etc/php5
.
..
apache
cgi
cli

注释

注: read 方法返回的目录项的顺序依赖于系统。

注: 本函数定义了内部类 Directory,意味着不能再用同样的名字定义用户自己的类。PHP 预定义类的完整列表见预定义类一节。

closedir

(PHP 3, PHP 4, PHP 5)

closedir -- 关闭目录句柄

说明

void closedir ( resource dir_handle )

关闭由 dir_handle 指定的目录流。流必须之前被 opendir() 所打开。

参数

dir_handle

目录句柄的 resource,之前由 opendir() 所打开的。

范例

例子 1. closedir() 例子

<?php
$dir = "/etc/php5/";

// Open a known directory, read directory into variable and then close
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        $directory = readdir($dh);
        closedir($dh);
    }
}
?>

getcwd

(PHP 4, PHP 5)

getcwd -- 取得当前工作目录

说明

string getcwd ( void )

取得当前工作目录。

返回值

成功则返回当前工作目录,失败返回 FALSE

在某些 Unix 的变种下,如果任何父目录没有设定可读或搜索模式,即使当前目录设定了,getcwd() 还是会返回 FALSE。有关模式与权限的更多信息见 chmod()

范例

例子 1. getcwd() 例子

<?php

// current directory
echo getcwd() . "\n";

chdir('cvs');

// current directory
echo getcwd() . "\n";

?>

上例的输出类似于:

/home/didou
/home/didou/cvs

opendir

(PHP 3, PHP 4, PHP 5)

opendir -- 打开目录句柄

说明

resource opendir ( string path [, resource context] )

打开一个目录句柄,可用于之后的 closedir()readdir()rewinddir() 调用中。

参数

path

要打开的目录路径

context

context 参数的说明见手册中的 Streams API 一章。

返回值

如果成功则返回目录句柄的 resource,失败则返回 FALSE

如果 path 不是一个合法的目录或者因为权限限制或文件系统错误而不能打开目录,opendir() 返回 FALSE 并产生一个 E_WARNING 级别的 PHP 错误信息。可以在 opendir() 前面加上“@”符号来抑制错误信息的输出。

更新日志

版本说明
5.0.0 path 支持 ftp:// URL wrapper
4.3.0 path 可以是任何支持目录列表的 URL,不过在 PHP 4 中只有 file:// URL wrapper 支持此功能

范例

例子 1. opendir() 例子

<?php
$dir = "/etc/php5/";

// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
        }
        closedir($dh);
    }
}
?>

上例的输出类似于:

filename: . : filetype: dir
filename: .. : filetype: dir
filename: apache : filetype: dir
filename: cgi : filetype: dir
filename: cli : filetype: dir

readdir

(PHP 3, PHP 4, PHP 5)

readdir -- 从目录句柄中读取条目

说明

string readdir ( resource dir_handle )

返回目录中下一个文件的文件名。文件名以在文件系统中的排序返回。

参数

dir_handle

目录句柄的 resource,之前由 opendir() 打开

返回值

成功则返回文件名,失败返回 FALSE

范例

例子 1. 列出目录中的所有文件

请留意下面例子中检查 readdir() 返回值的风格。这里明确地测试返回值是否全等于(值和类型都相同――更多信息参见比较运算符FALSE,否则任何目录项的名称求值为 FALSE 的都会导致循环停止(例如一个目录名为“0”)。

<?php
// 注意在 4.0.0-RC2 之前不存在 !== 运算符

if ($handle = opendir('/path/to/files')) {
    echo "Directory handle: $handle\n";
    echo "Files:\n";

    /* 这是正确地遍历目录方法 */
    while (false !== ($file = readdir($handle))) {
        echo "$file\n";
    }

    /* 这是错误地遍历目录的方法 */
    while ($file = readdir($handle)) {
        echo "$file\n";
    }

    closedir($handle);
}
?>

例子 2. 列出当前目录的所有文件并去掉 ...

<?php
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            echo "$file\n";
        }
    }
    closedir($handle);
}
?>

rewinddir

(PHP 3, PHP 4, PHP 5)

rewinddir -- 倒回目录句柄

说明

void rewinddir ( resource dir_handle )

dir_handle 指定的目录流重置到目录的开头。

参数

dir_handle

目录句柄的 resource,之前由 opendir() 打开

scandir

(PHP 5)

scandir -- 列出指定路径中的文件和目录

说明

array scandir ( string directory [, int sorting_order [, resource context]] )

返回一个 array,包含有 directory 中的文件和目录。

参数

directory

要被浏览的目录

sorting_order

默认的排序顺序是按字母升序排列。如果使用了可选参数 sorting_order(设为 1),则排序顺序是按字母降序排列。

context

context 参数的说明见手册中的 Streams API 一章。

返回值

成功则返回包含有文件名的 array,如果失败则返回 FALSE。如果 directory 不是个目录,则返回布尔值 FALSE 并生成一条 E_WARNING 级的错误。

范例

例子 1. 一个简单的 scandir() 例子

<?php
$dir    = '/tmp';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);

print_r($files1);
print_r($files2);
?>

上例的输出类似于:

Array
(
    [0] => .
    [1] => ..
    [2] => bar.php
    [3] => foo.txt
    [4] => somedir
)
Array
(
    [0] => somedir
    [1] => foo.txt
    [2] => bar.php
    [3] => ..
    [4] => .
)

例子 2. scandir() 在 PHP 4 中的实现

<?php
$dir = "/tmp";
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    $files[] = $filename;
}

sort($files);

print_r($files);

rsort($files);

print_r($files);

?>

上例的输出类似于:

Array
(
    [0] => .
    [1] => ..
    [2] => bar.php
    [3] => foo.txt
    [4] => somedir
)
Array
(
    [0] => somedir
    [1] => foo.txt
    [2] => bar.php
    [3] => ..
    [4] => .
)

注释

提示: 如果“fopen wrappers”已经被激活,则在本函数中可以把 URL 作为文件名来使用。请参阅 fopen() 函数来获取怎样指定文件名的详细信息以及支持 URL 封装协议的列表:附录 L

XXIX. DOM Functions

简介

The DOM extension is the replacement for the DOM XML extension from PHP 4. The extension still contains many old functions, but they should no longer be used. In particular, functions that are not object-oriented should be avoided.

The extension allows you to operate on an XML document with the DOM API.


安装

本函数库作为 PHP 内核的一部分,不用安装就能使用。


预定义类

The API of the module follows the DOM Level 2 standard as closely as possible. Consequently, the API is fully object-oriented. It is a good idea to have the DOM standard available when using this module.

This module defines a number of classes, which are explained in the following tables. Classes with an equivalent in the DOM standard are named DOMxxx.


DOMAttr

Extends DOMNode. The DOMAttr interface represents an attribute in an DOMElement object.


构造函数


方法


属性

表格 1.

NameTypeRead-onlyDescription
namestringyesThe name of the attribute
ownerElementDOMElementyesThe element which contains the attribute
schemaTypeInfoboolyesNot implemented yet, always return NULL
specifiedboolyesNot implemented yet, always return NULL
valuestringnoThe value of the attribute

DOMCharacterData

Extends DOMNode.


方法


属性

表格 2.

NameTypeRead-onlyDescription
datastringnoThe contents of the node
lengthintyesThe length of the contents

DOMComment

Extends DOMCharacterData.


构造函数


DOMDocument

Extends DOMNode.


构造函数


方法


属性

表格 3.

NameTypeRead-onlyDescription
actualEncodingstringyes 
configDOMConfigurationyes 
doctypeDOMDocumentTypeyes The Document Type Declaration associated with this document.
documentElementDOMElementyes This is a convenience attribute that allows direct access to the child node that is the document element of the document.
documentURIstringno The location of the document or NULL if undefined.
encodingstringno 
formatOutputboolno 
implementationDOMImplementationyes The DOMImplementation object that handles this document.
preserveWhiteSpaceboolnoDo not remove redundant white space. Default to TRUE.
recoverboolno 
resolveExternalsboolno Set it to TRUE to load external entities from a doctype declaration. This is useful for including character entities in your XML document.
standaloneboolno 
strictErrorCheckingboolnoThrows DOMException on errors. Default to TRUE.
substituteEntitiesboolno 
validateOnParseboolnoLoads and validates against the DTD. Default to FALSE.
versionstringno 
xmlEncodingstringyes An attribute specifying, as part of the XML declaration, the encoding of this document. This is NULL when unspecified or when it is not known, such as when the Document was created in memory.
xmlStandaloneboolno An attribute specifying, as part of the XML declaration, whether this document is standalone. This is FALSE when unspecified.
xmlVersionstringno An attribute specifying, as part of the XML declaration, the version number of this document. If there is no declaration and if this document supports the "XML" feature, the value is "1.0".

DOMDocumentType

Extends DOMNode

Each DOMDocument has a doctype attribute whose value is either NULL or a DOMDocumentType object.


属性

表格 4.

NameTypeRead-onlyDescription
publicIdstringyesThe public identifier of the external subset.
systemIdstringyesThe system identifier of the external subset. This may be an absolute URI or not.
namestringyesThe name of DTD; i.e., the name immediately following the DOCTYPE keyword.
entitiesDOMNamedNodeMapyes A DOMNamedNodeMap containing the general entities, both external and internal, declared in the DTD.
notationsDOMNamedNodeMapyes A DOMNamedNodeMap containing the notations declared in the DTD.
internalSubsetstringyes The internal subset as a string, or null if there is none. This is does not contain the delimiting square brackets.

DOMElement

Extends DOMNode.


构造函数


方法


属性

表格 5.

NameTypeRead-onlyDescription
schemaTypeInfoboolyesNot implemented yet, always return NULL
tagNamestringyesThe element name

DOMEntity

Extends DOMNode

This interface represents a known entity, either parsed or unparsed, in an XML document.


属性

表格 6.

NameTypeRead-onlyDescription
publicIdstringyes The public identifier associated with the entity if specified, and NULL otherwise.
systemIdstringyes The system identifier associated with the entity if specified, and NULL otherwise. This may be an absolute URI or not.
notationNamestringyes For unparsed entities, the name of the notation for the entity. For parsed entities, this is NULL.
actualEncodingstringno An attribute specifying the encoding used for this entity at the time of parsing, when it is an external parsed entity. This is NULL if it an entity from the internal subset or if it is not known.
encodingstringyes An attribute specifying, as part of the text declaration, the encoding of this entity, when it is an external parsed entity. This is NULL otherwise.
versionstringyes An attribute specifying, as part of the text declaration, the version number of this entity, when it is an external parsed entity. This is NULL otherwise.

DOMEntityReference

Extends DOMNode.


构造函数


DOMException

DOM operations raise exceptions under particular circumstances, i.e., when an operation is impossible to perform for logical reasons.

See also µÚ 20 章.


属性

表格 7.

NameTypeRead-onlyDescription
codeintyesAn integer indicating the type of error generated

DOMImplementation

The DOMImplementation interface provides a number of methods for performing operations that are independent of any particular instance of the document object model.


构造函数


方法


DOMNode

方法


属性

表格 8.

NameTypeRead-onlyDescription
nodeNamestringyesReturns the more accurate name for the current node type
nodeValuestringnoThe value of this node, depending on its type.
nodeTypeintyesGets the type of the node. One of the predefined XML_xxx_NODE constants
parentNodeDOMNodeyesThe parent of this node.
childNodesDOMNodeListyes A DOMNodeList that contains all children of this node. If there are no children, this is an empty DOMNodeList.
firstChildDOMNodeyes The first child of this node. If there is no such node, this returns NULL.
lastChildDOMNodeyes The last child of this node. If there is no such node, this returns NULL.
previousSiblingDOMNodeyes The node immediately preceding this node. If there is no such node, this returns NULL.
nextSiblingDOMNodeyes The node immediately following this node. If there is no such node, this returns NULL.
attributesDOMNamedNodeMapyes A DOMNamedNodeMap containing the attributes of this node (if it is a DOMElement) or NULL otherwise.
ownerDocumentDOMDocumentyes The DOMDocument object associated with this node.
namespaceURIstringyes The namespace URI of this node, or NULL if it is unspecified.
prefixstringno The namespace prefix of this node, or NULL if it is unspecified.
localNamestringyes Returns the local part of the qualified name of this node.
baseURIstringyes The absolute base URI of this node or NULL if the implementation wasn't able to obtain an absolute URI.
textContentstringno This attribute returns the text content of this node and its descendants.

DOMNodeList


方法


属性

表格 9.

NameTypeRead-onlyDescription
lengthintyes The number of nodes in the list. The range of valid child node indices is 0 to length - 1 inclusive.

DOMNotation

Extends DOMNode


属性

表格 10.

NameTypeRead-onlyDescription
publicIdstringyes 
systemIdstringyes 

DOMProcessingInstruction

Extends DOMNode.


构造函数


属性

表格 11.

NameTypeRead-onlyDescription
targetstringyes 
datastringno 

DOMText

Extends DOMCharacterData.


构造函数


方法


属性

表格 12.

NameTypeRead-onlyDescription
wholeTextstringyes 

DOMXPath


构造函数


方法


属性

表格 13.

NameTypeRead-onlyDescription
documentDOMDocument  

范例

Many examples in this reference require an XML file. We will use book.xml that contains the following:

例子 1. chapter.xml

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
 "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd" [
]>
<book id="listing">
 <title>My lists</title>
 <chapter id="books">
  <title>My books</title>
  <para>
   <informaltable>
    <tgroup cols="4">
     <thead>
      <row>
       <entry>Title</entry>
       <entry>Author</entry>
       <entry>Language</entry>
       <entry>ISBN</entry>
      </row>
     </thead>
     <tbody>
      <row>
       <entry>The Grapes of Wrath</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>0140186409</entry>
      </row>
      <row>
       <entry>The Pearl</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>014017737X</entry>
      </row>
      <row>
       <entry>Samarcande</entry>
       <entry>Amine Maalouf</entry>
       <entry>fr</entry>
       <entry>2253051209</entry>
      </row>
      <!-- TODO: I have a lot of remaining books to add.. -->
     </tbody>
    </tgroup>
   </informaltable>
  </para>
 </chapter>
</book>


预定义常量

以下常量由本扩展模块定义,因此只有在本扩展模块被编译到 PHP 中,或者在运行时被动态加载后才有效。

表格 14. XML constants

ConstantValueDescription
XML_ELEMENT_NODE (integer) 1Node is a DOMElement
XML_ATTRIBUTE_NODE (integer) 2Node is a DOMAttr
XML_TEXT_NODE (integer) 3Node is a DOMText
XML_CDATA_SECTION_NODE (integer) 4Node is a DOMCharacterData
XML_ENTITY_REF_NODE (integer) 5Node is a DOMEntityReference
XML_ENTITY_NODE (integer) 6Node is a DOMEntity
XML_PI_NODE (integer) 7Node is a DOMProcessingInstruction
XML_COMMENT_NODE (integer) 8Node is a DOMComment
XML_DOCUMENT_NODE (integer) 9Node is a DOMDocument
XML_DOCUMENT_TYPE_NODE (integer) 10Node is a DOMDocumentType
XML_DOCUMENT_FRAG_NODE (integer) 11Node is a DOMDocumentFragment
XML_NOTATION_NODE (integer) 12Node is a DOMNotation
XML_HTML_DOCUMENT_NODE (integer) 13 
XML_DTD_NODE (integer) 14 
XML_ELEMENT_DECL_NODE (integer) 15 
XML_ATTRIBUTE_DECL_NODE (integer) 16 
XML_ENTITY_DECL_NODE (integer) 17 
XML_NAMESPACE_DECL_NODE (integer) 18 
XML_ATTRIBUTE_CDATA (integer) 1 
XML_ATTRIBUTE_ID (integer) 2 
XML_ATTRIBUTE_IDREF (integer) 3 
XML_ATTRIBUTE_IDREFS (integer) 4 
XML_ATTRIBUTE_ENTITY (integer) 5 
XML_ATTRIBUTE_NMTOKEN (integer) 7 
XML_ATTRIBUTE_NMTOKENS (integer) 8 
XML_ATTRIBUTE_ENUMERATION (integer) 9 
XML_ATTRIBUTE_NOTATION (integer) 10 

表格 15. DOMException constants

ConstantValueDescription
DOM_INDEX_SIZE_ERR (integer) 1 If index or size is negative, or greater than the allowed value.
DOMSTRING_SIZE_ERR (integer) 2 If the specified range of text does not fit into a DOMString.
DOM_HIERARCHY_REQUEST_ERR (integer) 3If any node is inserted somewhere it doesn't belong
DOM_WRONG_DOCUMENT_ERR (integer) 4 If a node is used in a different document than the one that created it.
DOM_INVALID_CHARACTER_ERR (integer) 5 If an invalid or illegal character is specified, such as in a name.
DOM_NO_DATA_ALLOWED_ERR (integer) 6 If data is specified for a node which does not support data.
DOM_NO_MODIFICATION_ALLOWED_ERR (integer) 7 If an attempt is made to modify an object where modifications are not allowed.
DOM_NOT_FOUND_ERR (integer) 8 If an attempt is made to reference a node in a context where it does not exist.
DOM_NOT_SUPPORTED_ERR (integer) 9 If the implementation does not support the requested type of object or operation.
DOM_INUSE_ATTRIBUTE_ERR (integer) 10 If an attempt is made to add an attribute that is already in use elsewhere.
DOM_INVALID_STATE_ERR (integer) 11 If an attempt is made to use an object that is not, or is no longer, usable.
DOM_SYNTAX_ERR (integer) 12If an invalid or illegal string is specified.
DOM_INVALID_MODIFICATION_ERR (integer) 13If an attempt is made to modify the type of the underlying object.
DOM_NAMESPACE_ERR (integer) 14 If an attempt is made to create or change an object in a way which is incorrect with regard to namespaces.
DOM_INVALID_ACCESS_ERR (integer) 15 If a parameter or an operation is not supported by the underlying object.
DOM_VALIDATION_ERR (integer) 16 If a call to a method such as insertBefore or removeChild would make the Node invalid with respect to "partial validity", this exception would be raised and the operation would not be done.
目录
DOMAttr->__construct() --  Creates a new DOMAttr object
DOMAttr->isId() --  Checks if attribute is a defined ID
DOMCharacterData->appendData() --  Append the string to the end of the character data of the node
DOMCharacterData->deleteData() --  Remove a range of characters from the node
DOMCharacterData->insertData() --  Insert a string at the specified 16-bit unit offset
DOMCharacterData->replaceData() --  Replace a substring within the DOMCharacterData node
DOMCharacterData->substringData() --  Extracts a range of data from the node
DOMComment->__construct() --  Creates a new DOMComment object
DOMDocument->__construct() --  Creates a new DOMDocument object
DOMDocument->createAttribute() -- Create new attribute
DOMDocument->createAttributeNS() --  Create new attribute node with an associated namespace
DOMDocument->createCDATASection() -- Create new cdata node
DOMDocument->createComment() -- Create new comment node
DOMDocument->createDocumentFragment() -- Create new document fragment
DOMDocument->createElement() -- Create new element node
DOMDocument->createElementNS() --  Create new element node with an associated namespace
DOMDocument->createEntityReference() -- Create new entity reference node
DOMDocument->createProcessingInstruction() -- Creates new PI node
DOMDocument->createTextNode() -- Create new text node
DOMDocument->getElementById() -- Searches for an element with a certain id
DOMDocument->getElementsByTagName() -- Searches for all elements with given tag name
DOMDocument->getElementsByTagNameNS() --  Searches for all elements with given tag name in specified namespace
DOMDocument->importNode() -- Import node into current document
DOMDocument->load() --  Load XML from a file
DOMDocument->loadHTML() --  Load HTML from a string
DOMDocument->loadHTMLFile() --  Load HTML from a file
DOMDocument->loadXML() --  Load XML from a string
DOMDocument->normalize() --  Normalizes the document
DOMDocument->relaxNGValidate() --  Performs relaxNG validation on the document
DOMDocument->relaxNGValidateSource() --  Performs relaxNG validation on the document
DOMDocument->save() --  Dumps the internal XML tree back into a file
DOMDocument->saveHTML() --  Dumps the internal document into a string using HTML formatting
DOMDocument->saveHTMLFile() --  Dumps the internal document into a file using HTML formatting
DOMDocument->saveXML() --  Dumps the internal XML tree back into a string
DOMDocument->schemaValidate() --  Validates a document based on a schema
DOMDocument->schemaValidateSource() --  Validates a document based on a schema
DOMDocument->validate() --  Validates the document based on its DTD
DOMDocument->xinclude() --  Substitutes XIncludes in a DOMDocument Object
DOMElement->__construct() --  Creates a new DOMElement object
DOMElement->getAttribute() -- Returns value of attribute
DOMElement->getAttributeNode() -- Returns attribute node
DOMElement->getAttributeNodeNS() --  Returns attribute node
DOMElement->getAttributeNS() -- Returns value of attribute
DOMElement->getElementsByTagName() -- Gets elements by tagname
DOMElement->getElementsByTagNameNS() -- Get elements by namespaceURI and localName
DOMElement->hasAttribute() -- Checks to see if attribute exists
DOMElement->hasAttributeNS() --  Checks to see if attribute exists
DOMElement->removeAttribute() -- Removes attribute
DOMElement->removeAttributeNode() -- Removes attribute
DOMElement->removeAttributeNS() -- Removes attribute
DOMElement->setAttribute() -- Adds new attribute
DOMElement->setAttributeNode() -- Adds new attribute node to element
DOMElement->setAttributeNodeNS() -- Adds new attribute node to element
DOMElement->setAttributeNS() -- Adds new attribute
DOMAttr->__construct() --  Creates a new DOMEntityReference object
DOMImplementation->__construct() --  Creates a new DOMImplementation object
DOMImplementation->createDocument() --  Creates a DOMDocument object of the specified type with its document element
DOMImplementation->createDocumentType() --  Creates an empty DOMDocumentType object
DOMImplementation->hasFeature() --  Test if the DOM implementation implements a specific feature
DOMNamedNodeMap->getNamedItem() --  Retrieves a node specified by name
DOMNamedNodeMap->getNamedItemNS() --  Retrieves a node specified by local name and namespace URI
DOMNamedNodeMap->item() -- Retrieves a node specified by index
DOMNode->appendChild() --  Adds new child at the end of the children
DOMNode->cloneNode() --  Clones a node
DOMNode->hasAttributes() --  Checks if node has attributes
DOMNode->hasChildNodes() --  Checks if node has children
DOMNode->insertBefore() --  Adds a new child before a reference node
DOMNode->isSameNode() --  Indicates if two nodes are the same node
DOMNode->isSupported() --  Checks if feature is supported for specified version
DOMNode->lookupNamespaceURI() --  Gets the namespace URI of the node based on the prefix
DOMNode->lookupPrefix() --  Gets the namespace prefix of the node based on the namespace URI
DOMNode->normalize() --  Normalizes the node
DOMNode->removeChild() --  Removes child from list of children
DOMNode->replaceChild() --  Replaces a child
DOMNodelist->item() --  Retrieves a node specified by index
DOMProcessingInstruction->__construct() --  Creates a new DOMProcessingInstruction object
DOMText->__construct() --  Creates a new DOMText object
DOMText->isWhitespaceInElementContent() --  Indicates whether this text node contains whitespace
DOMText->splitText() --  Breaks this node into two nodes at the specified offset
DOMXPath->__construct() --  Creates a new DOMXPath object
DOMXPath->evaluate() --  Evaluates the given XPath expression and returns a typed result if possible.
DOMXPath->query() --  Evaluates the given XPath expression
DOMXPath->registerNamespace() --  Registers the namespace with the DOMXPath object
dom_import_simplexml --  Gets a DOMElement object from a SimpleXMLElement object

DOMAttr->__construct()

(no version information, might be only in CVS)

DOMAttr->__construct() --  Creates a new DOMAttr object

说明

class DOMAttr {

__construct ( string name [, string value] )

}

Creates a new DOMAttr object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument->createAttribute().

参数

name

The tag name of the attribute.

value

The value of the attribute.

范例

例子 1. Creating a new DOMAttr

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$attr = $element->setAttributeNode(new DOMAttr('attr', 'attrvalue'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root attr="attrvalue" /> */

?>

DOMAttr->isId()

(no version information, might be only in CVS)

DOMAttr->isId() --  Checks if attribute is a defined ID

说明

class DOMAttr {

bool isId ( void )

}

This function checks if the attribute is a defined ID.

According to the DOM standard this requires a DTD which defines the attribute ID to be of type ID. You need to validate your document with DOMDocument->validate() or DOMDocument::validateOnParse before using this function.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

范例

例子 1. DOMAttr->isId() Example

<?php

$doc = new DomDocument;

// We need to validate our document before refering to the id
$doc->validateOnParse = true;
$doc->Load('book.xml');

// We retrieve the attribute named id of the chapter element
$attr = $doc->getElementsByTagName('chapter')->item(0)->getAttributeNode('id');

var_dump($attr->isId()); // bool(true)

?>

DOMCharacterData->appendData()

(no version information, might be only in CVS)

DOMCharacterData->appendData() --  Append the string to the end of the character data of the node

说明

class DOMCharacterData {

void appendData ( string data )

}

Append the string data to the end of the character data of the node.

参数

data

The string to append.

返回值

无返回值。

DOMCharacterData->deleteData()

(no version information, might be only in CVS)

DOMCharacterData->deleteData() --  Remove a range of characters from the node

说明

class DOMCharacterData {

void deleteData ( int offset, int count )

}

Deletes count characters starting from position offset.

参数

offset

The offset from which to start removing.

count

The number of characters to delete. If the sum of offset and count exceeds the length, then all characters to the end of the data are deleted.

返回值

无返回值。

异常

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data, or if count is negative.

DOMCharacterData->insertData()

(no version information, might be only in CVS)

DOMCharacterData->insertData() --  Insert a string at the specified 16-bit unit offset

说明

class DOMCharacterData {

void insertData ( int offset, string data )

}

Inserts string data at position offset.

参数

offset

The character offset at which to insert.

data

The string to insert.

返回值

无返回值。

异常

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data.

DOMCharacterData->replaceData()

(no version information, might be only in CVS)

DOMCharacterData->replaceData() --  Replace a substring within the DOMCharacterData node

说明

class DOMCharacterData {

void replaceData ( int offset, int count, string data )

}

Replace count characters starting from position offset with data.

参数

offset

The offset from which to start replacing.

count

The number of characters to replace. If the sum of offset and count exceeds the length, then all characters to the end of the data are replaced.

data

The string with which the range must be replaced.

返回值

无返回值。

异常

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data, or if count is negative.

DOMCharacterData->substringData()

(no version information, might be only in CVS)

DOMCharacterData->substringData() --  Extracts a range of data from the node

说明

class DOMCharacterData {

string substringData ( int offset, int count )

}

Returns the specified substring.

参数

offset

Start offset of substring to extract.

count

The number of characters to extract.

返回值

The specified substring. If the sum of offset and count exceeds the length, then all 16-bit units to the end of the data are returned.

异常

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data, or if count is negative.

DOMComment->__construct()

(no version information, might be only in CVS)

DOMComment->__construct() --  Creates a new DOMComment object

说明

class DOMComment {

__construct ( [string value] )

}

Creates a new DOMComment object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument->createComment().

参数

value

The value of the comment.

范例

例子 1. Creating a new DOMComment

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$comment = $element->appendChild(new DOMComment('root comment'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root><!--root comment--></root> */

?>

DOMDocument->__construct()

(no version information, might be only in CVS)

DOMDocument->__construct() --  Creates a new DOMDocument object

说明

class DOMDocument {

__construct ( [string version [, string encoding]] )

}

Creates a new DOMDocument object.

参数

version

The version number of the document as part of the XML declaration.

encoding

The encoding of the document as part of the XML declaration.

范例

例子 1. Creating a new DOMDocument

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');

echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?> */

?>

DOMDocument->createAttribute()

(no version information, might be only in CVS)

DOMDocument->createAttribute() -- Create new attribute

说明

class DOMDocument {

DOMAttr createAttribute ( string name )

}

This function creates a new instance of class DOMAttr. 本节点不会出现在文档中,除非是用例如 DOMNode->appendChild() 函数来将其插入。

参数

name

The name of the attribute.

返回值

The new DOMAttr or FALSE if an error occured.

异常

DOM_INVALID_CHARACTER_ERR

Raised if name contains an invalid character.

DOMDocument->createAttributeNS()

(no version information, might be only in CVS)

DOMDocument->createAttributeNS() --  Create new attribute node with an associated namespace

说明

class DOMDocument {

DOMAttr createAttributeNS ( string namespaceURI, string qualifiedName )

}

This function creates a new instance of class DOMAttr. 本节点不会出现在文档中,除非是用例如 DOMNode->appendChild() 函数来将其插入。

参数

namespaceURI

The URI of the namespace.

qualifiedName

The tag name and prefix of the attribute, as prefix:tagname.

返回值

The new DOMAttr or FALSE if an error occured.

异常

DOM_INVALID_CHARACTER_ERR

Raised if qualifiedName contains an invalid character.

DOM_NAMESPACE_ERR

Raised if qualifiedName is a malformed qualified name, or if qualifiedName has a prefix and namespaceURI is NULL.

DOMDocument->createCDATASection()

(no version information, might be only in CVS)

DOMDocument->createCDATASection() -- Create new cdata node

说明

class DOMDocument {

DOMCDATASection createCDATASection ( string data )

}

This function creates a new instance of class DOMCDATASection. 本节点不会出现在文档中,除非是用例如 DOMNode->appendChild() 函数来将其插入。

参数

data

The content of the cdata.

返回值

The new DOMCDATASection or FALSE if an error occured.

DOMDocument->createComment()

(no version information, might be only in CVS)

DOMDocument->createComment() -- Create new comment node

说明

class DOMDocument {

DOMComment createComment ( string data )

}

This function creates a new instance of class DOMComment. 本节点不会出现在文档中,除非是用例如 DOMNode->appendChild() 函数来将其插入。

参数

data

The content of the comment.

返回值

The new DOMComment or FALSE if an error occured.

DOMDocument->createDocumentFragment()

(no version information, might be only in CVS)

DOMDocument->createDocumentFragment() -- Create new document fragment

说明

class DOMDocument {

DOMDocumentFragment createDocumentFragment ( void )

}

This function creates a new instance of class DOMDocumentFragment. 本节点不会出现在文档中,除非是用例如 DOMNode->appendChild() 函数来将其插入。

返回值

The new DOMDocumentFragment or FALSE if an error occured.

DOMDocument->createElement()

(no version information, might be only in CVS)

DOMDocument->createElement() -- Create new element node

说明

class DOMDocument {

DOMElement createElement ( string name [, string value] )

}

This function creates a new instance of class DOMElement. 本节点不会出现在文档中,除非是用例如 DOMNode->appendChild() 函数来将其插入。

参数

name

The tag name of the element.

value

The value of the element. By default, an empty element will be created. You can also set the value later with DOMElement->nodeValue.

返回值

Returns a new instance of class DOMElement or FALSE if an error occured.

异常

DOM_INVALID_CHARACTER_ERR

Raised if name contains an invalid character.

范例

例子 1. Creating a new element and inserting it as root

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');

$element = $dom->createElement('test', 'This is the root element!');

// We insert the new element as root (child of the document)
$dom->appendChild($element);

echo $dom->saveXML();
?>

上例将输出:

<?xml version="1.0" encoding="iso-8859-1"?>
<test>This is the root element!</test>

DOMDocument->createElementNS()

(no version information, might be only in CVS)

DOMDocument->createElementNS() --  Create new element node with an associated namespace

说明

class DOMDocument {

DOMElement createElementNS ( string namespaceURI, string qualifiedName [, string value] )

}

This function creates a new element node with an associated namespace. 本节点不会出现在文档中,除非是用例如 DOMNode->appendChild() 函数来将其插入。

参数

namespaceURI

The URI of the namespace.

qualifiedName

The qualified name of the element, as prefix:tagname.

value

The value of the element. By default, an empty element will be created. You can also set the value later with DOMElement->nodeValue.

返回值

The new DOMElement or FALSE if an error occured.

异常

DOM_INVALID_CHARACTER_ERR

Raised if qualifiedName contains an invalid character.

DOM_NAMESPACE_ERR

Raised if qualifiedName is a maformed qualified name.

范例

例子 1. Creating a new element and inserting it as root

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');

$element = $dom->createElementNS('http://www.example.com/XFoo', 'xfoo:test', 'This is the root element!');

// We insert the new element as root (child of the document)
$dom->appendChild($element);

echo $dom->saveXML();
?>

上例将输出:

<?xml version="1.0" encoding="iso-8859-1"?>
<xfoo:test xmlns:xfoo="http://www.example.com/XFoo">This is the root element!</xfoo:test>

DOMDocument->createEntityReference()

(no version information, might be only in CVS)

DOMDocument->createEntityReference() -- Create new entity reference node

说明

class DOMDocument {

DOMEntityReference createEntityReference ( string name )

}

This function creates a new instance of class DOMEntityReference. 本节点不会出现在文档中,除非是用例如 DOMNode->appendChild() 函数来将其插入。

参数

name

The content of the entity reference, e.g. the entity reference minus the leading & and the trailing ; characters.

返回值

The new DOMEntityReference or FALSE if an error occured.

异常

DOM_INVALID_CHARACTER_ERR

Raised if name contains an invalid character.

DOMDocument->createProcessingInstruction()

(no version information, might be only in CVS)

DOMDocument->createProcessingInstruction() -- Creates new PI node

说明

class DOMDocument {

DOMProcessingInstruction createProcessingInstruction ( string target [, string data] )

}

This function creates a new instance of class DOMProcessingInstruction. 本节点不会出现在文档中,除非是用例如 DOMNode->appendChild() 函数来将其插入。

参数

target

The target of the processing instruction.

data

The content of the processing instruction.

返回值

The new DOMProcessingInstruction or FALSE if an error occured.

异常

DOM_INVALID_CHARACTER_ERR

Raised if target contains an invalid character.

DOMDocument->createTextNode()

(no version information, might be only in CVS)

DOMDocument->createTextNode() -- Create new text node

说明

class DOMDocument {

DOMText createTextNode ( string content )

}

This function creates a new instance of class DOMText. 本节点不会出现在文档中,除非是用例如 DOMNode->appendChild() 函数来将其插入。

参数

content

The content of the text.

返回值

The new DOMText or FALSE if an error occured.

DOMDocument->getElementById()

(no version information, might be only in CVS)

DOMDocument->getElementById() -- Searches for an element with a certain id

说明

class DOMDocument {

DOMElement getElementById ( string elementId )

}

This function is similar to DOMDocument->getElementsByTagName() but searches for an element with a given id.

According to the DOM standard this requires a DTD which defines the attribute ID to be of type ID. You need to validate your document with DOMDocument->validate() or DOMDocument->validateOnParse before using this function.

参数

elementId

The unique id value for an element.

返回值

Returns the DOMElement or NULL if the element is not found.

范例

例子 1. DOMDocument->getElementById() Example

<?php

$doc = new DomDocument;

// We need to validate our document before refering to the id
$doc->validateOnParse = true;
$doc->Load('book.xml');

echo "The element whose id is books is: " . $doc->getElementById('books')->tagName . "\n";

?>

上例将输出:

The element whose id is books is: chapter

DOMDocument->getElementsByTagName()

(no version information, might be only in CVS)

DOMDocument->getElementsByTagName() -- Searches for all elements with given tag name

说明

class DOMDocument {

DOMNodeList getElementsByTagName ( string name )

}

This function returns a new instance of class DOMNodeList containing the elements with a given tag name.

参数

name

The name of the tag to match on. The special value * matches all tags.

返回值

A new DOMNodeList object containing all the matched elements.

DOMDocument->getElementsByTagNameNS()

(no version information, might be only in CVS)

DOMDocument->getElementsByTagNameNS() --  Searches for all elements with given tag name in specified namespace

说明

class DOMDocument {

DOMNodeList getElementsByTagNameNS ( string namespaceURI, string localName )

}

Returns a DOMNodeList of all elements with a given local name and a namespace URI.

参数

namespaceURI

The namespace URI of the elements to match on. The special value * matches all namespaces.

localName

The local name of the elements to match on. The special value * matches all local names.

返回值

A new DOMNodeList object containing all the matched elements.

范例

例子 1. Get all the XInclude elements

<?php

$xml = <<<EOD
<?xml version="1.0" ?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
<title>Books of the other guy..</title>
<para>
 <xi:include href="book.xml">
  <xi:fallback>
   <error>xinclude: book.xml not found</error>
  </xi:fallback>
 </xi:include>
 <include>
  This is another namespace
 </include>
</para>
</chapter>
EOD;
$dom = new DOMDocument;

// load the XML string defined above
$dom->loadXML($xml);

foreach ($dom->getElementsByTagNameNS('http://www.w3.org/2001/XInclude', '*') as $element) {
    echo 'local name: ', $element->localName, ', prefix: ', $element->prefix, "\n";
}
?>

上例将输出:

local name: include, prefix: xi
local name: fallback, prefix: xi

DOMDocument->importNode()

(no version information, might be only in CVS)

DOMDocument->importNode() -- Import node into current document

说明

class DOMDocument {

DOMNode importNode ( DOMNode importedNode [, bool deep] )

}

This function returns a copy of the node to import and associates it with the current document.

参数

importedNode

The node to import.

deep

If set to TRUE, this method will recursively import the subtree under the importedNode.

返回值

The copied node.

异常

DOMException is thrown if node cannot be imported.

DOMDocument->load()

(no version information, might be only in CVS)

DOMDocument->load() --  Load XML from a file

说明

class DOMDocument {

bool load ( string filename [, int options] )

}

Loads an XML document from a file.

This method may also be called statically to load and create a DOMDocument object. The static invocation may be used when no DOMDocument properties need to be set prior to loading.

参数

filename

The path to the XML document.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

范例

例子 1. Creating a Document

<?php
$doc = DOMDocument::load('book.xml');
echo $doc->saveXML();

$doc = new DOMDocument();
$doc->load('book.xml');
echo $doc->saveXML();
?>

DOMDocument->loadHTML()

(no version information, might be only in CVS)

DOMDocument->loadHTML() --  Load HTML from a string

说明

class DOMDocument {

bool loadHTML ( string source )

}

The function parses the HTML contained in the string source. Unlike loading XML, HTML does not have to be well-formed to load. This function may also be called statically to load and create a DOMDocument object. The static invocation may be used when no DOMDocument properties need to be set prior to loading.

参数

source

The HTML string.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

范例

例子 1. Creating a Document

<?php
$doc = DOMDocument::loadHTML("<html><body>Test<br></body></html>");
echo $doc->saveHTML();

$doc = new DOMDocument();
$doc->loadHTML("<html><body>Test<br></body></html>");
echo $doc->saveHTML();
?>

DOMDocument->loadHTMLFile()

(no version information, might be only in CVS)

DOMDocument->loadHTMLFile() --  Load HTML from a file

说明

class DOMDocument {

bool loadHTMLFile ( string filename )

}

The function parses the HTML document in the file named filename. Unlike loading XML, HTML does not have to be well-formed to load.

This function may also be called statically to load and create a DOMDocument object. The static invocation may be used when no DOMDocument properties need to be set prior to loading.

参数

filename

The path to the HTML file.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

范例

例子 1. Creating a Document

<?php
$doc = DOMDocument::loadHTMLFile("filename.html");
print $doc->saveHTML();

$doc = new DOMDocument();
$doc->loadHTMLFile("filename.html");
print $doc->saveHTML();
?>

DOMDocument->loadXML()

(no version information, might be only in CVS)

DOMDocument->loadXML() --  Load XML from a string

说明

class DOMDocument {

bool loadXML ( string source [, int options] )

}

Loads an XML document from a string.

This method may also be called statically to load and create a DOMDocument object. The static invocation may be used when no DOMDocument properties need to be set prior to loading.

参数

source

The string containing the XML.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

范例

例子 1. Creating a Document

<?php
$doc = DOMDocument::loadXML('<root><node/></root>');
echo $doc->saveXML();

$doc = new DOMDocument();
$doc->loadXML('<root><node/></root>');
echo $doc->saveXML();
?>

DOMDocument->normalize()

(no version information, might be only in CVS)

DOMDocument->normalize() --  Normalizes the document

说明

class DOMDocument {

void normalize ( void )

}

Normalizes the document.

返回值

无返回值。

DOMDocument->relaxNGValidate()

(no version information, might be only in CVS)

DOMDocument->relaxNGValidate() --  Performs relaxNG validation on the document

说明

class DOMDocument {

bool relaxNGValidate ( string filename )

}

Performs relaxNG validation on the document based on the given RNG schema.

参数

filename

The RNG file.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

DOMDocument->relaxNGValidateSource()

(no version information, might be only in CVS)

DOMDocument->relaxNGValidateSource() --  Performs relaxNG validation on the document

说明

class DOMDocument {

bool relaxNGValidateSource ( string source )

}

Performs relaxNG validation on the document based on the given RNG source.

参数

source

A string containing the RNG schema.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

DOMDocument->save()

(no version information, might be only in CVS)

DOMDocument->save() --  Dumps the internal XML tree back into a file

说明

class DOMDocument {

mixed save ( string filename [, integer options] )

}

Creates an XML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

参数

filename

The path to the saved XML document.

options

Additional Options. Currently only LIBXML_NOEMPTYTAG is supported.

返回值

Returns the number of bytes written or FALSE if an error occurred.

更新日志

版本说明
5.1.0 Added the options parameter

范例

例子 1. Saving a DOM tree into a file

<?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('book');
$root = $doc->appendChild($root);

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo 'Wrote: ' . $doc->save("/tmp/test.xml") . ' bytes'; // Wrote: 72 bytes

?>

DOMDocument->saveHTML()

(no version information, might be only in CVS)

DOMDocument->saveHTML() --  Dumps the internal document into a string using HTML formatting

说明

class DOMDocument {

string saveHTML ( void )

}

Creates an HTML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

返回值

Returns the HTML, or FALSE if an error occurred.

范例

例子 1. Saving a HTML tree into a string

<?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('html');
$root = $doc->appendChild($root);

$head = $doc->createElement('head');
$head = $root->appendChild($head);

$title = $doc->createElement('title');
$title = $head->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo $doc->saveHTML();

?>

DOMDocument->saveHTMLFile()

(no version information, might be only in CVS)

DOMDocument->saveHTMLFile() --  Dumps the internal document into a file using HTML formatting

说明

class DOMDocument {

int saveHTMLFile ( string filename )

}

Creates an HTML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

参数

filename

The path to the saved HTML document.

返回值

Returns the number of bytes written or FALSE if an error occurred.

范例

例子 1. Saving a HTML tree into a file

<?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('html');
$root = $doc->appendChild($root);

$head = $doc->createElement('head');
$head = $root->appendChild($head);

$title = $doc->createElement('title');
$title = $head->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo 'Wrote: ' . $doc->saveHTMLFile("/tmp/test.html") . ' bytes'; // Wrote: 129 bytes

?>

DOMDocument->saveXML()

(no version information, might be only in CVS)

DOMDocument->saveXML() --  Dumps the internal XML tree back into a string

说明

class DOMDocument {

string saveXML ( [DOMNode node [, integer options]] )

}

Creates an XML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

参数

node

Use this parameter to output only a specific node without XML declaration rather than the entire document.

options

Additional Options. Currently only LIBXML_NOEMPTYTAG is supported.

返回值

Returns the XML, or FALSE if an error occurred.

异常

DOM_WRONG_DOCUMENT_ERR

Raised if node is from another document.

更新日志

版本说明
5.1.0 Added the options parameter

范例

例子 1. Saving a DOM tree into a string

<?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('book');
$root = $doc->appendChild($root);

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo "Retrieving all the document:\n";
echo $doc->saveXML() . "\n";

echo "Retrieving only the title part:\n";
echo $doc->saveXML($title);

?>

上例将输出:

Retrieving all the document:
<?xml version="1.0"?>
<book>
  <title>This is the title</title>
</book>

Retrieving only the title part:
<title>This is the title</title>

DOMDocument->schemaValidate()

(no version information, might be only in CVS)

DOMDocument->schemaValidate() --  Validates a document based on a schema

说明

class DOMDocument {

bool schemaValidate ( string filename )

}

Validates a document based on the given schema file.

参数

filename

The path to the schema.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

DOMDocument->schemaValidateSource()

(no version information, might be only in CVS)

DOMDocument->schemaValidateSource() --  Validates a document based on a schema

说明

class DOMDocument {

bool schemaValidateSource ( string source )

}

Validates a document based on a schema defined in the given string.

参数

source

A string containing the schema.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

DOMDocument->validate()

(no version information, might be only in CVS)

DOMDocument->validate() --  Validates the document based on its DTD

说明

class DOMDocument {

bool validate ( void )

}

Validates the document based on its DTD.

You can also use the validateOnParse property of DOMDocument to make a DTD validation.

返回值

如果成功则返回 TRUE,失败则返回 FALSE。 If the document have no DTD attached, this method will return FALSE.

范例

例子 1. Example of DTD validation

<?php
$dom = new DOMDocument;
$dom->Load('book.xml');
if ($dom->validate()) {
    echo "This document is valid!\n";
}
?>

You can also validate your XML file while loading it:

<?php
$dom = new DOMDocument;
$dom->validateOnParse = true;
$dom->Load('book.xml');
?>

DOMDocument->xinclude()

(no version information, might be only in CVS)

DOMDocument->xinclude() --  Substitutes XIncludes in a DOMDocument Object

说明

class DOMDocument {

int xinclude ( [int options] )

}

This method substitutes XIncludes in a DOMDocument object.

注: Due to libxml2 automatically resolving entities, this method will produce unexpected results if the included XML file have an attached DTD.

参数

options

libxml parameters. Available since PHP 5.1.0 and Libxml 2.6.7.

返回值

Returns the number of XIncludes in the document.

范例

例子 1. DOMDocument->xinclude() example

<?php

$xml = <<<EOD
<?xml version="1.0" ?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
 <title>Books of the other guy..</title>
 <para>
  <xi:include href="book.xml">
   <xi:fallback>
    <error>xinclude: book.xml not found</error>
   </xi:fallback>
  </xi:include>
 </para>
</chapter>
EOD;

$dom = new DOMDocument;

// let's have a nice output
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;

// load the XML string defined above
$dom->loadXML($xml);

// substitute xincludes
$dom->xinclude();

echo $dom->saveXML();

?>

上例的输出类似于:

<?xml version="1.0"?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
  <title>Books of the other guy..</title>
  <para>
    <row xml:base="/home/didou/book.xml">
       <entry>The Grapes of Wrath</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>0140186409</entry>
      </row>
    <row xml:base="/home/didou/book.xml">
       <entry>The Pearl</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>014017737X</entry>
      </row>
    <row xml:base="/home/didou/book.xml">
       <entry>Samarcande</entry>
       <entry>Amine Maalouf</entry>
       <entry>fr</entry>
       <entry>2253051209</entry>
      </row>
  </para>
</chapter>

DOMElement->__construct()

(no version information, might be only in CVS)

DOMElement->__construct() --  Creates a new DOMElement object

说明

class DOMElement {

__construct ( string name [, string value [, string namespaceURI]] )

}

Creates a new DOMElement object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument->createElement() or DOMDocument->createElementNS().

参数

name

The tag name of the element. When also passing in namespaceURI, the element name may take a prefix to be associated with the URI.

value

The value of the element.

namespaceURI

A namespace URI to create the element within a specific namespace.

范例

例子 1. Creating a new DOMElement

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$element_ns = new DOMElement('pr:node1', 'thisvalue', 'http://xyz');
$element->appendChild($element_ns);
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?>
<root><pr:node1 xmlns:pr="http://xyz">thisvalue</pr:node1></root> */

?>

DOMElement->getAttribute()

(no version information, might be only in CVS)

DOMElement->getAttribute() -- Returns value of attribute

说明

class DOMElement {

string getAttribute ( string name )

}

Gets the value of the attribute with name name for the current node.

参数

name

The name of the attribute.

返回值

The value of the attribute, or an empty string if no attribute with the given name is found.

DOMElement->getAttributeNode()

(no version information, might be only in CVS)

DOMElement->getAttributeNode() -- Returns attribute node

说明

class DOMElement {

DOMAttr getAttributeNode ( string name )

}

Returns the attribute node with name name for the current element.

参数

name

The name of the attribute.

返回值

The attribute node.

DOMElement->getAttributeNodeNS()

(no version information, might be only in CVS)

DOMElement->getAttributeNodeNS() --  Returns attribute node

说明

class DOMElement {

DOMAttr getAttributeNodeNS ( string namespaceURI, string localName )

}

Returns the attribute node in namespace namespaceURI with local name localName for the current node.

参数

namespaceURI

The namespace URI.

localName

The local name.

返回值

The attribute node.

DOMElement->getAttributeNS()

(no version information, might be only in CVS)

DOMElement->getAttributeNS() -- Returns value of attribute

说明

class DOMElement {

string getAttributeNS ( string namespaceURI, string localName )

}

Gets the value of the attribute in namespace namespaceURI with local name localName for the current node.

参数

namespaceURI

The namespace URI.

localName

The local name.

返回值

The value of the attribute, or an empty string if no attribute with the given localName and namespaceURI is found.

DOMElement->getElementsByTagName()

(no version information, might be only in CVS)

DOMElement->getElementsByTagName() -- Gets elements by tagname

说明

class DOMElement {

DOMNodeList getElementsByTagName ( string name )

}

This function returns a new instance of the class DOMNodeList of all descendant elements with a given tag name, in the order in which they are encountered in a preorder traversal of this element tree.

参数

name

The tag name. Use * to return all elements within the element tree.

返回值

This function returns a new instance of the class DOMNodeList of all matched elements.

DOMElement->getElementsByTagNameNS()

(no version information, might be only in CVS)

DOMElement->getElementsByTagNameNS() -- Get elements by namespaceURI and localName

说明

class DOMElement {

DOMNodeList getElementsByTagNameNS ( string namespaceURI, string localName )

}

This function fetch all the descendant elements with a given localName and namespaceURI.

参数

namespaceURI

The namespace URI.

localName

The local name. Use * to return all elements within the element tree.

返回值

This function returns a new instance of the class DOMNodeList of all matched elements in the order in which they are encountered in a preorder traversal of this element tree.

DOMElement->hasAttribute()

(no version information, might be only in CVS)

DOMElement->hasAttribute() -- Checks to see if attribute exists

说明

class DOMElement {

bool hasAttribute ( string name )

}

Indicates whether attribute named name exists as a member of the element.

参数

name

The attribute name.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

DOMElement->hasAttributeNS()

(no version information, might be only in CVS)

DOMElement->hasAttributeNS() --  Checks to see if attribute exists

说明

class DOMElement {

bool hasAttributeNS ( string namespaceURI, string localName )

}

Indicates whether attribute in namespace namespaceURI named localName exists as a member of the element.

参数

namespaceURI

The namespace URI.

localName

The local name.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

DOMElement->removeAttribute()

(no version information, might be only in CVS)

DOMElement->removeAttribute() -- Removes attribute

说明

class DOMElement {

bool removeAttribute ( string name )

}

Removes attribute named name from the element.

参数

name

The name of the attribute.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOMElement->removeAttributeNode()

(no version information, might be only in CVS)

DOMElement->removeAttributeNode() -- Removes attribute

说明

class DOMElement {

bool removeAttributeNode ( DOMAttr oldnode )

}

Removes attribute oldnode from the element.

参数

oldnode

The attribute node.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND_ERROR

Raised if oldnode is not an attribute of the element.

DOMElement->removeAttributeNS()

(no version information, might be only in CVS)

DOMElement->removeAttributeNS() -- Removes attribute

说明

class DOMElement {

bool removeAttributeNS ( string namespaceURI, string localName )

}

Removes attribute is namespace namespaceURI named localName from the element.

参数

namespaceURI

The namespace URI.

localName

The local name.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOMElement->setAttribute()

(no version information, might be only in CVS)

DOMElement->setAttribute() -- Adds new attribute

说明

class DOMElement {

bool setAttribute ( string name, string value )

}

Sets an attribute with name name to the given value. If the attribute does not exist, it will be created.

参数

name

The name of the attribute.

value

The value of the attribute.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

范例

例子 1. Setting an attribute

<?php
$doc = new DOMDocument("1.0");
$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);
$newnode->setAttribute("align", "left");
?>

DOMElement->setAttributeNode()

(no version information, might be only in CVS)

DOMElement->setAttributeNode() -- Adds new attribute node to element

说明

class DOMElement {

DOMAttr setAttributeNode ( DOMAttr attr )

}

Adds new attribute node attr to element.

参数

attr

The attribute node.

返回值

Returns old node if the attribute has been replaced or NULL.

异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOMElement->setAttributeNodeNS()

(no version information, might be only in CVS)

DOMElement->setAttributeNodeNS() -- Adds new attribute node to element

说明

class DOMElement {

DOMAttr setAttributeNodeNS ( DOMAttr attr )

}

Adds new attribute node attr to element.

参数

name

The attribute node.

返回值

Returns the old node if the attribute has been replaced.

异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOMElement->setAttributeNS()

(no version information, might be only in CVS)

DOMElement->setAttributeNS() -- Adds new attribute

说明

class DOMElement {

void setAttributeNS ( string namespaceURI, string qualifiedName, string value )

}

Sets an attribute with namespace namespaceURI and name name to the given value. If the attribute does not exist, it will be created.

参数

namespaceURI

The namespace URI.

qualifiedName

The qualified name of the attribute, as prefix:tagname.

value

The value of the attribute.

返回值

无返回值。

异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NAMESPACE_ERR

Raised if qualifiedName is a malformed qualified name, or if qualifiedName has a prefix and namespaceURI is NULL.

DOMAttr->__construct()

(no version information, might be only in CVS)

DOMAttr->__construct() --  Creates a new DOMEntityReference object

说明

class DOMEntityReference {

__construct ( string name )

}

Creates a new DOMEntityReference object.

参数

name

The name of the entity reference.

范例

例子 1. Creating a new DOMEntityReference

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$entity = $element->appendChild(new DOMEntityReference('nbsp'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root>&nbsp;</root> */

?>

DOMImplementation->__construct()

(no version information, might be only in CVS)

DOMImplementation->__construct() --  Creates a new DOMImplementation object

说明

class DOMImplementation {

__construct ( (void); )

}

Creates a new DOMImplementation object.

DOMImplementation->createDocument()

(no version information, might be only in CVS)

DOMImplementation->createDocument() --  Creates a DOMDocument object of the specified type with its document element

说明

class DOMImplementation {

DOMDocument createDocument ( [string namespaceURI [, string qualifiedName [, DOMDocumentType doctype]]] )

}

Creates a DOMDocument object of the specified type with its document element.

参数

namespaceURI

The namespace URI of the document element to create.

qualifiedName

The qualified name of the document element to create.

doctype

The type of document to create or NULL.

返回值

A new DOMDocument object. If namespaceURI, qualifiedName, and doctype are null, the returned DOMDocument is empty with no document element

异常

DOM_WRONG_DOCUMENT_ERR

Raised if doctype has already been used with a different document or was created from a different implementation.

DOM_NAMESPACE_ERR

Raised if there is an error with the namespace, as determined by namespaceURI and qualifiedName.

DOMImplementation->createDocumentType()

(no version information, might be only in CVS)

DOMImplementation->createDocumentType() --  Creates an empty DOMDocumentType object

说明

class DOMImplementation {

DOMDocumentType createDocumentType ( [string qualifiedName [, string publicId [, string systemId]]] )

}

Creates an empty DOMDocumentType object. Entity declarations and notations are not made available. Entity reference expansions and default attribute additions do not occur.

参数

qualifiedName

The qualified name of the document type to create.

publicId

The external subset public identifier.

systemId

The external subset system identifier.

返回值

A new DOMDocumentType node with its ownerDocument set to NULL.

范例

例子 1. Creating a document with an attached DTD

<?php

// Creates an instance of the DOMImplementation class
$imp = new DOMImplementation;

// Creates a DOMDocumentType instance
$dtd = $imp->createDocumentType('graph', '', 'graph.dtd');

// Creates a DOMDocument instance
$dom = $imp->createDocument("", "", $dtd);

// Set other properties
$dom->encoding = 'UTF-8';
$dom->standalone = false;

// Create an empty element
$element = $dom->createElement('graph');

// Append the element
$dom->appendChild($element);

// Retrieve and print the document
echo $dom->saveXML();

?>

上例将输出:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE graph SYSTEM "graph.dtd">
<graph/>

异常

DOM_NAMESPACE_ERR

Raised if there is an error with the namespace, as determined by qualifiedName.

DOMImplementation->hasFeature()

(no version information, might be only in CVS)

DOMImplementation->hasFeature() --  Test if the DOM implementation implements a specific feature

说明

class DOMImplementation {

bool hasFeature ( string feature, string version )

}

Test if the DOM implementation implements a specific feature.

You can find a list of all features in the Conformance section of the DOM specification.

参数

feature

The feature to test.

version

The version number of the feature to test. In level 2, this can be either 2.0 or 1.0.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

范例

例子 1. Testing your DOM Implementation

<?php

$features = array(
  'Core'           => 'Core module',
  'XML'            => 'XML module',
  'HTML'           => 'HTML module',
  'Views'          => 'Views module',
  'Stylesheets'    => 'Style Sheets module',
  'CSS'            => 'CSS module',
  'CSS2'           => 'CSS2 module',
  'Events'         => 'Events module',
  'UIEvents'       => 'User interface Events module',
  'MouseEvents'    => 'Mouse Events module',
  'MutationEvents' => 'Mutation Events module',
  'HTMLEvents'     => 'HTML Events module',
  'Range'          => 'Range module',
  'Traversal'      => 'Traversal module'
);
               
foreach ($features as $key => $name) {
  if (DOMImplementation::hasFeature($key, '2.0')) {
    echo "Has feature $name\n";
  } else {
    echo "Missing feature $name\n";
  }
}

?>

DOMNamedNodeMap->getNamedItem()

(no version information, might be only in CVS)

DOMNamedNodeMap->getNamedItem() --  Retrieves a node specified by name

说明

class DOMNamedNodeMap {

DOMNode getNamedItem ( string name )

}

Retrieves a node specified by its nodeName.

参数

name

The nodeName of the node to retrieve.

返回值

A node (of any type) with the specified nodeName, or NULL if no node is found.

DOMNamedNodeMap->getNamedItemNS()

(no version information, might be only in CVS)

DOMNamedNodeMap->getNamedItemNS() --  Retrieves a node specified by local name and namespace URI

说明

class DOMNamedNodeMap {

DOMNode getNamedItemNS ( string namespaceURI, string localName )

}

Retrieves a node specified by localName and namespaceURI.

参数

namespaceURI

The namespace URI of the node to retrieve.

localName

The local name of the node to retrieve.

返回值

A node (of any type) with the specified local name and namespace URI, or NULL if no node is found.

DOMNamedNodeMap->item()

(no version information, might be only in CVS)

DOMNamedNodeMap->item() -- Retrieves a node specified by index

说明

class DOMNamedNodeMap {

DOMNode item ( int index )

}

Retrieves a node specified by index within the DOMNamedNodeMap object.

参数

index

Index into this map.

返回值

The node at the indexth position in the map, or NULL if that is not a valid index (greater than or equal to the number of nodes in this map).

DOMNode->appendChild()

(no version information, might be only in CVS)

DOMNode->appendChild() --  Adds new child at the end of the children

说明

class DOMNode {

DOMNode appendChild ( DOMNode newnode )

}

This functions appends a child to an existing list of children or creates a new list of children. The child can be created with e.g. DOMDocument->createElement(), DOMDocument->createTextNode() etc. or simply by using any other node.

参数

newnode

The appended child.

返回值

The node added.

异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly or if the previous parent of the node being inserted is readonly.

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of the newnode node, or if the node to append is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if newnode was created from a different document than the one that created this node.

范例

The following example will add a new element node to a fresh document.

例子 1. Adding a child

<?php

$doc = new DOMDocument;

$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);

echo $doc->saveXML();
?>

DOMNode->cloneNode()

(no version information, might be only in CVS)

DOMNode->cloneNode() --  Clones a node

说明

class DOMNode {

DOMNode cloneNode ( [bool deep] )

}

Creates a copy of the node.

参数

deep

Indicates whether to copy all descendant nodes. This parameter is defaulted to FALSE.

返回值

The cloned node.

DOMNode->hasAttributes()

(no version information, might be only in CVS)

DOMNode->hasAttributes() --  Checks if node has attributes

说明

class DOMNode {

bool hasAttributes ( void )

}

This method checks if the node has attributes. The tested node have to be an XML_ELEMENT_NODE.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

DOMNode->hasChildNodes()

(no version information, might be only in CVS)

DOMNode->hasChildNodes() --  Checks if node has children

说明

class DOMNode {

bool hasChildNodes ( void )

}

This function checks if the node has children.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

DOMNode->insertBefore()

(no version information, might be only in CVS)

DOMNode->insertBefore() --  Adds a new child before a reference node

说明

class DOMNode {

DOMNode insertBefore ( DOMNode newnode [, DOMNode refnode] )

}

This function inserts a new node right before the reference node. If you plan to do further modifications on the appended child you must use the returned node.

参数

newnode

The new node.

refnode

The reference node. If not supplied, newnode is appended to the children.

返回值

The inserted node.

异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly or if the previous parent of the node being inserted is readonly.

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of the newnode node, or if the node to append is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if newnode was created from a different document than the one that created this node.

DOM_NOT_FOUND

Raised if refnode is not a child of this node.

DOMNode->isSameNode()

(no version information, might be only in CVS)

DOMNode->isSameNode() --  Indicates if two nodes are the same node

说明

class DOMNode {

bool isSameNode ( DOMNode node )

}

This function indicates if two nodes are the same node. The comparison is not based on content

参数

node

The compared node.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

DOMNode->isSupported()

(no version information, might be only in CVS)

DOMNode->isSupported() --  Checks if feature is supported for specified version

说明

class DOMNode {

bool isSupported ( string feature, string version )

}

Checks if the asked feature is supported for the specified version.

参数

feature

The feature to test. See the example of DOMImplementation->hasFeature() for a list of features.

version

The version number of the feature to test.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

DOMNode->lookupNamespaceURI()

(no version information, might be only in CVS)

DOMNode->lookupNamespaceURI() --  Gets the namespace URI of the node based on the prefix

说明

class DOMNode {

string lookupNamespaceURI ( string prefix )

}

Gets the namespace URI of the node based on the prefix.

参数

prefix

The prefix of the namespace.

返回值

The namespace URI of the node.

DOMNode->lookupPrefix()

(no version information, might be only in CVS)

DOMNode->lookupPrefix() --  Gets the namespace prefix of the node based on the namespace URI

说明

class DOMNode {

string lookupPrefix ( string namespaceURI )

}

Gets the namespace prefix of the node based on the namespace URI.

参数

namespaceURI

The namespace URI.

返回值

The prefix of the namespace.

DOMNode->normalize()

(no version information, might be only in CVS)

DOMNode->normalize() --  Normalizes the node

说明

class DOMNode {

void normalize ( void )

}

Normalizes the node.

返回值

无返回值。

DOMNode->removeChild()

(no version information, might be only in CVS)

DOMNode->removeChild() --  Removes child from list of children

说明

class DOMNode {

DOMNode removeChild ( DOMNode oldnode )

}

This functions removes a child from a list of children.

参数

oldnode

The removed child.

返回值

If the child could be removed the functions returns the old child.

异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly.

DOM_NOT_FOUND

Raised if oldnode is not a child of this node.

范例

The following example will delete the chapter element of our XML document.

例子 1. Removing a child

<?php

$doc = new DOMDocument;
$doc->load('book.xml');

$book = $doc->documentElement;

// we retrieve the chapter and remove it from the book
$chapter = $book->getElementsByTagName('chapter')->item(0);
$oldchapter = $book->removeChild($chapter);

echo $doc->saveXML();
?>

上例将输出:

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN" 
          "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd">
<book id="listing">
 <title>My lists</title>
 
</book>

DOMNode->replaceChild()

(no version information, might be only in CVS)

DOMNode->replaceChild() --  Replaces a child

说明

class DOMNode {

DOMNode replaceChild ( DOMNode newnode, DOMNode oldnode )

}

This function replaces the child oldnode with the passed new node. If the new node is already a child it will not be added a second time. If the replacement succeeds the old node is returned.

参数

newnode

The new node. It must be a member of the target document, i.e. created by one of the DOMDocument->createXXX() methods or imported in the document by DOMDocument->importNode().

oldnode

The old node.

返回值

The old node or FALSE if an error occur.

异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly or if the previous parent of the node being inserted is readonly.

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of the newnode node, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if newnode was created from a different document than the one that created this node.

DOM_NOT_FOUND

Raised if oldnode is not a child of this node.

DOMNodelist->item()

(no version information, might be only in CVS)

DOMNodelist->item() --  Retrieves a node specified by index

说明

class DOMNodeList {

DOMNode item ( int index )

}

Retrieves a node specified by index within the DOMNodeList object.

提示: If you need to know the number of nodes in the collection, use the length property of the DOMNodeList object.

参数

index

Index of the node into the collection.

返回值

The node at the indexth position in the DOMNodeList, or NULL if that is not a valid index.

范例

例子 1. Traversing all the entries of the table

<?php

$doc = new DOMDocument;
$doc->load('book.xml');

$items = $doc->getElementsByTagName('entry');

for ($i = 0; $i < $items->length; $i++) {
    echo $items->item($i)->nodeValue . "\n";
}

?>

Alternatively, you can use foreach, which is a much more convenient way:

<?php

foreach ($items as $item) {
    echo $item->nodeValue . "\n";
}

?>

上例将输出:

Title
Author
Language
ISBN
The Grapes of Wrath
John Steinbeck
en
0140186409
The Pearl
John Steinbeck
en
014017737X
Samarcande
Amine Maalouf
fr
2253051209

DOMProcessingInstruction->__construct()

(no version information, might be only in CVS)

DOMProcessingInstruction->__construct() --  Creates a new DOMProcessingInstruction object

说明

class DOMProcessingInstruction {

__construct ( string name [, string value] )

}

Creates a new DOMProcessingInstruction object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument->createProcessingInstruction().

参数

name

The tag name of the processing instruction.

value

The value of the processing instruction.

范例

例子 1. Creating a new DOMProcessingInstruction

<?php

$dom = new DOMDocument('1.0', 'UTF-8');
$html = $dom->appendChild(new DOMElement('html'));
$body = $html->appendChild(new DOMElement('body'));
$pinode = new DOMProcessingInstruction('php', 'echo "Hello World"; ');
$body->appendChild($pinode);
echo $dom->saveXML(); 

?>

上例将输出:

<?xml version="1.0" encoding="UTF-8"?>
<html><body><?php echo "Hello World"; ?></body></html>

DOMText->__construct()

(no version information, might be only in CVS)

DOMText->__construct() --  Creates a new DOMText object

说明

class DOMText {

__construct ( [string value] )

}

Creates a new DOMText object.

参数

value

The value of the text node. If not supplied an empty text node is created.

范例

例子 1. Creating a new DOMText

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$text = $element->appendChild(new DOMText('root value'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root>root value</root> */

?>

DOMText->isWhitespaceInElementContent()

(no version information, might be only in CVS)

DOMText->isWhitespaceInElementContent() --  Indicates whether this text node contains whitespace

说明

class DOMText {

bool isWhitespaceInElementContent ( void )

}

Indicates whether this text node contains whitespace. The text node is determined to contain whitespace in element content during the load of the document.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

DOMText->splitText()

(no version information, might be only in CVS)

DOMText->splitText() --  Breaks this node into two nodes at the specified offset

说明

class DOMText {

DOMText splitText ( int offset )

}

Breaks this node into two nodes at the specified offset, keeping both in the tree as siblings.

After being split, this node will contain all the content up to the offset. If the original node had a parent node, the new node is inserted as the next sibling of the original node. When the offset is equal to the length of this node, the new node has no data.

参数

offset

The offset at which to split, starting from 0.

返回值

The new node of the same type, which contains all the content at and after the offset.

DOMXPath->__construct()

(no version information, might be only in CVS)

DOMXPath->__construct() --  Creates a new DOMXPath object

说明

class DOMXPath {

__construct ( DOMDocument doc )

}

Creates a new DOMXPath object.

参数

doc

The DOMDocument associated with the DOMXPath.

DOMXPath->evaluate()

(no version information, might be only in CVS)

DOMXPath->evaluate() --  Evaluates the given XPath expression and returns a typed result if possible.

说明

class DOMXPath {

mixed evaluate ( string expression [, DOMNode contextnode] )

}

Executes the given XPath expression and returns a typed result if possible.

参数

expression

The XPath expression to execute.

contextnode

The optional contextnode can be specified for doing relative XPath queries. By default, the queries are relative to the root element.

返回值

Returns a typed result if possible or a DOMNodeList containing all nodes matching the given XPath expression.

范例

例子 1. Getting the count of all the english books

<?php

$doc = new DOMDocument;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

$tbody = $doc->getElementsByTagName('tbody')->item(0);

// our query is relative to the tbody node
$query = 'count(row/entry[. = "en"])';

$entries = $xpath->evaluate($query, $tbody);
echo "There are $entries english books\n";

?>

上例将输出:

There are 2 english books

DOMXPath->query()

(no version information, might be only in CVS)

DOMXPath->query() --  Evaluates the given XPath expression

说明

class DOMXPath {

DOMNodeList query ( string expression [, DOMNode contextnode] )

}

Executes the given XPath expression.

参数

expression

The XPath expression to execute.

contextnode

The optional contextnode can be specified for doing relative XPath queries. By default, the queries are relative to the root element.

返回值

Returns a DOMNodeList containing all nodes matching the given XPath expression. Any expression which do not return nodes will return an empty DOMNodeList.

范例

例子 1. Getting all the english books

<?php

$doc = new DOMDocument;

// We don't want to bother with white spaces
$doc->preserveWhiteSpace = false;

$doc->Load('book.xml');

$xpath = new DOMXPath($doc);

// We starts from the root element
$query = '//book/chapter/para/informaltable/tgroup/tbody/row/entry[. = "en"]';

$entries = $xpath->query($query);

foreach ($entries as $entry) {
    echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
         " by {$entry->previousSibling->nodeValue}\n";
}
?>

上例将输出:

Found The Grapes of Wrath, by John Steinbeck
Found The Pearl, by John Steinbeck

We can also use the contextnode parameter to shorten our expression:

<?php

$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

$tbody = $doc->getElementsByTagName('tbody')->item(0);

// our query is relative to the tbody node
$query = 'row/entry[. = "en"]';

$entries = $xpath->query($query, $tbody);

foreach ($entries as $entry) {
    echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
         " by {$entry->previousSibling->nodeValue}\n";
}
?>

DOMXPath->registerNamespace()

(no version information, might be only in CVS)

DOMXPath->registerNamespace() --  Registers the namespace with the DOMXPath object

说明

class DOMXPath {

bool registerNamespace ( string prefix, string namespaceURI )

}

Registers the namespaceURI and prefix with the DOMXPath object.

参数

prefix

The prefix.

namespaceURI

The URI of the namespace.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

dom_import_simplexml

(PHP 5)

dom_import_simplexml --  Gets a DOMElement object from a SimpleXMLElement object

说明

DOMElement dom_import_simplexml ( SimpleXMLElement node )

This function takes the node node of class SimpleXML and makes it into a DOMElement node. This new object can then be used as a native DOMElement node.

参数

node

The SimpleXMLElement node.

返回值

The DOMElement node added or FALSE if any errors occur.

范例

例子 1. Import SimpleXML into DOM with dom_import_simplexml()

<?php

$sxe = simplexml_load_string('<books><book><title>blah</title></book></books>');

if ($sxe === false) {
    echo 'Error while parsing the document';
    exit;
}

$dom_sxe = dom_import_simplexml($sxe);
if (!$dom_sxe) {
    echo 'Error while converting XML';
    exit;
}

$dom = new DOMDocument('1.0');
$dom_sxe = $dom->importNode($dom_sxe, true);
$dom_sxe = $dom->appendChild($dom_sxe);

echo $dom->saveXML();

?>

XXX. DOM XML Functions

简介

The DOM XML extension has been overhauled in PHP 4.3.0 to better comply with the DOM standard. The extension still contains many old functions, but they should no longer be used. In particular, functions that are not object-oriented should be avoided.

The extension allows you to operate on an XML document with the DOM API. It also provides a function domxml_xmltree() to turn the complete XML document into a tree of PHP objects. Currently, this tree should be considered read-only - you can modify it, but this would not make any sense since DomDocument_dump_mem() cannot be applied to it. Therefore, if you want to read an XML file and write a modified version, use DomDocument_create_element(), DomDocument_create_text_node(), set_attribute(), etc. and finally the DomDocument_dump_mem() function.

注: 本扩展已被移动到 PECL 库中且自以下版本起不再被绑定到 PHP 中:5.0.0.

注: This extension is no longer marked experimental. It will, however, never be released with PHP 5, and will only be distributed with PHP 4. If you need DOM XML support with PHP 5 you can use the DOM extension. This domxml extension is not compatible with the DOM extension.


需求

This extension makes use of the GNOME XML library. Download and install this library. You will need at least libxml-2.4.14. To use DOM XSLT features you can use the libxslt library and EXSLT enhancements from http://www.exslt.org/. Download and install these libraries if you plan to use (enhanced) XSLT features. You will need at least libxslt-1.0.18.


安装

PECL 扩展未绑定于 PHP 中。 进一步信息例如新版本,下载,源程序,维护者信息以及更新日志可以在此找到: http://pecl.php.net/package/domxml.

在 PHP 4 中本 PECL 扩展的源程序位于 PHP 源程序中的 ext/ 目录下或者在上面的 PECL 连接中。 This extension is only available if PHP was configured with --with-dom[=DIR]. Add --with-dom-xslt[=DIR] to include DOM XSLT support. DIR is the libxslt install directory. Add --with-dom-exslt[=DIR] to include DOM EXSLT support, where DIR is the libexslt install directory.

Windows users will enable php_domxml.dll inside of php.ini in order to use these functions. 在 PHP 4 中本 DLL 位于 PHP Windows 执行包中的 extensions/ 目录下。 可以从 PHP 下载页面或者 http://snaps.php.net/ 下载此 PECL 扩展的 DLL 文件。 Also, there is one additional DLL that must be made available to your system's PATH in order for this extension to work. In PHP 4 this is in the dlls/ directory. It's name: For PHP <= 4.2.0, it's libxml2.dll. For PHP >= 4.3.0, it's iconv.dll. And as of PHP 5.0.0, iconv is compiled into your Windows PHP binaries by default so no extra DLL is needed.


Deprecated functions

There are quite a few functions that do not fit into the DOM standard and should no longer be used. These functions are listed in the following table. The function DomNode_append_child() has changed its behaviour. It now adds a child and not a sibling. If this breaks your application, use the non-DOM function DomNode_append_sibling().

表格 1. Deprecated functions and their replacements

Old functionNew function
xmldocdomxml_open_mem()
xmldocfiledomxml_open_file()
domxml_new_xmldocdomxml_new_doc()
domxml_dump_memDomDocument_dump_mem()
domxml_dump_mem_fileDomDocument_dump_file()
DomDocument_dump_mem_fileDomDocument_dump_file()
DomDocument_add_rootDomDocument_create_element() followed by DomNode_append_child()
DomDocument_dtdDomDocument_doctype()
DomDocument_rootDomDocument_document_element()
DomDocument_childrenDomNode_child_nodes()
DomDocument_imported_nodeNo replacement.
DomNode_add_childCreate a new node with e.g. DomDocument_create_element() and add it with DomNode_append_child().
DomNode_childrenDomNode_child_nodes()
DomNode_parentDomNode_parent_node()
DomNode_new_childCreate a new node with e.g. DomDocument_create_element() and add it with DomNode_append_child().
DomNode_set_contentCreate a new node with e.g. DomDocument_create_text_node() and add it with DomNode_append_child().
DomNode_get_contentContent is just a text node and can be accessed with DomNode_child_nodes().
DomNode_set_contentContent is just a text node and can be added with DomNode_append_child().


预定义常量

以下常量由本扩展模块定义,因此只有在本扩展模块被编译到 PHP 中,或者在运行时被动态加载后才有效。

表格 2. XML constants

ConstantValueDescription
XML_ELEMENT_NODE (integer) 1Node is an element
XML_ATTRIBUTE_NODE (integer) 2Node is an attribute
XML_TEXT_NODE (integer) 3Node is a piece of text
XML_CDATA_SECTION_NODE (integer) 4 
XML_ENTITY_REF_NODE (integer) 5 
XML_ENTITY_NODE (integer) 6Node is an entity like &nbsp;
XML_PI_NODE (integer) 7Node is a processing instruction
XML_COMMENT_NODE (integer) 8Node is a comment
XML_DOCUMENT_NODE (integer) 9Node is a document
XML_DOCUMENT_TYPE_NODE (integer) 10 
XML_DOCUMENT_FRAG_NODE (integer) 11 
XML_NOTATION_NODE (integer) 12 
XML_GLOBAL_NAMESPACE (integer) 1 
XML_LOCAL_NAMESPACE (integer) 2 
XML_HTML_DOCUMENT_NODE (integer)   
XML_DTD_NODE (integer)   
XML_ELEMENT_DECL_NODE (integer)   
XML_ATTRIBUTE_DECL_NODE (integer)   
XML_ENTITY_DECL_NODE (integer)   
XML_NAMESPACE_DECL_NODE (integer)   
XML_ATTRIBUTE_CDATA (integer)   
XML_ATTRIBUTE_ID (integer)   
XML_ATTRIBUTE_IDREF (integer)   
XML_ATTRIBUTE_IDREFS (integer)   
XML_ATTRIBUTE_ENTITY (integer)   
XML_ATTRIBUTE_NMTOKEN (integer)   
XML_ATTRIBUTE_NMTOKENS (integer)   
XML_ATTRIBUTE_ENUMERATION (integer)   
XML_ATTRIBUTE_NOTATION (integer)   
XPATH_UNDEFINED (integer)   
XPATH_NODESET (integer)   
XPATH_BOOLEAN (integer)   
XPATH_NUMBER (integer)   
XPATH_STRING (integer)   
XPATH_POINT (integer)   
XPATH_RANGE (integer)   
XPATH_LOCATIONSET (integer)   
XPATH_USERS (integer)   
XPATH_NUMBER (integer)   

Classes

The API of the module follows the DOM Level 2 standard as closely as possible. Consequently, the API is fully object-oriented. It is a good idea to have the DOM standard available when using this module. Though the API is object-oriented, there are many functions which can be called in a non-object-oriented way by passing the object to operate on as the first argument. These functions are mainly to retain compatibility to older versions of the extension, and should not be used when creating new scripts.

This API differs from the official DOM API in two ways. First, all class attributes are implemented as functions with the same name. Secondly, the function names follow the PHP naming convention. This means that a DOM function lastChild() will be written as last_child().

This module defines a number of classes, which are listed - including their method - in the following tables. Classes with an equivalent in the DOM standard are named DOMxxx.

表格 3. List of classes

Class nameParent classes
DomAttributeDomNode
DomCDataDomNode
DomCommentDomCData : DomNode
DomDocumentDomNode
DomDocumentTypeDomNode
DomElementDomNode
DomEntityDomNode
DomEntityReferenceDomNode
DomProcessingInstructionDomNode
DomTextDomCData : DomNode
ParserCurrently still called DomParser
XPathContext 

表格 4. DomDocument class (DomDocument : DomNode)

Method nameFunction nameRemark
doctypeDomDocument_doctype() 
document_elementDomDocument_document_element() 
create_elementDomDocument_create_element() 
create_text_nodeDomDocument_create_text_node() 
create_commentDomDocument_create_comment() 
create_cdata_sectionDomDocument_create_cdata_section() 
create_processing_instructionDomDocument_create_processing_instruction() 
create_attributeDomDocument_create_attribute() 
create_entity_referenceDomDocument_create_entity_reference() 
get_elements_by_tagnameDomDocument_get_elements_by_tagname() 
get_element_by_idDomDocument_get_element_by_id() 
dump_memDomDocument_dump_mem()not DOM standard
dump_fileDomDocument_dump_file()not DOM standard
html_dump_memDomDocument_html_dump_mem()not DOM standard
xpath_initxpath_initnot DOM standard
xpath_new_contextxpath_new_contextnot DOM standard
xptr_new_contextxptr_new_contextnot DOM standard

表格 5. DomElement class (DomElement : DomNode)

Method nameFunction nameRemark
tagnameDomElement_tagname() 
get_attributeDomElement_get_attribute() 
set_attributeDomElement_set_attribute() 
remove_attributeDomElement_remove_attribute() 
get_attribute_nodeDomElement_get_attribute_node() 
get_elements_by_tagnameDomElement_get_elements_by_tagname() 
has_attributeDomElement_has_attribute() 

表格 7. DomAttribute class (DomAttribute : DomNode)

Method name Remark
nameDomAttribute_name() 
valueDomAttribute_value() 
specifiedDomAttribute_specified() 

表格 8. DomProcessingInstruction class (DomProcessingInstruction : DomNode)

Method nameFunction nameRemark
targetDomProcessingInstruction_target() 
dataDomProcessingInstruction_data() 

表格 9. Parser class

Method nameFunction nameRemark
add_chunkParser_add_chunk() 
endParser_end() 

表格 10. XPathContext class

Method nameFunction nameRemark
evalXPathContext_eval() 
eval_expressionXPathContext_eval_expression() 
register_nsXPathContext_register_ns() 

表格 11. DomDocumentType class (DomDocumentType : DomNode)

Method nameFunction nameRemark
nameDomDocumentType_name() 
entitiesDomDocumentType_entities() 
notationsDomDocumentType_notations() 
public_idDomDocumentType_public_id() 
system_idDomDocumentType_system_id() 
internal_subsetDomDocumentType_internal_subset() 

The classes DomDtd is derived from DomNode. DomComment is derived from DomCData.


范例

Many examples in this reference require an XML string. Instead of repeating this string in every example, it will be put into a file which will be included by each example. This include file is shown in the following example section. Alternatively, you could create an XML document and read it with DomDocument_open_file().

例子 1. Include file example.inc with XML string

<?php
$xmlstr = "<?xml version='1.0' standalone='yes'?>
<!DOCTYPE chapter SYSTEM '/share/sgml/Norman_Walsh/db3xml10/db3xml10.dtd'
[ <!ENTITY sp \"spanish\">
]>
<!-- lsfj  -->
<chapter language='en'><title language='en'>Title</title>
 <para language='ge'>
  &sp;
  <!-- comment -->
  <informaltable ID='findme' language='&sp;'>
   <tgroup cols='3'>
    <tbody>
     <row><entry>a1</entry><entry
morerows='1'>b1</entry><entry>c1</entry></row>
<row><entry>a2</entry><entry>c2</entry></row>
     <row><entry>a3</entry><entry>b3</entry><entry>c3</entry></row>
    </tbody>
   </tgroup>
  </informaltable>
 </para>
</chapter>";
?>

目录
DomAttribute->name --  Returns the name of attribute
DomAttribute->set_value --  Sets the value of an attribute
DomAttribute->specified --  Checks if attribute is specified
DomAttribute->value --  Returns value of attribute
DomDocument->add_root --  Adds a root node [deprecated]
DomDocument->create_attribute -- Create new attribute
DomDocument->create_cdata_section -- Create new cdata node
DomDocument->create_comment -- Create new comment node
DomDocument->create_element_ns --  Create new element node with an associated namespace
DomDocument->create_element -- Create new element node
DomDocument->create_entity_reference --  Create an entity reference
DomDocument->create_processing_instruction -- Creates new PI node
DomDocument->create_text_node -- Create new text node
DomDocument->doctype --  Returns the document type
DomDocument->document_element --  Returns root element node
DomDocument->dump_file --  Dumps the internal XML tree back into a file
DomDocument->dump_mem --  Dumps the internal XML tree back into a string
DomDocument->get_element_by_id --  Searches for an element with a certain id
DomDocument->get_elements_by_tagname --  Returns array with nodes with given tagname in document or empty array, if not found
DomDocument->html_dump_mem --  Dumps the internal XML tree back into a string as HTML
DomDocument->xinclude --  Substitutes XIncludes in a DomDocument Object
DomDocumentType->entities() --  Returns list of entities
DomDocumentType->internal_subset() --  Returns internal subset
DomDocumentType->name() --  Returns name of document type
DomDocumentType->notations() --  Returns list of notations
DomDocumentType->public_id() --  Returns public id of document type
DomDocumentType->system_id() --  Returns the system id of document type
DomElement->get_attribute_node() --  Returns the node of the given attribute
DomElement->get_attribute() --  Returns the value of the given attribute
DomElement->get_elements_by_tagname() --  Gets elements by tagname
DomElement->has_attribute() --  Checks to see if an attribute exists in the current node
DomElement->remove_attribute() --  Removes attribute
DomElement->set_attribute() --  Sets the value of an attribute
DomElement->tagname() --  Returns the name of the current element
DomNode->add_namespace --  Adds a namespace declaration to a node
DomNode->append_child --  Adds a new child at the end of the children
DomNode->append_sibling --  Adds new sibling to a node
DomNode->attributes --  Returns list of attributes
DomNode->child_nodes --  Returns children of node
DomNode->clone_node --  Clones a node
DomNode->dump_node --  Dumps a single node
DomNode->first_child --  Returns first child of node
DomNode->get_content --  Gets content of node
DomNode->has_attributes --  Checks if node has attributes
DomNode->has_child_nodes --  Checks if node has children
DomNode->insert_before --  Inserts new node as child
DomNode->is_blank_node --  Checks if node is blank
DomNode->last_child --  Returns last child of node
DomNode->next_sibling --  Returns the next sibling of node
DomNode->node_name --  Returns name of node
DomNode->node_type --  Returns type of node
DomNode->node_value --  Returns value of a node
DomNode->owner_document --  Returns the document this node belongs to
DomNode->parent_node --  Returns the parent of the node
DomNode->prefix --  Returns name space prefix of node
DomNode->previous_sibling --  Returns the previous sibling of node
DomNode->remove_child --  Removes child from list of children
DomNode->replace_child --  Replaces a child
DomNode->replace_node --  Replaces node
DomNode->set_content --  Sets content of node
DomNode->set_name --  Sets name of node
DomNode->set_namespace --  Sets namespace of a node
DomNode->unlink_node --  Deletes node
DomProcessingInstruction->data --  Returns the data of ProcessingInstruction node
DomProcessingInstruction->target --  Returns the target of a ProcessingInstruction node
DomXsltStylesheet->process() --  Applies the XSLT-Transformation on a DomDocument Object
DomXsltStylesheet->result_dump_file() --  Dumps the result from a XSLT-Transformation into a file
DomXsltStylesheet->result_dump_mem() --  Dumps the result from a XSLT-Transformation back into a string
domxml_new_doc --  Creates new empty XML document
domxml_open_file -- Creates a DOM object from an XML file
domxml_open_mem -- Creates a DOM object of an XML document
domxml_version --  Gets the XML library version
domxml_xmltree --  Creates a tree of PHP objects from an XML document
domxml_xslt_stylesheet_doc --  Creates a DomXsltStylesheet Object from a DomDocument Object
domxml_xslt_stylesheet_file --  Creates a DomXsltStylesheet Object from an XSL document in a file
domxml_xslt_stylesheet --  Creates a DomXsltStylesheet object from an XSL document in a string
domxml_xslt_version --  Gets the XSLT library version
xpath_eval_expression --  Evaluates the XPath Location Path in the given string
xpath_eval --  Evaluates the XPath Location Path in the given string
xpath_new_context --  Creates new xpath context
xpath_register_ns_auto --  Register the given namespace in the passed XPath context
xpath_register_ns --  Register the given namespace in the passed XPath context
xptr_eval --  Evaluate the XPtr Location Path in the given string
xptr_new_context --  Create new XPath Context

DomAttribute->name

(no version information, might be only in CVS)

DomAttribute->name --  Returns the name of attribute

说明

class DomAttribute {

string name ( void )

}

Gets the name of the attribute.

返回值

Returns the name of the attribute.

Migrating to PHP 5

Use the name property of DOMAttr.

参见

DomAttribute->value for an example

DomAttribute->set_value

(no version information, might be only in CVS)

DomAttribute->set_value --  Sets the value of an attribute

说明

class DomAttribute {

bool set_value ( string content )

}

This function sets the value of an attribute.

参数

content

The new value.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

Migrating to PHP 5

Set the value property of DOMAttr.

DomAttribute->specified

(no version information, might be only in CVS)

DomAttribute->specified --  Checks if attribute is specified

说明

class DomAttribute {

bool specified ( void )

}

Checks if the attribute was explicitly given a value in the original document.

注: This method is not implemented yet.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

参见

The definition of specified in the DOM Recommendations

DomAttribute->value

(no version information, might be only in CVS)

DomAttribute->value --  Returns value of attribute

说明

class DomAttribute {

string value ( void )

}

This function returns the value of the attribute.

范例

例子 1. Getting all the attributes of a node

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
     echo "Error while parsing the document\n";
     exit;
}

$root = $dom->document_element();
$attrs = $root->attributes();

echo 'Attributes of ' . $root->node_name() . "\n";
foreach ($attrs as $attribute) {
     echo ' - ' . $attribute->name . ' : ' . $attribute->value . "\n";
}

?>

上例将输出:

Attributes of chapter
 - language : en

返回值

Returns the value of the attribute.

Migrating to PHP 5

Use the value property of DOMAttr.

DomDocument->add_root

(no version information, might be only in CVS)

DomDocument->add_root --  Adds a root node [deprecated]

说明

domelement DomDocument->add_root ( string name )

Adds a root element node to a dom document and returns the new node. The element name is given in the passed parameter.

例子 1. Creating a simple HTML document header

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->add_root("html");
$head = $root->new_child("head", "");
$head->new_child("title", "Hier der Titel");
echo htmlentities($doc->dump_mem());
?>

DomDocument->create_attribute

(no version information, might be only in CVS)

DomDocument->create_attribute -- Create new attribute

说明

domattribute DomDocument->create_attribute ( string name, string value )

This function returns a new instance of class DomAttribute. The name of the attribute is the value of the first parameter. The value of the attribute is the value of the second parameter. 本节点不会出现在文档中,除非是用例如 domnode_append_child() 函数来将其插入。

The return value is FALSE if an error occurred.

See also domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_cdata_section(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().

DomDocument->create_cdata_section

(no version information, might be only in CVS)

DomDocument->create_cdata_section -- Create new cdata node

说明

domcdata DomDocument->create_cdata_section ( string content )

This function returns a new instance of class DomCData. The content of the cdata is the value of the passed parameter. 本节点不会出现在文档中,除非是用例如 domnode_append_child() 函数来将其插入。

The return value is FALSE if an error occurred.

See also domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().

DomDocument->create_comment

(no version information, might be only in CVS)

DomDocument->create_comment -- Create new comment node

说明

domcomment DomDocument->create_comment ( string content )

This function returns a new instance of class DomComment. The content of the comment is the value of the passed parameter. 本节点不会出现在文档中,除非是用例如 domnode_append_child() 函数来将其插入。

The return value is FALSE if an error occurred.

See also domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().

DomDocument->create_element_ns

(no version information, might be only in CVS)

DomDocument->create_element_ns --  Create new element node with an associated namespace

说明

domelement DomDocument->create_element_ns ( string uri, string name [, string prefix] )

This function returns a new instance of class DomElement. The tag name of the element is the value of the passed parameter name. The URI of the namespace is the value of the passed parameter uri. If there is already a namespace declaration with the same uri in the root-node of the document, the prefix of this is taken, otherwise it will take the one provided in the optional parameter prefix or generate a random one. 本节点不会出现在文档中,除非是用例如 domnode_append_child() 函数来将其插入。

The return value is FALSE if an error occurred.

See also domdocument_create_element_ns(), domnode_add_namespace(), domnode_set_namespace(), domnode_append_child(), domdocument_create_text(), domdocument_create_comment(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().

DomDocument->create_element

(no version information, might be only in CVS)

DomDocument->create_element -- Create new element node

说明

domelement DomDocument->create_element ( string name )

This function returns a new instance of class DomElement. The tag name of the element is the value of the passed parameter. 本节点不会出现在文档中,除非是用例如 domnode_append_child() 函数来将其插入。

The return value is FALSE if an error occurred.

See also domdocument_create_element_ns(), domnode_append_child(), domdocument_create_text(), domdocument_create_comment(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().

DomDocument->create_entity_reference

(no version information, might be only in CVS)

DomDocument->create_entity_reference --  Create an entity reference

说明

domentityreference DomDocument->create_entity_reference ( string content )

This function returns a new instance of class DomEntityReference. The content of the entity reference is the value of the passed parameter. 本节点不会出现在文档中,除非是用例如 domnode_append_child() 函数来将其插入。

The return value is FALSE if an error occurred.

See also domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_cdata_section(), domdocument_create_processing_instruction(), domdocument_create_attribute(), and domnode_insert_before().

DomDocument->create_processing_instruction

(no version information, might be only in CVS)

DomDocument->create_processing_instruction -- Creates new PI node

说明

domprocessinginstruction DomDocument->create_processing_instruction ( string content )

This function returns a new instance of class DomCData. The content of the pi is the value of the passed parameter. 本节点不会出现在文档中,除非是用例如 domnode_append_child() 函数来将其插入。

The return value is FALSE if an error occurred.

See also domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_cdata_section(), domdocument_create_attribute(), domdocument_create_entity_reference(), and domnode_insert_before().

DomDocument->create_text_node

(no version information, might be only in CVS)

DomDocument->create_text_node -- Create new text node

说明

domtext DomDocument->create_text_node ( string content )

This function returns a new instance of class DomText. The content of the text is the value of the passed parameter. 本节点不会出现在文档中,除非是用例如 domnode_append_child() 函数来将其插入。

The return value is FALSE if an error occurred.

See also domnode_append_child(), domdocument_create_element(), domdocument_create_comment(), domdocument_create_text(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().

DomDocument->doctype

(no version information, might be only in CVS)

DomDocument->doctype --  Returns the document type

说明

domdocumenttype DomDocument->doctype ( void )

This function returns an object of class DomDocumentType. In versions of PHP before 4.3 this has been the class Dtd, but the DOM Standard does not know such a class.

See also the methods of class DomDocumentType.

DomDocument->document_element

(no version information, might be only in CVS)

DomDocument->document_element --  Returns root element node

说明

domelement DomDocument->document_element ( void )

This function returns the root element node of a document.

The following example returns just the element with name CHAPTER and prints it. The other node -- the comment -- is not returned.

例子 1. Retrieving root element

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();
print_r($root);
?>

上例将输出:

domelement Object
(
    [type] => 1
    [tagname] => chapter
    [0] => 6
    [1] => 137960648
)

DomDocument->dump_file

(no version information, might be only in CVS)

DomDocument->dump_file --  Dumps the internal XML tree back into a file

说明

string DomDocument->dump_file ( string filename [, bool compressionmode [, bool format]] )

Creates an XML document from the dom representation. This function usually is called after building a new dom document from scratch as in the example below. The format specifies whether the output should be neatly formatted, or not. The first parameter specifies the name of the filename and the second parameter, whether it should be compressed or not.

例子 1. Creating a simple HTML document header

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->create_element("HTML");
$root = $doc->append_child($root);
$head = $doc->create_element("HEAD");
$head = $root->append_child($head);
$title = $doc->create_element("TITLE");
$title = $head->append_child($title);
$text = $doc->create_text_node("This is the title");
$text = $title->append_child($text);
$doc->dump_file("/tmp/test.xml", false, true);
?>

See also domdocument_dump_mem(), and domdocument_html_dump_mem().

DomDocument->dump_mem

(no version information, might be only in CVS)

DomDocument->dump_mem --  Dumps the internal XML tree back into a string

说明

string DomDocument->dump_mem ( [bool format [, string encoding]] )

Creates an XML document from the dom representation. This function usually is called after building a new dom document from scratch as in the example below. The format specifies whether the output should be neatly formatted, or not.

例子 1. Creating a simple HTML document header

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->create_element("HTML");
$root = $doc->append_child($root);
$head = $doc->create_element("HEAD");
$head = $root->append_child($head);
$title = $doc->create_element("TITLE");
$title = $head->append_child($title);
$text = $doc->create_text_node("This is the title");
$text = $title->append_child($text);
echo "<PRE>";
echo htmlentities($doc->dump_mem(true));
echo "</PRE>";
?>

注: The first parameter was added in PHP 4.3.0.

See also domdocument_dump_file(), and domdocument_html_dump_mem().

DomDocument->get_element_by_id

(no version information, might be only in CVS)

DomDocument->get_element_by_id --  Searches for an element with a certain id

说明

domelement DomDocument->get_element_by_id ( string id )

This function is similar to domdocument_get_elements_by_tagname() but searches for an element with a given id. According to the DOM standard this requires a DTD which defines the attribute ID to be of type ID, though the current implementation simply does an xpath search for "//*[@ID = '%s']". This does not comply to the DOM standard which requires to return null if it is not known which attribute is of type id. This behaviour is likely to be fixed, so do not rely on the current behaviour.

See also domdocument_get_elements_by_tagname()

DomDocument->get_elements_by_tagname

(no version information, might be only in CVS)

DomDocument->get_elements_by_tagname --  Returns array with nodes with given tagname in document or empty array, if not found

说明

array DomDocument->get_elements_by_tagname ( string name )

See also domdocument_add_root()

DomDocument->html_dump_mem

(no version information, might be only in CVS)

DomDocument->html_dump_mem --  Dumps the internal XML tree back into a string as HTML

说明

string DomDocument->html_dump_mem ( void )

Creates an HTML document from the dom representation. This function usually is called after building a new dom document from scratch as in the example below.

例子 1. Creating a simple HTML document header

<?php

// Creates the document
$doc = domxml_new_doc("1.0");

$root = $doc->create_element("html");
$root = $doc->append_child($root);

$head = $doc->create_element("head");
$head = $root->append_child($head);

$title = $doc->create_element("title");
$title = $head->append_child($title);

$text = $doc->create_text_node("This is the title");
$text = $title->append_child($text);

echo $doc->html_dump_mem();
?>

上例将输出:

<html><head><title>This is the title</title></head></html>

See also domdocument_dump_file(), and domdocument_html_dump_mem().

DomDocument->xinclude

(no version information, might be only in CVS)

DomDocument->xinclude --  Substitutes XIncludes in a DomDocument Object

说明

int DomDocument->xinclude ( void )

This function substitutes XIncludes in a DomDocument object.

例子 1. Substituting Xincludes

<?php

// include.xml contains :
// <child>test</child> 

$xml = '<?xml version="1.0"?>
<root xmlns:xi="http://www.w3.org/2001/XInclude">
  <xi:include href="include.xml">
    <xi:fallback>
      <error>xinclude: include.xml not found</error>
    </xi:fallback>
  </xi:include>
</root>';

$domxml = domxml_open_mem($xml);
$domxml->xinclude();

echo $domxml->dump_mem();

?>

上例将输出:

<?xml version="1.0"?>
<root xmlns:xi="http://www.w3.org/2001/XInclude">
  <child>test</child>
</root>

If include.xml doesn't exist, you'll see:

<?xml version="1.0"?>
<root xmlns:xi="http://www.w3.org/2001/XInclude">
  <error>xinclude:dom.xml not found</error>
</root>

DomDocumentType->entities()

(no version information, might be only in CVS)

DomDocumentType->entities() --  Returns list of entities

说明

class DomDocumentType {

array entities ( void )

}

警告

本函数暂无文档,仅有参数列表。

Migrating to PHP 5

Use the entities property of the DOMDocumentType object.

DomDocumentType->internal_subset()

(no version information, might be only in CVS)

DomDocumentType->internal_subset() --  Returns internal subset

说明

class DomDocumentType {

bool internal_subset ( void )

}

警告

本函数暂无文档,仅有参数列表。

Migrating to PHP 5

Use the internalSubset property of the DOMDocumentType object.

DomDocumentType->name()

(no version information, might be only in CVS)

DomDocumentType->name() --  Returns name of document type

说明

class DomDocumentType {

string name ( void )

}

This function returns the name of the document type.

返回值

Returns the name of the DomDocumentType, as a string.

范例

例子 1. Getting the document type's name

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Error while parsing the document\n";
    exit;
}

$doctype = $dom->doctype();
echo $doctype->name(); // chapter

?>

Migrating to PHP 5

Use the name property of the DOMDocumentType object.

DomDocumentType->notations()

(no version information, might be only in CVS)

DomDocumentType->notations() --  Returns list of notations

说明

class DomDocumentType {

array notations ( void )

}

警告

本函数暂无文档,仅有参数列表。

Migrating to PHP 5

Use the notations property of the DOMDocumentType object.

DomDocumentType->public_id()

(no version information, might be only in CVS)

DomDocumentType->public_id() --  Returns public id of document type

说明

class DomDocumentType {

string public_id ( void )

}

This function returns the public id of the document type.

返回值

Returns the public id of the DomDocumentType, as a string.

范例

The following example echos nothing.

例子 1. Retrieving the public id

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$doctype = $dom->doctype();
echo $doctype->public_id();
?>

Migrating to PHP 5

Use the publicId property of the DOMDocumentType object.

DomDocumentType->system_id()

(no version information, might be only in CVS)

DomDocumentType->system_id() --  Returns the system id of document type

说明

class DomDocumentType {

string system_id ( void )

}

Returns the system id of the document type.

返回值

Returns the system id of the DomDocumentType, as a string.

范例

例子 1. Retrieving the system id

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$doctype = $dom->doctype();
echo $doctype->system_id();
?>

上例将输出:

/share/sgml/Norman_Walsh/db3xml10/db3xml10.dtd

Migrating to PHP 5

Use the systemId property of the DOMDocumentType object.

DomElement->get_attribute_node()

(no version information, might be only in CVS)

DomElement->get_attribute_node() --  Returns the node of the given attribute

说明

class DomElement {

DomAttribute get_attribute_node ( string name )

}

Returns the node of the given attribute in the current element.

参数

name

The name of the seeked attribute. This parameter is case sensitive.

返回值

Returns the node of the attribute as a DomAttribute or FALSE if no attribute with the given name is found.

范例

例子 1. Getting an attribute node

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Error while parsing the document\n";
    exit;
}

$root = $dom->document_element();
if ($attribute = $root->get_attribute_node('language')) {
    echo 'Language is: ' . $attribute->value() . "\n";
}

?>

Migrating to PHP 5

Use DOMElement->getAttributeNode().

DomElement->get_attribute()

(no version information, might be only in CVS)

DomElement->get_attribute() --  Returns the value of the given attribute

说明

class DomElement {

string get_attribute ( string name )

}

Returns the value of the given attribute in the current element.

Since PHP 4.3, if no attribute with given name is found, an empty string is returned.

参数

name

The name of the seeked attribute. This parameter is case sensitive.

返回值

Returns the name of the attribute as a string or an empty string if no attribute with the given name is found.

范例

例子 1. Getting the value of an attribute

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Error while parsing the document\n";
    exit;
}

// get chapter
$root = $dom->document_element();
echo $root->get_attribute('language'); // en

?>

Migrating to PHP 5

Use DOMElement->getAttribute().

DomElement->get_elements_by_tagname()

(no version information, might be only in CVS)

DomElement->get_elements_by_tagname() --  Gets elements by tagname

说明

class DomElement {

array get_elements_by_tagname ( string name )

}

Gets all the sub elements with the specific name within the current element.

参数

name

The name of the seeked element.

返回值

Returns an array of DomElement objects.

范例

例子 1. Getting a content

<?php
if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();

$node_array = $root->get_elements_by_tagname('element');

foreach ($node_array as $node) {
    echo ' - ' . $node->get_content() . "\n";
}

?>

Migrating to PHP 5

Use DOMElement->getElementsByTagName().

DomElement->has_attribute()

(no version information, might be only in CVS)

DomElement->has_attribute() --  Checks to see if an attribute exists in the current node

说明

class DomElement {

bool has_attribute ( string name )

}

This functions checks to see if an attribute named name exists in the current node.

参数

name

The name of the tested attribute.

返回值

Returns TRUE if the asked attribute exists, FALSE otherwise.

范例

例子 1. Testing the existence of an attribute

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Error while parsing the document\n";
    exit;
}

$root = $dom->document_element();

$buffer = '<html';
if ($root->has_attribute('language')) {
    $buffer .= 'lang="' . $root->get_attribute('language') . '"';
}
$buffer .= '>';

?>

Migrating to PHP 5

Use DOMElement->hasAttribute().

DomElement->remove_attribute()

(no version information, might be only in CVS)

DomElement->remove_attribute() --  Removes attribute

说明

class DomElement {

bool remove_attribute ( string name )

}

Removes an attribute from the current DomElement node.

参数

name

The name of the attribute to remove.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

Migrating to PHP 5

Use DOMElement->removeAttribute().

DomElement->set_attribute()

(no version information, might be only in CVS)

DomElement->set_attribute() --  Sets the value of an attribute

说明

class DomElement {

DomAttribute set_attribute ( string name, string value )

}

Sets an attribute with name name to the given value.

参数

name

The name of the attribute. If this attribute doesn't exist, it will be created.

value

The value of the attribute.

返回值

Returns the old DomAttribute node, or the new one if you are creating the attribute for the first time.

范例

例子 1. Setting an attribute

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$newnode = $doc->append_child($node);
$newnode->set_attribute("align", "left");
?>

Migrating to PHP 5

Use DOMElement->setAttribute().

DomElement->tagname()

(no version information, might be only in CVS)

DomElement->tagname() --  Returns the name of the current element

说明

class DomElement {

string tagname ( void )

}

Returns the name of the current node. Calling this function is the same as accessing the tagname property, or calling DomNode->node_name on the current node.

返回值

Returns the name of the current DomElement node.

范例

例子 1. Getting the node name

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Error while parsing the document\n";
    exit;
}

$root = $dom->document_element();
echo $root->tagname();   // chapter
echo $root->tagname;     // chapter
echo $root->node_name(); // chapter


?>

Migrating to PHP 5

Use the tagName property of the DOMElement object.

DomNode->add_namespace

(no version information, might be only in CVS)

DomNode->add_namespace --  Adds a namespace declaration to a node

说明

class DOMNode {

bool add_namespace ( string uri, string prefix )

}

This method adds a namespace declaration to a node.

注: This method is not part of the DOM specification.

参数

uri

The namespace URI of the node.

prefix

The namespace prefix of the node.

返回值

如果成功则返回 TRUE,失败则返回 FALSE

Migrating to PHP 5

You can set the namespace URI and prefix of a DOMElement or a DOMAttr at creation time by using DOMDocument->createElementNS() or DOMDocument->createAttributeNS().

注: Remember the an attribute does not inherit its namespace from the element it is attached to.

DomNode->append_child

(no version information, might be only in CVS)

DomNode->append_child --  Adds a new child at the end of the children

说明

class DOMNode {

DOMNode append_child ( DOMNode newnode )

}

This functions appends a child to an existing list of children or creates a new list of children.

参数

newnode

The node being appended. It can be created with e.g. DomDocument->create_element, DomDocument->create_text_node etc. or simply by using any other node.

注: You can not append a DOMAttribute using this method. Use DomElement->set_attribute() instead.

返回值

Returns the appended node on success or FALSE on failure.

更新日志

版本说明
4.3.0 You are not allowed anymore to insert a node from another document.
4.3.0 Prior to PHP 4.3.0, the new child is duplicated before being appended. Therefore the new child is a completely new copy which can be modified without changing the node which was passed to this function. If the node passed has children itself, they will be duplicated as well, which makes it quite easy to duplicate large parts of an XML document. The return value is the appended child. If you plan to do further modifications on the appended child you must use the returned node.
4.3.0 and 4.3.1 The new child newnode is first unlinked from its existing context, if it's already a child of DomNode. Therefore the newnode is moved and not copies anymore. This is the behaviour according to the W3C specifications. If you need the old behaviour, use DomNode->clone_node before appending.
4.3.2 The new child newnode is first unlinked from its existing context, if it's already in the tree. Same rules apply.

范例

The following example adds a new element node to a fresh document and sets the attribute align to left.

例子 1. Adding a child

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$newnode = $doc->append_child($node);
$newnode->set_attribute("align", "left");
?>

The above example could also be written as the following:

例子 2. Adding a child

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$node->set_attribute("align", "left");
$newnode = $doc->append_child($node);
?>

A more complex example is the one below. It first searches for a certain element, duplicates it including its children and adds it as a sibling. Finally a new attribute is added to one of the children of the new sibling and the whole document is dumped.

例子 3. Adding a child

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("informaltable");
print_r($elements);
$element = $elements[0];

$parent = $element->parent_node();
$newnode = $parent->append_child($element);
$children = $newnode->children();
$attr = $children[1]->set_attribute("align", "left");

$xmlfile = $dom->dump_mem();
echo htmlentities($xmlfile);
?>

The above example could also be done with DomNode->insert_before instead of DomNode->append_child.

Migrating to PHP 5

You should use DOMNode->appendChild().

DomNode->append_sibling

(no version information, might be only in CVS)

DomNode->append_sibling --  Adds new sibling to a node

说明

domelement DomNode->append_sibling ( domelement newnode )

This functions appends a sibling to an existing node. The child can be created with e.g. domdocument_create_element(), domdocument_create_text() etc. or simply by using any other node.

Before a new sibling is added it is first duplicated. Therefore the new child is a completely new copy which can be modified without changing the node which was passed to this function. If the node passed has children itself, they will be duplicated as well, which makes it quite easy to duplicate large parts of an XML document. The return value is the added sibling. If you plan to do further modifications on the added sibling you must use the returned node.

This function has been added to provide the behaviour of domnode_append_child() as it works till PHP 4.2.

See also domnode_append_before().

DomNode->attributes

(no version information, might be only in CVS)

DomNode->attributes --  Returns list of attributes

说明

array DomNode->attributes ( void )

This function only returns an array of attributes if the node is of type XML_ELEMENT_NODE.

(PHP >= 4.3 only) If no attributes are found, NULL is returned.

DomNode->child_nodes

(no version information, might be only in CVS)

DomNode->child_nodes --  Returns children of node

说明

array DomNode->child_nodes ( void )

Returns all children of the node.

See also domnode_next_sibling(), and domnode_previous_sibling().

DomNode->clone_node

(no version information, might be only in CVS)

DomNode->clone_node --  Clones a node

说明

domelement DomNode->clone_node ( void )

警告

本函数暂无文档,仅有参数列表。

DomNode->dump_node

(no version information, might be only in CVS)

DomNode->dump_node --  Dumps a single node

说明

string DomNode->dump_node ( void )

警告

本函数暂无文档,仅有参数列表。

See also domdocument_dump_mem().

DomNode->first_child

(no version information, might be only in CVS)

DomNode->first_child --  Returns first child of node

说明

domelement DomNode->first_child ( void )

Returns the first child of the node.

(PHP >= 4.3 only) If no first child is found, NULL is returned.

See also domnode_last_child(), and domnode_next_sibling(), domnode_previous_sibling().

DomNode->get_content

(no version information, might be only in CVS)

DomNode->get_content --  Gets content of node

说明

string DomNode->get_content ( void )

This function returns the content of the actual node.

例子 1. Getting a content

<?php
if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();

$node_array = $root->get_elements_by_tagname("element");

for ($i = 0; $i<count($node_array); $i++) {
    $node = $node_array[$i];
    echo "The element[$i] is: " . $node->get_content();
}

?>

DomNode->has_attributes

(no version information, might be only in CVS)

DomNode->has_attributes --  Checks if node has attributes

说明

bool DomNode->has_attributes ( void )

This function checks if the node has attributes.

See also domnode_has_child_nodes().

DomNode->has_child_nodes

(no version information, might be only in CVS)

DomNode->has_child_nodes --  Checks if node has children

说明

bool DomNode->has_child_nodes ( void )

This function checks if the node has children.

See also domnode_child_nodes().

DomNode->insert_before

(no version information, might be only in CVS)

DomNode->insert_before --  Inserts new node as child

说明

domelement DomNode->insert_before ( domelement newnode, domelement refnode )

This function inserts the new node newnode right before the node refnode. The return value is the inserted node. If you plan to do further modifications on the appended child you must use the returned node.

(PHP >= 4.3 only) If newnode already is part of a document, it will be first unlinked from its existing context. If refnode is NULL, then newnode will be inserted at the end of the list of children.

domnode_insert_before() is very similar to domnode_append_child() as the following example shows which does the same as the example at domnode_append_child().

例子 1. Adding a child

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("informaltable");
print_r($elements);
$element = $elements[0];

$newnode = $element->insert_before($element, $element);
$children = $newnode->children();
$attr = $children[1]->set_attribute("align", "left");

echo "<pre>";
$xmlfile = $dom->dump_mem();
echo htmlentities($xmlfile);
echo "</pre>";
?>

See also domnode_append_child().

DomNode->is_blank_node

(no version information, might be only in CVS)

DomNode->is_blank_node --  Checks if node is blank

说明

bool DomNode->is_blank_node ( void )

警告

本函数暂无文档,仅有参数列表。

DomNode->last_child

(no version information, might be only in CVS)

DomNode->last_child --  Returns last child of node

说明

domelement DomNode->last_child ( void )

Returns the last child of the node.

(PHP >= 4.3 only) If no last child is found, NULL is returned.

See also domnode_first_child(), and domnode_next_sibling(), domnode_previous_sibling().

DomNode->next_sibling

(no version information, might be only in CVS)

DomNode->next_sibling --  Returns the next sibling of node

说明

domelement DomNode->next_sibling ( void )

This function returns the next sibling of the current node. If there is no next sibling it returns FALSE (< 4.3) or null (>= 4.3). You can use this function to iterate over all children of a node as shown in the example.

例子 1. Iterate over children

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("tbody");
$element = $elements[0];
$child = $element->first_child();

while ($child) {
   print_r($child);
   $child = $child->next_sibling();
}
?>

See also domnode_previous_sibling().

DomNode->node_name

(no version information, might be only in CVS)

DomNode->node_name --  Returns name of node

说明

string DomNode->node_name ( void )

Returns name of the node. The name has different meanings for the different types of nodes as illustrated in the following table.

表格 1. Meaning of value

TypeMeaning
DomAttributevalue of attribute
DomAttribute 
DomCDataSection#cdata-section
DomComment#comment
DomDocument#document
DomDocumentTypedocument type name
DomElementtag name
DomEntityname of entity
DomEntityReferencename of entity reference
DomNotationnotation name
DomProcessingInstructiontarget
DomText#text

DomNode->node_type

(no version information, might be only in CVS)

DomNode->node_type --  Returns type of node

说明

int DomNode->node_type ( void )

Returns the type of the node. All possible types are listed in the table in the introduction.

例子 1.

<?php

include 'example.inc';

$dom = domxml_open_mem($xmlstr);

$chapter = $dom->document_element();

// Let's see the elements contained in chapter
foreach($chapter->child_nodes() as $node) {
  if ($node->node_type() == XML_ELEMENT_NODE) {
    echo $node->node_name() . "\n";
  }
}

?>

上例将输出:

title
para

DomNode->node_value

(no version information, might be only in CVS)

DomNode->node_value --  Returns value of a node

说明

string DomNode->node_value ( void )

Returns value of the node. The value has different meanings for the different types of nodes as illustrated in the following table.

表格 1. Meaning of value

TypeMeaning
DomAttributevalue of attribute
DomAttribute 
DomCDataSectioncontent
DomCommentcontent of comment
DomDocumentnull
DomDocumentTypenull
DomElementnull
DomEntitynull
DomEntityReferencenull
DomNotationnull
DomProcessingInstructionentire content without target
DomTextcontent of text

DomNode->owner_document

(no version information, might be only in CVS)

DomNode->owner_document --  Returns the document this node belongs to

说明

domdocument DomNode->owner_document ( void )

This function returns the document the current node belongs to.

The following example will create two identical lists of children.

例子 1. Finding the document of a node

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$node = $doc->append_child($node);
$children = $doc->children();
print_r($children);

$doc2 = $node->owner_document();
$children = $doc2->children();
print_r($children);
?>

See also domnode_insert_before().

DomNode->parent_node

(no version information, might be only in CVS)

DomNode->parent_node --  Returns the parent of the node

说明

domnode DomNode->parent_node ( void )

This function returns the parent node.

(PHP >= 4.3 only) If no parent is found, NULL is returned.

The following example will show two identical lists of children.

例子 1. Finding the document of a node

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$node = $doc->append_child($node);
$children = $doc->children();
print_r($children);

$doc2 = $node->parent_node();
$children = $doc2->children();
print_r($children);
?>

DomNode->prefix

(no version information, might be only in CVS)

DomNode->prefix --  Returns name space prefix of node

说明

string DomNode->prefix ( void )

Returns the name space prefix of the node.

DomNode->previous_sibling

(no version information, might be only in CVS)

DomNode->previous_sibling --  Returns the previous sibling of node

说明

domelement DomNode->previous_sibling ( void )

This function returns the previous sibling of the current node. If there is no previous sibling it returns FALSE (< 4.3) or NULL (>= 4.3). You can use this function to iterate over all children of a node as shown in the example.

See also domnode_next_sibling().

DomNode->remove_child

(no version information, might be only in CVS)

DomNode->remove_child --  Removes child from list of children

说明

domtext DomNode->remove_child ( domtext oldchild )

This functions removes a child from a list of children. If child cannot be removed or is not a child the function will return FALSE. If the child could be removed the functions returns the old child.

例子 1. Removing a child

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("tbody");
$element = $elements[0];
$children = $element->child_nodes();
$child = $element->remove_child($children[0]);

echo "<PRE>";
$xmlfile = $dom->dump_mem(true);
echo htmlentities($xmlfile);
echo "</PRE>";
?>

See also domnode_append_child().

DomNode->replace_child

(no version information, might be only in CVS)

DomNode->replace_child --  Replaces a child

说明

domelement DomNode->replace_child ( domelement oldnode, domelement newnode )

(PHP 4.2) This function replaces the child oldnode with the passed new node. If the new node is already a child it will not be added a second time. If the old node cannot be found the function returns FALSE. If the replacement succeeds the old node is returned.

(PHP 4.3) This function replaces the child oldnode with the passed newnode, even if the new node already is a child of the DomNode. If newnode was already inserted in the document it is first unlinked from its existing context. If the old node cannot be found the function returns FALSE. If the replacement succeeds the old node is returned. (This behaviour is according to the W3C specs).

See also domnode_append_child()

DomNode->replace_node

(no version information, might be only in CVS)

DomNode->replace_node --  Replaces node

说明

domelement DomNode->replace_node ( domelement newnode )

(PHP 4.2) This function replaces an existing node with the passed new node. Before the replacement newnode is copied if it has a parent to make sure a node which is already in the document will not be inserted a second time. This behaviour enforces doing all modifications on the node before the replacement or to refetch the inserted node afterwards with functions like domnode_first_child(), domnode_child_nodes() etc..

(PHP 4.3) This function replaces an existing node with the passed new node. It is not copied anymore. If newnode was already inserted in the document it is first unlinked from its existing context. If the replacement succeeds the old node is returned.

See also domnode_append_child()

DomNode->set_content

(no version information, might be only in CVS)

DomNode->set_content --  Sets content of node

说明

bool DomNode->set_content ( void )

警告

本函数暂无文档,仅有参数列表。

DomNode->set_name

(no version information, might be only in CVS)

DomNode->set_name --  Sets name of node

说明

bool DomNode->set_name ( void )

Sets name of node.

See also domnode_node_name().

DomNode->set_namespace

(no version information, might be only in CVS)

DomNode->set_namespace --  Sets namespace of a node

说明

void DomNode->set_namespace ( string uri [, string prefix] )

Sets the namespace of a node to uri. If there is already a namespace declaration with the same uri in one of the parent nodes of the node, the prefix of this is taken, otherwise it will take the one provided in the optional parameter prefix or generate a random one.

See also domdocument_create_element_ns(), and domnode_add_namespace()

DomNode->unlink_node

(no version information, might be only in CVS)

DomNode->unlink_node --  Deletes node

说明

void DomNode->unlink_node ( void )

警告

本函数暂无文档,仅有参数列表。

DomProcessingInstruction->data

(no version information, might be only in CVS)

DomProcessingInstruction->data --  Returns the data of ProcessingInstruction node

说明

class DomProcessingInstruction {

string data ( void )

}

This method gets the data of the ProcessingInstruction node.

返回值

Returns the data of the Processing Instruction.

Migrating to PHP 5

Use the data property of DOMProcessingInstruction.

DomProcessingInstruction->target

(no version information, might be only in CVS)

DomProcessingInstruction->target --  Returns the target of a ProcessingInstruction node

说明

class DomProcessingInstruction {

string target ( void )

}

This method gets the target of the ProcessingInstruction node.

返回值

Returns the target of the Processing Instruction.

Migrating to PHP 5

Use the target property of DOMProcessingInstruction.

DomXsltStylesheet->process()

(no version information, might be only in CVS)

DomXsltStylesheet->process() --  Applies the XSLT-Transformation on a DomDocument Object

说明

class DomXsltStylesheet {

DomDocument process ( DomDocument xml_doc [, array xslt_params [, bool is_xpath_param [, string profile_filename]]] )

}

Applies an XSLT Transformation on the given DomDocument object.

参数

xml_doc

The XML document being transformed, as a DomDocument object.

xslt_params

An associative array that takes pairs of parameter names and values.

is_xpath_param

If set to FALSE the values of the xslt_params will be quoted. This is the default behavior. It allows you to pass the values as PHP strings.

注: If your strings contains both single and double quotes, you must take care of quoting all the values by yourself and set this parameter to TRUE.

profile_filename

Set this to the path of a filename, if you want profiling information.

返回值

Returns the result of the processing, as a DomDocument object.

更新日志

版本说明
4.3.0 The profile_filename parameter was added.

DomXsltStylesheet->result_dump_file()

(no version information, might be only in CVS)

DomXsltStylesheet->result_dump_file() --  Dumps the result from a XSLT-Transformation into a file

说明

class DomXsltStylesheet {

string result_dump_file ( DomDocument xmldoc, string filename )

}

Since DomXsltStylesheet->process() always returns a well-formed XML DomDocument, no matter what output method was declared in <xsl:output> and similar attributes/elements, it's of not much use, if you want to output HTML 4 or text data.

This function on the contrary honors <xsl:output method="html|text"> and other output control directives. See the example for instruction on how to use it.

范例

例子 1. Saving the result of a XSLT transformation in a file

<?php
$filename = "stylesheet.xsl";
$xmldoc = domxml_open_file("data.xml");
$xsldoc = domxml_xslt_stylesheet_file($filename);
$result =  $xsldoc->process($xmldoc);
echo $xsldoc->result_dump_file($result, "filename");     
?>

DomXsltStylesheet->result_dump_mem()

(no version information, might be only in CVS)

DomXsltStylesheet->result_dump_mem() --  Dumps the result from a XSLT-Transformation back into a string

说明

class DomXsltStylesheet {

string result_dump_mem ( DomDocument xmldoc )

}

Since DomXsltStylesheet->process() always returns a well-formed XML DomDocument, no matter what output method was declared in <xsl:output> and similar attributes/elements, it's of not much use, if you want to output HTML 4 or text data.

This function on the contrary honors <xsl:output method="html|text"> and other output control directives. See the example for instruction on how to use it.

范例

例子 1. Outputting the result of a XSLT transformation

<?php
$filename = "stylesheet.xsl";
$xmldoc = domxml_open_file("data.xml");
$xsldoc = domxml_xslt_stylesheet_file($filename);
$result =  $xsldoc->process($xmldoc);
echo $xsldoc->result_dump_mem($result);     
?>

domxml_new_doc

(PHP 4 >= 4.2.1, PECL)

domxml_new_doc --  Creates new empty XML document

说明

DomDocument domxml_new_doc ( string version )

Creates a new Dom document from scratch and returns it.

参数

version

The XML version number of the document.

返回值

Returns a new DomDocument instance.

domxml_open_file

(PHP 4 >= 4.2.1, PECL)

domxml_open_file -- Creates a DOM object from an XML file

说明

DomDocument domxml_open_file ( string filename [, int mode [, array &error]] )

The function parses the XML document in the given file.

参数

filename

The path to the XML file. The file is accessed in read-only mode.

mode

This optional parameter can be used to change the behavior of this function.

You can use one of the following constants for it: DOMXML_LOAD_PARSING (default), DOMXML_LOAD_VALIDATING or DOMXML_LOAD_RECOVERING. You can add to it also DOMXML_LOAD_DONT_KEEP_BLANKS, DOMXML_LOAD_SUBSTITUTE_ENTITIES and DOMXML_LOAD_COMPLETE_ATTRS by bitwise or.

error

If used, it will contain the error messages. error must be passed in by reference.

返回值

Returns a DomDocument instance of the given file.

范例

例子 1. Opening an XML document from a file

<?php

if (!$dom = domxml_open_file("example.xml")) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();
?>

更新日志

版本说明
4.3.0 The parameters mode and error were added.

domxml_open_mem

(PHP 4 >= 4.2.1, PECL)

domxml_open_mem -- Creates a DOM object of an XML document

说明

DomDocument domxml_open_mem ( string str [, int mode [, array &error]] )

The function parses the XML document in the given string.

参数

str

The contents of the XML file.

mode

This optional parameter can be used to change the behavior of this function.

You can use one of the following constants for it: DOMXML_LOAD_PARSING (default), DOMXML_LOAD_VALIDATING or DOMXML_LOAD_RECOVERING. You can add to it also DOMXML_LOAD_DONT_KEEP_BLANKS, DOMXML_LOAD_SUBSTITUTE_ENTITIES and DOMXML_LOAD_COMPLETE_ATTRS by bitwise or.

error

If used, it will contain the error messages. error must be passed in by reference.

返回值

Returns a DomDocument instance of the given XML contents.

范例

例子 1. Opening an XML document in a string

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();
?>

domxml_version

(PHP 4 >= 4.1.0, PECL)

domxml_version --  Gets the XML library version

说明

string domxml_version ( void )

Gets the version of the XML library currently used.

返回值

The version of the XML library, as a string.

范例

例子 1. domxml_version() Example

<?php

echo domxml_version();

?>

上例的输出类似于:

20607

domxml_xmltree

(PHP 4 >= 4.2.1, PECL)

domxml_xmltree --  Creates a tree of PHP objects from an XML document

说明

DomDocument domxml_xmltree ( string str )

The function parses the XML document in str and returns a tree PHP objects as the parsed document.

This function is isolated from the other functions, which means you cannot access the tree with any of the other functions. Modifying it, for example by adding nodes, makes no sense since there is currently no way to dump it as an XML file.

However this function may be valuable if you want to read a file and investigate the content.

参数

str

The contents of the XML file.

返回值

Returns a tree of Dom objects starting by a DomDocument.

domxml_xslt_stylesheet_doc

(PHP 4 >= 4.2.0, PECL)

domxml_xslt_stylesheet_doc --  Creates a DomXsltStylesheet Object from a DomDocument Object

说明

DomXsltStylesheet domxml_xslt_stylesheet_doc ( DomDocument xsl_doc )

Creates a DomXsltStylesheet object from the given XSL document.

参数

xsl_doc

The XSL document, as a DomDocument object.

返回值

Returns a new instance of DomXsltStylesheet.

Migrating to PHP 5

Call XSLTProcessor->importStylesheet() with the xsl_doc parameter.

domxml_xslt_stylesheet_file

(PHP 4 >= 4.2.0, PECL)

domxml_xslt_stylesheet_file --  Creates a DomXsltStylesheet Object from an XSL document in a file

说明

DomXsltStylesheet domxml_xslt_stylesheet_file ( string xsl_file )

Creates a DomXsltStylesheet object from the given XSL file.

参数

xsl_file

The path to the XSL document, as a string.

返回值

Returns a new instance of DomXsltStylesheet.

Migrating to PHP 5

Call XSLTProcessor->importStylesheet() with DOMDocument::load($xsl_file) as parameter.

domxml_xslt_stylesheet

(PHP 4 >= 4.2.0, PECL)

domxml_xslt_stylesheet --  Creates a DomXsltStylesheet object from an XSL document in a string

说明

DomXsltStylesheet domxml_xslt_stylesheet ( string xsl_buf )

Creates a DomXsltStylesheet object from the given XSL buffer.

参数

xsl_buf

The XSL document, as a string.

返回值

Returns a new instance of DomXsltStylesheet.

Migrating to PHP 5

Call XSLTProcessor->importStylesheet() with DOMDocument::loadXML($xsl_buf) as parameter.

domxml_xslt_version

(PHP 4 >= 4.2.0, PECL)

domxml_xslt_version --  Gets the XSLT library version

说明

int domxml_xslt_version ( void )

Gets the XSLT library version.

返回值

Returns the version number of the XSLT library, as an integer.

范例

例子 1. domxml_xslt_version() Example

<?php

echo domxml_xslt_version();

?>

上例的输出类似于:

10112

xpath_eval_expression

(PHP 4 >= 4.0.4, PECL)

xpath_eval_expression --  Evaluates the XPath Location Path in the given string

说明

class XPathContext {

XPathObject xpath_eval_expression ( string expression [, domnode contextnode] )

}XPathObject xpath_eval_expression ( XPathContext xpath_context, string expression [, domnode contextnode] )

例子 1. xpath_eval_expression() Example

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Error while parsing the document\n";
    exit;
}

$xpath = xpath_new_context($dom);
var_dump(xpath_eval_expression($xpath, '/chapter/@language'));

?>

上例将输出:

object(XPathObject)(2) {
   ["type"]=>
   int(1)
   ["nodeset"]=>
   array(1) {
     [0]=>
     object(domattribute)(5) {
       ["type"]=>
       int(2)
       ["name"]=>
       string(8) "language"
       ["value"]=>
       string(2) "en"
       [0]=>
       int(7)
       [1]=>
       int(138004256)
     }
  }
}

See also xpath_eval().

xpath_eval

(PHP 4 >= 4.0.4, PECL)

xpath_eval --  Evaluates the XPath Location Path in the given string

说明

class XPathContext {

XPathObject xpath_eval ( string xpath_expression [, domnode contextnode] )

}XPathObject xpath_eval ( XPathContext xpath_context, string xpath_expression [, domnode contextnode] )

The optional contextnode can be specified for doing relative XPath queries.

See also xpath_new_context().

xpath_new_context

(PHP 4 >= 4.0.4, PECL)

xpath_new_context --  Creates new xpath context

说明

XPathContext xpath_new_context ( domdocument dom_document )

See also xpath_eval().

xpath_register_ns_auto

(PECL)

xpath_register_ns_auto --  Register the given namespace in the passed XPath context

说明

bool xpath_register_ns_auto ( XPathContext xpath_context [, object context_node] )

警告

本函数暂无文档,仅有参数列表。

返回值

如果成功则返回 TRUE,失败则返回 FALSE

xpath_register_ns

(PHP 4 >= 4.2.0, PECL)

xpath_register_ns --  Register the given namespace in the passed XPath context

说明

bool xpath_register_ns ( XPathContext xpath_context, string prefix, string uri )

警告

本函数暂无文档,仅有参数列表。

返回值

如果成功则返回 TRUE,失败则返回 FALSE

xptr_eval

(PHP 4 >= 4.0.4, PECL)

xptr_eval --  Evaluate the XPtr Location Path in the given string

说明

class XPathContext {

int xptr_eval ( string eval_str [, domnode contextnode] )

}int xptr_eval ( XPathContext xpath_context, string eval_str [, domnode contextnode] )

警告

本函数暂无文档,仅有参数列表。

xptr_new_context

(PHP 4 >= 4.0.4, PECL)

xptr_new_context --  Create new XPath Context

说明

XPathContext xptr_new_context ( void )

警告

本函数暂无文档,仅有参数列表。

XXXI. Error Handling and Logging Functions

简介

These are functions dealing with error handling and logging. They allow you to define your own error handling rules, as well as modify the way the errors can be logged. This allows you to change and enhance error reporting to suit your needs.

With the logging functions, you can send messages directly to other machines, to an email (or email to pager gateway!), to system logs, etc., so you can selectively log and monitor the most important parts of your applications and websites.

The error reporting functions allow you to customize what level and kind of error feedback is given, ranging from simple notices to customized functions returned during errors.


需求

要编译本扩展模块不需要外部库文件。


安装

本函数库作为 PHP 内核的一部分,不用安装就能使用。


运行时配置

这些函数的行为受 php.ini 的影响。

表格 1. Errors and Logging Configuration Options

NameDefaultChangeableChangelog
error_reportingNULLPHP_INI_ALL 
display_errors"1"PHP_INI_ALL 
display_startup_errors"0"PHP_INI_ALLAvailable since PHP 4.0.3.
log_errors"0"PHP_INI_ALL 
log_errors_max_len"1024"PHP_INI_ALLAvailable since PHP 4.3.0.
ignore_repeated_errors"0"PHP_INI_ALLAvailable since PHP 4.3.0.
ignore_repeated_source"0"PHP_INI_ALLAvailable since PHP 4.3.0.
report_memleaks"1"PHP_INI_ALLAvailable since PHP 4.3.0.
track_errors"0"PHP_INI_ALL 
html_errors"1"PHP_INI_ALLPHP_INI_SYSTEM in PHP <= 4.2.3. Available since PHP 4.0.2.
docref_root""PHP_INI_ALLAvailable since PHP 4.3.0.
docref_ext""PHP_INI_ALLAvailable since PHP 4.3.2.
error_prepend_stringNULLPHP_INI_ALL 
error_append_stringNULLPHP_INI_ALL 
error_logNULLPHP_INI_ALL 
warn_plus_overloadingNULLPHP_INI?? 
有关 PHP_INI_* 常量进一步的细节与定义参见附录 G

以下是配置选项的简要解释。

error_reporting integer

Set the error reporting level. The parameter is either an integer representing a bit field, or named constants. The error_reporting levels and constants are described in Predefined Constants, and in php.ini. To set at runtime, use the error_reporting() function. See also the display_errors directive.

In PHP 4 and PHP 5 the default value is E_ALL & ~E_NOTICE. This setting does not show E_NOTICE level errors. You may want to show them during development.

注: Enabling E_NOTICE during development has some benefits. For debugging purposes: NOTICE messages will warn you about possible bugs in your code. For example, use of unassigned values is warned. It is extremely useful to find typos and to save time for debugging. NOTICE messages will warn you about bad style. For example, $arr[item] is better to be written as $arr['item'] since PHP tries to treat "item" as constant. If it is not a constant, PHP assumes it is a string index for the array.

注: In PHP 5 a new error level E_STRICT is available. As E_STRICT is not included within E_ALL you have to explicitly enable this kind of error level. Enabling E_STRICT during development has some benefits. STRICT messages will help you to use the latest and greatest suggested method of coding, for example warn you about using deprecated functions.

In PHP 3, the default setting is (E_ERROR | E_WARNING | E_PARSE), meaning the same thing. Note, however, that since constants are not supported in PHP 3's php3.ini, the error_reporting setting there must be numeric; hence, it is 7.

display_errors boolean

This determines whether errors should be printed to the screen as part of the output or if they should be hidden from the user.

注: This is a feature to support your development and should never be used on production systems (e.g. systems connected to the internet).

注: Although display_errors may be set at runtime (with ini_set ()), it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.

display_startup_errors boolean

Even when display_errors is on, errors that occur during PHP's startup sequence are not displayed. It's strongly recommended to keep display_startup_errors off, except for debugging.

log_errors boolean

Tells whether script error messages should be logged to the server's error log or error_log. This option is thus server-specific.

注: You're strongly advised to use error logging in place of error displaying on production web sites.

log_errors_max_len integer

Set the maximum length of log_errors in bytes. In error_log information about the source is added. The default is 1024 and 0 allows to not apply any maximum length at all. This length is applied to logged errors, displayed errors and also to $php_errormsg.

当使用 integer 类型时,其值以字节为度量单位。还可以用简化符号,说明见此 FAQ

ignore_repeated_errors boolean

Do not log repeated messages. Repeated errors must occur in the same file on the same line until ignore_repeated_source is set true.

ignore_repeated_source boolean

Ignore source of message when ignoring repeated messages. When this setting is On you will not log errors with repeated messages from different files or sourcelines.

report_memleaks boolean

If this parameter is set to Off, then memory leaks will not be shown (on stdout or in the log). This has only effect in a debug compile, and if error_reporting includes E_WARNING in the allowed list

track_errors boolean

If enabled, the last error message will always be present in the variable $php_errormsg.

html_errors boolean

Turn off HTML tags in error messages. The new format for HTML errors produces clickable messages that direct the user to a page describing the error or function in causing the error. These references are affected by docref_root and docref_ext.

docref_root string

The new error format contains a reference to a page describing the error or function causing the error. In case of manual pages you can download the manual in your language and set this ini directive to the URL of your local copy. If your local copy of the manual can be reached by '/manual/' you can simply use docref_root=/manual/. Additional you have to set docref_ext to match the fileextensions of your copy docref_ext=.html. It is possible to use external references. For example you can use docref_root=http://manual/en/ or docref_root="http://landonize.it/?how=url&theme=classic&filter=Landon &url=http%3A%2F%2Fwww.php.net%2F"

Most of the time you want the docref_root value to end with a slash '/'. But see the second example above which does not have nor need it.

注: This is a feature to support your development since it makes it easy to lookup a function description. However it should never be used on production systems (e.g. systems connected to the internet).

docref_ext string

See docref_root.

注: The value of docref_ext must begin with a dot '.'.

error_prepend_string string

String to output before an error message.

error_append_string string

String to output after an error message.

error_log string

Name of the file where script errors should be logged. The file should be writable by the web server's user. If the special value syslog is used, the errors are sent to the system logger instead. On Unix, this means syslog(3) and on Windows NT it means the event log. The system logger is not supported on Windows 95. See also: syslog().

warn_plus_overloading boolean

If enabled, this option makes PHP output a warning when the plus (+) operator is used on strings. This is to make it easier to find scripts that need to be rewritten to using the string concatenator instead (.).


预定义常量

以下常量作为 PHP 核心的一部分一直有效。

注: You may use these constant names in php.ini but not outside of PHP, like in httpd.conf, where you'd use the bitmask values instead.

表格 2. Errors and Logging

ValueConstantDescriptionNote
1 E_ERROR (integer) Fatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted.  
2 E_WARNING (integer) Run-time warnings (non-fatal errors). Execution of the script is not halted.  
4 E_PARSE (integer) Compile-time parse errors. Parse errors should only be generated by the parser.  
8 E_NOTICE (integer) Run-time notices. Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script.  
16 E_CORE_ERROR (integer) Fatal errors that occur during PHP's initial startup. This is like an E_ERROR, except it is generated by the core of PHP. since PHP 4
32 E_CORE_WARNING (integer) Warnings (non-fatal errors) that occur during PHP's initial startup. This is like an E_WARNING, except it is generated by the core of PHP. since PHP 4
64 E_COMPILE_ERROR (integer) Fatal compile-time errors. This is like an E_ERROR, except it is generated by the Zend Scripting Engine. since PHP 4
128 E_COMPILE_WARNING (integer) Compile-time warnings (non-fatal errors). This is like an E_WARNING, except it is generated by the Zend Scripting Engine. since PHP 4
256 E_USER_ERROR (integer) User-generated error message. This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error(). since PHP 4
512 E_USER_WARNING (integer) User-generated warning message. This is like an E_WARNING, except it is generated in PHP code by using the PHP function trigger_error(). since PHP 4
1024 E_USER_NOTICE (integer) User-generated notice message. This is like an E_NOTICE, except it is generated in PHP code by using the PHP function trigger_error(). since PHP 4
2047 E_ALL (integer) All errors and warnings, as supported, except of level E_STRICT.  
2048 E_STRICT (integer) Run-time notices. Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code. since PHP 5

The above values (either numerical or symbolic) are used to build up a bitmask that specifies which errors to report. You can use the bitwise operators to combine these values or mask out certain types of errors. Note that only '|', '~', '!', '^' and '&' will be understood within php.ini, however, and that no bitwise operators will be understood within php3.ini.


范例

Below we can see an example of using the error handling capabilities in PHP. We define an error handling function which logs the information into a file (using an XML format), and e-mails the developer in case a critical error in the logic happens.

例子 1. Using error handling in a script

<?php
// we will do our own error handling
error_reporting(0);

// user defined error handling function
function userErrorHandler($errno, $errmsg, $filename, $linenum, $vars) 
{
    // timestamp for the error entry
    $dt = date("Y-m-d H:i:s (T)");

    // define an assoc array of error string
    // in reality the only entries we should
    // consider are E_WARNING, E_NOTICE, E_USER_ERROR,
    // E_USER_WARNING and E_USER_NOTICE
    $errortype = array (
                E_ERROR           => "Error",
                E_WARNING         => "Warning",
                E_PARSE           => "Parsing Error",
                E_NOTICE          => "Notice",
                E_CORE_ERROR      => "Core Error",
                E_CORE_WARNING    => "Core Warning",
                E_COMPILE_ERROR   => "Compile Error",
                E_COMPILE_WARNING => "Compile Warning",
                E_USER_ERROR      => "User Error",
                E_USER_WARNING    => "User Warning",
                E_USER_NOTICE     => "User Notice",
                E_STRICT          => "Runtime Notice"
                );
    // set of errors for which a var trace will be saved
    $user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE);
    
    $err = "<errorentry>\n";
    $err .= "\t<datetime>" . $dt . "</datetime>\n";
    $err .= "\t<errornum>" . $errno . "</errornum>\n";
    $err .= "\t<errortype>" . $errortype[$errno] . "</errortype>\n";
    $err .= "\t<errormsg>" . $errmsg . "</errormsg>\n";
    $err .= "\t<scriptname>" . $filename . "</scriptname>\n";
    $err .= "\t<scriptlinenum>" . $linenum . "</scriptlinenum>\n";

    if (in_array($errno, $user_errors)) {
        $err .= "\t<vartrace>" . wddx_serialize_value($vars, "Variables") . "</vartrace>\n";
    }
    $err .= "</errorentry>\n\n";
    
    // for testing
    // echo $err;

    // save to the error log, and e-mail me if there is a critical user error
    error_log($err, 3, "/usr/local/php4/error.log");
    if ($errno == E_USER_ERROR) {
        mail("phpdev@example.com", "Critical User Error", $err);
    }
}


function distance($vect1, $vect2) 
{
    if (!is_array($vect1) || !is_array($vect2)) {
        trigger_error("Incorrect parameters, arrays expected", E_USER_ERROR);
        return NULL;
    }

    if (count($vect1) != count($vect2)) {
        trigger_error("Vectors need to be of the same size", E_USER_ERROR);
        return NULL;
    }

    for ($i=0; $i<count($vect1); $i++) {
        $c1 = $vect1[$i]; $c2 = $vect2[$i];
        $d = 0.0;
        if (!is_numeric($c1)) {
            trigger_error("Coordinate $i in vector 1 is not a number, using zero", 
                            E_USER_WARNING);
            $c1 = 0.0;
        }
        if (!is_numeric($c2)) {
            trigger_error("Coordinate $i in vector 2 is not a number, using zero", 
                            E_USER_WARNING);
            $c2 = 0.0;
        }
        $d += $c2*$c2 - $c1*$c1;
    }
    return sqrt($d);
}

$old_error_handler = set_error_handler("userErrorHandler");

// undefined constant, generates a warning
$t = I_AM_NOT_DEFINED;

// define some "vectors"
$a = array(2, 3, "foo");
$b = array(5.5, 4.3, -1.6);
$c = array(1, -3);

// generate a user error
$t1 = distance($c, $b) . "\n";

// generate another user error
$t2 = distance($b, "i am not an array") . "\n";

// generate a warning
$t3 = distance($a, $b) . "\n";

?>


参见

See also syslog().

目录
debug_backtrace -- Generates a backtrace
debug_print_backtrace --  Prints a backtrace
error_log -- Send an error message somewhere
error_reporting -- Sets which PHP errors are reported
restore_error_handler -- Restores the previous error handler function
restore_exception_handler --  Restores the previously defined exception handler function
set_error_handler --  Sets a user-defined error handler function
set_exception_handler --  Sets a user-defined exception handler function
trigger_error -- Generates a user-level error/warning/notice message
user_error -- Alias of trigger_error()

debug_backtrace

(PHP 4 >= 4.3.0, PHP 5)

debug_backtrace -- Generates a backtrace

说明

array debug_backtrace ( void )

debug_backtrace() generates a PHP backtrace.

返回值

Returns an associative array. The possible returned elements are as follows:

表格 1. Possible returned elements from debug_backtrace()

NameTypeDescription
functionstring The current function name. See also __FUNCTION__.
lineinteger The current line number. See also __LINE__.
filestring The current file name. See also __FILE__.
classstring The current class name. See also __CLASS__
typestring The current call type. If a method call, "->" is returned. If a static method call, "::" is returned. If a function call, nothing is returned.
argsarray If inside a function, this lists the functions arguments. If inside an included file, this lists the included file name(s).

范例

例子 1. debug_backtrace() example

<?php
// filename: a.php

function a_test($str)
{
    echo "\nHi: $str";
    var_dump(debug_backtrace());
}

a_test('friend');
?>

<?php
// filename: b.php
include_once '/tmp/a.php';
?>

Results similar to the following when executing /tmp/b.php:

Hi: friend
array(2) {
[0]=>
array(4) {
    ["file"] => string(10) "/tmp/a.php"
    ["line"] => int(10)
    ["function"] => string(6) "a_test"
    ["args"]=>
    array(1) {
      [0] => &string(6) "friend"
    }
}
[1]=>
array(4) {
    ["file"] => string(10) "/tmp/b.php"
    ["line"] => int(2)
    ["args"] =>
    array(1) {
      [0] => string(10) "/tmp/a.php"
    }
    ["function"] => string(12) "include_once"
  }
}

debug_print_backtrace

(PHP 5)

debug_print_backtrace --  Prints a backtrace

说明

void debug_print_backtrace ( void )

debug_print_backtrace() prints a PHP backtrace. It prints the function calls, included/required files and eval()ed stuff.

参数

This function has no parameters.

返回值

无返回值。

范例

例子 1. debug_print_backtrace() example

<?php
// include.php file

function a() {
    b();
}

function b() {
    c();
}

function c(){
    debug_print_backtrace();
}

a();

?>


<?php
// test.php file
// this is the file you should run

include 'include.php';
?>

上例的输出类似于:

#0  eval() called at [/tmp/include.php:5]
#1  a() called at [/tmp/include.php:17]
#2  include(/tmp/include.php) called at [/tmp/test.php:3]

#0  c() called at [/tmp/include.php:10]
#1  b() called at [/tmp/include.php:6]
#2  a() called at [/tmp/include.php:17]
#3  include(/tmp/include.php) called at [/tmp/test.php:3]

error_log

(PHP 3, PHP 4, PHP 5)

error_log -- Send an error message somewhere

说明

bool error_log ( string message [, int message_type [, string destination [, string extra_headers]]] )

Sends an error message to the web server's error log, a TCP port or to a file.

参数

message

The error message that should be logged.

message_type

Says where the error should go. The possible message types are as follows:

表格 1. error_log() log types

0 message is sent to PHP's system logger, using the Operating System's system logging mechanism or a file, depending on what the error_log configuration directive is set to. This is the default option.
1 message is sent by email to the address in the destination parameter. This is the only message type where the fourth parameter, extra_headers is used.
2 message is sent through the PHP debugging connection. This option is only available if remote debugging has been enabled. In this case, the destination parameter specifies the host name or IP address and optionally, port number, of the socket receiving the debug information. This option is only available in PHP 3.
3 message is appended to the file destination. A newline is not automatically added to the end of the message string.

destination

The destination. Its meaning depends on the message parameter as described above.

extra_headers

The extra headers. It's used when the message parameter is set to 1. This message type uses the same internal function as mail() does.

范例

例子 1. error_log() examples

<?php
// Send notification through the server log if we can not
// connect to the database.
if (!Ora_Logon($username, $password)) {
    error_log("Oracle database not available!", 0);
}

// Notify administrator by email if we run out of FOO
if (!($foo = allocate_new_foo())) {
    error_log("Big trouble, we're all out of FOOs!", 1,
               "operator@example.com");
}

// other ways of calling error_log():
error_log("You messed up!", 2, "127.0.0.1:7000");
error_log("You messed up!", 2, "loghost");
error_log("You messed up!", 3, "/var/tmp/my-errors.log");
?>

error_reporting

(PHP 3, PHP 4, PHP 5)

error_reporting -- Sets which PHP errors are reported

说明

int error_reporting ( [int level] )

The error_reporting() function sets the error_reporting directive at runtime. PHP has many levels of errors, using this function sets that level for the duration (runtime) of your script.

参数

level

The new error_reporting level. It takes on either a bitmask, or named constants. Using named constants is strongly encouraged to ensure compatibility for future versions. As error levels are added, the range of integers increases, so older integer-based error levels will not always behave as expected.

The available error level constants are listed below. The actual meanings of these error levels are described in the predefined constants.

表格 1. error_reporting() level constants and bit values

valueconstant
1 E_ERROR
2 E_WARNING
4 E_PARSE
8 E_NOTICE
16 E_CORE_ERROR
32 E_CORE_WARNING
64 E_COMPILE_ERROR
128 E_COMPILE_WARNING
256 E_USER_ERROR
512 E_USER_WARNING
1024 E_USER_NOTICE
2047 E_ALL
2048 E_STRICT

返回值

Returns the old error_reporting level.

范例

例子 1. error_reporting() examples

<?php

// Turn off all error reporting
error_reporting(0);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);

// Report all PHP errors (bitwise 63 may be used in PHP 3)
error_reporting(E_ALL);

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

?>

注释

警告

With PHP > 5.0.0 E_STRICT with value 2048 is available. E_ALL does NOT include error level E_STRICT. Most of E_STRICT errors are evaluated at the compile time thus such errors are not reported in the file where error_reporting is enhanced to include E_STRICT errors.

参见

The display_errors directive
ini_set()

restore_error_handler

(PHP 4 >= 4.0.1, PHP 5)

restore_error_handler -- Restores the previous error handler function

说明

bool restore_error_handler ( void )

Used after changing the error handler function using set_error_handler(), to revert to the previous error handler (which could be the built-in or a user defined function).

返回值

This function always returns TRUE

范例

例子 1. restore_error_handler() example

Decide if unserialize() caused an error, then restore the original error handler.

<?php
function unserialize_handler($errno, $errstr)
{
    echo "Invalid serialized value.\n";
}

$serialized = 'foo';
set_error_handler('unserialize_handler');
$original = unserialize($serialized);
restore_error_handler();
?>

上例将输出:

Invalid serialized value.

注释

注: Calling restore_error_handler() from the error_handler function is ignored.

restore_exception_handler

(PHP 5)

restore_exception_handler --  Restores the previously defined exception handler function

说明

bool restore_exception_handler ( void )

Used after changing the exception handler function using set_exception_handler(), to revert to the previous exception handler (which could be the built-in or a user defined function).

返回值

This function always returns TRUE

set_error_handler

(PHP 4 >= 4.0.1, PHP 5)

set_error_handler --  Sets a user-defined error handler function

说明

mixed set_error_handler ( callback error_handler [, int error_types] )

Sets a user function (error_handler) to handle errors in a script.

This function can be used for defining your own way of handling errors during runtime, for example in applications in which you need to do cleanup of data/files when a critical error happens, or when you need to trigger an error under certain conditions (using trigger_error()).

It is important to remember that the standard PHP error handler is completely bypassed. error_reporting() settings will have no effect and your error handler will be called regardless - however you are still able to read the current value of error_reporting and act appropriately. Of particular note is that this value will be 0 if the statement that caused the error was prepended by the @ error-control operator.

Also note that it is your responsibility to die() if necessary. If the error-handler function returns, script execution will continue with the next statement after the one that caused an error.

The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.

If errors occur before the script is executed (e.g. on file uploads) the custom error handler cannot be called since it is not registered at that time.

参数

error_handler

The user function needs to accept two parameters: the error code, and a string describing the error. Then there are three optional parameters that may be supplied: the filename in which the error occurred, the line number in which the error occurred, and the context in which the error occurred (an array that points to the active symbol table at the point the error occurred). The function can be shown as:

handler ( int errno, string errstr [, string errfile [, int errline [, array errcontext]]] )

errno

The first parameter, errno, contains the level of the error raised, as an integer.

errstr

The second parameter, errstr, contains the error message, as a string.

errfile

The third parameter is optional, errfile, which contains the filename that the error was raised in, as a string.

errline

The fourth parameter is optional, errline, which contains the line number the error was raised at, as an integer.

errcontext

The fifth parameter is optional, errcontext, which is an array that points to the active symbol table at the point the error occurred. In other words, errcontext will contain an array of every variable that existed in the scope the error was triggered in.

error_types

Can be used to mask the triggering of the error_handler function just like the error_reporting ini setting controls which errors are shown. Without this mask set the error_handler will be called for every error regardless to the setting of the error_reporting setting.

返回值

Returns a string containing the previously defined error handler (if any), or FALSE on error. If the previous handler was a class method, this function will return an indexed array with the class and the method name.

更新日志

版本说明
5.0.0 The error_types parameter was introduced.
4.3.0 Instead of a function name, an array containing an object reference and a method name can also be supplied as the error_handler.
4.0.2 Three optional parameters for the error_handler user function was introduced. These are the filename, the line number, and the context.

范例

例子 1. Error handling with set_error_handler() and trigger_error()

The example below shows the handling of internal exceptions by triggering errors and handling them with a user defined function:

<?php
// set the error reporting level for this script
error_reporting(E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE);

// error handler function
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
  switch ($errno) {
  case E_USER_ERROR:
    echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
    echo "  Fatal error in line $errline of file $errfile";
    echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
    echo "Aborting...<br />\n";
    exit(1);
    break;
  case E_USER_WARNING:
    echo "<b>My WARNING</b> [$errno] $errstr<br />\n";
    break;
  case E_USER_NOTICE:
    echo "<b>My NOTICE</b> [$errno] $errstr<br />\n";
    break;
  default:
    echo "Unkown error type: [$errno] $errstr<br />\n";
    break;
  }
}

// function to test the error handling
function scale_by_log($vect, $scale)
{
  if (!is_numeric($scale) || $scale <= 0) {
    trigger_error("log(x) for x <= 0 is undefined, you used: scale = $scale", E_USER_ERROR);
  }

  if (!is_array($vect)) {
    trigger_error("Incorrect input vector, array of values expected", E_USER_WARNING);
    return null;
  }

  for ($i=0; $i<count($vect); $i++) {
    if (!is_numeric($vect[$i]))
      trigger_error("Value at position $i is not a number, using 0 (zero)", E_USER_NOTICE);
      $temp[$i] = log($scale) * $vect[$i];
    }
    return $temp;
  }

// set to the user defined error handler
$old_error_handler = set_error_handler("myErrorHandler");

// trigger some errors, first define a mixed array with a non-numeric item
echo "vector a\n";
$a = array(2,3, "foo", 5.5, 43.3, 21.11);
print_r($a);

// now generate second array, generating a warning
echo "----\nvector b - a warning (b = log(PI) * a)\n";
$b = scale_by_log($a, M_PI);
print_r($b);

// this is trouble, we pass a string instead of an array
echo "----\nvector c - an error\n";
$c = scale_by_log("not array", 2.3);
var_dump($c);

// this is a critical error, log of zero or negative number is undefined
echo "----\nvector d - fatal error\n";
$d = scale_by_log($a, -2.5);

?>

上例的输出类似于:

vector a
Array
(
    [0] => 2
    [1] => 3
    [2] => foo
    [3] => 5.5
    [4] => 43.3
    [5] => 21.11
)
----
vector b - a warning (b = log(PI) * a)
<b>WARNING</b> [1024] Value at position 2 is not a number, using 0 (zero)<br />
Array
(
    [0] => 2.2894597716988
    [1] => 3.4341896575482
    [2] => 0
    [3] => 6.2960143721717
    [4] => 49.566804057279
    [5] => 24.165247890281
)
----
vector c - an error
<b>ERROR</b> [512] Incorrect input vector, array of values expected<br />
NULL
----
vector d - fatal error
<b>FATAL</b> [256] log(x) for x <= 0 is undefined, you used: scale = -2.5<br />
Fatal error in line 36 of file trigger_error.php, PHP 4.0.2 (Linux)<br />
Aborting...<br />

set_exception_handler

(PHP 5)

set_exception_handler --  Sets a user-defined exception handler function

说明

string set_exception_handler ( callback exception_handler )

Sets the default exception handler if an exception is not caught within a try/catch block. Execution will stop after the exception_handler is called.

The exception_handler must be defined before calling set_exception_handler(). This handler function needs to accept one parameter, which will be the exception object that was thrown.

参数

exception_handler

Name of the function to be called when an uncaught exception occurs.

返回值

Returns the name of the previously defined exception handler, or FALSE on error. If no previous handler was defined, an empty string is returned.

范例

例子 1. set_exception_handler() example

<?php
function exception_handler($exception) {
  echo "Uncaught exception: " , $exception->getMessage(), "\n";
}

set_exception_handler('exception_handler');

throw new Exception('Uncaught Exception');
echo "Not Executed\n";
?>

trigger_error

(PHP 4 >= 4.0.1, PHP 5)

trigger_error -- Generates a user-level error/warning/notice message

说明

bool trigger_error ( string error_msg [, int error_type] )

Used to trigger a user error condition, it can be used by in conjunction with the built-in error handler, or with a user defined function that has been set as the new error handler (set_error_handler()).

This function is useful when you need to generate a particular response to an exception at runtime.

参数

error_msg

The designated error message for this error. It's limited to 1024 characters in length. Any additional characters beyond 1024 will be truncated.

error_type

The designated error type for this error. It only works with the E_USER family of constants, and will default to E_USER_NOTICE.

返回值

This function returns FALSE if wrong error_type is specified, TRUE otherwise.

范例

例子 1. trigger_error() example

See set_error_handler() for a more extensive example.

<?php
if (assert($divisor == 0)) {
    trigger_error("Cannot divide by zero", E_USER_ERROR);
}
?>

user_error

(PHP 4, PHP 5)

user_error -- Alias of trigger_error()

说明

本函数是该函数的别名: trigger_error().

XXXII. Exif Functions

简介

With the exif extension you are able to work with image meta data. For example, you may use exif functions to read meta data of pictures taken from digital cameras by working with information stored in the headers of the JPEG and TIFF images.


需求

Your PHP must be compiled in with --enable-exif. PHP does not require any additional library for the exif module. Windows users must also have the mbstring extension enabled.


安装

To enable exif-support configure PHP with --enable-exif

Windows users must enable both the php_mbstring.dll and php_exif.dll DLL's in php.ini. The php_mbstring.dll DLL must be loaded before the php_exif.dll DLL so adjust your php.ini accordingly.


运行时配置

这些函数的行为受 php.ini 的影响。

mbstring 模块可用时,exif 支持用户注释中的 Unicode 和 JIS 字符编码的自动转换。这是通过先用指定字符集将注释解码,把结果再用另一个符合你的 HTTP 输出的字符集编码来实现的。

表格 1. Exif configuration options

名称默认值可修改范围更新记录
exif.encode_unicode"ISO-8859-15"PHP_INI_ALL自 PHP 4.3.0 起可用。
exif.decode_unicode_motorola"UCS-2BE"PHP_INI_ALL自 PHP 4.3.0 起可用。
exif.decode_unicode_intel"UCS-2LE"PHP_INI_ALL自 PHP 4.3.0 起可用。
exif.encode_jis""PHP_INI_ALL自 PHP 4.3.0 起可用。
exif.decode_jis_motorola"JIS"PHP_INI_ALL自 PHP 4.3.0 起可用。
exif.decode_jis_intel"JIS"PHP_INI_ALL自 PHP 4.3.0 起可用。
有关 PHP_INI_* 常量进一步的细节与定义参见附录 G

以下是配置选项的简要解释。

exif.encode_unicode string

exif.encode_unicode 定义了 UNICODE 用户注释被处理的字符集。默认为 ISO-8859-15,可用于大多数非亚洲国家。本设置可以为空或者必须为一个 mbstring 所支持的编码。如果为空,则使用当前 mbstring 内部使用的编码。

exif.decode_unicode_motorola string

exif.decode_unicode_motorola 定义了 Unicode 编码的用户注释的图像内部字符集,如果图像是摩托罗拉字节顺序(big-endian)的话。本设置不能为空但可以指定一个 mbstring 支持的编码列表。默认为 UCS-2BE。

exif.decode_unicode_intel string

exif.decode_unicode_intel 定义了 Unicode 编码的用户注释的图像内部字符集,如果图像是英特尔字节顺序(little-endian)的话。本设置不能为空但可以指定一个 mbstring 支持的编码列表。默认为 UCS-2LE。

exif.encode_jis string

exif.encode_jis 定义了 JIS 用户注释被处理的字符集。默认为空值,迫使函数使用当前 mbstring 使用的内部编码。

exif.decode_jis_motorola string

exif.decode_jis_motorola 定义了 JIS 编码的用户注释的图像内部字符集,如果图像是摩托罗拉字节顺序(big-endian)的话。本设置不能为空但可以指定一个 mbstring 支持的编码列表。默认为 JIS。

exif.decode_jis_intel string

exif.decode_jis_intel 定义了 JIS 编码的用户注释的图像内部字符集,如果图像是英特尔字节顺序(litle-endian)的话。本设置不能为空但可以指定一个 mbstring 支持的编码列表。默认为 JIS。


资源类型

本扩展模块未定义任何资源类型。


预定义常量

以下常量由本扩展模块定义,因此只有在本扩展模块被编译到 PHP 中,或者在运行时被动态加载后才有效。

EXIF_USE_MBSTRING (integer)

The exif_imagetype() lists several related built-in constants.

目录
exif_imagetype -- 判断一个图像的类型
exif_read_data --  从 JPEGTIFF 文件中读取 EXIF 头信息
exif_tagname -- Get the header name for an index
exif_thumbnail -- 取得嵌入在 TIFF 或 JPEG 图像中的缩略图
read_exif_data -- exif_read_data() 的别名

exif_imagetype

(PHP 4 >= 4.3.0, PHP 5)

exif_imagetype -- 判断一个图像的类型

说明

int exif_imagetype ( string filename )

exif_imagetype() 读取一个图像的第一个字节并检查其签名。

本函数可用来避免调用其它 exif 函数用到了不支持的文件类型上或和 $_SERVER['HTTP_ACCEPT'] 结合使用来检查浏览器是否可以显示某个指定的图像。

参数

filename

被检查的图像文件名。

返回值

如果发现了恰当的签名则返回一个对应的常量,否则返回 FALSE。返回值和 getimagesize() 返回的数组中的索引 2 的值是一样的,但本函数快得多。

更新日志

版本说明
4.3.2 支持 JPCJP2JPXJB2XBM 以及 WBMP
4.3.0支持 SWC

预定义常量

定义有以下常量,并代表了 exif_imagetype() 可能的返回值:

表格 1. 图像类型常量

常量
1IMAGETYPE_GIF
2IMAGETYPE_JPEG
3IMAGETYPE_PNG
4IMAGETYPE_SWF
5IMAGETYPE_PSD
6IMAGETYPE_BMP
7IMAGETYPE_TIFF_II(Intel 字节顺序)
8 IMAGETYPE_TIFF_MM(Motorola 字节顺序)
9IMAGETYPE_JPC
10IMAGETYPE_JP2
11IMAGETYPE_JPX
12IMAGETYPE_JB2
13IMAGETYPE_SWC
14IMAGETYPE_IFF
15IMAGETYPE_WBMP
16IMAGETYPE_XBM

范例

例子 1. exif_imagetype() 例子

<?php

if (exif_imagetype("image.gif") != IMAGETYPE_GIF) {
    echo "The picture is not a gif";
}

?>

exif_read_data

(PHP 4 >= 4.2.0, PHP 5)

exif_read_data --  从 JPEGTIFF 文件中读取 EXIF 头信息

说明

array exif_read_data ( string filename [, string sections [, bool arrays [, bool thumbnail]]] )

exif_read_data() 函数从 JPEG 或 TIFF 图像文件中读取 EXIF 头信息。这样就可以读取数码相机产生的元数据。

Exif 头信息往往存在于数码相机生成的 JPEG/TIFF 图像中,但不幸的是每个数码相机制造商的标记都不同,因此(编写代码时)不能依赖于某个特定的 Exif 头信息。

Height 和 Width 是用和 getimagesize() 一样的方法计算的,因此它们的值不能是任何返回的头信息的部分。此外 html 是一个 height/width 的文本字符串可以用于普通的 HTML 中。

当一个 Exif 头信息包含有一个 Copyright 时注意它本身可以包含两个值。解决方案和 Exif 2.10 标准不一致,COMPUTED 区段会同时返回 Copyright.PhotographerCopyright.Editor,但是 IFD0 区段则包含有一个字节数组用 NULL 字符分隔开两个项目。或者只有第一项如果数据类型错误的话(Exif 的正常行为)。COMPUTED 也会包含 Copyright,要么是原始的版权字符串,要么是逗号分隔的摄像与编辑的版权信息。

UserComment 标记和 Copyright 有同样的问题。它也可以存储两个值,第一个是使用的编码方式,第二个是其值本身。如果这样则 IFD0 区段仅包含编码方式或者一个字节数组。COMPUTED 区段将存储两个值到 UserCommentEncodingUserCommentUserComment 在两种情况下都可用因此应该优先使用它而不是 IFD0 区段中的该值。

exif_read_data() 还会根据 EXIF 规范(http://exif.org/Exif2-2.PDF,第 20 页)来验证 EXIF 数据。

注: Windows ME/XP 在连接到数码相机时能清除掉 Exif 头信息。更多信息见 http://www.canon.co.jp/Imaging/NOTICE/011214-e.html

参数

filename

被读取的图像文件名。不能是 URL

sections

是需要存在于文件中的逗号分隔的区段列表用来产生结果数组。如果未找到所请求的区段则返回值为 FALSE

FILEFileName, FileSize, FileDateTime, SectionsFound
COMPUTED html,Width,Height,IsColor,可能有更多其它的。Height 和 Width 是用和 getimagesize() 一样的方法计算的,因此它们的值不能是任何返回的头信息的部分。此外 html 是一个 height/width 的文本字符串可以用于普通的 HTML 中。
ANY_TAG任何包含有标记的信息,例如 IFD0,EXIF,...
IFD0 所有 IFD0 的标记数据。在标准的图像文件中这包含了图像大小及其它。
THUMBNAIL 如果有第二个 IFD,文件应该包含有缩略图。所有有关嵌入缩略图的标记信息都存储在本区。
COMMENTJPEG 图像的注释头信息。
EXIF EXIF 区段是 IFDO 的子区,包含有图像的更多详细信息。大多数内容都是数码相机相关的。

arrays

指定了是否每个区段都成为一个数组。sections COMPUTEDTHUMBNAILCOMMENT 区段总是成为数组,因为它们里面包含的名字和其它区段冲突。

thumbnail

当设定为 TRUE 时,读取缩略图本身。否则只读取标记数据。

返回值

返回一个关联数组,键名是头信息名,值为与其相应的值。如果没有可供返回的数据,exif_read_data() 将返回 FALSE

更新日志

版本说明
4.3.0 可以读取所有嵌入的 IFD 数据,包括数组(也返回数组)。此外嵌入的缩略图的大小包括在 THUMBNAIL 子数组中并且 exif_read_data() 可以将缩略图按照 TIFF 格式返回。最后,不再有返回值最大长度的限制了(直到达到内存限定)。
4.3.0 如果 PHP 有 mbstring 支持,则用户注释可以自动改变编码。此外,如果用户注释使用 Unicode 或 JIS 编码,将会根据 EXIF 在 php.ini 中的 设置被自动改变。
4.3.0 如果图像包含任何 IFD0 数据,则 COMPUTED 会包含有一项 ByteOrderMotorola,对于 little-endian (intel) 字节顺序,其值为 0,对于 big-endian (motorola) 字节顺序,其值为 1。此外,COMPUTED 和 UserComment 在数据类型出错时也不再仅包含第一个版权条目。

范例

例子 1. exif_read_data() 例子

<?php
echo "test1.jpg:<br />\n";
$exif = exif_read_data('tests/test1.jpg', 'IFD0');
echo $exif===false ? "No header data found.<br />\n" : "Image contains headers<br />\n";

$exif = exif_read_data('tests/test2.jpg', 0, true);
echo "test2.jpg:<br />\n";
foreach ($exif as $key => $section) {
    foreach ($section as $name => $val) {
        echo "$key.$name: $val<br />\n";
    }
}
?>

第一个调用失败了,因为图像没有头信息。

上例的输出类似于:

test1.jpg:
No header data found.
test2.jpg:
FILE.FileName: test2.jpg
FILE.FileDateTime: 1017666176
FILE.FileSize: 1240
FILE.FileType: 2
FILE.SectionsFound: ANY_TAG, IFD0, THUMBNAIL, COMMENT
COMPUTED.html: width="1" height="1"
COMPUTED.Height: 1
COMPUTED.Width: 1
COMPUTED.IsColor: 1
COMPUTED.ByteOrderMotorola: 1
COMPUTED.UserComment: Exif test image.
COMPUTED.UserCommentEncoding: ASCII
COMPUTED.Copyright: Photo (c) M.Boerger, Edited by M.Boerger.
COMPUTED.Copyright.Photographer: Photo (c) M.Boerger
COMPUTED.Copyright.Editor: Edited by M.Boerger.
IFD0.Copyright: Photo (c) M.Boerger
IFD0.UserComment: ASCII
THUMBNAIL.JPEGInterchangeFormat: 134
THUMBNAIL.JPEGInterchangeFormatLength: 523
COMMENT.0: Comment #1.
COMMENT.1: Comment #2.
COMMENT.2: Comment #3end
THUMBNAIL.JPEGInterchangeFormat: 134
THUMBNAIL.Thumbnail.Height: 1
THUMBNAIL.Thumbnail.Height: 1

exif_tagname

(PHP 4 >= 4.2.0, PHP 5)

exif_tagname -- Get the header name for an index

说明

string exif_tagname ( string index )

警告

本函数暂无文档,仅有参数列表。

参数

index

The image index

返回值

Returns the header name, or FALSE if index is undefined.

exif_thumbnail

(PHP 4 >= 4.2.0, PHP 5)

exif_thumbnail -- 取得嵌入在 TIFF 或 JPEG 图像中的缩略图

说明

string exif_thumbnail ( string filename [, int &width [, int &height [, int &imagetype]]] )

exif_thumbnail() 读取 TIFF 或 JPEG 图像中的嵌入缩略图。如果图像不包含缩略图则返回 FALSE

参数 widthheightimagetype 自 PHP 4.3.0 起可用,返回缩略图的大小和类型。有可能 exif_thumbnail() 不能创建图像但可以测定其大小,此情况下返回值是 FALSE,但是 widthheight 的值已经传回了。

如果想用此函数发送缩略图,应该用 header() 函数发送 mime 类型信息。下面的例子演示了此方法:

例子 1. exif_thumbnail() 例子

<?php
if (array_key_exists('file',$_REQUEST)) {
    $image = exif_thumbnail($_REQUEST['file'], $width, $height, $type);
} else {
    $image = false;
}
if ($image!==false) {
    header("Content-type: ".image_type_to_mime_type($type));
    echo $image;
    exit;
} else {
    // no thumbnail available, handle the error here
    echo "No thumbnail available";
}
?>

自 PHP 4.3.0 起,exif_thumbnail() 函数可以以 TIFF 格式返回缩略图。

注: 本函数仅在 PHP 编译时使用了 --enable-exif 选项时可用。其功能和行为在 PHP 4.2 改变了。

注: 本函数不需要 GD 图像库。

参见 exif_read_data()image_type_to_mime_type()

read_exif_data

(PHP 4 >= 4.0.1, PHP 5)

read_exif_data -- exif_read_data() 的别名

说明

本函数是 exif_read_data() 的别名。

XXXIII. File Alteration Monitor Functions

简介

FAM monitors files and directories, notifying interested applications of changes. More information about FAM is available at http://oss.sgi.com/projects/fam/.

A PHP script may specify a list of files for FAM to monitor using the functions provided by this extension.

The FAM process is started when the first connection from any application to it is opened. It exits after all connections to it have been closed.

注: 本扩展已被移动到 PECL 库中且自以下版本起不再被绑定到 PHP 中:5.1.0.

注: 本扩展模块在 Windows 平台下不可用。


需求

This extension uses the functions of the FAM library, developed by SGI. Therefore you have to download and install the FAM library.


安装

To use PHP's FAM support you must compile PHP --with-fam[=DIR] where DIR is the location of the directory containing the lib and include directories.


运行时配置

本扩展模块在 php.ini 中未定义任何配置选项。


预定义常量

以下常量由本扩展模块定义,因此只有在本扩展模块被编译到 PHP 中,或者在运行时被动态加载后才有效。

表格 1. FAM event constants

ConstantDescription
FAMChanged (integer) Some value which can be obtained with fstat(1) changed for a file or directory.
FAMDeleted (integer) A file or directory was deleted or renamed.
FAMStartExecuting (integer) An executable file started executing.
FAMStopExecuting (integer) An executable file that was running finished.
FAMCreated (integer) A file was created in a directory.
FAMMoved (integer) This event never occurs.
FAMAcknowledge (integer) An event in response to fam_cancel_monitor().
FAMExists (integer) An event upon request to monitor a file or directory. When a directory is monitored, an event for that directory and every file contained in that directory is issued.
FAMEndExist (integer) Event after the last FAMEExists event.
目录
fam_cancel_monitor -- Terminate monitoring
fam_close -- Close FAM connection
fam_monitor_collection -- Monitor a collection of files in a directory for changes
fam_monitor_directory -- Monitor a directory for changes
fam_monitor_file -- Monitor a regular file for changes
fam_next_event -- Get next pending FAM event
fam_open -- Open connection to FAM daemon
fam_pending -- Check for pending FAM events
fam_resume_monitor -- Resume suspended monitoring
fam_suspend_monitor -- Temporarily suspend monitoring

fam_cancel_monitor

(PHP 5 <= 5.0.4)

fam_cancel_monitor -- Terminate monitoring

说明

bool fam_cancel_monitor ( resource fam, resource fam_monitor )

fam_cancel_monitor() terminates monitoring on a resource previously requested using one of the fam_monitor_ functions. In addition an FAMAcknowledge event occurs.

See also fam_monitor_file(), fam_monitor_directory(), fam_monitor_collection(), and fam_suspend_monitor()

fam_close

(PHP 5 <= 5.0.4)

fam_close -- Close FAM connection

说明

void fam_close ( resource fam )

fam_close() closes a connection to the FAM service previously opened using fam_open().

fam_monitor_collection

(PHP 5 <= 5.0.4)

fam_monitor_collection -- Monitor a collection of files in a directory for changes

说明

resource fam_monitor_collection ( resource fam, string dirname, int depth, string mask )

fam_monitor_collection() requests monitoring for a collection of files within a directory. The actual files to be monitored are specified by a directory path in dirname, the maximum search depth starting from this directory and a shell pattern mask restricting the file names to look for.

A FAM event will be generated whenever the status of the files change. The possible event codes are described in detail in the constants part of this section.

See also fam_monitor_file(), fam_monitor_directory(), fam_cancel_monitor(), fam_suspend_monitor(), and fam_resume_monitor().

fam_monitor_directory

(PHP 5 <= 5.0.4)

fam_monitor_directory -- Monitor a directory for changes

说明

resource fam_monitor_directory ( resource fam, string dirname )

fam_monitor_directory() requests monitoring for a directory and all contained files. A FAM event will be generated whenever the status of the directory (i.e. the result of function stat() on that directory) or its content (i.e. the results of readdir()) change.

The possible event codes are described in detail in the constants part of this section.

See also fam_monitor_file(), fam_monitor_collection(), fam_cancel_monitor(), fam_suspend_monitor(), and fam_resume_monitor().

fam_monitor_file

(PHP 5 <= 5.0.4)

fam_monitor_file -- Monitor a regular file for changes

说明

resource fam_monitor_file ( resource fam, string filename )

fam_monitor_file() requests monitoring for a single file. A FAM event will be generated whenever the file status (i.e. the result of function stat() on that file) changes.

The possible event codes are described in detail in the constants part of this section.

See also fam_monitor_directory(), fam_monitor_collection(), fam_cancel_monitor(), fam_suspend_monitor(), and fam_resume_monitor().

fam_next_event

(PHP 5 <= 5.0.4)

fam_next_event -- Get next pending FAM event

说明

array fam_next_event ( resource fam )

fam_next_event() returns the next pending FAM event. The function will block until an event is available which can be checked for using fam_pending().

fam_next_event() will return an array that contains a FAM event code in element 'code', the path of the file this event applies to in element 'filename' and optionally a hostname in element 'hostname'.

The possible event codes are described in detail in the constants part of this section.

See also fam_pending().

fam_open

(PHP 5 <= 5.0.4)

fam_open -- Open connection to FAM daemon

说明

resource fam_open ( [string appname] )

fam_open() opens a connection to the FAM service daemon. The optional parameter appname should be set to a string identifying the application for logging reasons.

See also fam_close().

fam_pending

(PHP 5 <= 5.0.4)

fam_pending -- Check for pending FAM events

说明

int fam_pending ( resource fam )

fam_pending() returns non-zero if events are available to be fetched using fam_next_event().

See also fam_next_event().

fam_resume_monitor

(PHP 5 <= 5.0.4)

fam_resume_monitor -- Resume suspended monitoring

说明

bool fam_resume_monitor ( resource fam, resource fam_monitor )

fam_resume_monitor() resumes monitoring of a resource previously suspend using fam_suspend_monitor().

See also fam_suspend_monitor().

fam_suspend_monitor

(PHP 5 <= 5.0.4)

fam_suspend_monitor -- Temporarily suspend monitoring

说明

bool fam_suspend_monitor ( resource fam, resource fam_monitor )

fam_suspend_monitor() temporarily suspend monitoring of a resource previously requested using one of the fam_monitor_ functions. Monitoring can later be continued using fam_resume_monitor() without the need of requesting a complete new monitor.

See also fam_resume_monitor(), and fam_cancel_monitor().

XXXIV. filePro Functions

简介

These functions allow read-only access to data stored in filePro databases.

filePro is a registered trademark of fP Technologies, Inc. You can find more information about filePro at http://www.fptech.com/.


安装

filePro support in PHP is not enabled by default. To enable the bundled read-only filePro support you need to use the--enable-filepro configuration option when compiling PHP.

目录
filepro_fieldcount -- Find out how many fields are in a filePro database
filepro_fieldname -- Gets the name of a field
filepro_fieldtype -- Gets the type of a field
filepro_fieldwidth -- Gets the width of a field
filepro_retrieve -- Retrieves data from a filePro database
filepro_rowcount -- Find out how many rows are in a filePro database
filepro -- Read and verify the map file

filepro_fieldcount

(PHP 3, PHP 4, PHP 5)

filepro_fieldcount -- Find out how many fields are in a filePro database

Description

int filepro_fieldcount ( void )

Returns the number of fields (columns) in the opened filePro database.

See also filepro().

filepro_fieldname

(PHP 3, PHP 4, PHP 5)

filepro_fieldname -- Gets the name of a field

Description

string filepro_fieldname ( int field_number )

Returns the name of the field corresponding to field_number.

filepro_fieldtype

(PHP 3, PHP 4, PHP 5)

filepro_fieldtype -- Gets the type of a field

Description

string filepro_fieldtype ( int field_number )

Returns the edit type of the field corresponding to field_number.

filepro_fieldwidth

(PHP 3, PHP 4, PHP 5)

filepro_fieldwidth -- Gets the width of a field

Description

int filepro_fieldwidth ( int field_number )

Returns the width of the field corresponding to field_number.

filepro_retrieve

(PHP 3, PHP 4, PHP 5)

filepro_retrieve -- Retrieves data from a filePro database

Description

string filepro_retrieve ( int row_number, int field_number )

Returns the data from the specified location in the database. The row_number parameter must be between zero and the total number of rows minus one (0..filepro_rowcount() - 1). Likewise, field_number accepts values between zero and the total number of fields minus one (0..filepro_fieldcount() - 1)

注: 安全模式被激活时,PHP 将检查被操作的文件或者目录是否与正在执行的脚本有相同的 UID(所有者)。

filepro_rowcount

(PHP 3, PHP 4, PHP 5)

filepro_rowcount -- Find out how many rows are in a filePro database

Description

int filepro_rowcount ( void )

Returns the number of rows in the opened filePro database.

注: 安全模式被激活时,PHP 将检查被操作的文件或者目录是否与正在执行的脚本有相同的 UID(所有者)。

See also filepro().

filepro

(PHP 3, PHP 4, PHP 5)

filepro -- Read and verify the map file

Description

bool filepro ( string directory )

This reads and verifies the map file, storing the field count and info.

No locking is done, so you should avoid modifying your filePro database while it may be opened in PHP.

注: 安全模式被激活时,PHP 将检查被操作的文件或者目录是否与正在执行的脚本有相同的 UID(所有者)。

XXXV. Filesystem 文件系统函数


需求

无需外部库文件就可以加入本扩展模块的支持。但如要使 PHP 在 Linux 上支持 LFS(大文件)的话,必须有最新的 glibc 并在编译时加入参数:-D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64


安装

本函数库作为 PHP 内核的一部分,不用安装就能使用。


运行时配置

这些函数的行为受 php.ini 的影响。

表格 1. 文件系统和流配置选项

名称默认值可修改范围更新记录
allow_url_fopen"1"PHP_INI_SYSTEMPHP_INI_ALL in PHP <= 4.3.4. PHP 4.0.4 版以后可用。
user_agentNULLPHP_INI_ALLPHP 4.3.0 版以后可用。
default_socket_timeout"60"PHP_INI_ALLPHP 4.3.0 版以后可用。
from""PHP_INI_ALL 
auto_detect_line_endings"0"PHP_INI_ALLPHP 4.3.0 版以后可用。

以下是配置选项的简要解释。

allow_url_fopen boolean

本选项激活了 URL 形式的 fopen 封装协议使得可以访问 URL 对象例如文件。默认的封装协议提供用 ftp 和 http 协议来访问远程文件,一些扩展库例如 zlib 可能会注册更多的封装协议。

注: 出于安全性考虑,这个选项只能通过 php.ini 中设置。

注: 本选项是版本 4.0.3 发行后立即引进的。4.0.3 以及以前的版本只能在编译时通过配置项 --disable-url-fopen-wrapper 来取消此特性。

警告

Windows 版在 PHP 4.3.0 之前,下列函数不支持远程文件访问:include()include_once(), require()require_once()参考 LV, Image 图像函数 扩展库中的 imagecreatefromXXX 函数。

user_agent string

定义 PHP 发送的 User-Agent。

default_socket_timeout integer

基于 socket 的流的默认超时时间(秒)。

注: 本配置参数是 PHP 4.3.0 引进的。

from string

定义匿名 ftp 的密码(email 地址)。

auto_detect_line_endings boolean

当设为 On 时,PHP 将检查通过 fgets()file() 取得的数据中的行结束符号是符合 Unix,MS-Dos,还是 Macintosh 的习惯。

这使得 PHP 可以和 Macintosh 系统交互操作,但是默认值是 Off,因为在检测第一行的 EOL 习惯时会有很小的性能损失,而且在 Unix 系统下使用回车符号作为项目分隔符的人们会遭遇向下不兼容的行为。

注: 本配置参数是 PHP 4.3.0 引进的。


预定义常量

以下常量由本扩展模块定义,因此只有在本扩展模块被编译到 PHP 中,或者在运行时被动态加载后才有效。

GLOB_BRACE (integer)

GLOB_ONLYDIR (integer)

GLOB_MARK (integer)

GLOB_NOSORT (integer)

GLOB_NOCHECK (integer)

GLOB_NOESCAPE (integer)

PATHINFO_DIRNAME (integer)

PATHINFO_BASENAME (integer)

PATHINFO_EXTENSION (integer)

FILE_USE_INCLUDE_PATH (integer)

FILE_APPEND (integer)

FILE_IGNORE_NEW_LINES (integer)

FILE_SKIP_EMPTY_LINES (integer)


参见

相关函数参见目录函数程序执行函数

有关可以用于远程文件的各种 URL 封装协议的说明列表,参见附录 L

目录
basename -- 返回路径中的文件名部分
chgrp -- 改变文件所属的组
chmod -- 改变文件模式
chown -- 改变文件的所有者
clearstatcache -- 清除文件状态缓存
copy -- 拷贝文件
delete -- 参见 unlink()unset()
dirname -- 返回路径中的目录部分
disk_free_space -- 返回目录中的可用空间
disk_total_space -- 返回一个目录的磁盘总大小
diskfreespace -- disk_free_space()的别名
fclose -- 关闭一个已打开的文件指针
feof -- 测试文件指针是否到了文件结束的位置
fflush -- 将缓冲内容输出到文件
fgetc -- 从文件指针中读取字符
fgetcsv -- 从文件指针中读入一行并解析 CSV 字段
fgets -- 从文件指针中读取一行
fgetss -- 从文件指针中读取一行并过滤掉 HTML 标记
file_exists -- 检查文件或目录是否存在
file_get_contents -- 将整个文件读入一个字符串
file_put_contents -- 将一个字符串写入文件
file -- 把整个文件读入一个数组中
fileatime -- 取得文件的上次访问时间
filectime -- 取得文件的 inode 修改时间
filegroup -- 取得文件的组
fileinode -- 取得文件的 inode
filemtime -- 取得文件修改时间
fileowner -- 取得文件的所有者
fileperms -- 取得文件的权限
filesize -- 取得文件大小
filetype -- 取得文件类型
flock -- 轻便的咨询文件锁定
fnmatch -- 用模式匹配文件名
fopen -- 打开文件或者 URL
fpassthru -- 输出文件指针处的所有剩余数据
fputcsv -- 将行格式化为 CSV 并写入文件指针
fputs -- fwrite()的别名
fread -- 读取文件(可安全用于二进制文件)
fscanf -- 从文件中格式化输入
fseek -- 在文件指针中定位
fstat -- 通过已打开的文件指针取得文件信息
ftell -- 返回文件指针读/写的位置
ftruncate -- 将文件截断到给定的长度
fwrite -- 写入文件(可安全用于二进制文件)
glob -- 寻找与模式匹配的文件路径
is_dir -- 判断给定文件名是否是一个目录
is_executable -- 判断给定文件名是否可执行
is_file -- 判断给定文件名是否为一个正常的文件
is_link -- 判断给定文件名是否为一个符号连接
is_readable -- 判断给定文件名是否可读
is_uploaded_file -- 判断文件是否是通过 HTTP POST 上传的
is_writable -- 判断给定的文件名是否可写
is_writeable -- is_writable()的别名
link -- 建立一个硬连接
linkinfo -- 获取一个连接的信息
lstat -- 给出一个文件或符号连接的信息
mkdir -- 新建目录
move_uploaded_file -- 将上传的文件移动到新位置
parse_ini_file -- 解析一个配置文件
pathinfo -- 返回文件路径的信息
pclose -- 关闭进程文件指针
popen -- 打开进程文件指针
readfile -- 输出一个文件
readlink -- 返回符号连接指向的目标
realpath -- 返回规范化的绝对路径名
rename -- 重命名一个文件或目录
rewind -- 倒回文件指针的位置
rmdir -- 删除目录
set_file_buffer -- stream_set_write_buffer()的别名
stat -- 给出文件的信息
symlink -- 建立符号连接
tempnam -- 建立一个具有唯一文件名的文件
tmpfile -- 建立一个临时文件
touch -- 设定文件的访问和修改时间
umask -- 改变当前的 umask
unlink -- 删除文件

basename

(PHP 3, PHP 4, PHP 5)

basename -- 返回路径中的文件名部分

说明

string basename ( string path [, string suffix] )

给出一个包含有指向一个文件的全路径的字符串,本函数返回基本的文件名。如果文件名是以 suffix 结束的,那这一部分也会被去掉。

在 Windows 中,斜线(/)和反斜线(\)都可以用作目录分隔符。在其它环境下是斜线(/)。

例子 1. basename() 例子

<?php
$path = "/home/httpd/html/index.php";
$file = basename($path);        // $file is set to "index.php"
$file = basename($path,".php"); // $file is set to "index"
?>

注: suffix 参数是 PHP 4.1.0 新加的。

参见 dirname()

chgrp

(PHP 3, PHP 4, PHP 5)

chgrp -- 改变文件所属的组

说明

bool chgrp ( string filename, mixed group )

尝试将文件 filename 所属的组改成 group(通过组名或组 ID 指定)。只有超级用户可以任意修改文件的组,其它用户可能只能将文件的组改成该用户自己所在的组。

如果成功则返回 TRUE,失败则返回 FALSE

注: 本函数不能作用于远程文件,被检查的文件必须通过服务器的文件系统访问。

注: 安全模式被激活时,PHP 将检查被操作的文件或者目录是否与正在执行的脚本有相同的 UID(所有者)。

参见 chown()chmod()

chmod

(PHP 3, PHP 4, PHP 5)

chmod -- 改变文件模式

说明

bool chmod ( string filename, int mode )

尝试将 filename 所指定文件的模式改成 mode 所给定的。

注意 mode 不会被自动当成八进制数值,而且也不能用字符串(例如 "g+w")。要确保正确操作,需要给 mode 前面加上 0:

<?php
chmod("/somedir/somefile", 755);   // 十进制数,可能不对
chmod("/somedir/somefile", "u+rwx,go+rx"); // 字符串,不对
chmod("/somedir/somefile", 0755);  // 八进制数,正确的 mode 值
?>

mode 参数包含三个八进制数按顺序分别指定了所有者、所有者所在的组以及所有人的访问限制。每一部分都可以通过加入所需的权限来计算出所要的权限。数字 1 表示使文件可执行,数字 2 表示使文件可写,数字 4 表示使文件可读。加入这些数字来制定所需要的权限。有关 UNIX 系统的文件权限可以阅读手册“man 1 chmod”和“man 2 chmod”。

<?php
// Read and write for owner, nothing for everybody else
chmod("/somedir/somefile", 0600);

// Read and write for owner, read for everybody else
chmod("/somedir/somefile", 0644);

// Everything for owner, read and execute for others
chmod("/somedir/somefile", 0755);

// Everything for owner, read and execute for owner's group
chmod("/somedir/somefile", 0750);
?>

如果成功则返回 TRUE,失败则返回 FALSE

注: 当前用户指的是执行 PHP 的用户。很可能和通常的 shell 或者 FTP 用户不是同一个。在大多数系统下文件模式只能被文件所有者的用户改变。

注: 本函数不能作用于远程文件,被检查的文件必须通过服务器的文件系统访问。

注: 安全模式打开的时候,PHP 会检查所操作的文件是否和正在执行的脚本具有相同的 UID (所有者)。要注意的是,不能修改 SUID,SGID 和 sticky bits。

参见 chown()chgrp()

chown

(PHP 3, PHP 4, PHP 5)

chown -- 改变文件的所有者

说明

bool chown ( string filename, mixed user )

尝试将文件 filename 的所有者改成用户 user(由用户名或用户 ID 指定)。只有超级用户可以改变文件的所有者。

如果成功则返回 TRUE,失败则返回 FALSE

注: 本函数不能作用于远程文件,被检查的文件必须通过服务器的文件系统访问。

注: 安全模式被激活时,PHP 将检查被操作的文件或者目录是否与正在执行的脚本有相同的 UID(所有者)。

参见 chmod()

clearstatcache

(PHP 3, PHP 4, PHP 5)

clearstatcache -- 清除文件状态缓存

说明

void clearstatcache ( void )

当使用 stat()lstat() 或者任何列在受影响函数表(见下面)中的函数时,PHP 将缓存这些函数的返回信息以提供更快的性能。然而在某些情况下,你可能想清除被缓存的信息。例如如果在一个脚本中多次检查同一个文件,而该文件在此脚本执行期间有被删除或修改的危险时,你需要清除文件状态缓存。这种情况下,可以用 clearstatcache() 函数来清除被 PHP 缓存的该文件信息。

必须注意的是,对于不存在的文件,PHP 并不会缓存其信息。所以如果调用 file_exists() 来检查不存在的文件,在该文件没有被创建之前,它都会返回 FALSE。如果该文件被创建了,就算以后被删除,它都会返回 TRUE

注: 本函数缓存特定文件名的信息,因此只在对同一个文件名进行多次操作并且需要该文件信息不被缓存时才需要调用 clearstatcache()

受影响的函数包括 stat()lstat()file_exists()is_writable()is_readable()is_executable()is_file()is_dir()is_link()filectime()fileatime()filemtime()fileinode()filegroup()fileowner()filesize()filetype()fileperms()

copy

(PHP 3, PHP 4, PHP 5)

copy -- 拷贝文件

说明

bool copy ( string source, string dest )

将文件从 source 拷贝到 dest。如果成功则返回 TRUE,失败则返回 FALSE

例子 1. copy() 例子

<?php
$file = 'example.txt';
$newfile = 'example.txt.bak';

if (!copy($file, $newfile)) {
    echo "failed to copy $file...\n";
}
?>

如果要移动文件的话,请使用 rename() 函数。

注: 从 PHP 4.3.0 开始,如果启用了“fopen wrappers”的话,sourcedest 都可以是 URL。更多细节见 fopen()。如果 dest 是一个 URL,则如果封装协议不支持覆盖已有的文件时拷贝操作会失败。

警告

如果目标文件已存在,将会被覆盖。

Windows 兼容: 如果复制一个零字节的文件,copy() 将返回 FALSE ,但文件也会被正确复制。

参见 move_uploaded_file()rename() 和手册中关于文件上传处理一节。

delete

(no version information, might be only in CVS)

delete -- 参见 unlink()unset()

说明

void delete ( string file )

这是个虚构的手册条目来给那些本来是找 unlink() 或者 unset() 的人提供一些有用的信息。

参见 unlink() 来删除文件,unset() 来删除变量。

dirname

(PHP 3, PHP 4, PHP 5)

dirname -- 返回路径中的目录部分

说明

string dirname ( string path )

给出一个包含有指向一个文件的全路径的字符串,本函数返回去掉文件名后的目录名。

在 Windows 中,斜线(/)和反斜线(\)都可以用作目录分隔符。在其它环境下是斜线(/)。

例子 1. dirname() 例子

<?php
$path = "/etc/passwd";
$file = dirname($path); // $file is set to "/etc"
?>

注: 在 PHP 4.0.3 中,dirname() 被修正为 POSIX 兼容。本质上就意味着如果在 path 中没有斜线,则返回一个点('.'),表示当前目录。否则返回的是把 path 中结尾的 /component(最后一个斜线以及后面部分)去掉之后的字符串。注意这意味着在老的函数返回一个空字符串的情形下你通常从 dirname() 得到的是斜线或者一个点。

dirname() 从 PHP 4.3.0 开始有所改变 请看以下例子:

<?php
 
// PHP 4.3.0 以前
dirname('c:/'); // 返回 '.'
 
// PHP 4.3.0 以后
dirname('c:/'); // 返回 'c:'
 
?>

dirname() 的操作从 PHP 5.0.0 版开始是二进制安全的。

参见 basename()pathinfo()realpath()

disk_free_space

(PHP 4 >= 4.1.0, PHP 5)

disk_free_space -- 返回目录中的可用空间

说明

float disk_free_space ( string directory )

给出一个包含有一个目录的字符串,本函数将根据相应的文件系统或磁盘分区返回可用的字节数。

例子 1. disk_free_space() 例子

<?php
// $df 包含根目录下可用的字节数
$df = disk_free_space("/");
//在 Windows 下:
disk_free_space("C:");
disk_free_space("D:");
?>

注: 本函数不能作用于远程文件,被检查的文件必须通过服务器的文件系统访问。

参见 disk_total_space()

disk_total_space

(PHP 4 >= 4.1.0, PHP 5)

disk_total_space -- 返回一个目录的磁盘总大小

说明

float disk_total_space ( string directory )

给出一个包含有一个目录的字符串,本函数将根据相应的文件系统或磁盘分区返回所有的字节数。

例子 1. disk_total_space() 例子

<?php
// $df 包含 "/" 目录的磁盘大小
$df = disk_total_space("/");

//在 Windows 下:
disk_total_space("C:");
disk_total_space("D:");
?>

注: 本函数不能作用于远程文件,被检查的文件必须通过服务器的文件系统访问。

参见 disk_free_space()

【译者注】本函数返回的是该目录所在的磁盘分区的总大小,因此在给出同一个磁盘分区的不同目录作为参数所得到的结果完全相同。在 Unix 和 Windows 200x/XP 中都支持将一个磁盘分区加载为一个子目录,这时正确使用本函数就很有意义。

diskfreespace

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

diskfreespace -- disk_free_space()的别名

说明

本函数是该函数的别名:disk_free_space()

fclose

(PHP 3, PHP 4, PHP 5)

fclose -- 关闭一个已打开的文件指针

说明

bool fclose ( resource handle )

handle 指向的文件关闭。

如果成功则返回 TRUE,失败则返回 FALSE

文件指针必须有效,并且是通过 fopen()fsockopen() 成功打开的。

例子 1. 一个简单 fclose() 例子

<?php
  $handle = fopen('somefile.txt', 'r');
  fclose($handle);
?>

feof

(PHP 3, PHP 4, PHP 5)

feof -- 测试文件指针是否到了文件结束的位置

说明

bool feof ( resource handle )

如果文件指针到了 EOF 或者出错时则返回 TRUE,否则返回一个错误(包括 socket 超时),其它情况则返回 FALSE

警告

如果服务器没有关闭由 fsockopen() 所打开的连接,feof() 会一直等待直到超时而返回 TRUE。默认的超时限制是 60 秒,可以使用 stream_set_timeout() 来改变这个值。

文件指针必须是有效的,并且必须指向一个由 fopen()fsockopen() 成功打开的文件。

fflush

(PHP 4 >= 4.0.1, PHP 5)

fflush -- 将缓冲内容输出到文件

说明

bool fflush ( resource handle )

本函数强制将所有缓冲的输出写入 handle 文件句柄所指向的资源。 如果成功则返回 TRUE,失败则返回 FALSE

文件指针必须是有效的,并且必须指向一个由 fopen()fsockopen() 成功打开的文件。

fgetc

(PHP 3, PHP 4, PHP 5)

fgetc -- 从文件指针中读取字符

说明

string fgetc ( resource handle )

返回一个包含有一个字符的字符串,该字符从 handle 指向的文件中得到。碰到 EOF 则返回 FALSE

文件指针必须是有效的,并且必须指向一个由 fopen()fsockopen() 成功打开的文件。

警告

本函数可能返回布尔值 FALSE,但也可能返回一个与 FALSE 等值的非布尔值,例如 0 或者 ""。请参阅布尔类型章节以获取更多信息。应使用 === 运算符来测试本函数的返回值。

例子 1. fgetc() 例子

<?php
$fp = fopen('somefile.txt', 'r');
if (!$fp) {
    echo 'Could not open file somefile.txt';
}
while (false !== ($char = fgetc($fp))) {
    echo "$char\n";
}
?>

注: 本函数可安全用于二进制对象。

参见 fread()fopen()popen()fsockopen()fgets()

fgetcsv

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

fgetcsv -- 从文件指针中读入一行并解析 CSV 字段

说明

array fgetcsv ( int handle [, int length [, string delimiter [, string enclosure]]] )

handle

一个由 fopen()popen()fsockopen() 产生的有效文件指针。

length (可选)

必须大于 CVS 文件内最长的一行。在 PHP 5 中该参数是可选的。如果忽略(在 PHP 5.0.4 以后的版本中设为 0)该参数的话,那么长度就没有限制,不过可能会影响执行效率。

delimiter (可选)

设置字段分界符(只允许一个字符),默认值为逗号。

enclosure (可选)

设置字段环绕符(只允许一个字符),默认值为双引号。该参数是在 PHP 4.3.0 中添加的。

fgets() 类似,只除了 fgetcsv() 解析读入的行并找出 CSV 格式的字段然后返回一个包含这些字段的数组。

fgetcsv() 出错时返回 FALSE,包括碰到文件结束时。

注: CSV 文件中的空行将被返回为一个包含有单个 null 字段的数组,不会被当成错误。

例子 1. 读取并显示 CSV 文件的整个内容

<?php
$row = 1;
$handle = fopen("test.csv","r");
while ($data = fgetcsv($handle, 1000, ",")) {
    $num = count($data);
    echo "<p> $num fields in line $row: <br>\n";
    $row++;
    for ($c=0; $c < $num; $c++) {
        echo $data[$c] . "<br>\n";
    }
}
fclose($handle);
?>

从 PHP 4.3.5 起,fgetcsv() 的操作是二进制安全的。

注: 该函数对区域设置是敏感的。比如说 LANG 设为 en_US.UTF-8 的话,单字节编码的文件就会出现读取错误。

注: 如果碰到 PHP 在读取文件时不能识别 Macintosh 文件的行结束符,可以激活 auto_detect_line_endings 运行时配置选项。

参见 explode()file()pack()fputcsv()

fgets

(PHP 3, PHP 4, PHP 5)

fgets -- 从文件指针中读取一行

说明

string fgets ( int handle [, int length] )

handle 指向的文件中读取一行并返回长度最多为 length - 1 字节的字符串。碰到换行符(包括在返回值中)、EOF 或者已经读取了 length - 1 字节后停止(看先碰到那一种情况)。如果没有指定 length,则默认为 1K,或者说 1024 字节。

出错时返回 FALSE

通常的缺陷:

习惯了 C 语言中 fgets() 语法的人应该注意到 EOF 是怎样被返回的。

文件指针必须是有效的,并且必须指向一个由 fopen()fsockopen() 成功打开的文件。

以下是一个简单例子:

例子 1. 逐行读取文件

<?php
$handle = fopen("/tmp/inputfile.txt", "r");
while (!feof($handle)) {
    $buffer = fgets($fd, 4096);
    echo $buffer;
}
fclose($handle);
?>

注: length 参数从 PHP 4.2.0 起成为可选项,如果忽略,则行的长度被假定为 1024。从 PHP 4.3 开始,忽略掉 length 将继续从流中读取数据直到行结束。如果文件中的大多数行都大于 8KB,则在脚本中指定最大行的长度在利用资源上更为有效。

注: 从 PHP 4.3 开始本函数可以安全用于二进制文件。早期的版本则不行。

注: 如果碰到 PHP 在读取文件时不能识别 Macintosh 文件的行结束符,可以激活 auto_detect_line_endings 运行时配置选项。

参见 fread()fgetc()stream_get_line()fopen()popen()fsockopen()stream_set_timeout()

fgetss

(PHP 3, PHP 4, PHP 5)

fgetss -- 从文件指针中读取一行并过滤掉 HTML 标记

说明

string fgetss ( resource handle [, int length [, string allowable_tags]] )

fgets() 相同,只除了 fgetss 尝试从读取的文本中去掉任何 HTML 和 PHP 标记。

可以用可选的第三个参数指定哪些标记不被去掉。

注: allowable_tags 是 PHP 3.0.13,PHP 4.0.0 新加的。

参数 length 从 PHP 5 起开始可选。

注: 如果碰到 PHP 在读取文件时不能识别 Macintosh 文件的行结束符,可以激活 auto_detect_line_endings 运行时配置选项。

参见 fgets()fopen()fsockopen()popen()strip_tags()

file_exists

(PHP 3, PHP 4, PHP 5)

file_exists -- 检查文件或目录是否存在

说明

bool file_exists ( string filename )

如果由 filename 指定的文件或目录存在则返回 TRUE,否则返回 FALSE

在 Windows 中要用 //computername/share/filename 或者 \\computername\share\filename 来检查网络中的共享文件。

例子 1. 测试一个文件是否存在

<?php
$filename = '/path/to/foo.txt';

if (file_exists($filename)) {
    echo "The file $filename exists";
} else {
    echo "The file $filename does not exist";
}
?>

注: 本函数的结果会被缓存。更多信息参见 clearstatcache()

提示: PHP 5.0.0 起本函数也可被某些 URL wrapper 使用。参考附录 L 来看哪些 wrapper 支持 stat() 系列函数的功能。

警告

如果因为安全模式的限制而导致不能访问文件的话,该函数会返回 FALSE。然而,如果文件在 safe_mode_include_dir 所指定的目录内的话,仍然可以使用 include 来包含。

参见 is_readable()is_writable()is_file()file()

file_get_contents

(PHP 4 >= 4.3.0, PHP 5)

file_get_contents -- 将整个文件读入一个字符串

说明

string file_get_contents ( string filename [, bool use_include_path [, resource context [, int offset [, int maxlen]]]] )

file() 一样,只除了 file_get_contents() 把文件读入一个字符串。将在参数 offset 所指定的位置开始读取长度为 maxlen 的内容。如果失败,file_get_contents() 将返回 FALSE

file_get_contents() 函数是用来将文件的内容读入到一个字符串中的首选方法。如果操作系统支持还会使用内存映射技术来增强性能。

注: 如果要打开有特殊字符的 URL (比如说有空格),就需要使用 urlencode() 进行 URL 编码。

注: context 参数可以用 NULL 来忽略。

更新日志

版本说明
5.0.0 添加了对 context 的支持。
5.1.0 添加了 offsetmaxlen 参数。

注释

注: 本函数可安全用于二进制对象。

提示: 如果“fopen wrappers”已经被激活,则在本函数中可以把 URL 作为文件名来使用。请参阅 fopen() 函数来获取怎样指定文件名的详细信息以及支持 URL 封装协议的列表:附录 L

注: 对 context 的支持是 PHP 5.0.0 添加的。有关 context 的说明请参考参考 CXLI, Stream Functions

警告

当使用 SSL 时,Microsoft IIS 将违反协议不发送 close_notify 标记就关闭连接。PHP 将在到达数据尾端时报告 "SSL: Fatal Protocol Error"。要绕过此问题,应将 error_reporting 级别降低为不包括警告。PHP 4.3.7 及更高版本可以在当使用 https:// 封装协议打开流的时候检测出有此问题的 IIS 服务器并抑制警告。如果使用 fsockopen() 来创建一个 ssl:// 套接字,则需要自己检测并抑制警告信息。

file_put_contents

(PHP 5)

file_put_contents -- 将一个字符串写入文件

说明

int file_put_contents ( string filename, string data [, int flags [, resource context]] )

和依次调用 fopen()fwrite() 以及 fclose() 功能一样。

参数 data 可以是数组(但不能为多元数组),这就相当于 file_put_contents($filename, join('', $array))

自 PHP 5.1.0 起,data 参数也可以被指定为 stream 资源,这里 stream 中所保存的缓存数据将被写入到指定文件中,这种用法就相似于使用 stream_copy_to_stream() 函数。

参数

filename

要被写入数据的文件名

data

要写入的数据。类型可以是 stringarray 或者是 stream 资源(如上面所说的那样).

flags

flags 可以是 FILE_USE_INCLUDE_PATH, FILE_APPEND 和/或 LOCK_EX (获得一个独占锁定),然而使用 FILE_USE_INCLUDE_PATH 时要特别谨慎。

context

一个 context 资源

返回值

该函数将返回写入到文件内数据的字节数

更新日志

版本说明
5.1.0 添加了对 LOCK_EX 的支持和 data 参数处理 stream 资源的功能。

注释

注: 本函数可安全用于二进制对象。

注: 对 context 的支持是 PHP 5.0.0 添加的。有关 context 的说明请参考参考 CXLI, Stream Functions

提示: 如果“fopen wrappers”已经被激活,则在本函数中可以把 URL 作为文件名来使用。请参阅 fopen() 函数来获取怎样指定文件名的详细信息以及支持 URL 封装协议的列表:附录 L

file

(PHP 3, PHP 4, PHP 5)

file -- 把整个文件读入一个数组中

说明

array file ( string filename [, int use_include_path [, resource context]] )

readfile() 一样,只除了 file() 将文件作为一个数组返回。数组中的每个单元都是文件中相应的一行,包括换行符在内。如果失败 file() 返回 FALSE

如果也想在 include_path 中搜寻文件的话,可以将可选参数 use_include_path 设为 "1"。

<?php
// 将一个文件读入数组。本例中通过 HTTP 从 URL 中取得 HTML 源文件。
$lines = file('http://www.example.com/');
// 在数组中循环,显示 HTML 的源文件并加上行号。
foreach ($lines as $line_num => $line) {
    echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
// 另一个例子将 web 页面读入字符串。参见 file_get_contents()。
$html = implode('', file ('http://www.example.com/'));
?>

提示: 如果“fopen wrappers”已经被激活,则在本函数中可以把 URL 作为文件名来使用。请参阅 fopen() 函数来获取怎样指定文件名的详细信息以及支持 URL 封装协议的列表:附录 L

注: 返回的数组中每一行都包括了行结束符,因此如果不需要行结束符时还需要使用 rtrim() 函数。

注: 如果碰到 PHP 在读取文件时不能识别 Macintosh 文件的行结束符,可以激活 auto_detect_line_endings 运行时配置选项。

注: 从 PHP 4.3.0 开始可以用 file_get_contents() 来将文件读入到一个字符串返回。

从 PHP 4.3.0 开始 file() 可以安全用于二进制文件。

注: 对 context 的支持是 PHP 5.0.0 添加的。有关 context 的说明请参考参考 CXLI, Stream Functions

警告

当使用 SSL 时,Microsoft IIS 将违反协议不发送 close_notify 标记就关闭连接。PHP 将在到达数据尾端时报告 "SSL: Fatal Protocol Error"。要绕过此问题,应将 error_reporting 级别降低为不包括警告。PHP 4.3.7 及更高版本可以在当使用 https:// 封装协议打开流的时候检测出有此问题的 IIS 服务器并抑制警告。如果使用 fsockopen() 来创建一个 ssl:// 套接字,则需要自己检测并抑制警告信息。

参见 readfile()fopen()fsockopen()popen()file_get_contents()include()

fileatime

(PHP 3, PHP 4, PHP 5)

fileatime -- 取得文件的上次访问时间

说明

int fileatime ( string filename )

返回文件上次被访问的时间,如果出错则返回 FALSE。时间以 Unix 时间戳的方式返回。

注意:一个文件的 atime 应该在不论何时读取了此文件中的数据块时被更改。当一个应用程序定期访问大量文件或目录时很影响性能。有些 Unix 文件系统可以在加载时关闭 atime 的更新以提高这类程序的性能。USENET 新闻组假脱机是一个常见的例子。在这种文件系统下本函数没有用处。

注: 本函数的结果会被缓存。更多信息参见 clearstatcache()

提示: PHP 5.0.0 起本函数也可被某些 URL wrapper 使用。参考附录 L 来看哪些 wrapper 支持 stat() 系列函数的功能。

例子 1. fileatime() 例子

<?php

// 输出类似:somefile.txt was last accessed: December 29 2002 22:16:23.

$filename = 'somefile.txt';
if (file_exists($filename)) {
    echo "$filename was last accessed: " . date("F d Y H:i:s.", fileatime($filename));
}

?>

参见 filemtime()fileinode()date()

filectime

(PHP 3, PHP 4, PHP 5)

filectime -- 取得文件的 inode 修改时间

说明

int filectime ( string filename )

返回文件上次 inode 被修改的时间,如果出错则返回 FALSE。时间以 Unix 时间戳的方式返回。

注意:在大多数 Unix 文件系统中,当一个文件的 inode 数据被改变时则该文件被认为是修改了。也就是说,当文件的权限,所有者,所有组或其它 inode 中的元数据被更新时。参见 filemtime()(这才是你想用于在 web 页面中建立“最后更新时间”脚注的函数)和 fileatime()

注意某些 Unix 说明文本中把 ctime 说成是该文件建立的时间,这是错的。在大多数 Unix 文件系统中没有 Unix 文件的建立时间。

注: 本函数的结果会被缓存。更多信息参见 clearstatcache()

提示: PHP 5.0.0 起本函数也可被某些 URL wrapper 使用。参考附录 L 来看哪些 wrapper 支持 stat() 系列函数的功能。

例子 1. 一个 fileatime() 的例子

<?php

// 输出类似:somefile.txt was last changed: December 29 2002 22:16:23.

$filename = 'somefile.txt';
if (file_exists($filename)) {
    echo "$filename was last changed: " . date("F d Y H:i:s.", filectime($filename));
}

?>

参见 filemtime()

filegroup

(PHP 3, PHP 4, PHP 5)

filegroup -- 取得文件的组

说明

int filegroup ( string filename )

取得该文件所属组的 ID。如果出错则返回 FALSE。组 ID 以数字格式返回,用 posix_getgrgid() 来将其解析为组名。如果失败返回 FALSE 以及一个 E_WARNING 级别的错误。

本函数的结果会被缓存。详细信息见 clearstatcache()

注: 本函数的结果会被缓存。更多信息参见 clearstatcache()

提示: PHP 5.0.0 起本函数也可被某些 URL wrapper 使用。参考附录 L 来看哪些 wrapper 支持 stat() 系列函数的功能。

参见 fileowner()safe_mode_gid

fileinode

(PHP 3, PHP 4, PHP 5)

fileinode -- 取得文件的 inode

说明

int fileinode ( string filename )

返回文件的 inode 节点号,出错时返回 FALSE

注: 本函数的结果会被缓存。更多信息参见 clearstatcache()

提示: PHP 5.0.0 起本函数也可被某些 URL wrapper 使用。参考附录 L 来看哪些 wrapper 支持 stat() 系列函数的功能。

参见 stat()

filemtime

(PHP 3, PHP 4, PHP 5)

filemtime -- 取得文件修改时间

说明

int filemtime ( string filename )

返回文件上次被修改的时间,出错时返回 FALSE。时间以 Unix 时间戳的方式返回,可用于 date()

注: 本函数的结果会被缓存。更多信息参见 clearstatcache()

提示: PHP 5.0.0 起本函数也可被某些 URL wrapper 使用。参考附录 L 来看哪些 wrapper 支持 stat() 系列函数的功能。

本函数返回文件中的数据块上次被写入的时间,也就是说,文件的内容上次被修改的时间。

例子 1. filemtime() 例子

<?php
// outputs e.g.  somefile.txt was last modified: December 29 2002 22:16:23.
$filename = 'somefile.txt';
if (file_exists($filename)) {
    echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));

}
?>

参见 filectime()stat()touch()getlastmod()

fileowner

(PHP 3, PHP 4, PHP 5)

fileowner -- 取得文件的所有者

说明

int fileowner ( string filename )

返回文件所有的用户 ID,如果出错则返回 FALSE。用户 ID 以数字格式返回,用 posix_getpwuid() 来将其解析为用户名。

注: 本函数的结果会被缓存。更多信息参见 clearstatcache()

提示: PHP 5.0.0 起本函数也可被某些 URL wrapper 使用。参考附录 L 来看哪些 wrapper 支持 stat() 系列函数的功能。

参见 stat()

fileperms

(PHP 3, PHP 4, PHP 5)

fileperms -- 取得文件的权限

说明

int fileperms ( string filename )

返回文件的访问权限,如果出错则返回 FALSE

注: 本函数的结果会被缓存。更多信息参见 clearstatcache()

提示: PHP 5.0.0 起本函数也可被某些 URL wrapper 使用。参考附录 L 来看哪些 wrapper 支持 stat() 系列函数的功能。

例子 1. 以八进制的形式显示文件的权限

<?php
echo substr(sprintf('%o', fileperms('/tmp')), -4);
echo substr(sprintf('%o', fileperms('/etc/passwd')), -4);
?>

上例将输出:

1777
0644

例子 2. 输出全部权限

<?php
$perms = fileperms('/etc/passwd');
 
if (($perms & 0xC000) == 0xC000) {
    // Socket
    $info = 's';
} elseif (($perms & 0xA000) == 0xA000) {
    // Symbolic Link
    $info = 'l';
} elseif (($perms & 0x8000) == 0x8000) {
    // Regular
    $info = '-';
} elseif (($perms & 0x6000) == 0x6000) {
    // Block special
    $info = 'b';
} elseif (($perms & 0x4000) == 0x4000) {
    // Directory
    $info = 'd';
} elseif (($perms & 0x2000) == 0x2000) {
    // Character special
    $info = 'c';
} elseif (($perms & 0x1000) == 0x1000) {
    // FIFO pipe
    $info = 'p';
} else {
    // Unknown
    $info = 'u';
}
 
// Owner
$info .= (($perms & 0x0100) ? 'r' : '-');
$info .= (($perms & 0x0080) ? 'w' : '-');
$info .= (($perms & 0x0040) ?
            (($perms & 0x0800) ? 's' : 'x' ) :
            (($perms & 0x0800) ? 'S' : '-'));
 
// Group
$info .= (($perms & 0x0020) ? 'r' : '-');
$info .= (($perms & 0x0010) ? 'w' : '-');
$info .= (($perms & 0x0008) ?
            (($perms & 0x0400) ? 's' : 'x' ) :
            (($perms & 0x0400) ? 'S' : '-'));
 
// World
$info .= (($perms & 0x0004) ? 'r' : '-');
$info .= (($perms & 0x0002) ? 'w' : '-');
$info .= (($perms & 0x0001) ?
            (($perms & 0x0200) ? 't' : 'x' ) :
            (($perms & 0x0200) ? 'T' : '-'));
 
echo $info;
?>

上例将输出:

-r--r--r--

参见 is_readable()stat()

filesize

(PHP 3, PHP 4, PHP 5)

filesize -- 取得文件大小

说明

int filesize ( string filename )

返回文件大小的字节数,如果出错返回 FALSE (在错误报告级别为 E_WARNING的情况下)。

注: 因为 PHP 的整数类型是有符号的,并且大多数平台使用 32 位整数,filesize() 函数在碰到大于 2GB 的文件时可能会返回非预期的结果。对于 2GB 到 4GB 之间的文件通常可以使用 sprintf("%u", filesize($file)) 来克服此问题。

注: 本函数的结果会被缓存。更多信息参见 clearstatcache()

提示: PHP 5.0.0 起本函数也可被某些 URL wrapper 使用。参考附录 L 来看哪些 wrapper 支持 stat() 系列函数的功能。

例子 1. filesize() 例子

<?php

// 输出类似:somefile.txt: 1024 bytes

$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';

?>

参见 file_exists()

filetype

(PHP 3, PHP 4, PHP 5)

filetype -- 取得文件类型

说明

string filetype ( string filename )

返回文件的类型。可能的值有 fifo,char,dir,block,link,file 和 unknown。

如果出错则返回 FALSE。如果 stat 调用失败或者文件类型未知的话 filetype() 还会产生一个 E_NOTICE 消息。

注: 本函数的结果会被缓存。更多信息参见 clearstatcache()

提示: PHP 5.0.0 起本函数也可被某些 URL wrapper 使用。参考附录 L 来看哪些 wrapper 支持 stat() 系列函数的功能。

例子 1. filetype() 例子

<?php

echo filetype('/etc/passwd');  // file
echo filetype('/etc/');        // dir

?>

参见 is_dir()is_file()is_link()file_exists()stat()mime_content_type()

flock

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

flock -- 轻便的咨询文件锁定

说明

bool flock ( int handle, int operation [, int &wouldblock] )

PHP 支持以咨询方式(也就是说所有访问程序必须使用同一方式锁定, 否则它不会工作)锁定全部文件的一种轻便方法。

注: 在 Windows 下 flock() 将会强制执行。

flock() 操作的 handle 必须是一个已经打开的文件指针。operation 可以是以下值之一:

  • 要取得共享锁定(读取程序),将 operation 设为 LOCK_SH(PHP 4.0.1 以前的版本设置为 1)。

  • 要取得独占锁定(写入程序),将 operation 设为 LOCK_EX(PHP 4.0.1 以前的版本中设置为 2)。

  • 要释放锁定(无论共享或独占),将 operation 设为 LOCK_UN(PHP 4.0.1 以前的版本中设置为 3)。

  • 如果你不希望 flock() 在锁定时堵塞,则给 operation 加上 LOCK_NB(PHP 4.0.1 以前的版本中设置为 4)。

flock() 允许你执行一个简单的可以在任何平台中使用的读取/写入模型(包括大部分的 Unix 派生版和甚至是 Windows)。如果锁定会堵塞的话(EWOULDBLOCK 错误码情况下),请将可选的第三个参数设置为 TRUE。锁定操作也可以被 fclose() 释放(代码执行完毕时也会自动调用)。

如果成功则返回 TRUE,失败则返回 FALSE

例子 1. flock() 例子

<?php

$fp = fopen("/tmp/lock.txt", "w+");

if (flock($fp, LOCK_EX)) { // 进行排它型锁定
    fwrite($fp, "Write something here\n");
    flock($fp, LOCK_UN); // 释放锁定
} else {
    echo "Couldn't lock the file !";
}

fclose($fp);

?>

注: 由于 flock() 需要一个文件指针, 因此你可能需要一个锁定文件来保护到你打算通过写模式打开来截断的文件的访问(在 fopen() 函数中加入 "w" 或 "w+")。

警告

flock() 不能在 NFS 以及其他的一些网络文件系统中正常工作。详细资料请检查你的操作系统文档。

在部分操作系统中,flock() 以处理级执行。当用一个多线程服务器 API(比如 ISAPI)时,您可能不可以依靠 flock() 来保护文件,因为在同一服务器内运行在其它线程的 PHP 脚本可以对该文件进行处理。

flock() 不支持旧的文件系统,如 FAT 以及它的派生系统。因此,它在这种情况下经常会返回一个 FALSE 值(尤其是指 Windows 98 的用户)。

fnmatch

(PHP 4 >= 4.3.0, PHP 5)

fnmatch -- 用模式匹配文件名

说明

bool fnmatch ( string pattern, string string [, int flags] )

fnmatch() 检查传入的 string 是否匹配给出的 shell 统配符 pattern

此函数对于文件名尤其有用,但也可以用于普通的字符串。普通用户可能习惯于 shell 模式或者至少其中最简单的形式 '?''*' 通配符,因此使用 fnmatch() 来代替 ereg() 或者 preg_match() 来进行前端搜索表达式输入对于非程序员用户更加方便。

例子 1. 用 shell 中的通配符模式匹配来检查颜色

<?php
if (fnmatch("*gr[ae]y", $color)) {
  echo "some form of gray ...";
}
?>

警告

目前该函数无法在 Windows 或其它非 POSIX 兼容的系统上使用

参见 glob()ereg()preg_match() 和 UNIX 中 fnmatch(3) 的手册中的标志名(只要本文档中还未包括它们)。

fopen

(PHP 3, PHP 4, PHP 5)

fopen -- 打开文件或者 URL

说明

resource fopen ( string filename, string mode [, bool use_include_path [, resource zcontext]] )

fopen()filename 指定的名字资源绑定到一个流上。如果 filename 是 "scheme://..." 的格式,则被当成一个 URL,PHP 将搜索协议处理器(也被称为封装协议)来处理此模式。如果该协议尚未注册封装协议,PHP 将发出一条消息来帮助检查脚本中潜在的问题并将 filename 当成一个普通的文件名继续执行下去。

如果 PHP 认为 filename 指定的是一个本地文件,将尝试在该文件上打开一个流。该文件必须是 PHP 可以访问的,因此需要确认文件访问权限允许该访问。如果激活了 安全模式 或者 open_basedir 则会应用进一步的限制。

如果 PHP 认为 filename 指定的是一个已注册的协议,而该协议被注册为一个网络 URL,PHP 将检查并确认 allow_url_fopen 已被激活。如果关闭了,PHP 将发出一个警告,而 fopen 的调用则失败。

注: 所支持的协议列表见附录 L。某些协议(也被称为 wrappers)支持 contextphp.ini 选项。参见相应的页面哪些选项可以被设定。(也就是 php.ini 的值 user_agent 用在 http 协议中。)有关

注: 对 context 的支持是 PHP 5.0.0 添加的。有关 context 的说明请参考参考 CXLI, Stream Functions

注: 自 PHP 4.3.2 起,对所有区别二进制和文本模式的平台默认模式都被设为二进制模式。如果你在升级后脚本碰到问题,尝试暂时使用 't' 标记,直到所有的脚本都照以下所说的改为更具移植性以后。

mode 参数指定了所要求到该流的访问类型。可以是以下:

表格 1. fopen() 中的 mode 的可能值列表

mode说明
'r' 只读方式打开,将文件指针指向文件头。
'r+' 读写方式打开,将文件指针指向文件头。
'w' 写入方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。
'w+' 读写方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。
'a' 写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。
'a+' 读写方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。
'x' 创建并以写入方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE,并生成一条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。这和给 底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。此选项被 PHP 4.3.2 以及以后的版本所支持,仅能用于本地文件。
'x+' 创建并以读写方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE,并生成一条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。这和给 底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。此选项被 PHP 4.3.2 以及以后的版本所支持,仅能用于本地文件。

注: 不同的操作系统家族具有不同的行结束习惯。当你写入一个文本文件并想插入一个新行时,你需要使用符合你操作系统的行结束符号。基于 Unix 的系统使用 \n 作为行结束字符,基于 Windows 的系统使用 \r\n 作为行结束字符,基于 Macintosh 的系统使用 \r 作为行结束字符。

如果写入文件时使用了错误的行结束符号,则其它应用程序打开这些文件时可能会表现得很怪异。

Windows 下提供了一个文本转换标记('t')可以透明地将 \n 转换为 \r\n。与此对应你还可以使用 'b' 来强制使用二进制模式,这样就不会转换你的数据。要使用这些标记,要么用 'b' 或者用 't' 作为 mode 参数的最后一个字符。

默认的转换模式依赖于 SAPI 和你使用的 PHP 版本,因此为了便于移植鼓励你总是指定恰当的标记。当操作以 \n 作为行结束定界符的纯文本文件时,如果你还期望这些文件可以用于其它应用程序例如 Notepad,则应该在脚本中使用 't' 模式。在所有其它情况下使用 'b'

在操作二进制文件时如果没有指定 'b' 标记,可能会碰到一些奇怪的问题,包括坏掉的图片文件以及关于 \r\n 字符的奇怪问题。

注: 为移植性考虑,强烈建议在用 fopen() 打开文件时总是使用 'b' 标记。

注: 再一次,为移植性考虑,强烈建议你重写那些依赖于 't' 模式的代码使其使用正确的行结束符并改成 'b' 模式。

如果也需要在 include_path 中搜寻文件的话,可以将可选的第三个参数 use_include_path 设为 '1' 或 TRUE

如果打开失败,本函数返回 FALSE

例子 1. fopen() 例子

<?php
$handle = fopen("/home/rasmus/file.txt", "r");
$handle = fopen("/home/rasmus/file.gif", "wb");
$handle = fopen("http://www.example.com/", "r");
$handle = fopen("ftp://user:password@example.com/somefile.txt", "w");
?>

如果在用服务器模块版本的 PHP 时在打开和写入文件上遇到问题,记住要确保所使用的文件是服务器进程所能够访问的。

在 Windows 平台上,要小心转义文件路径中的每个反斜线,或者用斜线。

<?php
$handle = fopen("c:\\data\\info.txt", "r");
?>

警告

当使用 SSL 时,Microsoft IIS 将违反协议不发送 close_notify 标记就关闭连接。PHP 将在到达数据尾端时报告 "SSL: Fatal Protocol Error"。要绕过此问题,应将 error_reporting 级别降低为不包括警告。PHP 4.3.7 及更高版本可以在当使用 https:// 封装协议打开流的时候检测出有此问题的 IIS 服务器并抑制警告。如果使用 fsockopen() 来创建一个 ssl:// 套接字,则需要自己检测并抑制警告信息。

注: 安全模式被激活时,PHP 将检查被操作的目录是否和正在执行的脚本有相同的 UID(所有者)。

参见附录 Lfclose()fgets()fread()fwrite()fsockopen()file()file_exists()is_readable()stream_set_timeout()popen()

fpassthru

(PHP 3, PHP 4, PHP 5)

fpassthru -- 输出文件指针处的所有剩余数据

说明

int fpassthru ( resource handle )

将给定的文件指针从当前的位置读取到 EOF 并把结果写到输出缓冲区。

如果发生错误, fpassthru() 返回 FALSE。 否则 fpassthru() 返回从 handle 读取并传递到输出的字符数目。

文件指针必须是有效的,并且必须指向一个由 fopen()fsockopen() 成功打开的文件。

如果已经向文件写入数据,就必须调用 rewind() 来将文件指针指向文件头。

如果既不修改文件也不在特定位置检索,只想将文件的内容下载到输出缓冲区,应该使用 readfile(),这样可以省去 fopen() 调用。

注: 当在 Windows 系统中将 fpassthru() 用于二进制文件时,要确保在用 fopen() 打开文件时在 mode 中附加了 b 来将文件以二进制方式打开。

鼓励在处理二进制文件时使用 b 标志,即使系统并不需要,这样可以使脚本的移植性更好。

例子 1. 对二进制文件使用 fpassthru()

<?php

// 以二进制格式打开文件
$name = './img/ok.png'
$fp = fopen($name, 'rb');

// 发送合适的报头
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));

// 发送图片并终止脚本
fpassthru($fp);
exit;

?>

参见 readfile()fopen()popen()fsockopen()

fputcsv

(PHP 5 >= 5.1.0RC1)

fputcsv -- 将行格式化为 CSV 并写入文件指针

说明

int fputcsv ( resource handle [, array fields [, string delimiter [, string enclosure]]] )

fputcsv() 将一行(用 fields 数组传递)格式化为 CSV 格式并写入由 handle 指定的文件。返回写入字符串的长度,出错则返回 FALSE

可选的 delimiter 参数设定字段分界符(只允许一个字符)。默认为逗号:,

可选的 enclosure 参数设定字段字段环绕符(只允许一个字符)。默认为双引号:"

例子 1. fputcsv() 例子

<?php

$list = array (
    'aaa,bbb,ccc,dddd',
    '123,456,789',
    '"aaa","bbb"'
);

$fp = fopen('file.csv', 'w');

foreach ($list as $line) {
    fputcsv($fp, split(',', $line));
}

fclose($fp);
?>

注: 如果碰到 PHP 在读取文件时不能识别 Macintosh 文件的行结束符,可以激活 auto_detect_line_endings 运行时配置选项。

参见 fgetcsv()

fputs

(PHP 3, PHP 4, PHP 5)

fputs -- fwrite()的别名

说明

本函数是该函数的别名:fwrite()

fread

(PHP 3, PHP 4, PHP 5)

fread -- 读取文件(可安全用于二进制文件)

说明

string fread ( int handle, int length )

fread() 从文件指针 handle 读取最多 length 个字节。 该函数在读取完 length 个字节数,或到达 EOF 的时候,或(对于网络流)当一个包可用时就会停止读取文件,视乎先碰到哪种情况。

// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize ($filename));
fclose($handle);

警告

在区分二进制文件和文本文件的系统上(如 Windows)打开文件时,fopen() 函数的 mode 参数要加上 'b'。

$filename = "c:\\files\\somepic.gif";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize ($filename));
fclose($handle);

警告

当从网络流或者管道读取时,例如在读取从远程文件popen() 以及 proc_open() 的返回时,读取会在一个包可用之后停止。这意味着你应该如下例所示将数据收集起来合并成大块。

<?php
$handle = fopen ("http://www.example.com/", "rb");
$contents = "";
while (!feof($handle)) {
  $contents .= fread($handle, 8192);
}
fclose($handle);
?>

注: 如果你只是想将一个文件的内容读入到一个字符串中,用 file_get_contents(),它的性能比上面的代码好得多。

参见 fwrite()fopen()fsockopen()popen()fgets()fgetss()fscanf()file()fpassthru()

fscanf

(PHP 4 >= 4.0.1, PHP 5)

fscanf -- 从文件中格式化输入

说明

mixed fscanf ( resource handle, string format [, mixed &...] )

fscanf() 函数和 sscanf() 相似,但是它从与 handle 关联的文件中接受输入并根据指定的 format(定义于 sprintf() 的文档中)来解释输入。如果只给此函数传递了两个参数,解析后的值会被作为数组返回。否则,如果提供了可选参数,此函数将返回被赋值的数目。可选参数必须用引用传递。

格式字符串中的任何空白会与输入流中的任何空白匹配。这意味着甚至格式字符串中的制表符 \t 也会与输入流中的一个空格字符匹配。

例子 1. fscanf() 例子

<?php
$handle = fopen("users.txt","r");
while ($userinfo = fscanf($handle, "%s\t%s\t%s\n")) {
    list ($name, $profession, $countrycode) = $userinfo;
    //... do something with the values
}
fclose($handle);
?>

例子 2. users.txt 的内容

javier  argonaut        pe
hiroshi sculptor        jp
robert  slacker us
luigi   florist it

注: 在 PHP 4.3.0 之前,从文件中读入的最大字符数是 512(或者第一个 \n,看先碰到哪种情况)。从 PHP 4.3.0 起可以读取任意长的行。

参见 fread()fgets()fgetss()sscanf()printf()sprintf()

fseek

(PHP 3, PHP 4, PHP 5)

fseek -- 在文件指针中定位

说明

int fseek ( resource handle, int offset [, int whence] )

在与 handle 关联的文件中设定文件指针位置。新位置,从文件头开始以字节数度量,是以 whence 指定的位置加上 offsetwhence 的值定义为:

SEEK_SET - 设定位置等于 offset 字节。
SEEK_CUR - 设定位置为当前位置加上 offset
SEEK_END - 设定位置为文件尾加上 offset。(要移动到文件尾之前的位置,需要给 offset 传递一个负值。)

如果没有指定 whence,默认为 SEEK_SET

成功则返回 0;否则返回 -1。注意移动到 EOF 之后的位置不算错误。

例子 1. fseek() 例子

<?php

$fp = fopen('somefile.txt');

// read some data
$data = fgets($fp, 4096);

// move back to the begining of the file
// same as rewind($fp);
fseek($fp, 0);

?>

可能不能用于在 fopen() 中以 "http://" 或 "ftp://" 格式打开所返回的文件指针。在附加模式(加参数 "a" 打开文件)中 ftell() 会返回未定义错误。

注: whence 参数是 PHP 4.0.0 之后增加的。

注: 如果你使用附加模试("a" 或 "a+"),任何写入文件数据都会被附加上去,而文件的位置将会被忽略。

参见 ftell()rewind()

fstat

(PHP 4, PHP 5)

fstat -- 通过已打开的文件指针取得文件信息

说明

array fstat ( resource handle )

获取由文件指针 handle 所打开文件的统计信息。本函数和 stat() 函数相似,除了它是作用于已打开的文件指针而不是文件名。

返回一个数组具有该文件的统计信息,该数组的格式详细说明于手册中 stat() 页面里。

例子 1. fstat() 例子

<?php

// 打开文件
$fp = fopen("/etc/passwd", "r");

// 取得统计信息
$fstat = fstat($fp);

// 关闭文件
fclose($fp);

// 只显示关联数组部分
print_r(array_slice($fstat, 13));

?>

上例的输出类似于:

Array
(
    [dev] => 771
    [ino] => 488704
    [mode] => 33188
    [nlink] => 1
    [uid] => 0
    [gid] => 0
    [rdev] => 0
    [size] => 1114
    [atime] => 1061067181
    [mtime] => 1056136526
    [ctime] => 1056136526
    [blksize] => 4096
    [blocks] => 8
)

注: 本函数不能作用于远程文件,被检查的文件必须通过服务器的文件系统访问。

ftell

(PHP 3, PHP 4, PHP 5)

ftell -- 返回文件指针读/写的位置

说明

int ftell ( resource handle )

返回由 handle 指定的文件指针的位置,也就是文件流中的偏移量。

如果出错,返回 FALSE

文件指针必须是有效的,且必须指向一个通过 fopen()popen() 成功打开的文件。 在附加模式(加参数 "a" 打开文件)中 ftell() 会返回未定义错误。

例子 1. ftell() 例子

<?php

// 打开文件并读些数据
$fp = fopen("/etc/passwd", "r");
$data = fgets($fp, 12);

// 现在指针到哪里了?
echo ftell($fp); // 11

fclose($fp);

?>

参见 fopen()popen()fseek()rewind()

ftruncate

(PHP 4, PHP 5)

ftruncate -- 将文件截断到给定的长度

说明

bool ftruncate ( resource handle, int size )

接受文件指针 handle 作为参数,并将文件大小截取为 size。如果成功则返回 TRUE,失败则返回 FALSE

注: 文件只会在 append 模式下改变。在 write 模式下,必须加上 fseek() 操作。

注: 在 PHP 4.3.3 之前,ftruncate() 在成功时返回一个 integer 值 1,而不是 booleanTRUE

参见 fopen()fseek()

fwrite

(PHP 3, PHP 4, PHP 5)

fwrite -- 写入文件(可安全用于二进制文件)

说明

int fwrite ( resource handle, string string [, int length] )

fwrite()string 的内容写入 文件指针 handle 处。 如果指定了 length,当写入了 length 个字节或者写完了 string 以后,写入就会停止,视乎先碰到哪种情况。

fwrite() 返回写入的字符数,出现错误时则返回 FALSE

注意如果给出了 length 参数,则 magic_quotes_runtime 配置选项将被忽略,而 string 中的斜线将不会被抽去。

注: 在区分二进制文件和文本文件的系统上(如 Windows) 打开文件时,fopen() 函数的 mode 参数要加上 'b'。

例子 1. 一个简单的 fwrite() 例子

<?php
$filename = 'test.txt';
$somecontent = "添加这些文字到文件\n";

// 首先我们要确定文件存在并且可写。
if (is_writable($filename)) {

    // 在这个例子里,我们将使用添加模式打开$filename,
    // 因此,文件指针将会在文件的开头,
    // 那就是当我们使用fwrite()的时候,$somecontent将要写入的地方。
    if (!$handle = fopen($filename, 'a')) {
         echo "不能打开文件 $filename";
         exit;
    }

    // 将$somecontent写入到我们打开的文件中。
    if (fwrite($handle, $somecontent) === FALSE) {
        echo "不能写入到文件 $filename";
        exit;
    }

    echo "成功地将 $somecontent 写入到文件$filename";

    fclose($handle);

} else {
    echo "文件 $filename 不可写";
}
?>

参见 fread()fopen()fsockopen()popen()file_put_contents()

glob

(PHP 4 >= 4.3.0, PHP 5)

glob -- 寻找与模式匹配的文件路径

说明

array glob ( string pattern [, int flags] )

glob() 函数依照 libc glob() 函数使用的规则寻找所有与 pattern 匹配的文件路径,类似于一般 shells 所用的规则一样。不进行缩写扩展或参数替代。

返回一个包含有匹配文件/目录的数组。如果出错返回 FALSE

有效标记为:

  • GLOB_MARK - 在每个返回的项目中加一个斜线

  • GLOB_NOSORT - 按照文件在目录中出现的原始顺序返回(不排序)

  • GLOB_NOCHECK - 如果没有文件匹配则返回用于搜索的模式

  • GLOB_NOESCAPE - 反斜线不转义元字符

  • GLOB_BRACE - 扩充 {a,b,c} 来匹配 'a','b' 或 'c'

  • GLOB_ONLYDIR - 仅返回与模式匹配的目录项

    注: 在 PHP 4.3.3 版本之前 GLOB_ONLYDIR 在 Windows 或者其它不使用 GNU C 库的系统上不可用

  • GLOB_ERR - 停止并读取错误信息(比如说不可读的目录),默认的情况下忽略所有错误

    注: GLOB_ERR 是 PHP 5.1 添加的。

例子 1. 怎样用 glob() 方便地替代 opendir() 和相关函数

<?php
foreach (glob("*.txt") as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
}
?>

上例的输出类似于:

funclist.txt size 44686
funcsummary.txt size 267625
quickref.txt size 137820

注: 本函数不能作用于远程文件,被检查的文件必须通过服务器的文件系统访问。

参见 opendir()readdir()closedir()fnmatch()

is_dir

(PHP 3, PHP 4, PHP 5)

is_dir -- 判断给定文件名是否是一个目录

说明

bool is_dir ( string filename )

如果文件名存在并且为目录则返回 TRUE。如果 filename 是一个相对路径,则按照当前工作目录检查其相对路径。

注: 本函数的结果会被缓存。更多信息参见 clearstatcache()

例子 1. is_dir() 例子

<?
var_dump(is_dir('a_file.txt')) . "\n";
var_dump(is_dir('bogus_dir/abc')) . "\n";
 
var_dump(is_dir('..')); //one dir up
?>

上例将输出:

bool(false)
bool(false)
bool(true)

提示: PHP 5.0.0 起本函数也可被某些 URL wrapper 使用。参考附录 L 来看哪些 wrapper 支持 stat() 系列函数的功能。

参见 chdir()diropendir()is_file()is_link()

is_executable

(PHP 3, PHP 4, PHP 5)

is_executable -- 判断给定文件名是否可执行

说明

bool is_executable ( string filename )

如果文件存在且可执行则返回 TRUE

is_executable() 自 PHP 5.0.0 版起可用于 Windows

例子 1. is_executable() 例子

<?php

$file = '/home/vincent/somefile.sh';

if (is_executable($file)) {
    echo $file.' is executable';
} else {
    echo $file.' is not executable';
}

?>

注: 本函数的结果会被缓存。更多信息参见 clearstatcache()

提示: PHP 5.0.0 起本函数也可被某些 URL wrapper 使用。参考附录 L 来看哪些 wrapper 支持 stat() 系列函数的功能。

参见 is_file()is_link()

is_file

(PHP 3, PHP 4, PHP 5)

is_file -- 判断给定文件名是否为一个正常的文件

说明

bool is_file ( string filename )

如果文件存在且为正常的文件则返回 TRUE

例子 1. is_file() 例子

<?php
var_dump(is_file('a_file.txt')) . "\n";
var_dump(is_file('/usr/bin/')) . "\n";
?>

上例将输出:

bool(true)
bool(false)

注: 本函数的结果会被缓存。更多信息参见 clearstatcache()

提示: PHP 5.0.0 起本函数也可被某些 URL wrapper 使用。参考附录 L 来看哪些 wrapper 支持 stat() 系列函数的功能。

参见 is_dir()is_link()

is_link

(PHP 3, PHP 4, PHP 5)

is_link -- 判断给定文件名是否为一个符号连接

说明

bool is_link ( string filename )

如果文件存在并且是一个符号连接则返回 TRUE

注: 本函数的结果会被缓存。更多信息参见 clearstatcache()

提示: PHP 5.0.0 起本函数也可被某些 URL wrapper 使用。参考附录 L 来看哪些 wrapper 支持 stat() 系列函数的功能。

参见 is_dir()is_file()readlink()

is_readable

(PHP 3, PHP 4, PHP 5)

is_readable -- 判断给定文件名是否可读

说明

bool is_readable ( string filename )

如果文件存在并且可读则返回 TRUE

记住 PHP 也许只能以运行 webserver 的用户名(通常为 'nobody')来访问文件。不计入安全模式的限制。

例子 1. is_writable() 例子

<?php
$filename = 'test.txt';
if (is_readable($filename)) {
    echo 'The file is readable';
} else {
    echo 'The file is not readable';
}
?>

注: 本函数的结果会被缓存。更多信息参见 clearstatcache()

提示: PHP 5.0.0 起本函数也可被某些 URL wrapper 使用。参考附录 L 来看哪些 wrapper 支持 stat() 系列函数的功能。

参见 is_writable()file_exists()fgets()

is_uploaded_file

(PHP 3 >= 3.0.17, PHP 4 >= 4.0.3, PHP 5)

is_uploaded_file -- 判断文件是否是通过 HTTP POST 上传的

说明

bool is_uploaded_file ( string filename )

如果 filename 所给出的文件是通过 HTTP POST 上传的则返回 TRUE。这可以用来确保恶意的用户无法欺骗脚本去访问本不能访问的文件,例如 /etc/passwd

这种检查显得格外重要,如果上传的文件有可能会造成对用户或本系统的其他用户显示其内容的话。

为了能使 is_uploaded_file() 函数正常工作,必段指定类似于 $_FILES['userfile']['tmp_name'] 的变量,而在从客户端上传的文件名 $_FILES['userfile']['name'] 不能正常运作。

例子 1. is_uploaded_file() 例子

<?php
 
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
   echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n";
   echo "Displaying contents\n";
   readfile($_FILES['userfile']['tmp_name']);
} else {
   echo "Possible file upload attack: ";
   echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
}
 
?>

is_uploaded_file() 仅可用于 PHP 3 的 3.0.16 版之后,以及 PHP 4 的 4.0.2 版之后。如果你执意要用老版本,可以用下面的函数来保护自己:

注: 以下例子不能用于 PHP 4 的 4.0.2 版之后。它依赖的 PHP 内部函数在该版本之后改变了。

例子 2. is_uploaded_file() 可运行于 PHP 4 < 4.0.3 的例子

<?php
/* Userland test for uploaded file. */
function is_uploaded_file($filename)
{
    if (!$tmp_file = get_cfg_var('upload_tmp_dir')) {
        $tmp_file = dirname(tempnam('', ''));
    }
    $tmp_file .= '/' . basename($filename);
    /* User might have trailing slash in php.ini... */
    return (ereg_replace('/+', '/', $tmp_file) == $filename);
}

/* This is how to use it, since you also don't have
 * move_uploaded_file() in these older versions: */
if (is_uploaded_file($HTTP_POST_FILES['userfile'])) {
    copy($HTTP_POST_FILES['userfile'], "/place/to/put/uploaded/file");
} else {
    echo "Possible file upload attack: filename '$HTTP_POST_FILES[userfile]'.";
}
?>

参见 move_uploaded_file(),以及文件上传处理一章中的简单使用例子。

is_writable

(PHP 4, PHP 5)

is_writable -- 判断给定的文件名是否可写

说明

bool is_writable ( string filename )

如果文件存在并且可写则返回 TRUEfilename 参数可以是一个允许进行是否可写检查的目录名。

记住 PHP 也许只能以运行 webserver 的用户名(通常为 'nobody')来访问文件。不计入安全模式的限制。

例子 1. is_writable() 例子

<?php
$filename = 'test.txt';
if (is_writable($filename)) {
    echo 'The file is writable';
} else {
    echo 'The file is not writable';
}
?>

注: 本函数的结果会被缓存。更多信息参见 clearstatcache()

提示: PHP 5.0.0 起本函数也可被某些 URL wrapper 使用。参考附录 L 来看哪些 wrapper 支持 stat() 系列函数的功能。

See also is_readable(), file_exists(), and fwrite().

is_writeable

(PHP 3, PHP 4, PHP 5)

is_writeable -- is_writable()的别名

说明

本函数是该函数的别名:is_writable()

link

(PHP 3, PHP 4, PHP 5)

link -- 建立一个硬连接

说明

bool link ( string target, string link )

link() 建立一个硬连接。如果成功则返回 TRUE,失败则返回 FALSE

注: 本函数不能作用于远程文件,被检查的文件必须通过服务器的文件系统访问。

注: 本函数未在 Windows 平台下实现。

参见 symlink() 来建立软连接,以及 readlink()linkinfo()

linkinfo

(PHP 3, PHP 4, PHP 5)

linkinfo -- 获取一个连接的信息

说明

int linkinfo ( string path )

linkinfo() 返回 lstat 系统调用所返回的 UNIX C stat 结构中的 st_dev 字段。本函数用来验证一个连接(由 path 所指向的)是否确实存在(使用 stat.h 中的 S_ISLNK 宏同样的方法)。如果出错则返回 0 或 FALSE

例子 1. linkinfo() 例子

<?php

echo linkinfo('/vmlinuz'); // 835

?>

注: 本函数未在 Windows 平台下实现。

参见 symlink()link()readlink()

lstat

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

lstat -- 给出一个文件或符号连接的信息

说明

array lstat ( string filename )

获取由 filename 指定的文件或符号连接的统计信息。本函数和 stat() 函数相同,只除了如果 filename 参数是符号连接的话,则该符号连接的状态被返回,而不是该符号连接所指向的文件的状态。

有关 lstat() 返回的数组结构见手册中 stat() 函数的页面。

注: 本函数的结果会被缓存。更多信息参见 clearstatcache()

提示: PHP 5.0.0 起本函数也可被某些 URL wrapper 使用。参考附录 L 来看哪些 wrapper 支持 stat() 系列函数的功能。

参见 stat()

mkdir

(PHP 3, PHP 4, PHP 5)

mkdir -- 新建目录

说明

bool mkdir ( string pathname [, int mode] )

尝试新建一个由 pathname 指定的目录。

注意也许想用八进制数指定模式,也就是说该数应以零打头。模式也会被当前的 umask 修改,可以用 umask() 来改变。

注: Mode 在 Windows 下被忽略。自 PHP 4.2.0 起成为可选项。

默认的 mode 是 0777,意味着最大可能的访问权。有关 mode 的更多信息请阅读 chmod() 页面。

例子 1. mkdir() 例子

<?php
mkdir("/path/to/my/dir", 0700);
?>

注: 自 PHP 5.0.0 rmdir() 也可用于某些 URL 封装协议。参见附录 L 的列表看看 rmdir() 支持哪些 URL 封装协议。

注: recursive 参数是 PHP 5.0.0 添加的。

如果成功则返回 TRUE,失败则返回 FALSE

参见 rmdir()

move_uploaded_file

(PHP 4 >= 4.0.3, PHP 5)

move_uploaded_file -- 将上传的文件移动到新位置

说明

bool move_uploaded_file ( string filename, string destination )

本函数检查并确保由 filename 指定的文件是合法的上传文件(即通过 PHP 的 HTTP POST 上传机制所上传的)。如果文件合法,则将其移动为由 destination 指定的文件。

如果 filename 不是合法的上传文件,不会出现任何操作,move_uploaded_file() 将返回 FALSE

如果 filename 是合法的上传文件,但出于某些原因无法移动,不会出现任何操作,move_uploaded_file() 将返回 FALSE。此外还会发出一条警告。

这种检查显得格外重要,如果上传的文件有可能会造成对用户或本系统的其他用户显示其内容的话。

注: move_uploaded_file()安全模式open_basedir 都是敏感的。不过,限制只针对 destination 路径,因为允许移动上传的文件名 filename 可能会与这些限制产生冲突。move_uploaded_file() 仅作用于通过 PHP 上传的文件以确保这个操作的安全性。

警告

如果目标文件已经存在,将会被覆盖。

参见 is_uploaded_file(),以及文件上传处理一章中的简单使用例子。

parse_ini_file

(PHP 4, PHP 5)

parse_ini_file -- 解析一个配置文件

说明

array parse_ini_file ( string filename [, bool process_sections] )

parse_ini_file() 载入一个由 filename 指定的 ini 文件,并将其中的设置作为一个联合数组返回。如果将最后的 process_sections 参数设为 TRUE,将得到一个多维数组,包括了配置文件中每一节的名称和设置。process_sections 的默认值是 FALSE

注: 本函数和 php.ini 文件没有关系,该文件在运行脚本时就已经处理过了。本函数可以用来读取你自己的应用程序的配置文件。

注: 如果 ini 文件中的值包含任何非字母数字的字符,需要将其括在双引号中(")。

注: 自 PHP 4.2.1 其本函数也受到安全模式open_basedir 的影响。

注: 自 PHP 5.0 版本开始,该函数也处理选项值内的新行。

注: 有些保留字不能作为 ini 文件中的键名,包括:null,yes,no,true 和 false。值为 null,no 和 false 等效于 "",值为 yes 和 true 等效于 "1"。字符 |&~![()" 也不能用在键名的任何地方,而且这些字符在选项值中有着特殊的意义。

ini 文件的结构和 php.ini 的相似。

常量也可以在 ini 文件中被解析,因此如果在运行 parse_ini_file() 之前定义了常量作为 ini 的值,将会被集成到结果中去。只有 ini 的值会被求值。例如:

例子 1. sample.ini 的内容

; This is a sample configuration file
; Comments start with ';', as in php.ini

[first_section]
one = 1
five = 5
animal = BIRD

[second_section]
path = /usr/local/bin
URL = "http://www.example.com/~username"

例子 2. parse_ini_file() 例子

<?php

define('BIRD', 'Dodo bird');

// Parse without sections
$ini_array = parse_ini_file("sample.ini");
print_r($ini_array);

// Parse with sections
$ini_array = parse_ini_file("sample.ini", true);
print_r($ini_array);

?>

上例将输出:

Array
(
    [one] => 1
    [five] => 5
    [animal] => Dodo bird
    [path] => /usr/local/bin
    [URL] => http://www.example.com/~username
)
Array
(
    [first_section] => Array
        (
            [one] => 1
            [five] => 5
            [animal] = Dodo bird
        )

    [second_section] => Array
        (
            [path] => /usr/local/bin
            [URL] => http://www.example.com/~username
        )

)

由数字组成的键名和小节名会被 PHP 当作整数来处理,因此以 0 开头的数字会被当作八进制而以 0x 开头的会被当作十六进制。

pathinfo

(PHP 4 >= 4.0.3, PHP 5)

pathinfo -- 返回文件路径的信息

说明

array pathinfo ( string path [, int options] )

pathinfo() 返回一个联合数组包含有 path 的信息。包括以下的数组单元:dirnamebasenameextension

可以通过参数 options 指定要返回哪些单元。它们包括:PATHINFO_DIRNAMEPATHINFO_BASENAMEPATHINFO_EXTENSION。默认是返回全部的单元。

例子 1. pathinfo() 例子

<?php
$path_parts = pathinfo("/www/htdocs/index.html");
echo $path_parts["dirname"] . "\n";
echo $path_parts["basename"] . "\n";
echo $path_parts["extension"] . "\n";
?>

上例将输出:

/www/htdocs
index.html
html

注: 有关取得当前路径信息的说明,请阅读预定义变量一节。

参见 dirname()basename()parse_url()realpath()

pclose

(PHP 3, PHP 4, PHP 5)

pclose -- 关闭进程文件指针

说明

int pclose ( resource handle )

关闭用 popen() 打开的指向管道的文件指针。

文件指针必须有效,且必须是成功调用 popen() 所返回的。

返回运行的进程的终止状态。

参见 popen()

popen

(PHP 3, PHP 4, PHP 5)

popen -- 打开进程文件指针

说明

resource popen ( string command, string mode )

打开一个指向进程的管道,该进程由派生给定的 command 命令执行而产生。

返回一个和 fopen() 所返回的相同的文件指针,只不过它是单向的(只能用于读或写)并且必须用 pclose() 来关闭。此指针可以用于 fgets()fgetss()fwrite()

如果出错返回 FALSE

注: 如果需要双向支持,使用 proc_open()

例子 1. popen() 例子

<?php
$handle = popen("/bin/ls", "r");
?>

注: 如果未找到要执行的命令,会返回一个合法的资源。这看上去很怪,但有道理。它允许你访问 shell 返回的任何错误信息:

<?php
error_reporting(E_ALL);

/* 加入重定向以得到标准错误输出 stderr。 */
$handle = popen('/path/to/spooge 2>&1', 'r');
echo "'$handle'; " . gettype($handle) . "\n";
$read = fread($handle, 2096);
echo $read;
pclose($handle);
?>

注: 在打开了安全模式时,只能执行在 safe_mode_exec_dir 之内的程序。为实用起见目前不能在指向程序的路径中包含 .. 成分。

警告

在打开了安全模式时,初始命令字符串之后的所有词都被看成一个单一的参数。因此,echo y | echo x 就成了 echo "y | echo x"

参见 pclose()fopen()proc_open()

readfile

(PHP 3, PHP 4, PHP 5)

readfile -- 输出一个文件

说明

int readfile ( string filename [, bool use_include_path [, resource context]] )

读入一个文件并写入到输出缓冲。

返回从文件中读入的字节数。如果出错返回 FALSE 并且除非是以 @readfile() 形式调用,否则会显示错误信息。

提示: 如果“fopen wrappers”已经被激活,则在本函数中可以把 URL 作为文件名来使用。请参阅 fopen() 函数来获取怎样指定文件名的详细信息以及支持 URL 封装协议的列表:附录 L

如果也想在 include_path 中搜索文件,可以使用可选的第二个参数并将其设为 TRUE

注: 对 context 的支持是 PHP 5.0.0 添加的。有关 context 的说明请参考参考 CXLI, Stream Functions

参见 fpassthru()file()fopen()include()require()virtual()file_get_contents()附录 L

readlink

(PHP 3, PHP 4, PHP 5)

readlink -- 返回符号连接指向的目标

说明

string readlink ( string path )

readlink() 和同名的 C 函数做同样的事,返回符号连接的内容。如果出错返回 FALSE

例子 1. readlink() 例子

<?php

// output e.g. /boot/vmlinux-2.4.20-xfs
echo readlink('/vmlinuz');

?>

注: 本函数未在 Windows 平台下实现。

参见 is_link()symlink()linkinfo()

realpath

(PHP 4, PHP 5)

realpath -- 返回规范化的绝对路径名

说明

string realpath ( string path )

realpath() 扩展所有的符号连接并且处理输入的 path 中的 '/./', '/../' 以及多余的 '/' 并返回规范化后的绝对路径名。返回的路径中没有符号连接,'/./' 或 '/../' 成分。

realpath() 失败时返回 FALSE,比如说文件不存在的话。在 BSD 系统上,如果仅仅是 path 不存在的话,PHP 并不会像其它系统那样返回 FALSE

例子 1. realpath() 例子

<?php
$real_path = realpath("../../index.php");
?>

参见 basename()dirname()pathinfo()

rename

(PHP 3, PHP 4, PHP 5)

rename -- 重命名一个文件或目录

说明

bool rename ( string oldname, string newname [, resource context] )

尝试把 oldname 重命名为 newname

如果成功则返回 TRUE,失败则返回 FALSE

例子 1. rename() 例子

<?php
rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt");
?>

注: 在 PHP 4.3.3 之前,rename() 不能在基于 *nix 的系统中跨磁盘分区重命名文件。

注: 自 PHP 5.0.0 起 rename() 也可用于某些 URL 封装协议。参见附录 L 的列表看看 rename() 支持哪些 URL 封装协议。

注: 用于 oldname 中的封装协议必须和用于 newname 中的相匹配。

注: 对 context 的支持是 PHP 5.0.0 添加的。有关 context 的说明请参考参考 CXLI, Stream Functions

参见 copy()unlink()move_uploaded_file()

rewind

(PHP 3, PHP 4, PHP 5)

rewind -- 倒回文件指针的位置

说明

bool rewind ( resource handle )

handle 的文件位置指针设为文件流的开头。

如果成功则返回 TRUE,失败则返回 FALSE

文件指针必须合法,并且指向由 fopen() 成功打开的文件。

注: 如果将文件以附加("a" 或者 "a+")模式打开,写入文件的任何数据总是会被附加在后面,不管文件指针的位置。

参见 fseek()ftell()

rmdir

(PHP 3, PHP 4, PHP 5)

rmdir -- 删除目录

说明

bool rmdir ( string dirname )

尝试删除 dirname 所指定的目录。 该目录必须是空的,而且要有相应的权限。如果成功则返回 TRUE,失败则返回 FALSE

注: 自 PHP 5.0.0 起 rmdir() 也可用于某些 URL 封装协议。参见附录 L 的列表看看 rmdir() 支持哪些 URL 封装协议。

注: 对 context 的支持是 PHP 5.0.0 添加的。有关 context 的说明请参考参考 CXLI, Stream Functions

注: 安全模式被激活时,PHP 将检查被操作的目录是否和正在执行的脚本有相同的 UID(所有者)。

参见 mkdir()unlink()

set_file_buffer

(PHP 3 >= 3.0.8, PHP 4 >= 4.0.1, PHP 5)

set_file_buffer -- stream_set_write_buffer()的别名

说明

本函数是该函数的别名:stream_set_write_buffer()

stat

(PHP 3, PHP 4, PHP 5)

stat -- 给出文件的信息

说明

array stat ( string filename )

获取由 filename 指定的文件的统计信息。如果 filename 是符号连接,则统计信息是关于被连接文件本身的,而不是符号连接。lstat()stat() 相同,只除了它会返回符号连接的状态。

如果出错,stat() 返回 FALSE,并且发出一条警告。

返回一个数组包含有文件的统计信息,该数组具有以下列出的单元,数组下标从零开始。除了数字索引之外自 PHP 4.0.6 起还可以通过关联索引来访问。

表格 1. stat()fstat() 返回格式

数字下标关联键名(自 PHP 4.0.6)说明
0devdevice number - 设备名
1inoinode number - inode 号码
2modeinode protection mode - inode 保护模式
3nlinknumber of links - 被连接数目
4uiduserid of owner - 所有者的用户id
5gidgroupid of owner- 所有者的组 id
6rdevdevice type, if inode device * - 设备类型,如果是 inode 设备的话
7sizesize in bytes - 文件大小的字节数
8atimetime of last access (unix timestamp) - 上次访问时间(Unix 时间戳)
9mtimetime of last modification (unix timestamp) - 上次修改时间(Unix 时间戳)
10ctimetime of last change (unix timestamp) - 上次改变时间(Unix 时间戳)
11blksizeblocksize of filesystem IO * - 文件系统 IO 的块大小
12blocksnumber of blocks allocated - 所占据块的数目
* - 仅在支持 st_blksize 类型的系统下有效。其它系统(如 Windows)返回 -1。

注: 本函数的结果会被缓存。更多信息参见 clearstatcache()

提示: PHP 5.0.0 起本函数也可被某些 URL wrapper 使用。参考附录 L 来看哪些 wrapper 支持 stat() 系列函数的功能。

参见 lstat()fstat()filemtime()filegroup()

symlink

(PHP 3, PHP 4, PHP 5)

symlink -- 建立符号连接

说明

bool symlink ( string target, string link )

symlink() 对于已有的 target 建立一个名为 link 的符号连接。

如果成功则返回 TRUE,失败则返回 FALSE

注: 本函数未在 Windows 平台下实现。

参见 link() 来建立硬连接,以及 readlink()linkinfo()

tempnam

(PHP 3, PHP 4, PHP 5)

tempnam -- 建立一个具有唯一文件名的文件

说明

string tempnam ( string dir, string prefix )

在指定目录中建立一个具有唯一文件名的文件。如果该目录不存在,tempnam() 会在系统临时目录中生成一个文件,并返回其文件名。

在 PHP 4.0.6 之前,tempnam() 函数的行为取决于系统。在 Windows 下 TMP 环境变量会越过 dir 参数,在 Linux 下 TMPDIR 环境变量优先,而在 SVR4 下总是使用 dir 参数,如果其指向的目录存在的话。如果有疑问请参考系统文档中的 tempnam(3) 函数。

注: 如果 PHP 不能在指定的 dir 参数中创建文件,则退回到系统默认值。

返回新的临时文件名,出错返回 FALSE

例子 1. tempnam() 例子

<?php
$tmpfname = tempnam("/tmp", "FOO");
$handle = fopen($tmpfname, "w");
fwrite($handle, "writing to tempfile");
fclose($handle);
// do here something
unlink($tmpfname);
?>

注: 本函数的行为在 4.0.3 版中改变了。也会建立一个临时文件以避免竞争情形,即有可能会在产生出作为文件名的字符串与脚本真正建立该文件之间会在文件系统中存在同名文件。注意,如果不再需要该文件则要删除此文件,不会自动删除的。

参见 tmpfile()unlink()

tmpfile

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

tmpfile -- 建立一个临时文件

说明

resource tmpfile ( void )

以读写 (w+) 模式建立一个具有唯一文件名的临时文件,返回一个与 fopen() 所返回相似的文件句柄。文件会在关闭后(用 fclose())自动被删除,或当脚本结束后。

详细信息请参考系统手册中的 tmpfile(3) 函数,以及 stdio.h 头文件。

例子 1. tmpfile() 例子

<?php
$temp = tmpfile();
fwrite($temp, "writing to tempfile");
fseek($temp, 0);
echo fread($temp, 1024);
fclose($temp); // this removes the file
?>

上例将输出:

writing to tempfile

参见 tempnam()

touch

(PHP 3, PHP 4, PHP 5)

touch -- 设定文件的访问和修改时间

说明

bool touch ( string filename [, int time [, int atime]] )

尝试将由 filename 给出的文件的访问和修改时间设定为给出的时间。如果没有给出可选参数 time,则使用当前时间。这和 utime(有时也叫做 utimes)所作的等价。如果给出了第三个参数 atime,则给定文件的访问时间会被设为 atime。注意访问时间总是会被修改的,不论有几个参数。

如果文件不存在,则会被创建。如果成功则返回 TRUE,失败则返回 FALSE

例子 1. touch() 例子

<?php
if (touch($FileName)) {
    echo "$FileName modification time has been changed to present time";
} else {
    echo "Sorry, could not change modification time of $FileName";
}
?>

umask

(PHP 3, PHP 4, PHP 5)

umask -- 改变当前的 umask

说明

int umask ( [int mask] )

umask() 将 PHP 的 umask 设定为 mask & 0777 并返回原来的 umask。当 PHP 被作为服务器模块使用时,在每个请求结束后 umask 会被恢复。

无参数调用 umask() 会返回当前的 umask。

注: 在多线程的服务器上尽量避免使用这个函数。创建文件后要改变其权限最好还是使用 chmod()。使用 umask() 会导致并发程序和服务器发生不可预知的情况,因为它们是使用相同的 umask 的。

例子 1. umask() 例子

<?php
$old = umask(0);
chmod("/path/some_dir/some_file.txt", 0755);
umask($old);

// Checking
if ($old != umask()) {
    die('An error occured while changing back the umask');
}
?>

unlink

(PHP 3, PHP 4, PHP 5)

unlink -- 删除文件

说明

bool unlink ( string filename )

删除 filename。和 Unix C 的 unlink() 函数相似。如果成功则返回 TRUE,失败则返回 FALSE

注: 自 PHP 5.0.0 起 unlink() 也可以用于某些 URL 封装协议。参考附录 L 中的列表看哪些封装协议支持 unlink()

注: 对 context 的支持是 PHP 5.0.0 添加的。有关 context 的说明请参考参考 CXLI, Stream Functions

参见目录删除函数 rmdir()

XXXVI. Firebird/InterBase Functions

简介

Firebird/InterBase is a relational database offering many ANSI SQL-92 features that runs on Linux, Windows, and a variety of Unix platforms. Firebird/InterBase offers excellent concurrency, high performance, and powerful language support for stored procedures and triggers. It has been used in production systems, under a variety of names since 1981.

InterBase is the name of the closed-source variant of this RDBMS that was developed by Borland/Inprise. More information about InterBase is available at http://www.borland.com/interbase/.

Firebird is a commercially independent project of C and C++ programmers, technical advisors and supporters developing and enhancing a multi-platform relational database management system based on the source code released by Inprise Corp (now known as Borland Software Corp) under the InterBase Public License v.1.0 on 25 July, 2000. More information about Firebird is available at http://www.firebirdsql.org/.

注: This extension supports InterBase versions 5 and up and all versions of Firebird. Support for InterBase version 5.x will be dropped in PHP 5.

This database uses a single quote (') character for escaping, a behavior similar to the Sybase database, add to your php.ini the following directive:

magic_quotes_sybase = On


安装

To enable InterBase support configure PHP --with-interbase[=DIR], where DIR is the InterBase base install directory, which defaults to /usr/interbase.

Note to Win32 Users: In order to enable this module on a Windows environment, you must copy gds32.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32). In case you installed the InterBase database server on the same machine PHP is running on, you will have this DLL already. Therefore you don't need to copy gds32.dll from the DLL folder.


运行时配置

这些函数的行为受 php.ini 的影响。

表格 1. InterBase configuration options

NameDefaultChangeableChangelog
ibase.allow_persistent"1"PHP_INI_SYSTEM 
ibase.max_persistent"-1"PHP_INI_SYSTEM 
ibase.max_links"-1"PHP_INI_SYSTEM 
ibase.default_dbNULLPHP_INI_SYSTEMAvailable since PHP 5.0.0.
ibase.default_userNULLPHP_INI_ALL 
ibase.default_passwordNULLPHP_INI_ALL 
ibase.default_charsetNULLPHP_INI_ALLAvailable since PHP 5.0.0.
ibase.timestampformat"%Y-%m-%d %H:%M:%S"PHP_INI_ALL 
ibase.dateformat"%Y-%m-%d"PHP_INI_ALL 
ibase.timeformat"%H:%M:%S"PHP_INI_ALL 
有关 PHP_INI_* 常量进一步的细节与定义参见附录 G

以下是配置选项的简要解释。

ibase.allow_persistent boolean

Whether to allow persistent connections to Firebird/InterBase.

ibase.max_persistent integer

The maximum number of persistent Firebird/InterBase connections per process. New connections created with ibase_pconnect() will be non-persistent if this number would be exceeded.

ibase.max_links integer

The maximum number of Firebird/InterBase connections per process, including persistent connections.

ibase.default_db string

The default database to connect to when ibase_[p]connect() is called without specifying a database name. If this value is set and SQL safe mode is enabled, no other connections than to this database will be allowed.

ibase.default_user string

The user name to use when connecting to a database if no user name is specified.

ibase.default_password string

The password to use when connecting to a database if no password is specified.

ibase.default_charset string

The character set to use when connecting to a database if no character set is specified.

ibase.timestampformat string

ibase.dateformat string

ibase.timeformat string

These directives are used to set the date and time formats that are used when returning dates and times from a result set, or when binding arguments to date and time parameters.


预定义常量

以下常量由本扩展模块定义,因此只有在本扩展模块被编译到 PHP 中,或者在运行时被动态加载后才有效。

The following constants can be passed to ibase_trans() to specify transaction behaviour.

表格 2. Firebird/InterBase transaction flags

ConstantDescription
IBASE_DEFAULT The default transaction settings are to be used. This default is determined by the client library, which defines it as IBASE_WRITE|IBASE_CONCURRENCY|IBASE_WAIT in most cases.
IBASE_READStarts a read-only transaction.
IBASE_WRITEStarts a read-write transaction.
IBASE_CONSISTENCYStarts a transaction with the isolation level set to 'consistency', which means the transaction cannot read from tables that are being modified by other concurrent transactions.
IBASE_CONCURRENCYStarts a transaction with the isolation level set to 'concurrency' (or 'snapshot'), which means the transaction has access to all tables, but cannot see changes that were committed by other transactions after the transaction was started.
IBASE_COMMITTEDStarts a transaction with the isolation level set to 'read committed'. This flag should be combined with either IBASE_REC_VERSION or IBASE_REC_NO_VERSION. This isolation level allows access to changes that were committed after the transaction was started. If IBASE_REC_NO_VERSION was specified, only the latest version of a row can be read. If IBASE_REC_VERSION was specified, a row can even be read when a modification to it is pending in a concurrent transaction.
IBASE_WAITIndicated that a transaction should wait and retry when a conflict occurs.
IBASE_NOWAITIndicated that a transaction should fail immediately when a conflict occurs.

The following constants can be passed to ibase_fetch_row(), ibase_fetch_assoc() or ibase_fetch_object() to specify fetch behaviour.

表格 3. Firebird/InterBase fetch flags

ConstantDescription
IBASE_FETCH_BLOBSAlso available as IBASE_TEXTfor backward compatibility. Causes BLOB contents to be fetched inline, instead of being fetched as BLOB identifiers.
IBASE_FETCH_ARRAYSCauses arrays to be fetched inline. Otherwise, array identifiers are returned. Array identifiers can only be used as arguments to INSERT operations, as no functions to handle array identifiers are currently available.
IBASE_UNIXTIMECauses date and time fields not to be returned as strings, but as UNIX timestamps (the number of seconds since the epoch, which is 1-Jan-1970 0:00 UTC). Might be problematic if used with dates before 1970 on some systems.

The following constants are used to pass requests and options to the service API functions (ibase_server_info(), ibase_db_info (), ibase_backup(), ibase_restore () and ibase_maintain_db()). Please refer to the Firebird/InterBase manuals for the meaning of these options.

IBASE_BKP_IGNORE_CHECKSUMS

IBASE_BKP_IGNORE_LIMBO

IBASE_BKP_METADATA_ONLY

IBASE_BKP_NO_GARBAGE_COLLECT

IBASE_BKP_OLD_DESCRIPTIONS

IBASE_BKP_NON_TRANSPORTABLE

IBASE_BKP_CONVERT

Options to ibase_backup()

IBASE_RES_DEACTIVATE_IDX

IBASE_RES_NO_SHADOW

IBASE_RES_NO_VALIDITY

IBASE_RES_ONE_AT_A_TIME

IBASE_RES_REPLACE

IBASE_RES_CREATE

IBASE_RES_USE_ALL_SPACE

Options to ibase_restore()

IBASE_PRP_PAGE_BUFFERS

IBASE_PRP_SWEEP_INTERVAL

IBASE_PRP_SHUTDOWN_DB

IBASE_PRP_DENY_NEW_TRANSACTIONS

IBASE_PRP_DENY_NEW_ATTACHMENTS

IBASE_PRP_RESERVE_SPACE

IBASE_PRP_RES_USE_FULL

IBASE_PRP_RES

IBASE_PRP_WRITE_MODE

IBASE_PRP_WM_ASYNC

IBASE_PRP_WM_SYNC

IBASE_PRP_ACCESS_MODE

IBASE_PRP_AM_READONLY

IBASE_PRP_AM_READWRITE

IBASE_PRP_SET_SQL_DIALECT

IBASE_PRP_ACTIVATE

IBASE_PRP_DB_ONLINE

IBASE_RPR_CHECK_DB

IBASE_RPR_IGNORE_CHECKSUM

IBASE_RPR_KILL_SHADOWS

IBASE_RPR_MEND_DB

IBASE_RPR_VALIDATE_DB

IBASE_RPR_FULL

IBASE_RPR_SWEEP_DB

Options to ibase_maintain_db()

IBASE_STS_DATA_PAGES

IBASE_STS_DB_LOG

IBASE_STS_HDR_PAGES

IBASE_STS_IDX_PAGES

IBASE_STS_SYS_RELATIONS

Options to ibase_db_info()

IBASE_SVC_SERVER_VERSION

IBASE_SVC_IMPLEMENTATION

IBASE_SVC_GET_ENV

IBASE_SVC_GET_ENV_LOCK

IBASE_SVC_GET_ENV_MSG

IBASE_SVC_USER_DBPATH

IBASE_SVC_SVR_DB_INFO

IBASE_SVC_GET_USERS

Options to ibase_server_info()

目录
ibase_add_user --  Add a user to a security database (only for IB6 or later)
ibase_affected_rows --  Return the number of rows that were affected by the previous query
ibase_backup --  Initiates a backup task in the service manager and returns immediately
ibase_blob_add --  Add data into a newly created blob
ibase_blob_cancel --  Cancel creating blob
ibase_blob_close --  Close blob
ibase_blob_create --  Create a new blob for adding data
ibase_blob_echo --  Output blob contents to browser
ibase_blob_get --  Get len bytes data from open blob
ibase_blob_import --  Create blob, copy file in it, and close it
ibase_blob_info --  Return blob length and other useful info
ibase_blob_open --  Open blob for retrieving data parts
ibase_close --  Close a connection to an InterBase database
ibase_commit_ret -- Commit a transaction without closing it
ibase_commit -- Commit a transaction
ibase_connect --  Open a connection to an InterBase database
ibase_db_info --  Request statistics about a database
ibase_delete_user --  Delete a user from a security database (only for IB6 or later)
ibase_drop_db --  Drops a database
ibase_errcode --  Return an error code
ibase_errmsg --  Return error messages
ibase_execute -- Execute a previously prepared query
ibase_fetch_assoc --  Fetch a result row from a query as an associative array
ibase_fetch_object -- Get an object from a InterBase database
ibase_fetch_row -- Fetch a row from an InterBase database
ibase_field_info --  Get information about a field
ibase_free_event_handler --  Cancels a registered event handler
ibase_free_query --  Free memory allocated by a prepared query
ibase_free_result -- Free a result set
ibase_gen_id --  Increments the named generator and returns its new value
ibase_maintain_db --  Execute a maintenance command on the database server
ibase_modify_user --  Modify a user to a security database (only for IB6 or later)
ibase_name_result --  Assigns a name to a result set
ibase_num_fields --  Get the number of fields in a result set
ibase_num_params --  Return the number of parameters in a prepared query
ibase_param_info --  Return information about a parameter in a prepared query
ibase_pconnect --  Open a persistent connection to an InterBase database
ibase_prepare --  Prepare a query for later binding of parameter placeholders and execution
ibase_query -- Execute a query on an InterBase database
ibase_restore --  Initiates a restore task in the service manager and returns immediately
ibase_rollback_ret -- Roll back a transaction without closing it
ibase_rollback -- Roll back a transaction
ibase_server_info --  Request information about a database server
ibase_service_attach --  Connect to the service manager
ibase_service_detach --  Disconnect from the service manager
ibase_set_event_handler --  Register a callback function to be called when events are posted
ibase_timefmt --  Sets the format of timestamp, date and time type columns returned from queries
ibase_trans -- Begin a transaction
ibase_wait_event --  Wait for an event to be posted by the database

ibase_add_user

(PHP 4 >= 4.2.0, PHP 5)

ibase_add_user --  Add a user to a security database (only for IB6 or later)

Description

bool ibase_add_user ( resource service_handle, string user_name, string password [, string first_name [, string middle_name [, string last_name]]] )

PHP 4 uses server, dba_user_name and dba_user_password instead of service_handle parameter.

警告

本函数暂无文档,仅有参数列表。

See also ibase_modify_user() and ibase_delete_user().

ibase_affected_rows

(PHP 5)

ibase_affected_rows --  Return the number of rows that were affected by the previous query

Description

int ibase_affected_rows ( [resource link_identifier] )

This function returns the number of rows that were affected by the previous query (INSERT, UPDATE or DELETE) that was executed from within the transaction context specified by link_identifier. If link_identifier is a connection resource, its default transaction is used.

See also ibase_query() and ibase_execute().

ibase_backup

(PHP 5)

ibase_backup --  Initiates a backup task in the service manager and returns immediately

Description

mixed ibase_backup ( resource service_handle, string source_db, string dest_file [, int options [, bool verbose]] )

警告

本函数暂无文档,仅有参数列表。

ibase_blob_add

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_add --  Add data into a newly created blob

Description

void ibase_blob_add ( resource blob_handle, string data )

ibase_blob_add() adds data into a blob created with ibase_blob_create(). Returns NULL on success or FALSE on failure.

See also ibase_blob_cancel(), ibase_blob_close(), ibase_blob_create() and ibase_blob_import().

ibase_blob_cancel

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_cancel --  Cancel creating blob

Description

bool ibase_blob_cancel ( resource blob_handle )

This function will discard a BLOB created by ibase_create_blob() if it has not yet been closed by ibase_blob_close(). 如果成功则返回 TRUE,失败则返回 FALSE

See also ibase_blob_close(), ibase_blob_create() and ibase_blob_import().

ibase_blob_close

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_close --  Close blob

Description

mixed ibase_blob_close ( resource blob_handle )

This function closes a BLOB that has either been opened for reading by ibase_open_blob() or has been opened for writing by ibase_create_blob(). If the BLOB was being read, this function returns TRUE on success, if the BLOB was being written to, this function returns a string containing the BLOB id that has been assigned to it by the database. On failure, this function returns FALSE.

See also ibase_blob_cancel() and ibase_blob_open().

ibase_blob_create

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_create --  Create a new blob for adding data

Description

resource ibase_blob_create ( [resource link_identifier] )

ibase_blob_create() creates a new BLOB for filling with data. It returns a BLOB handle for later use with ibase_blob_add() or FALSE on failure.

See also ibase_blob_add(), ibase_blob_cancel(), ibase_blob_close() and ibase_blob_import().

ibase_blob_echo

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_echo --  Output blob contents to browser

Description

bool ibase_blob_echo ( resource link_identifier, string blob_id )

bool ibase_blob_echo ( string blob_id )

This function opens a BLOB for reading and sends its contents directly to standard output (the browser, in most cases). 如果成功则返回 TRUE,失败则返回 FALSE

See also ibase_blob_open(), ibase_blob_close() and ibase_blob_get().

ibase_blob_get

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_get --  Get len bytes data from open blob

Description

string ibase_blob_get ( resource blob_handle, int len )

This function returns at most len bytes from a BLOB that has been opened for reading by ibase_blob_open(). Returns FALSE on failure.

<?php
    $sql       = "SELECT blob_value FROM table";
    $result    = ibase_query($sql);
    $data      = ibase_fetch_object($result);
    $blob_data = ibase_blob_info($data->BLOB_VALUE);
    $blob_hndl = ibase_blob_open($data->BLOB_VALUE);
    echo         ibase_blob_get($blob_hndl, $blob_data[0]);
?>

Whilst this example doesn't do much more than a 'ibase_blob_echo($data->BLOB_VALUE)' would do, it does show you how to get information into a $variable to manipulate as you please.

注: It is not possible to read from a BLOB that has been opened for writing by ibase_blob_create().

See also ibase_blob_open(), ibase_blob_close() and ibase_blob_echo().

ibase_blob_import

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_import --  Create blob, copy file in it, and close it

Description

string ibase_blob_import ( resource link_identifier, resource file_handle )

string ibase_blob_import ( resource file_handle )

This function creates a BLOB, reads an entire file into it, closes it and returns the assigned BLOB id. The file handle is a handle returned by fopen(). Returns FALSE on failure.

例子 1. ibase_blob_import() example

<?php
$dbh = ibase_connect($host, $username, $password);
$filename = '/tmp/bar';

$fd = fopen($filename, 'r');
if ($fd) {

    $blob = ibase_blob_import($dbh, $fd);
    fclose($fd);

    if (!is_string($blob)) {
        // import failed
    } else {
        $query = "INSERT INTO foo (name, data) VALUES ('$filename', ?)";
        $prepared = ibase_prepare($dbh, $query);
        if (!ibase_execute($prepared, $blob)) {
            // record insertion failed
        }
    }
} else {
    // unable to open the data file
}
?>

See also ibase_blob_add(), ibase_blob_cancel(), ibase_blob_close() and ibase_blob_create().

ibase_blob_info

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_info --  Return blob length and other useful info

Description

array ibase_blob_info ( resource link_identifier, string blob_id )

array ibase_blob_info ( string blob_id )

Returns an array containing information about a BLOB. The information returned consists of the length of the BLOB, the number of segments it contains, the size of the largest segment, and whether it is a stream BLOB or a segmented BLOB.

ibase_blob_open

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_open --  Open blob for retrieving data parts

Description

resource ibase_blob_open ( resource link_identifier, string blob_id )

resource ibase_blob_open ( string blob_id )

ibase_blob_open() opens an existing BLOB for reading. It returns a BLOB handle for later use with ibase_blob_get() or FALSE on failure.

See also ibase_blob_close(), ibase_blob_echo() and ibase_blob_get().

ibase_close

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_close --  Close a connection to an InterBase database

Description

bool ibase_close ( [resource connection_id] )

Closes the link to an InterBase database that's associated with a connection id returned from ibase_connect(). If the connection id is omitted, the last opened link is assumed. Default transaction on link is committed, other transactions are rolled back. 如果成功则返回 TRUE,失败则返回 FALSE

See also ibase_connect() and ibase_pconnect().

ibase_commit_ret

(PHP 5)

ibase_commit_ret -- Commit a transaction without closing it

Description

bool ibase_commit_ret ( [resource link_or_trans_identifier] )

If called without an argument, this function commits the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be committed. If the argument is a transaction identifier, the corresponding transaction will be committed. The transaction context will be retained, so statements executed from within this transaction will not be invalidated. 如果成功则返回 TRUE,失败则返回 FALSE

ibase_commit

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_commit -- Commit a transaction

Description

bool ibase_commit ( [resource link_or_trans_identifier] )

If called without an argument, this function commits the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be committed. If the argument is a transaction identifier, the corresponding transaction will be committed. 如果成功则返回 TRUE,失败则返回 FALSE

ibase_connect

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_connect --  Open a connection to an InterBase database

Description

resource ibase_connect ( [string database [, string username [, string password [, string charset [, int buffers [, int dialect [, string role [, int sync]]]]]]]] )

Establishes a connection to an InterBase server. The database argument has to be a valid path to database file on the server it resides on. If the server is not local, it must be prefixed with either 'hostname:' (TCP/IP), '//hostname/' (NetBEUI) or 'hostname@' (IPX/SPX), depending on the connection protocol used. username and password can also be specified with PHP configuration directives ibase.default_user and ibase.default_password. charset is the default character set for a database. buffers is the number of database buffers to allocate for the server-side cache. If 0 or omitted, server chooses its own default. dialect selects the default SQL dialect for any statement executed within a connection, and it defaults to the highest one supported by client libraries.

In case a second call is made to ibase_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling ibase_close().

例子 1. ibase_connect() example

<?php
    $host = 'localhost:/path/to/your.gdb';

    $dbh = ibase_connect($host, $username, $password);
    $stmt = 'SELECT * FROM tblname';
    $sth = ibase_query($dbh, $stmt);
    while ($row = ibase_fetch_object($sth)) {
        echo $row->email, "\n";
    }
    ibase_free_result($sth);
    ibase_close($dbh);
?>

注: The optional buffers parameter was added in PHP 4.0.0.

注: The optional dialect parameter was added in PHP 4.0.0 and is functional only with InterBase 6 and up.

注: The optional role parameter was added in PHP 4.0.0 and is functional only with InterBase 5 and up.

注: If you get some error like "arithmetic exception, numeric overflow, or string truncation. Cannot transliterate character between character sets" (this occurs when you try use some character with accents) when using this and after ibase_query() you must set the character set (i.e. ISO8859_1 or your current character set).

See also ibase_pconnect() and ibase_close().

ibase_db_info

(PHP 5)

ibase_db_info --  Request statistics about a database

Description

string ibase_db_info ( resource service_handle, string db, int action [, int argument] )

警告

本函数暂无文档,仅有参数列表。

ibase_delete_user

(PHP 4 >= 4.2.0, PHP 5)

ibase_delete_user --  Delete a user from a security database (only for IB6 or later)

Description

bool ibase_delete_user ( resource service_handle, string user_name )

PHP 4 uses server, dba_user_name and dba_user_password instead of service_handle parameter.

警告

本函数暂无文档,仅有参数列表。

See also ibase_add_user() and ibase_modify_user().

ibase_drop_db

(PHP 5)

ibase_drop_db --  Drops a database

Description

bool ibase_drop_db ( [resource connection] )

This functions drops a database that was opened by either ibase_connect() or ibase_pconnect(). The database is closed and deleted from the server. 如果成功则返回 TRUE,失败则返回 FALSE

See also ibase_connect() and ibase_pconnect().

ibase_errcode

(PHP 5)

ibase_errcode --  Return an error code

Description

int ibase_errcode ( void )

Returns the error code that resulted from the most recent InterBase function call. Returns FALSE if no error occurred.

See also ibase_errmsg().

ibase_errmsg

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_errmsg --  Return error messages

Description

string ibase_errmsg ( void )

Returns the error message that resulted from the most recent InterBase function call. Returns FALSE if no error occurred.

See also ibase_errcode().

ibase_execute

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_execute -- Execute a previously prepared query

Description

resource ibase_execute ( resource query [, mixed bind_arg [, mixed ...]] )

Execute a query prepared by ibase_prepare(). If the query raises an error, returns FALSE. If it is successful and there is a (possibly empty) result set (such as with a SELECT query), returns a result identifier. If the query was successful and there were no results, returns TRUE.

This is a lot more effective than using ibase_query() if you are repeating a same kind of query several times with only some parameters changing.

例子 1. ibase_execute() example

<?php
   
$dbh = ibase_connect($host, $username, $password); 

$updates = array(
    1 => 'Eric',
    5 => 'Filip',
    7 => 'Larry'
);

$query = ibase_prepare($dbh, "UPDATE FOO SET BAR = ? WHERE BAZ = ?");

foreach ($updates as $baz => $bar) {
    ibase_execute($query, $bar, $baz);
}

?>

注: In PHP 5.0.0 and up, this function returns the number of rows affected by the query (if > 0 and applicable to the statement type). A query that succeeded, but did not affect any rows (e.g. an UPDATE of a non-existent record) will return TRUE.

See also ibase_query().

ibase_fetch_assoc

(PHP 4 >= 4.3.0, PHP 5)

ibase_fetch_assoc --  Fetch a result row from a query as an associative array

Description

array ibase_fetch_assoc ( resource result [, int fetch_flag] )

ibase_fetch_assoc() returns an associative array that corresponds to the fetched row. Subsequent calls will return the next row in the result set, or FALSE if there are no more rows.

ibase_fetch_assoc() fetches one row of data from the result. If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using ibase_fetch_row() or use alias names in your query.

fetch_flag is a combination of the constants IBASE_TEXT and IBASE_UNIXTIME ORed together. Passing IBASE_TEXT will cause this function to return BLOB contents instead of BLOB ids. Passing IBASE_UNIXTIME will cause this function to return date/time values as Unix timestamps instead of as formatted strings.

See also ibase_fetch_row() and ibase_fetch_object().

ibase_fetch_object

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_fetch_object -- Get an object from a InterBase database

Description

object ibase_fetch_object ( resource result_id [, int fetch_flag] )

Fetches a row as a pseudo-object from a result_id obtained either by ibase_query() or ibase_execute().

<?php
    $dbh = ibase_connect($host, $username, $password);
    $stmt = 'SELECT * FROM tblname';
    $sth = ibase_query($dbh, $stmt);
    while ($row = ibase_fetch_object($sth)) {
        echo $row->email . "\n";
    }
    ibase_close($dbh);
?>

Subsequent calls to ibase_fetch_object() return the next row in the result set, or FALSE if there are no more rows.

fetch_flag is a combination of the constants IBASE_TEXT and IBASE_UNIXTIME ORed together. Passing IBASE_TEXT will cause this function to return BLOB contents instead of BLOB ids. Passing IBASE_UNIXTIME will cause this function to return date/time values as Unix timestamps instead of as formatted strings.

See also ibase_fetch_row() and ibase_fetch_assoc().

ibase_fetch_row

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_fetch_row -- Fetch a row from an InterBase database

Description

array ibase_fetch_row ( resource result_identifier [, int fetch_flag] )

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

ibase_fetch_row() fetches one row of data from the result associated with the specified result_identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

Subsequent calls to ibase_fetch_row() return the next row in the result set, or FALSE if there are no more rows.

fetch_flag is a combination of the constants IBASE_TEXT and IBASE_UNIXTIME ORed together. Passing IBASE_TEXT will cause this function to return BLOB contents instead of BLOB ids. Passing IBASE_UNIXTIME will cause this function to return date/time values as Unix timestamps instead of as formatted strings.

See also ibase_fetch_assoc() and ibase_fetch_object().

ibase_field_info

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_field_info --  Get information about a field

Description

array ibase_field_info ( resource result, int field_number )

Returns an array with information about a field after a select query has been run. The array is in the form of name, alias, relation, length, type.

<?php
    $rs = ibase_query("SELECT * FROM tablename"); 
    $coln = ibase_num_fields($rs);
    for ($i = 0; $i < $coln; $i++) {
        $col_info = ibase_field_info($rs, $i); 
        echo "name: ". $col_info['name']. "\n"; 
        echo "alias: ". $col_info['alias']. "\n"; 
        echo "relation: ". $col_info['relation']. "\n"; 
        echo "length: ". $col_info['length']. "\n"; 
        echo "type: ". $col_info['type']. "\n"; 
    }
?>

See also: ibase_num_fields().

ibase_free_event_handler

(PHP 5)

ibase_free_event_handler --  Cancels a registered event handler

Description

bool ibase_free_event_handler ( resource event )

This function causes the registered event handler specified by event to be cancelled. The callback function will no longer be called for the events it was registered to handle. 如果成功则返回 TRUE,失败则返回 FALSE

See also ibase_set_event_handler().

ibase_free_query

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_free_query --  Free memory allocated by a prepared query

Description

bool ibase_free_query ( resource query )

Free a query prepared by ibase_prepare(). 如果成功则返回 TRUE,失败则返回 FALSE

ibase_free_result

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_free_result -- Free a result set

Description

bool ibase_free_result ( resource result_identifier )

Frees a result set that has been created by ibase_query() or ibase_execute(). 如果成功则返回 TRUE,失败则返回 FALSE

ibase_gen_id

(PHP 5)

ibase_gen_id --  Increments the named generator and returns its new value

Description

mixed ibase_gen_id ( string generator [, int increment [, resource link_identifier]] )

警告

本函数暂无文档,仅有参数列表。

Returns new generator value as integer, or as string if the value is too big.

ibase_maintain_db

(PHP 5)

ibase_maintain_db --  Execute a maintenance command on the database server

Description

bool ibase_maintain_db ( resource service_handle, string db, int action [, int argument] )

警告

本函数暂无文档,仅有参数列表。

ibase_modify_user

(PHP 4 >= 4.2.0, PHP 5)

ibase_modify_user --  Modify a user to a security database (only for IB6 or later)

Description

bool ibase_modify_user ( resource service_handle, string user_name, string password [, string first_name [, string middle_name [, string last_name]]] )

PHP 4 uses server, dba_user_name and dba_user_password instead of service_handle parameter.

警告

本函数暂无文档,仅有参数列表。

See also ibase_add_user() and ibase_delete_user().

ibase_name_result

(PHP 5)

ibase_name_result --  Assigns a name to a result set

Description

bool ibase_name_result ( resource result, string name )

This function assigns a name to a result set. This name can be used later in UPDATE|DELETE ... WHERE CURRENT OF name statements. 如果成功则返回 TRUE,失败则返回 FALSE

<?php
 $result = ibase_query("SELECT field1,field2 FROM table FOR UPDATE");
    ibase_name_result($result, "my_cursor");

    $updateqry = ibase_prepare("UPDATE table SET field2 = ? WHERE CURRENT OF my_cursor");

    for ($i = 0; ibase_fetch_row($result); ++$i) {
        ibase_execute($updateqry, $i);
    }
?>

See also ibase_prepare() and ibase_execute().

ibase_num_fields

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_num_fields --  Get the number of fields in a result set

Description

int ibase_num_fields ( resource result_id )

Returns an integer containing the number of fields in a result set.

<?php
    $rs = ibase_query("SELECT * FROM tablename"); 
    $coln = ibase_num_fields($rs);
    for ($i = 0; $i < $coln; $i++) {
        $col_info = ibase_field_info($rs, $i); 
        echo "name: " . $col_info['name'] . "\n"; 
        echo "alias: " . $col_info['alias'] . "\n"; 
        echo "relation: " . $col_info['relation'] . "\n"; 
        echo "length: " . $col_info['length'] . "\n"; 
        echo "type: " . $col_info['type'] . "\n"; 
    }
?>

See also: ibase_field_info().

ibase_num_params

(PHP 5)

ibase_num_params --  Return the number of parameters in a prepared query

Description

int ibase_num_params ( resource query )

This function returns the number of parameters in the prepared query specified by query. This is the number of binding arguments that must be present when calling ibase_execute().

See also ibase_prepare() and ibase_param_info().

ibase_param_info

(PHP 5)

ibase_param_info --  Return information about a parameter in a prepared query

Description

array ibase_param_info ( resource query, int param_number )

Returns an array with information about a parameter after a query has been prepared. The array is in the form of name, alias, relation, length, type.

See also ibase_field_info() and ibase_num_params().

ibase_pconnect

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_pconnect --  Open a persistent connection to an InterBase database

Description

resource ibase_pconnect ( [string database [, string username [, string password [, string charset [, int buffers [, int dialect [, string role [, int sync]]]]]]]] )

ibase_pconnect() acts very much like ibase_connect() with two major differences. First, when connecting, the function will first try to find a (persistent) link that's already opened with the same parameters. If one is found, an identifier for it will be returned instead of opening a new connection. Second, the connection to the InterBase server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ibase_close() will not close links established by ibase_pconnect()). This type of link is therefore called 'persistent'.

注: buffers was added in PHP 4.0.0.

注: dialect was added in PHP 4.0.0. It is functional only with InterBase 6 and versions higher than that.

注: role was added in PHP 4.0.0. It is functional only with InterBase 5 and versions higher than that.

See also ibase_close() and ibase_connect() for the meaning of parameters passed to this function. They are exactly the same.

ibase_prepare

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_prepare --  Prepare a query for later binding of parameter placeholders and execution

Description

resource ibase_prepare ( string query )

resource ibase_prepare ( resource link_identifier, string query )

resource ibase_prepare ( resource link_identifier, string trans, string query )

Prepare a query for later binding of parameter placeholders and execution (via ibase_execute()).

ibase_query

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_query -- Execute a query on an InterBase database

Description

resource ibase_query ( [resource link_identifier, string query [, int bind_args]] )

Performs a query on an InterBase database. If the query raises an error, returns FALSE. If it is successful and there is a (possibly empty) result set (such as with a SELECT query), returns a result identifier. If the query was successful and there were no results, returns TRUE.

例子 1. ibase_query() example

<?php

    $host = 'localhost:/path/to/your.gdb';

    $dbh = ibase_connect($host, $username, $password);
    $stmt = 'SELECT * FROM tblname';

    $sth = ibase_query($dbh, $stmt) or die(ibase_errmsg());

?>

注: In PHP 5.0.0 and up, this function will return the number of rows affected by the query for INSERT, UPDATE and DELETE statements. In order to retain backward compatibility, it will return TRUE for these statements if the query succeeded without affecting any rows.

注: If you get some error like "arithmetic exception, numeric overflow, or string truncation. Cannot transliterate character between character sets" (this occurs when you try use some character with accents) when using this and after ibase_query() you must set the character set (i.e. ISO8859_1 or your current character set).

See also ibase_errmsg(), ibase_fetch_row(), ibase_fetch_object(), and ibase_free_result().

ibase_restore

(PHP 5)

ibase_restore --  Initiates a restore task in the service manager and returns immediately

Description

mixed ibase_restore ( resource service_handle, string source_file, string dest_db [, int options [, bool verbose]] )

警告

本函数暂无文档,仅有参数列表。

ibase_rollback_ret

(PHP 5)

ibase_rollback_ret -- Roll back a transaction without closing it

Description

bool ibase_rollback_ret ( [resource link_or_trans_identifier] )

If called without an argument, this function rolls back the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be rolled back. If the argument is a transaction identifier, the corresponding transaction will be rolled back. The transaction context will be retained, so statements executed from within this transaction will not be invalidated. 如果成功则返回 TRUE,失败则返回 FALSE

ibase_rollback

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_rollback -- Roll back a transaction

Description

bool ibase_rollback ( [resource link_or_trans_identifier] )

If called without an argument, this function rolls back the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be rolled back. If the argument is a transaction identifier, the corresponding transaction will be rolled back. 如果成功则返回 TRUE,失败则返回 FALSE

ibase_server_info

(PHP 5)

ibase_server_info --  Request information about a database server

Description

string ibase_server_info ( resource service_handle, int action )

警告

本函数暂无文档,仅有参数列表。

ibase_service_attach

(PHP 5)

ibase_service_attach --  Connect to the service manager

Description

resource ibase_service_attach ( string host, string dba_username, string dba_password )

警告

本函数暂无文档,仅有参数列表。

ibase_service_detach

(PHP 5)

ibase_service_detach --  Disconnect from the service manager

Description

bool ibase_service_detach ( resource service_handle )

警告

本函数暂无文档,仅有参数列表。

ibase_set_event_handler

(PHP 5)

ibase_set_event_handler --  Register a callback function to be called when events are posted

Description

resource ibase_set_event_handler ( callback event_handler, string event_name1 [, string event_name2 [, string ...]] )

resource ibase_set_event_handler ( resource connection, callback event_handler, string event_name1 [, string event_name2 [, string ...]] )

This function registers a PHP user function as event handler for the specified events. The callback is called with the event name and the link resource as arguments whenever one of the specified events is posted by the database. The callback must return FALSE if the event handler should be canceled. Any other return value is ignored. This function accepts up to 15 event arguments.

<?php

function event_handler($event_name, $link) 
{
    if ($event_name=="NEW ORDER") {
        // process new order
        ibase_query($link, "UPDATE orders SET status='handled'");
    } else if ($event_name=="DB_SHUTDOWN") {
        // free event handler 
        return false;
    }
}

ibase_set_event_handler($link, "event_handler", "NEW_ORDER", "DB_SHUTDOWN");
?>

The return value is an event resource. This resource can be used to free the event handler using ibase_free_event_handler().

See also ibase_free_event_handler() and ibase_wait_event().

ibase_timefmt

(PHP 3 >= 3.0.6, PHP 4)

ibase_timefmt --  Sets the format of timestamp, date and time type columns returned from queries

Description

int ibase_timefmt ( string format [, int columntype] )

Sets the format of timestamp, date or time type columns returned from queries. Internally, the columns are formatted by c-function strftime(), so refer to its documentation regarding to the format of the string. columntype is one of the constants IBASE_TIMESTAMP, IBASE_DATE and IBASE_TIME. If omitted, defaults to IBASE_TIMESTAMP for backwards compatibility.

<?php
    /* InterBase 6 TIME-type columns will be returned in
     * the form '05 hours 37 minutes'. */
    ibase_timefmt("%H hours %M minutes", IBASE_TIME);
?>

You can set defaults for these formats with the PHP configuration directives ibase.timestampformat, ibase.dateformat and ibase.timeformat.

注: This function has been removed from PHP 5, use ini_set() instead.

ibase_trans

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_trans -- Begin a transaction

Description

resource ibase_trans ( [int trans_args [, resource link_identifier]] )

Begins a transaction.

trans_args can be a combination of IBASE_READ, IBASE_WRITE, IBASE_COMMITTED, IBASE_CONSISTENCY, IBASE_CONCURRENCY, IBASE_REC_VERSION, IBASE_REC_NO_VERSION, IBASE_WAIT and IBASE_NOWAIT.

注: The behaviour of this function has been changed in PHP 5.0.0. The first call to ibase_trans() will not return the default transaction of a connection. All transactions started by ibase_trans() will be rolled back at the end of the script if they were not committed or rolled back by either ibase_commit() or ibase_rollback().

注: In PHP 5.0.0. and up, this function will accept multiple trans_args and link_identifier arguments. This allows transactions over multiple database connections, which are committed using a 2-phase commit algorithm. This means you can rely on the updates to either succeed in every database, or fail in every database. It does NOT mean you can use tables from different databases in the same query!

If you use transactions over multiple databases, you will have to specify both the link_id and transaction_id in calls to ibase_query() and ibase_prepare().

ibase_wait_event

(PHP 5)

ibase_wait_event --  Wait for an event to be posted by the database

Description

string ibase_wait_event ( string event_name1 [, string event_name2 [, string ...]] )

string ibase_wait_event ( resource connection, string event_name1 [, string event_name2 [, string ...]] )

This function suspends execution of the script until one of the specified events is posted by the database. The name of the event that was posted is returned. This function accepts up to 15 event arguments.

See also ibase_set_event_handler() and ibase_free_event_handler().

XXXVII. Firebird/Interbase Functions (PDO_FIREBIRD)

简介

警告

本扩展模块是实验性的。本模块的行为,包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本扩展模块风险自担。

PDO_FIREBIRD is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Firebird and Interbase databases.

目录
PDO_FIREBIRD DSN -- Connecting to Firebird and Interbase databases

PDO_FIREBIRD DSN

(no version information, might be only in CVS)

PDO_FIREBIRD DSN -- Connecting to Firebird and Interbase databases

说明

The PDO_FIREBIRD Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is firebird:.

DataSource

The hostname on which the database server resides.

Port

The port number for the server on which the database is running.

Database

The name of the database.

User

The name of the user that will connect to the database.

Password

The password for the user.

范例

例子 1. PDO_firebird DSN examples

The following example shows a PDO_FIREBIRD DSN for connecting to Firebird and Interbase databases:
firebird:User=john;Password=mypass;Database=DATABASE.GDE;DataSource=localhost;Port=3050

XXXVIII. Forms