2005-09-12
版权 © 1997-2005 PHP 文档组
版权信息
© Copyright 1997 - 2005 PHP 文档组版权所有。发布本资料须遵守开放出版许可协议 1.0 或者更新版本。一份开放出版许可协议的拷贝已随本手册发布,其最新版本位于 http://www.opencontent.org/openpub/。
未经版权所有者明确授权,禁止发行本文档被实质上修改的版本。
未经版权所有者事先授权,禁止将此作品及其衍生作品以标准(纸质)书籍形式发行。
如果有兴趣再发行或再版本手册的全部或部分内容,不论修改过与否,或者有任何问题,请联系版权所有者 doc-license@lists.php.net。注意本地址映射到一个公开归档的邮件列表。
本手册中 Zend API 一章是根据 Zend Technologies 提供的内容而来。
本手册主要由函数参考组成,但也包括语言参考,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.
PHP(“PHP: Hypertext Preprocessor”,超文本预处理器的字母缩写)是一种被广泛应用的开放源代码的多用途脚本语言,它可嵌入到 HTML中,尤其适合 web 开发。
以上是一个简单的回答,不过这是什么意思呢?请看如下例子:
请注意这个范例和其它用 C 或 Perl 语言写的脚本之间的区别――与用大量的命令来编写程序以输出 HTML 不同的是,我们用 PHP 编写了一个 HTML 脚本,其中嵌入了一些代码来做一些事情(例如,在本例中输出了一些文本)。PHP 代码被包含在特殊的起始符和结束符中,使得可以进出“PHP 模式”。
和客户端的 JavaScript 不同的是,PHP 代码是运行在服务端的。如果在服务器上建立了如上例类似的代码,则在运行该脚本后,客户端就能接收到其结果,但他们无法得知其背后的代码是如何运作的。甚至可以将 web 服务器设置成让 PHP 来处理所有的 HTML 文件,这么一来,用户就无法得知服务端到底做了什么。
使用 PHP 的一大好处是它对于初学者来说极其简单,同时也给专业的程序员提供了各种高级的特性。当看到 PHP 长长的特性列表时,请不要害怕。可以很快的入门,只需几个小时就可以自己写一些简单的脚本。
尽管 PHP 的开发是以服务端脚本为目的,但事实上其功能远不局限与此。请继续读后面的章节,在“PHP 能做什么”一节中将获得更多的信息。如果对 web 编程感兴趣,也可以阅读简明教程。
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 支持如下数据库:
同时还有一个 DBX 扩展库使得可以自由地使用该扩展库支持的任何数据库。另外,PHP 还支持 ODBC,即 Open Database Connection Standard(开放数据库连接标准),因此可以连接任何其它支持该世界标准的数据库。
Adabas D InterBase PostgreSQL dBase FrontBase SQLite Empress mSQL Solid FilePro(只读) Direct MS-SQL Sybase Hyperwave MySQL Velocis IBM DB2 ODBC Unix dbm Informix Oracle(OCI7 和 OCI8) Ingres Ovrimos
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 所有的特性和可提供的便利,请参阅安装以及函数参考有关章节以获取关于这里提到的扩展库更多的信息。
本章将给出关于 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 下,会发现 rpmfind 和 PBone 能够在获取 RPM 时提供帮助。也可以使用 apt-get 搜索 Debian 的相关软件包。
在 web 服务器根目录(DOCUMENT_ROOT)下建立一个文件名为 hello.php,然后完成如下内容:
该程序非常的简单,它仅仅只是利用了 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 模块和配置信息。请花一些时间来查看这些重要的信息。
现在来编写一些更实用的脚本,比如检查浏览页面的访问者在用什么浏览器。要达到这个目的,需要检查用户的 agent 字符串,它是浏览器发送的 HTTP 请求的一部分。该信息被存储在一个变量中。在 PHP 中,变量总是以一个美元符开头。我们现在感兴趣的变量是 $_SERVER['HTTP_USER_AGENT']。
注: $_SERVER 是一个特殊的 PHP 保留变量,它包含了 web 服务器提供的所有信息,被称为自动全局变量(或“超全局变量”)。请查阅本手册“超全局变量”中的有关内容以获取更多信息。这些特殊的变量是在 PHP 4.1.0 版本引入的。在这之前使用 $HTTP_*_VARS 数组,如 $HTTP_SERVER_VARS。尽管现在已经不用了,但它们在新版本中仍然存在(参见“旧代码”一节中的注解)。
要显示该变量,只需简单地进行如下操作:
PHP 有很多种不同类型的变量。在以上例子中我们打印了一个数组的单元。数组是一类非常有用的变量。
$_SERVER 只是 PHP 自动全局化的变量之一。可以查阅“保留变量”一节来查看这些变量的列表,或者也可以通过上节例子中 phpinfo() 函数的输出来查看。
可以在一个 PHP 标识中加入多个 PHP 语句,也可以建立一个代码块来做比简单的 echo 更多的事情。例如,如果需要识别 Internet Explorer,可以进行如下操作:
这里要介绍一些新的原理。上面用了一个 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 并运行其花括号 {} 内的代码;否则,则不运行这些代码。可以自己尝试利用 if,else 以及其它的函数,例如 strtoupper() 和 strlen(),来建立类似的脚本。在本手册中相关的页面也包含有范例。如果对如何使用函数不是很确定,可以阅读手册中有关“如何阅读函数定义”和“函数”的有关章节。
以下我们进一步显示如何进出 PHP 模式,甚至是在一个 PHP 代码块的中间:
例子 2-5. 混和 HTML 和 PHP 模式
该脚本的输出可能是:
|
和以上我们用一个 PHP 的 echo 语句来输出不同的是,我们跳出了 PHP 模式来直接写 HTML 代码。这里很值得注意的一点是,对于这两种情况而言,脚本的逻辑效率是相同的。在判断了 strpos() 函数的返回值是 TRUE 或是 FALSE,也就是判断了字符串 'MSIE' 是否被找到之后,最终只有一个 HTML 块被发送给浏览者。
PHP 一个很有用的特点体现在它处理 PHP 表单的方式。需要理解的非常重要的原理,是表单的任何元素都在 PHP 脚本中自动生效。请参阅本手册中“PHP 的外部变量”以获取关于在 PHP 中使用表单的详细信息及范例。以下是 HTML 表单的范例:
该表单中并没有什么特殊的地方,其中没有使用任何特殊的标识符。当用户填写了该表单并点击了提交按钮,页面 action.php 将被调用。在该文件中,可以加入如下内容:
该脚本进行的工作应该已经很明显了,这儿并没有其它更复杂的内容。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 下,老版本的代码应该可以在不作任何改动的情况下(理想地)运行。不过实际上,还是必须对老的代码做一些改动。
有可能影响到老版本的代码的最重要的两点改动分别是:
取消了旧的 $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 其它的功能。
安装前,首先需要知道想用 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 找到。建议选择一个最近的镜象服务器下载。
本节将指导如何在 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 下安装 PHP 的说明和提示。我们在另外的页面也有 Apache 2 的安装和说明。
可以从核心配置选项列表以及位于手册对应部分的特定扩展配置选项中选择参数并在安装步骤第 10 步将它们添加到 configure 命令中。版本号在这里被省略了以保证此说明的正确性。需要将这里的“xxx”替换为自己使用的文件的正确值。
例子 4-1. PHP 的 Apache 共享模块版本安装说明
|
也可以将 PHP 作为静态对象来安装:
例子 4-2. PHP 的 Apache 静态模块版本安装说明
|
根据 Unix 系统和 Apache 安装方法的不同,有很多方法停止和重启动 Apache。以下是一些不同的 Apache/UNIX 下重启动 Apache 的典型命令。需要把 /path/to/ 替换成自己系统上的确切路径。
例子 4-3. 重启动 Apache 的示例命令
|
apachectl 和 http(s)dctl 程序所在的路径在不同系统中通常不一样。如果系统中有 locate 或者 whereis 或者 which 命令,那么可以帮助找到这些控制程序。
编译 PHP 和 Apache 的不同例子还有:
此配置将生成在 Apache 的 httpd.conf 文件中用 LoadModule 加载的 libphp4.so 共享库。而 PostgreSQL 支持将嵌入到 libphp4.so 库中。
此配置将生成 Apache 的 libphp4.so 共享库,并且还生成 pgsql.so 共享库,可以在 php.ini 文件中用 extension 指令加载,或者在 PHP 脚本中用 dl() 函数明确地加载。
此配置将生成 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 可执行文件。
此配置和上面一样――除了没有在最后的 httpd 可执行文件中包括 PostgreSQL 的支持以及生成了一个 pgsql.so 共享库以外。该共享库可以在 php.ini 文件中或者用 dl() 函数加载。
当选择不同的方法编译 PHP 时,需要考虑每种方法的优势和缺点。用共享对象方式编译 PHP 意味着可以单独编译 Apache,并且不用在添加或修改了 PHP 的时候重新编译所有程序。用内置方法编译 PHP(静态方式)意味着 PHP 可以加载和运行得更快。更多信息见 Apache 的 DSO 支持页面。
注: Apache 默认的 httpd.conf 文件中目前包括类似如下的内容:
除非把它修改成“Group nogroup”或者其它类似的(“Group daemon”也很通用),PHP 将不能打开文件。
注: 确认在使用 --with-apxs=/path/to/apxs 时指向 Apache 安装后的目录中的 apxs。绝对不能用 Apache 源程序中的 apxs 而要用安装后的 apxs。
本节包括在 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 或更高版本兼容。
- PHP 4.3.0 或更高版本,可从 http://www.php.net/downloads.php 下载。
- 最新的稳定开发版。取得源代码 http://snaps.php.net/php4-latest.tar.gz 或下载 Windows 可执行程序 http://snaps.php.net/win32/php4-win32-latest.zip。
- 预发布版,可从 http://qa.php.net/ 下载。
- 总是可以通过匿名 CVS 取得 PHP。
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 共享模块版本)
|
按照上面的步骤便可以使 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。
PHP 4 可以被编译为 Caudium web 服务器的一个 Pike 模块。注意 PHP 3 中不支持。请参考下面的安装说明以将 PHP 4 安装到 Caudium 服务器中。
例子 4-5. Caudium 安装指南
|
当然可以将各种 PHP 4 的扩展模块编译到 Caudium 服务器中。请参考扩展库各自配置选项的说明。
注: 当编译 PHP 4 的 MySQL 的支持时,必须确认使用了正常的 MySQL 客户端代码。否则如果 Pike 已经支持 MySQL,就会产生冲突。应该在编译的时候使用 --with-mysql 选项指定 MySQL 的安装目录。
要将 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 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。
从 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) |
请确认 PATH 变量包含适当的目录 PATH=.:/usr/local/bin:/usr/sbin:/usr/bin:/usr/ccs/bin,并使用 export PATH 命令将其导出为环境变量。
gunzip php-x.x.x.tar.gz(如果使用 .gz 版本,否则跳到 4)
tar xvf php-x.x.x.tar
进入 PHP 解压缩后的目录:cd ../php-x.x.x
在下面的步骤中,请确认 Netscape 服务器安装在 /opt/netscape/suitespot/ 目录中。否则,将下面命令中的该路径修改为正确的路径并运行:
./configure --with-mysql=/usr/local/mysql \ --with-nsapi=/opt/netscape/suitespot/ \ --enable-libgcc |
运行 make,然后运行 make install。
在执行了基础的安装并阅读相应的 Readme 文件后,还需要执行一些额外的配置步骤。
Sun/iPlanet/Netscape 的配置说明. 首先需要为 LD_LIBRARY_PATH 环境变量添加一些路径,以便服务器找到所需的共享库。可以使用 web 服务器的启动脚本很好的完成这一工作。启动脚本通常位于:/path/to/server/https-servername/start。或许需要编辑其配置文件,它位于:/path/to/server/https-servername/config/。
添加下面一行到 mime.types(可以在管理服务器中添加):
type=magnus-internal/x-httpd-php exts=php |
编辑 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"] |
在 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 脚本组成的目录时由必要执行(类似于一个 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> |
认证的设置:PHP 认证不能与其它任何类型的认证一起工作。所有认证被传递到 PHP 脚本。要为整个服务器配置 PHP 认证,在默认对象中添加下面一行:
<Object name="default"> AuthTrans fn=php4_auth_trans . . . </Object> |
要在单一目录使用 PHP 认证,添加如下内容:
<Object ppath="d:\path\to\authenticated\dir\*"> AuthTrans fn=php4_auth_trans </Object> |
注: PHP 使用的堆栈大小取决于 web 服务器的配置。如果运行很大的 PHP 脚本时程序崩溃,推荐在 Admin Server(在“MAGNUS EDITOR”一节)中增大此项。
当编写 PHP 脚本时,应特别注意 Sun JSWS/Sun ONE WS/iPlanet/Netscape 是一个多线程 web 服务器。因此,所有请求都运行在相同的进程空间(Web 服务器自己的空间),该空间仅有一套环境变量。如果想获得 CGI 变量,例如 PATH_INFO、HTTP_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 为 "404 Not Found" 或类似的错误代码生成错误页面。将下面几行添加到 obj.conf 中以覆盖默认的错误页面:
Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...] |
另一种可能是生成自造目录列表。只要创建一个 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...] |
NSAPI 模块现在支持 nsapi_virtual() 函数(别名:virtual()),用来在 web 服务器上创建子请求(subrequests)和在 web 页面插入请求的结果。此函数使用了一些 NSAPI 中还没有文档说明的函数。在 Unix 下,该模块自动查找需要的函数,若它们存在则使用它们。若不存在,函数 nsapi_virtual() 被禁用。
注: 但是要注意,对 nsapi_virtual() 的支持是试验性质的!
默认为将 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 3 编译为 CGI 程序,可以通过键入 make bench 来进行一下性能的基准测试。注意如果默认打开了安全模式,则超过 30 秒的允许范围测试可能不能完成。这是因为 set_time_limit() 不能用于安全模式。用 max_execution_time 配置选项来为你自己的脚本控制此时间限制。make bench 会忽略配置文件。
注: make bench 仅能用于 PHP 3。
某些服务器提供的环境变量没有定义在当前的 CGI/1.1 标准中。只有下列变量定义在其中:AUTH_TYPE,CONTENT_LENGTH,CONTENT_TYPE,GATEWAY_INTERFACE,PATH_INFO,PATH_TRANSLATED,QUERY_STRING,REMOTE_ADDR,REMOTE_HOST,REMOTE_IDENT,REMOTE_USER,REQUEST_METHOD,SCRIPT_NAME,SERVER_NAME,SERVER_PORT,SERVER_PROTOCOL 和 SERVER_SOFTWARE。其它的变量均作为“供应商扩展(vendor extensions)”来对待。
本章节的内容和提示仅限于将 PHP 安装到 HP-UX 系统上(此文章是由 paul_mckay at clearwater-it dot co dot uk 编写的)。
注: 本文涉及的技巧适用于 PHP 4.0.4 和 Apache 1.3.9。
安装 PHP 需要一个 gzip,可以从如下地址得到该软件的二进制版本的发行包 http://hpux.connect.org.uk/ftp/hpux/Gnu/gzip-1.2.4a/gzip-1.2.4a-sd-10.20.depot.Z,下载后解压缩,并且使用 swinstall 安装。
安装 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。
安装 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。
安装 PHP 需要 bison,可以从如下地址得到该软件的二进制版本的发行包 http://hpux.connect.org.uk/ftp/hpux/Gnu/bison-1.28/bison-1.28-sd-10.20.depot.gz,安装方式同上。
安装 PHP 需要 flex,需要从 http://www.gnu.org 的镜像站点下载一个该软件的源代码。它被放置于一个 非 gnu 目录的 ftp 服务器上。下载这个文件,并且使用 gunzip 解压缩,然后执行 tar -xvf。进入新创建的 flex 目录并运行 ./configure,再执行 make 以及 make install。
如果这里出现了错误,很可能是由于 gcc 等工具不在路径中,应将其添加到环境变量 PATH 中。
下载 PHP 和 apache 的源代码。
下载后对他们分别执行 gunzip 和 tar -xvf。在开始编译他们之前我们需要修改一些文件。
首先 configure 文件需要被修改,因为它似乎忘记自己是在 hpux 系统下了,有更好的方法解决此问题,但最省事的是在配置脚本的第 47286 行加入 lt_target=hpux10.20。
其次是修改 Apache GuessOS 文件。在文件 apache_1.3.9/src/helpers 的第 89 行,将参数 echo "hp${HPUXMACH}-hpux${HPUXVER}"; exit 0 替换为 echo "hp${HPUXMACH}-hp-hpux${HPUXVER}"; exit 0。
不能把 PHP 作为共享对象方式安装到 HP-UX, 因此你必须将其编译成为一个静态方式,参照 Apache 站点的指导就可以完成。
这样就完成了 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 就应该可以正常工作了。
本章节的内容和提示仅限于将 PHP 安装到 OpenBSD 3.6 系统上。
使用二进制包安装 PHP 到 OpenBSD 系统上是被推荐的同时也是最简单的方法。PHP 核心包已经从其他模块中分离出来了并且每个模块可以被独立的安装/卸载而不影响其他模块。所有这些安装 PHP 需要的文件可以在 OpenBSD 光盘或者在 FTP 站点上找到。
需要安装的 PHP 核心包的文件是 php4-core-4.3.8.tgz,它包含了基本的引擎(包括 gettext 和 iconv)。其次,可能还需要安装一些模块包,如:php4-mysql-4.3.8.tgz 或 php4-imap-4.3.8.tgz。需要使用命令 phpxs 去激活它,并且再通过修改 php.ini 文件来屏蔽他们。
例子 4-6. 在 OpenBSD 系统下的软件包的安装示例
|
阅读用户手册中的 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 系统上安装 PHP 的说明和提示。
本节包含了在 Gentoo Linux 系统下安装 PHP 的说明和提示。
当可以下载和自己编译 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:
可以在 Gentoo 网站上的 Portage 手册中获得更多关于 emerge 的信息。
如果需要使用 Apache 2,可以在上例中简单的使用 emerge apache 命令。
在上一节,PHP 安装时几乎没有安装任何激活的模块。在写本文档时,唯一被激活的模块是 XML,因为 PEAR 需要它。这可能不是想要的,不久就会发现需要更多激活的模块,例如 MySQL、gettext、GD 等。
当自己从源代码编译 PHP 时,需要使用 configure 激活所需模块。而在 Gentoo 中,只需使用 USE 标记,它会被自动传递到配置脚本中。要了解 USE 标记在 emerge 中是怎么工作的,可以尝试:
例子 4-8. 获得所有可用的 USE 标记列表
|
可以从输出中看到,PHP 可用使用很多 USE 标记。请仔细查看和选择所需要的标记。如果选择的标记所需的库没有安装,Portage 会自动编译它们。可以再次使用 emerge -pv 命令以了解 Portage 会根据 USE 标记编译哪些内容。例如,如果没有安装 X,而在 USE 标记中包括了 X,Portage 将会首先编译 X,然后再编译 PHP。这会花去好几个小时。
如果要编译 PHP 并使其支持 MySQL、cURL 和 GD,使用的命令为:
在上例中,不要忘记同时 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 下安装 PHP 的说明和提示。
当然可以下载 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:
最后要考虑的是自己的软件包列表是否是最新版。如果最近没有更新过,那需要在做任何事之前先 apt-get update。这样就可以使用最近稳定版的 Apache 和 PHP 软件包了。
所有准备做好之后,就可以按照下面的例子来安装 Apache 和 PHP:
APT 将自动安装 Apache 1.3 的 PHP 4 模块以及所有依赖的库并激活之。如果在安装过程中没有被要求重启动 Apache,那必须手工进行:
上一节中 PHP 仅安装了核心模块。但可能不够用,用户很快就会发现需要更多的激活模块,例如 MySQL,cURL,GD 等。
当自己从源代码编译 PHP 时,需要通过 configure 命令来激活模块。用 APT 则只需安装附加的软件包。这些包都命名为“php4-*”(或“php5-*”,如果安装了第三方的 PHP 5 的话)。
从上面的输出中可以看到,还有很多 PHP 模块可安装(除了 php4-cgi,php4-cli 或 php4-pear 这些特殊软件包)。仔细察看并安装自己所需要的。如果选择了一个模块而没有相应的库,APT 会自动安装所有依赖的库。
如果选择将 MySQL,cURL 和 GD 支持添加到 PHP 中,则其命令类似于:
APT 会自动把适当的行添加到不同的 php.ini(/etc/php4/apache/php.ini,/etc/php4/cgi/php.ini 等)中去。
只需像之前那样重新启动 Apache 来激活这些模块。
如果看到了 PHP 源代码而不是脚本应该产生的结果,则 APT 可能没有 /etc/apache/conf.d/php4 包括到 Apache 1.3 配置中去。请确保下面一行出现在 /etc/apache/httpd.conf 文件中并重启动 Apache:
如果安装了更多模块但其函数不能在脚本中使用,请确保相应的配置行出现在 php.ini 中,如上面所说。APT 可能会由于混乱的 debconf 配置而在安装附加模块时失败。
本章包括在 Mac OS X 平台下安装 PHP 的说明和提示。Mac OS X 有两个不同的版本,客户版和服务器版,本手册两者均会介绍。请注意 PHP 不能在 Mac OS 9 和更早版本下运行。
Mac OS X 下有几个预编译和打包的 PHP 版本。可以通过它使用标准的配置的 PHP,但是若需要不同的功能集(比如一个安全服务器,或者一个不同的数据库驱动程序),可能需要自己编译 PHP 和/或 web 服务器。如果不熟悉如何自己编译软件,可以试着找一下包含自己所需功能的 PHP 预编译版本。
获得最新版本的 Apache 和 PHP。
将它们的 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 |
如果想对编译做些优化,可以添加下面一行:
setenv OPTIM=-O2 |
接下来,进入 PHP 4 源代码目录,并进行 configure 操作。
./configure --prefix=/usr \
--sysconfdir=/etc \
--localstatedir=/var \
--mandir=/usr/share/man \
--with-xml \
--with-apache=/src/apache_1.3.12 |
输入 make 和 make install。这样在 Apache 源代码目录中会创建一名为 src/modules/php4 的目录。
现在,重新配置 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 |
从 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 下为 Apache 服务器安装 PHP 模块,并添加 MySQL 和 PostgreSQL 的支持。本说明是由 Marc Liyanage 提供的。
| 警告 |
请注意,在按照下面的步骤操作时,应该停止 Apache 服务器! |
按照下面的步骤安装:
打开终端窗口。
输入 wget http://www.diax.ch/users/liyanage/software/macosx/libphp4.so.gz,等待下载完毕。
输入 gunzip libphp4.so.gz。
输入 sudo apxs -i -a -n php4 libphp4.so。
现在输入 sudo open -a TextEdit /etc/httpd/httpd.conf。TextEdit 将把 web 服务器的配置文件打开。在文件的末尾找到下面两行(使用查找命令):
#AddType application/x-httpd-php .php #AddType application/x-httpd-php-source .phps |
最后,输入 sudo apachectl graceful 重新启动 web 服务器。
PHP 现在应该已经配置好,并且正在运行了。可以在 Sites 文件夹创建一名为 test.php 的文件。该文件的内容为: <?php phpinfo() ?>。
现在在 web 浏览器浏览 127.0.0.1/~your_username/test.php。应该可以看到一个表格列出了 PHP 模块的信息。
本节内容适用于 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 认可的,因为我们相信,手动安装是系统安全和优化的最好选择。 |
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 目录结构
|
或:
例子 6-2. PHP 5 目录结构
|
请注意它们之间的不同和相似之处。PHP 4 和 PHP 5 都有一个 CGI 可执行文件、一个 CLI 可执行文件和服务器模块,但是它们位于不同的文件夹和/或有着不同的命名。PHP 4 将服务器模块放在 sapi 文件夹,而 PHP 5 并没有此目录,它的服务器模块文件位于 PHP 根文件夹中。PHP 5 的扩展支持 DLL 文件也并没有放在一个单独的目录中。
注: 在 PHP 4 中,需要将位于 dll 和 sapi 文件夹中的文件移动到主文件夹中(例如 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.dll(php5ts.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-dist 和 php.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。例如:
选择 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 是一个只运行在 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> |
注: 在 PHP 4 中,该引擎被命名为“ActivePHP”,如果使用 PHP 4,应该将上例中的“PHPScript”替换为“ActivePHP”。
注: ActiveScript 不使用默认的 php.ini 文件,而仅在调用它的 .exe 文件所在目录中寻找。如果想装载 PHP 扩展等,应该创建 php-activescript.ini 并将其放入那个目录。
本节包括针对 IIS(Microsoft Internet Information Server)的说明与提示。
| 警告 |
如果使用 CGI 方式安装,则服务器对于某些可能的攻击是开放的。请阅读 CGI 安全一章以学习如何防御这些攻击。 |
首先请阅读手工安装步骤。不要跳过这一步,这里提供了将 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_dir 和 doc_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.dll 和 php_curl.dll,存放于 PHP 下载的 ZIP 包中(自动安装包里没有)。在 PHP 5 中,很多扩展库都是 PECL 的一部分,可以从“Collection of PECL modules”包中下载,例如 php_zip.dll 和 php_ssh2.dll。点击进入 PHP 下载页。
在定义应用程序扩展名映射时,应选中“检查文件是否存在”。以极小的性能为代价,IIS(或者 PWS)会在调用 PHP 之前检查脚本文件是否存在并选出认证方法。这意味着 web 服务器会提供一个有道理的 404 形式错误信息而不是一条 CGI 错误说什么 PHP 没有输出任何数据。
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.dll 或 php5isapi.dll)或者 CGI 文件(php.exe 或 php-cgi.exe)作为“文件路径”后点“确定”,然后选中“设置扩展状态为允许”并点“确定”。
要使用 index.php 作为默认文档,在“文档”标签页中选择“添加”。输入 index.php 并点“确定”。用上下箭头按钮调整顺序。这和在 Apache 中设定 DirectoryIndex 相似。
对于每个要关联为 PHP 脚本的后缀都要重复以上步骤。.php 是最常用的,此外为兼容一些遗留下来的老程序可能还需要加上 .php3。
如果过些时候之后碰到 CPU 占用率达到 100%,则取消选中“缓存 ISAPI 应用程序”(“主目录”下点“配置”按钮”)。
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 支持的目录并选择“属性”。选中“执行”,并确认。
配置此服务器的推荐方法是使用随包发布的注册表文件(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 下安装 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 的 httpd.conf 文件:
例子 6-3. PHP 作为 Apache 1.3.x 的一个模块 这里假设 PHP 安装在 c:\php。如果不是这样请根据情况修改路径。 对于 PHP 4:
对于 PHP 5:
两个 PHP 版本都需要添加的内容:
|
如果按照手动安装步骤将 PHP 解压到 C:\php\,需要在 Apache 的配置文件中添加如下内容以使 PHP 按照 CGI 方式运行:
| 警告 |
如果使用 CGI 方式安装,则服务器对于某些可能的攻击是开放的。请阅读 CGI 安全一章以学习如何防御这些攻击。 |
如果想发布语法高亮的 php 文件,没有类似于模块方式下 PHP 那种方便的方法。选择了使用 CGI 方式运行 PHP,需要使用 highlight_file() 函数来进行语法高亮。创建一个 PHP 文件,加入下述代码即可:<?php highlight_file('some_php_script.php'); ?>。
本节包括在 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 或更高版本兼容。
- PHP 4.3.0 或更高版本,可从 http://www.php.net/downloads.php 下载。
- 最新的稳定开发版。取得源代码 http://snaps.php.net/php4-latest.tar.gz 或下载 Windows 可执行程序 http://snaps.php.net/win32/php4-win32-latest.zip。
- 预发布版,可从 http://qa.php.net/ 下载。
- 总是可以通过匿名 CVS 取得 PHP。
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。
需要将以下三行加入到 Apache 的 httpd.conf 配置文件中以设定 CGI:
| 警告 |
如果使用 CGI 方式安装,则服务器对于某些可能的攻击是开放的。请阅读 CGI 安全一章以学习如何防御这些攻击。 |
需要将以下两行加入到 Apache 的 httpd.conf 配置文件中以设定 Apache 2.0 的 PHP 模块:
例子 6-6. PHP 在 Apache 2.0 中的模块方式
|
注: 记得用自己 PHP 实际所在的路径替换掉上例中的 c:/php/。要留意在 LoadModule 指令中用的是 php4apache2.dll 或 php5apache2.dll,而不是 php4apache.dll 或 php5apache.dll,后者是设计用于 Apache 1.3.x 的。
注: 如果要使用内容协商机制,请阅读有关 FAQ。
| 警告 |
不要在安装中混合使用来自不同 PHP 版本的 DLL。使用下载回来的 PHP 版本中所提供的 DLL 和扩展库是唯一选择。 |
本节包含针对在 Windows 下 Sun Java System web 服务器,Sun ONE web 服务器,iPlanet 和 Netscape 服务器的 PHP 安装说明与提示。
自 PHP 4.3.3 起可以通过 NSAPI 模块使用 PHP 脚本来产生定制目录列表于错误页面。也可以使用为兼容 Apache 的附加函数。目前使用的 web 服务器的支持请阅读有关子请求的说明。
要将 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。
要将 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"] |
在 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 脚本的目录时需要(类似 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> |
重启动 web 服务使改动生效。
对每个要运行 PHP 的 web 服务器实例都进行以上步骤。
注: 更多将 PHP 设置为 NSAPI内容见:http://benoit.noss.free.fr/php/install-php4.html。
注: PHP 使用的堆栈大小(stacksize)依赖于 web 服务器的配置。如果在运行很大的 PHP 脚本时死掉,建议在管理服务器中增大此值(在 "MAGNUS EDITOR" 一节中)。
在写 PHP 脚本时很重要一点是 Sun JSWS/Sun ONE WS/iPlanet/Netscape 是多线程 web 服务器。因此所有的请求都运行于同一个进程空间(即 web 服务器自己的空间)而此空间只有一个环境。如果想取得 CGI 变量例如 PATH_INFO,HTTP_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 来为 "404 Not Found" 或类似的错误提示生成错误页面。对每个想要覆盖的错误页面在 obj.conf 中的对象里加入下面这行:
Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...] |
还可以生成自己定制的目录列表。只要创建一个显示目录列表的 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...] |
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" |
可以用 phpinfo() 函数来检查状态。
注: 但要注意:对 nsapi_virtual() 的支持是试验性质的!
本节包括针对 Windows 下的 OmniHTTPd 的内容与提示。
注: 应该首先阅读手工安装步骤!
| 警告 |
如果使用 CGI 方式安装,则服务器对于某些可能的攻击是开放的。请阅读 CGI 安全一章以学习如何防御这些攻击。 |
要在 OmniHTTPd 中安装 PHP 需要完成以下步骤。这是 CGI 方式的安装。OmniHTTPd 支持 SAPI,但是有测试显示以 ISAPI 模块方式使用 PHP 不太稳定。
CGI 用户重要提示: 请阅读 FAQ:cgi.force_redirect 中的重要细节。此选项需要被设为 0。
安装 OmniHTTPd 服务器。
右键点击系统托盘中蓝色的 OmniHTTPd 图标并选择 Properties
点击 web Server Global Settings
在“External”标签页,输入:virtual = .php | actual = c:\php\php.exe(如果是 PHP 5 则用 php-cgi.exe),并点击 Add 按钮
在 Mime 标签页,输入:virtual = wwwserver/stdcgi | actual = .php,并点击 Add 按钮
点击 OK
对每个想要和 PHP 关联的后缀都重复 2 - 6 步。
注: 有些 OmniHTTPd 安装包中内置了 PHP 支持。可以在安装时选择自定义安装,取消选中 PHP 部分。推荐使用最新的 PHP 可执行包。有些 OmniHTTPd 服务器内置了 PHP 4 beta 版,应该选择不安装内置版而安装自己的版本。如果服务器已经安装了,则在上面的第 4 和 5 步用 Replace 按钮来设置新的准确的信息。
本节包含针对 Windows 下的 Sambar 服务器的说明和提示。
注: 应该首先阅读手工安装步骤!
下面列出了怎样在 Windows 下设置 Sambar 服务器的 ISAPI 模块。
在 Sambar 安装目录中找到 mappings.ini 文件(在 config 目录中)。
打开 mappings.ini 并在 [ISAPI] 部分加入下面一行:
重启动 Sambar 服务器以使改动生效。
本节包含针对 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 下编译这么难?两个原因:
Windows 下还没有愿意免费共享代码的开发人员群体。直接结果就是没有足够的投资去建立支持这种开发方式的体系。大体上,尽量得到的可用资源都是从 Unix 下的工具来的。不要奇怪这种传统不会时出现。
下面几乎所有的说明都是“看过就忘”的类型。所以坐稳当并且尽可能忠实地按照说明来做。
要编译 PHP 需要 Microsoft 开发环境。推荐使用 Microsoft Visuaul C++ 6.0。要释放下载的文件还需要一个解压缩工具(例如:Winzip)。如果还没有解压缩的工具,可以从 InfoZip 下载一个免费版本。
在开始之前,需要先下载...
PHP 站点中的 win32 编译工具 http://www.php.net/extra/win32build.zip。
PHP 使用的 DNS 解析器的源代码:http://www.php.net/extra/bindlib_w32.zip。用这个替代 win32build.zip 中的 resolv.lib。
如果计划把 PHP 编译成 Apache 的静态模块那还需要 Apache 源程序。
最后,还需要 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 |
注: Cygwin 用户应省略上一步。正确安装的 Cygwin 环境已强制提供了 bison.simple 和 bison.exe 文件。
下一步是配置 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 库。自己决定是需要调试信息(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"
对于初学者最好的上手方法是编译 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.exe 在 c:\work\php-4.x.x.\Debug_TS 或 Release_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 下安装完 PHP 和 web 服务器之后,可能想要安装一些扩展库来获得更多功能。可以通过修改 php.ini 来选择当 PHP 启动时加载哪些扩展库。也可以在脚本中通过使用 dl() 来动态加载。
PHP 扩展库的 DLL 文件都具有 php_ 前缀。
很多扩展库都内置于 Windows 版的 PHP 之中。这意味着要加载这些扩展库不需要额外的 DLL 文件和 extension 配置指令。Windows 下的 PHP 扩展库列表列出了需要或曾经需要额外 PHP DLL 文件的扩展库。下面是内置的扩展库列表:
PHP 4 中(截止到 PHP 4.3.11):BCMath,Caledar,COM,Ctype,FTP,MySQL,ODBC,Overload,PCRE,Session,Tokenizer,WDDX,XML 和 Zlib。
PHP 5 中(截止到 5.0.4)有以下修改。新增内置:DOM,LibXML,Iconv,SimpleXML,SPL 和SQLite。以下不再内置:MySQL 和 Overload。
PHP 搜索扩展库的默认位置在 PHP 4 中是 C:\php4\extensions,在 PHP 5 中是 C:\php5。要修改此项以符合用户自己的 PHP 设置,需要编辑 php.ini 文件:
需要修改 extension_dir 设置以指向用户放置扩展库的目录或者说放置 php_*.dll 文件的位置。例如:
要在 php.ini 中启用某扩展库,需要去掉该行 extension=php_*.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.dll | bzip2 压缩函数库 | 无 |
| php_calendar.dll | 历法转换函数库 | 自 PHP 4.0.3 起内置 |
| php_cpdf.dll | ClibPDF 函数库 | 无 |
| php_crack.dll | 密码破解函数库 | 无 |
| php_ctype.dll | ctype 家族函数库 | 自 PHP 4.3.0 起内置 |
| php_curl.dll | CURL,客户端 URL 库函数库 | 需要:libeay32.dll,ssleay32.dll(已附带) |
| php_cybercash.dll | 网络现金支付函数库 | PHP <= 4.2.0 |
| php_db.dll | DBM 函数库 | 已废弃。用 DBA 替代之(php_dba.dll) |
| php_dba.dll | DBA:数据库(dbm 风格)抽象层函数库 | 无 |
| php_dbase.dll | dBase 函数库 | 无 |
| php_dbx.dll | dbx 函数库 | |
| php_domxml.dll | DOM XML 函数库 | PHP <= 4.2.0 需要:libxml2.dll(已附带),PHP >= 4.3.0 需要:iconv.dll(已附带) |
| php_dotnet.dll | .NET 函数库 | PHP <= 4.1.1 |
| php_exif.dll | EXIF 函数库 | 需要 php_mbstring.dll。并且在 php.ini 中,php_exif.dll 必须在 php_mbstring.dll之后加载。 |
| php_fbsql.dll | FrontBase 函数库 | PHP <= 4.2.0 |
| php_fdf.dll | FDF:表单数据格式化函数库 | 需要:fdftk.dll(已附带) |
| php_filepro.dll | filePro 函数库 | 只读访问 |
| php_ftp.dll | FTP 函数库 | 自 PHP 4.0.3 起内置 |
| php_gd.dll | GD 库图像函数库 | 在 PHP 4.3.2 中删除。此外注意在 GD1 中不能用真彩色函数,用 php_gd2.dll 替代。 |
| php_gd2.dll | GD 库图像函数库 | GD2 |
| php_gettext.dll | Gettext 函数库 | PHP <= 4.2.0 需要 gnu_gettext.dll(已附带),PHP >= 4.2.3 需要 libintl-1.dll,iconv.dll(已附带)。 |
| php_hyperwave.dll | HyperWave 函数库 | 无 |
| php_iconv.dll | ICONV 字符集转换 | 需要:iconv-1.3.dll(已附带),PHP >=4.2.1 需要 iconv.dll |
| php_ifx.dll | Informix 函数库 | 需要:Informix 库 |
| php_iisfunc.dll | IIS 管理函数库 | 无 |
| php_imap.dll | IMAP,POP3 和 NNTP 函数库 | 无 |
| php_ingres.dll | Ingres II 函数库 | 需要:Ingres II 库 |
| php_interbase.dll | InterBase functions | 需要:gds32.dll(已附带) |
| php_java.dll | Java 函数库 | PHP <= 4.0.6 需要:jvm.dll(已附带) |
| php_ldap.dll | LDAP 函数库 | PHP <= 4.2.0 需要 libsasl.dll(已附带),PHP >= 4.3.0 需要 libeay32.dll,ssleay32.dll(已附带) |
| php_mbstring.dll | 多字节字符串函数库 | 无 |
| php_mcrypt.dll | Mcrypt 加密函数库 | 需要:libmcrypt.dll |
| php_mhash.dll | Mhash 函数库 | PHP >= 4.3.0 需要:libmhash.dll(已附带) |
| php_mime_magic.dll | Mimetype 函数库 | 需要:magic.mime(已附带) |
| php_ming.dll | Ming 函数库(Flash) | 无 |
| php_msql.dll | mSQL 函数库 | 需要:msql.dll(已附带) |
| php_mssql.dll | MSSQL 函数库 | 需要:ntwdblib.dll(已附带) |
| php_mysql.dll | MySQL 函数库 | PHP >= 5.0.0 需要 libmysql.dll(已附带) |
| php_mysqli.dll | MySQLi 函数库 | PHP >= 5.0.0 需要 libmysql.dll(PHP <= 5.0.2 中是 libmysqli.dll)(已附带) |
| php_oci8.dll | Oracle 8 函数库 | 需要:Oracle 8.1+ 客户端库 |
| php_openssl.dll | OpenSSL 函数库 | 需要:libeay32.dll(已附带) |
| php_oracle.dll | Oracle 函数库 | 需要:Oracle 7 客户端库 |
| php_overload.dll | 对象重载函数库 | 自 PHP 4.3.0 起内置 |
| php_pdf.dll | PDF 函数库 | 无 |
| php_pgsql.dll | PostgreSQL 函数库 | 无 |
| php_printer.dll | 打印机函数库 | 无 |
| php_shmop.dll | 共享内存函数库 | 无 |
| php_snmp.dll | SNMP 函数库 | 仅用于 Windows NT! |
| php_soap.dll | SOAP 函数库 | PHP >= 5.0.0 |
| php_sockets.dll | Socket 函数库 | 无 |
| php_sybase_ct.dll | Sybase 函数库 | 需要:Sybase 客户端库 |
| php_tidy.dll | Tidy 函数库 | PHP >= 5.0.0 |
| php_tokenizer.dll | Tokenizer 函数库 | 自 PHP 4.3.0 起内置 |
| php_w32api.dll | W32api 函数库 | 无 |
| php_xmlrpc.dll | XML-RPC 函数库 | PHP >= 4.2.1 需要 iconv.dll(已附带) |
| php_xslt.dll | XSLT 函数库 | PHP <= 4.2.0 需要 sablot.dll,expat.dll(已附带)。PHP >= 4.2.1 需要 sablot.dll,expat.dll,iconv.dll(已附带)。 |
| php_yaz.dll | YAZ 函数库 | 需要:yaz.dll(已附带) |
| php_zip.dll | Zip 文件函数库 | 只读访问 |
| php_zlib.dll | ZLib 压缩函数库 | 自 PHP 4.3.0 起内置 |
PECL 是通过 PEAR 打包系统来的 PHP 扩展库仓库,本章内容示范了怎样取得并安装 PECL 扩展。
以下指南中假定 /your/phpsrcdir/ 是 PHP 源程序的路径,extname 是 PECL 扩展库的名字。自己根据实际情况调整。此外还假定用户熟悉 pear 命令。
要使用共享扩展库,必须经过编译,安装,然后加载。以下说明的方法提供了怎样编译和安装扩展库德各种指导,但并不会自动加载它们。可以通过将其包括在 php.ini 中用 extension PHP 指令加载,或者 用 dl() 函数。
当编译 PHP 模块时,拥有各种工具(autoconf,automake,libtool 等)的已知好使的版本很重要。所需工具和所需版本的详情见匿名 CVS 说明。
下载 PECL 扩展库有几种方法,如:
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。
和其它任何 PHP 扩展库的 DLL 一样,把 PECL 扩展库的 DLL 移动到 extension_dir 目录并将其包括入 php.ini 来安装。例如:
extension=php_extname.dll |
然后重新启动 web 服务器。
PEAR 使建立共享 PHP 扩展库更容易。用 pear 命令这样做:
$ pear install extname |
这将下载 extname 的源代码,编译之,并将 extname.so 安装到 extension_dir 中。然后 extname.so 就可以通过 php.ini 加载了。
默认情况下,pear 命令不会安装标记为 alpha 或 beta 状态的包。如果没有 stable 包可用,也可以用以下命令安装一个 beta 包:
$ pear install extname-beta |
也可以用此命令安装一个指定的版本:
$ pear install extname-0.1 |
有时候不能用 pear 安装命令。这可能是因为在防火墙后面,或者是因为想要安装的扩展库还没有 PEAR 兼容的包,例如 CVS 中尚未发布的扩展库。如果要编译这种扩展库,可以用更底层的编译工具来手工进行编译。
phpize 命令是用来准备 PHP 扩展库的编译环境的。下面例子中,扩展库的源程序位于 extname 目录中:
$ cd extname $ phpize $ ./configure $ make # make install |
成功的安装将创建 extname.so 并放置于 PHP 的扩展库目录中。需要调整 php.ini,加入 extension=extname.so 这一行之后才能使用此扩展库。
有时可能需要将扩展库静态编译到 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 |
如果还卡着,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/ 来报告错误。请不要在邮件列表或私人信件中发送错误报告。错误跟踪系统也可以用来提出对新特性的要求。
在提交错误报告之前请先阅读怎样报告错误!
配置文件(PHP 3 中是 php3.ini,自 PHP 4 起是 php.ini)在 PHP 启动时被读取。对于服务器模块版本的 PHP,仅在 web 服务器启动时读取一次。对于 CGI 和 CLI 版本,每次调用都会读取。
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:\windows 或 C:\winnt),或 --with-config-file-path 编译时选项指定的位置
如果存在 php-SAPI.ini(SAPI 是当前所用的 SAPI 名称,因此实际文件名为 php-cli.ini 或 php-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 例子
|
自 PHP 5.1.0 起,有可能在 .ini 文件内引用已存在的 .ini 变量。例如:open_basedir = ${open_basedir} ":/new/dir"。
当使用 PHP 作为 Apache 模块时,也可以用 Apache 的配置文件(例如 httpd.conf)和 .htaccess 文件中的指令来修改 PHP 的配置设定。需要有“AllowOverride Options”或“AllowOverride All”权限才可以。
在 PHP 4 和 PHP 5 中,有几个 Apache 指令可以使用户在 Apache 配置文件内部修改 PHP 的配置。哪些指令属于 PHP_INI_ALL,PHP_INI_PERDIR 或 PHP_INI_SYSTEM 中的哪一个,请参考附录中的 php.ini 配置选项列表。
注: 在 PHP 3 中,每个 php3.ini 中的配置设定都有相应的 Apache 指令,不过名字前要加上前缀“php3_”。
设定指定的值。只能用于 PHP_INI_ALL 或 PHP_INI_PERDIR 类型的指令。要清除先前设定的值,把 value 设为 none。
注: 不要用 php_value 设定布尔值。应该用 php_flag(见下面)。
用来设定布尔值的配置指令。仅能用于 PHP_INI_ALL 和 PHP_INI_PERDIR 类型的指令。
设定指定的指令的值。不能用于 .htaccess 文件。任何用 php_admin_value 设定的指令都不能被 .htaccess 或 virtualhost 中的指令覆盖。要清除先前设定的值,把 value 设为 none。
用来设定布尔值的配置指令。不能用于 .htaccess 文件。任何用 php_admin_flag 设定的指令都不能被 .htaccess 或 virtualhost 中的指令覆盖。
例子 9-2. Apache 配置例子
|
| 注意 |
PHP 常量不存在于 PHP 之外。例如在 httpd.conf 中不能使用 PHP 常量如 E_ALL 或 E_NOTICE 来设定 error_reporting 指令,因为其无意义,实际等于 0。应该用相应的掩码值来替代。这些常量可以在 php.ini 中使用。 |
在 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,都可以在脚本中通过 ini_set() 而在运行时修改某个值。更多信息见手册中 ini_set() 的页面。
如果对自己系统中的配置设定及其当前值的完整列表感兴趣,可以运行 phpinfo() 函数并查看其结果的页面。也可以在运行时用 ini_get() 或 get_cfg_var() 取得个别配置指令的值。
当 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> |
还可以用更高级的结构:
可以在 PHP 中使用四对不同的开始和结束标记。其中两种,<?php ?> 和 <script language="php"> </script> 总是可用的。另两种是短标记和 ASP 风格标记,可以在 php.ini 配置文件中打开或关闭。尽管有些人觉得短标记和 ASP 风格标记很方便,但移植性较差,通常不推荐。
注: 此外注意如果将 PHP 嵌入到 XML 或 XHTML 中则需要使用 <?php ?> 以保持符合标准。
例子 10-2. PHP 开始和结束标记
|
上例中的 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 支持 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 支持八种原始类型。
四种标量类型:
两种复合类型: 最后是两种特殊类型: 为了确保代码的易读性,本手册还介绍了一些伪类型: 可能还会读到一些关于“双精度(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 表达了真值,可以为 TRUE 或 FALSE。
注: 布尔类型是 PHP 4 引进的。
要明示地将一个值转换成 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。
如果给定的一个数超出了 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 中解决了。 |
要明示地将一个值转换为 integer,用 (int) 或 (integer) 强制转换。不过大多数情况下都不需要强制转换,因为当运算符,函数或流程控制需要一个 integer 参数时,值会自动转换。还可以通过函数 intval() 来将一个值转换成整型。
参见类型戏法。
浮点数(也叫浮点数,双精度数或实数)可以用以下任何语法定义:
形式上:LNUM [0-9]+
DNUM ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
EXPONENT_DNUM ( ({LNUM} | {DNUM}) [eE][+-]? {LNUM}) |
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-4. 定界符字符串例子
|
注: 定界符支持是 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. 一些字符串例子
|
字符串可以用“.”(点)运算符连接。注意这里不能用“+”(加)运算符。更多信息参见字符串运算符。
有很多实用函数来改变字符串。
普通函数见字符串函数一节,高级搜索和替换见正则表达式函数(两种风格:Perl 和 POSIX 扩展)。
还有 URL 字符串函数,以及加密/解密字符串的函数(mcrypt 和 mhash)。
最后,如果还是找不到想要的函数,参见字符类型函数。
可以用 (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) 的部分。
如果想测试本节中的任何例子,可以拷贝和粘贴这些例子并且加上下面这一行自己看看会发生什么:
不要指望在将一个字符转换成整型时能够得到该字符的编码(可能也会在 C 中这么做)。如果希望在字符编码和字符之间转换,请使用 ord() 和 chr() 函数。
PHP 中的数组实际上是一个有序图。图是一种把 values 映射到 keys 的类型。此类型在很多方面做了优化,因此可以把它当成真正的数组来使用,或列表(矢量),散列表(是图的一种实现),字典,集合,栈,队列以及更多可能性。因为可以用另一个 PHP 数组作为值,也可以很容易地模拟树。
解释这些结构超出了本手册的范围,但对于每种结构至少会发现一个例子。要得到这些结构的更多信息,建议参考有关此广阔主题的外部著作。
可以用 array() 语言结构来新建一个 array。它接受一定数量用逗号分隔的 key => value 参数对。
array( [key =>]
value
, ...
)
// key 可以是 integer 或者 string
// value 可以是任何值 |
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 可以为任何值。 |
<?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() 函数允许取消一个数组中的键名。要注意数组将不会重建索引。
foreach 控制结构是专门用于数组的。它提供了一个简单的方法来遍历数组。
应该始终在用字符串表示的数组索引上加上引号。例如用 $foo['bar'] 而不是 $foo[bar]。但是为什么 $foo[bar] 错了呢?可能在老的脚本中见过如下语法:
这样是错的,但可以正常运行。那么为什么错了呢?原因是此代码中有一个未定义的常量(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 也可以用已知常量,可能之前已经见过 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"; ?> |
<?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"; ?> |
如同在以上例子中解释的那样,$foo[bar] 起作用但其实是错误的。它起作用是因为根据语法的预期,bar 被当成了一个常量表达式。然而,在这个例子中不存在名为 bar 的常量。PHP 就假定指的是字面上的 bar,也就是字符串 "bar",但忘记加引号了。
在未来的某一时刻,PHP 开发小组可能会想新增一个常量或者关键字,或者用户可能希望以后在自己的程序中引入新的常量,那就有麻烦了。例如已经不能这样用 empty 和 default 这两个词了,因为他们是保留字。
注: 重申一次,在双引号字符串中,不给索引加上引号是合法的因此 "$foo[bar]"是合法的。至于为什么参见以上的例子和字符串中的变量解析中的解释。
对于任何的类型:整型、浮点、字符串、布尔和资源,如果将一个值转换为数组,将得到一个仅有一个元素的数组(其下标为 0),该元素即为此标量的值。
如果将一个对象转换成一个数组,所得到的数组的元素为该对象的属性(成员变量),其键名为成员变量名。
如果将一个 NULL 值转换成数组,将得到一个空数组。
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 5 中可以通过引用传递来做到。之前的版本需要需要采取别的方法:
例子 11-8. 集合
上例将输出:
|
本例产生一个基于一的数组。
数组是有序的。也可以使用不同的排序函数来改变顺序。更多信息参见数组函数。可以用 count() 函数来数出数组中元素的个数。
因为数组中的值可以为任意值,也可是另一个数组。这样可以产生递归或多维数组。
例子 11-12. 递归和多维数组
|
需要注意数组的赋值总是会涉及到值的拷贝。需要在复制数组时用引用符号(&)。
如果将一个对象转换成对象,它将不会有任何变化。如果其它任何类型的值被转换成对象,内置类 stdClass 的一个实例将被建立。如果该值为 NULL,则新的实例为空。对于任何其它的值,名为 scalar 的成员变量将包含该值。
特殊的 NULL 值表示一个变量没有值。NULL 类型唯一可能的值就是 NULL。
注: NULL 类型是 PHP 4 引进的。
在下列情况下一个变量被认为是 NULL:
被赋值为 NULL。
尚未被赋值。
被 unset()。
有些诸如 call_user_function() 或 usort() 的函数接受用户自定义的函数作为一个参数。Callback 函数不仅可以是一个简单的函数,它还可以是一个对象的方法,包括静态类的方法。
一个 PHP 函数用函数名字符串来传递。可以传递任何内置的或者用户自定义的函数,除了 array(),echo(),empty(),eval(),exit(),isset(),list(),print() 和 unset()。
一个对象的方法以数组的形式来传递,数组的下标 0 指明对象名,下标 1 指明方法名。
对于没有实例化为对象的静态类,要传递其方法,将数组 0 下标指明的对象名换成该类的名称即可。
例子 11-13. Callback 函数实例
|
PHP 在变量定义中不需要(或不支持)明示的类型定义;变量类型是根据使用该变量的上下文所决定的。也就是说,如果把一个字符串值赋给变量 var,var 就成了一个字符串。如果又把一个整型值赋给 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 应该变成一个第一个元素是“f”的数组呢,还是“f”成了字符串 $a 的第一个字符?
目前版本的 PHP 将以上第二个赋值理解成字符串的偏移量标识,即 $a 变成了 "f",尽管如此,这种自动转换的地结果应该被认为未定义。PHP 4 引入了新的花括号语法来访问字符串的字符,请使用该语法来替代以上的操作:
请参阅访问和修改字符串中的字符一节以获取更多信息。
PHP 中的类型强制转换和 C 中的非常像:在要转换的变量之前加上用括号括起来的目标类型。
允许的强制转换有:
(int),(integer) - 转换成整型
(bool),(boolean) - 转换成布尔型
(float),(double),(real) - 转换成浮点型
(string) - 转换成字符串
(array) - 转换成数组
(object) - 转换成对象
注意在括号内允许有空格和制表符,所以下面两个例子功能相同:
注: 为了将一个变量还原为字符串,还可以将变量放置在双引号中。
当在某些类型之间强制转换时确切地会发生什么可能不是很明显。更多信息见如下小节:
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 提供了大量的预定义变量。由于许多变量依赖于运行的服务器的版本和设置,及其它因素,所以并没有详细的说明文档。一些预定义变量在 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.0 和 4.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 超全局变量
包含一个引用指向每个当前脚本的全局范围内有效的变量。该数组的键名为全局变量的名称。从 PHP 3 开始存在 $GLOBALS 数组。
变量由 web 服务器设定或者直接与当前脚本的执行环境相关联。类似于旧数组 $HTTP_SERVER_VARS 数组(依然有效,但反对使用)。
经由 URL 请求提交至脚本的变量。类似于旧数组 $HTTP_GET_VARS 数组(依然有效,但反对使用)。
经由 HTTP POST 方法提交至脚本的变量。类似于旧数组 $HTTP_POST_VARS 数组(依然有效,但反对使用)。
经由 HTTP Cookies 方法提交至脚本的变量。类似于旧数组 $HTTP_COOKIE_VARS 数组(依然有效,但反对使用)。
经由 HTTP POST 文件上传而提交至脚本的变量。类似于旧数组 $HTTP_POST_FILES 数组(依然有效,但反对使用)。详细信息请参阅 POST 方法上传。
执行环境提交至脚本的变量。类似于旧数组 $HTTP_ENV_VARS 数组(依然有效,但反对使用)。
经由 GET,POST 和 COOKIE 机制提交至脚本的变量,因此该数组并不值得信任。所有包含在该数组中的变量的存在与否以及变量的顺序均按照 php.ini 中的 variables_order 配置指示来定义。此数组在 PHP 4.1.0 之前没有直接对应的版本。参见 import_request_variables()。
| 注意 |
自 PHP 4.3.0 起,$_FILES 中的文件信息不再存在于 $_REQUEST 中。 |
注: 当运行于命令行模式时,此数组将不会包含 argv 和 argc 条目;它们已经存在于数组 $_SERVER 中。
当前注册给脚本会话的变量。类似于旧数组 $HTTP_SESSION_VARS 数组(依然有效,但反对使用)。详细信息,请参照 Session 处理函数章节。
变量的范围即它定义的上下文背景(也就是它的生效范围)。大部分的 PHP 变量只有一个单独的范围。这个单独的范围跨度同样包含了 include 和 require 引入的文件。例如:
这里变量 $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 的例子:
以上脚本的输出将是“3”。在函数中申明了全局变量 $a 和 $b,任何变量的所有引用变量都会指向到全局变量。对于一个函数能够申明的全局变量的最大个数,PHP 没有限制。
在全局范围内访问变量的第二个办法,是用特殊的 PHP 自定义 $GLOBALS 数组。前面的例子可以写成:
在 $GLOBALS 数组中,每一个变量为一个元素,键名对应变量名,值对应变量的内容。$GLOBALS 之所以在全局范围内存在,是因为 $GLOBALS 是一个超全局变量。以下范例显示了超全局变量的用处:
变量范围的另一个重要特性是静态变量(static variable)。静态变量仅在局部函数域中存在,但当程序执行离开此作用域时,其值并不丢失。看看下面的例子:
本函数没什么用处,因为每次调用时都会将 $a 的值设为 0 并输出 "0"。将变量加一的 $a++ 没有作用,因为一旦退出本函数则变量 $a 就不存在了。要写一个不会丢失本次计数值的计数函数,要将变量 $a 定义为静态的:
现在,每次调用 Test() 函数都会输出 $a 的值并加一。
静态变量也提供了一种处理递归函数的方法。递归函数是一种调用自己的函数。写递归函数时要小心,因为可能会无穷递归下去。必须确保有充分的方法来中止递归。一下这个简单的函数递归计数到 10,使用静态变量 $count 来判断何时停止:
在 Zend 引擎 1 代,它驱动了 PHP4,对于变量的 static 和 global 定义是以 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() 函数时其值并没有被记住。
有时候使用可变变量名是很方便的。就是说,一个变量的变量名可以动态的设置和使用。一个普通的变量通过声明来设置,例如:
一个可变变量获取了一个普通变量的值作为这个可变变量的变量名。在上面的例子中 hello 使用了两个美元符号($)以后,就可以作为一个可变变量的变量了。例如:
这时,两个变量都被定义了:$a 的内容是“hello”并且 $hello 的内容是“world”。因此,可以表述为:
以下写法更准确并且会输出同样的结果:
它们都会输出:hello world。
要将可变变量用于数组,必须解决一个模棱两可的问题。这就是当写下 $$a[1] 时,解析器需要知道是想要 $a[1] 作为一个变量呢,还是想要 $$a 作为一个变量并取出该变量中索引为 [1] 的值。解决此问题的语法是,对第一种情况用 ${$a[1]},对第二种情况用 ${$a}[1]。
| 警告 |
注意,在 PHP 的函数和类的方法中,超全局变量不能用作可变变量。 |
当一个表单体交给 PHP 脚本时,表单中的信息会自动在脚本中可用。有很多方法访问此信息,例如:
根据特定的设置和个人的喜好,有很多种方法访问 HTML 表单中的数据。例如:
例子 12-9. 从一个简单的 POST HTML 表单访问数据
|
使用 GET 表单也类似,只不过要用适当的 GET 预定义变量。GET 也适用于 QUERY_STRING(URL 中在“?”之后的信息)。因此,举例说,http://www.example.com/test.php?id=3 包含有可用 $_GET['id'] 访问的 GET 数据。参见 $_REQUEST 和 import_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 3 中,变量使用中的数组仅限于一维数组。在 PHP 4 中,没有此种限制。
当提交表单时,可以用一幅图像代替标准的提交按钮,用类似这样的标记:
当用户点击到图像中的某处时,相应的表单会被传送到服务器,并加上两个变量 sub_x 和 sub_y。它们包含了用户点击图像的坐标。有经验的用户可能会注意到被浏览器发送的实际变量名包含的是一个点而不是下划线(即 sub.x 和 sub.y),但 PHP 自动将点转换成了下划线。
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 不会改变传递给脚本中的变量名。然而应该注意到点(句号)不是 PHP 变量名中的合法字符。至于原因,看看:
<?php $varname.ext; /* 非法变量名 */ ?> |
出于此原因,要注意 PHP 将会自动将变量名中的点替换成下划线。
因为 PHP 会判断变量类型并在需要时进行转换(通常情况下),因此在某一时刻给定的变量是何种类型并不明显。PHP 包括几个函数可以判断变量的类型,例如:gettype(),is_array(),is_float(),is_int(),is_object() 和 is_string()。参见类型一章。
常量是一个简单值的标识符(名字)。如同其名称所暗示的,在脚本执行期间该值不能改变(除了所谓的魔术常量,它们其实不是常量)。常量默认为大小写敏感。按照惯例常量标识符总是大写的。
常量名和其它任何 PHP 标签遵循同样的命名规则。合法的常量名以字母或下划线开始,后面跟着任何字母,数字或下划线。用正则表达式是这样表达的:[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
例子 13-1. 合法与非法的常量名
|
注: 在这里,字母是 a-z,A-Z,以及从 127 到 255(0x7f-0xff)的 ASCII 字符。
和 superglobals 一样,常量的范围是全局的。不用管作用域就可以在脚本的任何地方访问常量。有关作用得更多信息请阅读手册中的变量范围。
可以用 define() 函数来定义常量。一个常量一旦被定义,就不能再改变或者取消定义。
常量只能包含标量数据(boolean,integer,float 和 string)。
可以简单的通过指定其名字来取得常量的值,不要在常量前面加上 $ 符号。如果常量名是动态的,也可以用函数 constant() 来读取常量的值。用 get_defined_constants() 可以获得所有已定义的常量列表。
注: 常量和(全局)变量在不同的名字空间中。这意味着例如 TRUE 和 $TRUE 是不同的。
如果使用了一个未定义的常量,PHP 假定想要的是该常量本身的名字,如同用字符串调用它一样(CONSTANT 对应 "CONSTANT")。此时将发出一个 E_NOTICE 级的错误。参见手册中为什么 $foo[bar] 是错误的(除非事先用 define() 将 bar 定义为一个常量)。如果只想检查是否定义了某常量,用 defined() 函数。
常量和变量不同:
常量前面没有美元符号($);
常量只能用 define() 函数定义,而不能通过赋值语句;
常量可以不用理会变量范围的规则而在任何地方定义和访问;
常量一旦定义就不能被重新定义或者取消定义;
常量的值只能是标量。
参见类常量。
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()。
表达式是 PHP 最重要的基石。在 PHP 中,几乎所写的任何东西都是一个表达式。简单但却最精确的定义一个表达式的方式就是“任何有值的东西”。
最基本的表达式形式是常量和变量。当键入“$a = 5”,即将值“5”分配给变量 $a。“5”,很明显,其值为 5,换句话说“5”是一个值为 5 的表达式(在这里,“5”是一个整型常量)。
赋值之后,所期待情况是 $a 的值为 5,因而如果写下 $b = $a,期望的是它犹如 $b = 5 一样。换句话说,$a 是一个值也为 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 在读取变量的值之后,增加变量的值,因而叫做“后递增”)。
一个常用到表达式类型是比较表达式。这些表达式求值 FALSE 或 TRUE。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),等等。
还有一个表达式,如果没有在别的语言中看到过的话,可能看上去很奇怪,即三元条件运算符:
如果第一个子表达式的值是 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。常量 TRUE 和 FALSE(大小写无关)是两种可能的 Boolean 值。如果有必要,一个表达式将自动转换为 Boolean。参见类型强制转换一节。
PHP 提供了一套完整强大的表达式,而为它提供完整的文件资料已经超出了本手册的范围。上面的例子应该为你提供了一个好的关于什么是表达式和怎样构建一个有用的表达式的概念。在本手册的其余部分,我们将始终使用 expr 来表示一个有效的 PHP 表达式。
运算符是可以通过给出的一或多个值(用编程行话来说,表达式)来产生另一个值(因而整个结构成为一个表达式)的东西。所以可以认为函数或任何会返回一个值(例如 print)的结构是运算符,而那些没有返回值的(例如 echo)是别的东西。
有三种类型的运算符。第一种是一元运算符,只运算一个值,例如 !(取反运算符)或 ++(加一运算符)。第二种是有限二元运算符,PHP 支持的大多数运算符都是这种。列表见下节运算符优先级。
第三种是三元运算符:?:。它应该被用来根据一个表达式在另两个表达式中选择一个,而不是用来在两个语句或者程序路线中选择。把整个三元表达式放在扩号里是个很好的主意。
运算符优先级指定了两个表达式绑定得有多“紧密”。例如,表达式 1 + 5 * 3 的结果是 16 而不是 18 是因为乘号(“*”)的优先级比加号(“+”)高。必要时可以用括号来强制改变优先级。例如:(1 + 5) * 3 的值为 18。如果运算符优先级相同,则使用从左到右的左联顺序。
下表从高到低列出了运算符的优先级。同一行中的运算符具有相同优先级,此时它们的结合方向决定求值顺序。
表格 15-1. 运算符优先级
| 结合方向 | 运算符 | 附加信息 |
|---|---|---|
| 非结合 | new | new |
| 左 | [ | array() |
| 非结合 | ++ -- | 递增/递减运算符 |
| 非结合 | ! ~ - (int) (float) (string) (array) (object) @ | 类型 |
| 左 | * / % | 算数运算符 |
| 左 | + - . | 算数运算符和字符串运算符 |
| 左 | << >> | 位运算符 |
| 非结合 | < <= > >= | 比较运算符 |
| 非结合 | == != === !== | 比较运算符 |
| 左 | & | 位运算符和引用 |
| 左 | ^ | 位运算符 |
| 左 | | | 位运算符 |
| 左 | && | 逻辑运算符 |
| 左 | || | 逻辑运算符 |
| 左 | ? : | 三元运算符 |
| 右 | = += -= *= /= .= %= &= |= ^= <<= >>= | 赋值运算符 |
| 左 | and | 逻辑运算符 |
| 左 | xor | 逻辑运算符 |
| 左 | or | 逻辑运算符 |
| 左 | , | 多处用到 |
左联表示表达式从左向右求值,右联相反。
注: 尽管 ! 比 = 的优先级高,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 = 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 & $b | And(按位与) | 将把 $a 和 $b 中都为 1 的位设为 1。 |
| $a | $b | Or(按位或) | 将把 $a 或者 $b 中为 1 的位设为 1。 |
| $a ^ $b | Xor(按位异或) | 将把 $a 和 $b 中不同的位设为 1。 |
| ~ $a | Not(按位非) | 将 $a 中为 0 的位设为 1,反之亦然。 |
| $a << $b | Shift left(左移) | 将 $a 中的位向左移动 $b 次(每一次移动都表示“乘以 2”)。 |
| $a >> $b | Shift 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 类型 | 结果 |
|---|---|---|
| null 或 string | string | 将 NULL 转换为 "",进行数字或词汇比较 |
| bool 或 null | 任何其它类型 | 转换为 bool,FALSE < TRUE |
| object | object | 内置类可以定义自己的比较,不同类不能比较,相同类和数组同样方式比较属性(PHP 4 中),PHP 5 有其自己的说明 |
| string,resource 或 number | string,resource 或 number | 将字符串和资源转换成数字,按普通数学比较 |
| array | array | 具有较少成员的数组较小,如果运算数 1 中的键不存在于运算数 2 中则数组无法比较,否则挨个值比较(见下例) |
| array | 任何其它类型 | array 总是更大 |
| object | 任何其它类型 | object 总是更大 |
例子 15-2. 标准数组比较代码
|
参见 strcasecmp(),strcmp(),数组运算符和类型一章。
另一个条件运算符是“?:”(或三元)运算符 。
注: 注意三元运算符是个语句,因此其求值不是变量,而是语句的结果。如果想通过引用返回一个变量这点就很重要。在一个通过引用返回的函数中语句 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() 调用,常量,等等之前。不能把它放在函数或类的定义之前,也不能用于条件结构例如 if 和 foreach 等。
参见 error_reporting() 及手册中错误处理及日志函数的有关章节。
| 警告 |
目前的“@”错误控制运算符前缀甚至使导致脚本终止的严重错误的错误报告也失效。这意味着如果在某个不存在或类型错误的函数调用前用了“@”来抑制错误信息,那脚本会没有任何迹象显示原因而死在那里。 |
PHP 支持一个执行运算符:反引号(``)。注意这不是单引号!PHP 将尝试将反引号中的内容作为外壳命令来执行,并将其输出信息返回(例如,可以赋给一个变量而不是简单地丢弃到标准输出)。使用反引号运算符“`”的效果与函数 shell_exec() 相同。
注: 反引号运算符在激活了安全模式或者关闭了 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-7. 逻辑运算符
| 例子 | 名称 | 结果 |
|---|---|---|
| $a and $b | And(逻辑与) | TRUE,如果 $a 与 $b 都为 TRUE。 |
| $a or $b | Or(逻辑或) | TRUE,如果 $a 或 $b 任一为 TRUE。 |
| $a xor $b | Xor(逻辑异或) | TRUE,如果 $a 或 $b 任一为 TRUE,但不同时是。 |
| ! $a | Not(逻辑非) | TRUE,如果 $a 不为 TRUE。 |
| $a && $b | And(逻辑与) | TRUE,如果 $a 与 $b 都为 TRUE。 |
| $a || $b | Or(逻辑或) | TRUE,如果 $a 或 $b 任一为 TRUE。 |
“与”和“或”有两种不同形式运算符的原因是它们运算的优先级不同(见运算符优先级)。
有两个字符串运算符。第一个是连接运算符(“.”),它返回其左右参数连接后的字符串。第二个是连接赋值运算符(“.=”),它将右边参数附加到左边的参数后。更多信息见赋值运算符。
表格 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"
} |
数组中的单元如果具有相同的键名和值则比较时相等。
PHP 有一个类型运算符:instanceof。instanceof 用来测定一个给定的对象是否来自指定的对象类。
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()。
任何 PHP 脚本都是由一系列语句构成的。一条语句可以是一个赋值语句,一个函数调用,一个循环,甚至一个什么也不做的(空语句)条件语句。语句通常以分号结束。此外,还可以用花括号将一组语句封装成一个语句组。语句组本身可以当作是一行语句。本章讲述了各种语句类型。
if 结构是很多语言包括 PHP 在内最重要的特性之一,它允许按照条件执行代码片段。PHP 的 if 结构和 C 语言相似:
如同在表达式一章中定义的,expression 按照布尔求值。如果 expression 的值为 TRUE,PHP 将执行 statement,如果值为 FALSE - 将忽略 statement。有关哪些值被视为 FALSE 的更多信息参见转换为布尔值一节。
如果 $a 大于 $b,则以下例子将显示 a is bigger than b:
经常需要按照条件执行不止一条语句,当然并不需要给每条语句都加上一个 if 子句。可以将这些语句放入语句组中。例如,如果 $a 大于 $b,以下代码将显示 a is bigger than b 并且将 $a 的值赋给 $b:
if 语句可以无限层地嵌套在其它 if 语句中,这给程序的不同部分的条件执行提供了充分的弹性。
经常需要在满足某个条件时执行一条语句,而在不满足该条件时执行其它语句,这正是 else 的功能。else 延伸了 if 语句,可以在 if 语句中的表达式的值为 FALSE 时执行语句。例如以下代码在 $a 大于 $b 时显示 a is bigger than b,反之则显示 a is NOT bigger than b:
else 语句仅在 if 以及 elseif(如果有的话)语句中的表达式的值为 FALSE 时执行(参见 elseif)。elseif,和此名称暗示的一样,是 if 和 else 的组合。和 else 一样,它延伸了 if 语句,可以在原来的 if 表达式值为 FALSE 时执行不同语句。但是和 else 不一样的是,它仅在 elseif 的条件表达式值为 TRUE 时执行语句。例如以下代码将根据条件分别显示 a is bigger than b,a 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 语句。第一个表达式值为 TRUE 的 elseif 语句(如果有的话)将会执行。在 PHP 中,也可以写成“else if”(两个单词),它和“elseif”(一个单词)的行为完全一样。句法分析的含义有少许区别(如果你熟悉 C 语言的话,这是同样的行为),但是底线是两者会产生完全一样的行为。
elseif 的语句仅在之前的 if 或 elseif 的表达式值为 FALSE,而当前的 elseif 表达式值为 TRUE 时执行。
PHP 提供了一些流程控制的替代语法,包括 if,while,for,foreach 和 switch。替代语法的基本形式是把左花括号({)换成冒号(:),把右花括号(})分别换成 endif;,endwhile;,endfor;,endforeach; 以及 endswitch;。
在上面的例子中,HTML 内容“A is equal to 5”用替代语法嵌套在 if 语句中。该 HTML 的内容仅在 $a 等于 5 时显示。
替代语法同样可以用在 else 和 elseif 中。下面是一个包括 elseif 和 else 的 if 结构用替代语法格式写的例子:
while 循环是 PHP 中最简单的循环类型。它和 C 语言中的 while 表现得一样。while 语句的基本格式是:
while 语句的含意很简单,它告诉 PHP 只要 while 表达式的值为 TRUE 就重复执行嵌套中的循环语句。表达式的值在每次开始循环时检查,所以即使这个值在循环语句中改变了,语句也不会停止执行,直到本次循环结束。有时候如果 while 表达式的值一开始就是 FALSE,则循环语句一次都不会执行。
和 if 语句一样,可以在 while 循环中用花括号括起一个语句组,或者用替代语法:
下面两个例子完全一样,都显示数字 1 到 10:
do-while 和 while 循环非常相似,区别在于表达式的值是在每次循环结束时检查而不是开始时。和正规的 while 循环主要的区别是 do-while 的循环语句保证会执行一次(表达式的真值在每次循环结束后检查),然而在正规的 while 循环中就不一定了(表达式真值在循环开始时检查,如果一开始就为 FALSE 则整个循环立即终止)。
do-while 循环只有一种语法:
以上循环将正好运行一次,因为经过第一次循环后,当检查表达式的真值时,其值为 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 循环是 PHP 中最复杂的循环结构。它的行为和 C 语言的相似。 for 循环的语法是:
第一个表达式(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 循环的替代语法。
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 之前加上 & 来修改数组的单元。此方法将以引用赋值而不是拷贝一个值。
此方法仅在被遍历的数组可以被引用时才可用(例如是个变量)。
注: 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 结束当前 for,foreach,while,do-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 在循环结构用用来跳过本次循环中剩余的代码并在条件求值为真时开始执行下一次循环。
注: 注意在 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 " Middle<br />\n";
while (1) {
echo " 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 语句和具有同样表达式的一系列的 IF 语句相似。很多场合下需要把同一个变量(或表达式)与很多不同的值比较,并根据它等于哪个值来执行不同的代码。这正是 switch 语句的用途。
注: 注意和其它语言不同,continue 语句作用到 switch 上的作用类似于 break。如果在循环中有一个 switch 并希望 continue 到外层循环中的下一个轮回,用 continue 2。
下面两个例子使用两种不同方法实现同样的事,一个用一系列的 if 语句,另一个用 switch 语句:
为避免错误,理解 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 支持替代语法的流程控制。更多信息见流程控制的替代语法一节。
declare 结构用来设定一段代码的执行指令。declare 的语法和其它流程控制结构相似:
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
?> |
Tick 是一个在 declare 代码段中解释器每执行 N 条低级语句就会发生的事件。N 的值是在 declare 中的 directive 部分用 ticks=N 来指定的。
在每个 tick 中出现的事件是由 register_tick_function() 来指定的。更多细节见下面的例子。注意每个 tick 中可以出现多个事件。
例子 16-3. 评估一段 PHP 代码的执行时间
|
Ticks 很适合用来做调试,以及实现简单的多任务,后台 I/O 和很多其它任务。
如果在一个函数中调用 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() 语句包含并运行指定文件。有关包括如何工作的详细信息见 include() 的文档。
require() 和 include() 除了怎样处理失败之外在各方面都完全一样。include() 产生一个警告而 require() 则导致一个致命错误。换句话说,如果想在丢失文件时停止处理页面,那就别犹豫了,用 require() 吧。include() 就不是这样,脚本会继续运行。同时也要确认设置了合适的include_path。
例子 16-4. 基本的 require() 例子
|
更多例子参见 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() 语句包含并运行指定文件。
以下文档也适用于 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() 例子
|
如果 include 出现于调用文件中的一个函数里,则被调用的文件中所包含的所有代码将表现得如同它们是在该函数内部定义的一样。所以它将遵循该函数的变量范围。
例子 16-6. 函数中的包含
|
当一个文件被包含时,语法解析器在目标文件的开头脱离 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 而定),但必须产生出一个合法的 PHP 脚本,因为其将被本地服务器处理。如果来自远程服务器的文件应该在远端运行而只输出结果,那用 readfile() 函数更好。另外还要格外小心以确保远程的脚本产生出合法并且是所需的代码。 |
相关信息参见使用远程文件,fopen() 和 file()。
因为 include() 和 require() 是特殊的语言结构,在条件语句中使用必须将其放在语句组中(花括号中)。
处理返回值:可以在被包括的文件中使用 return() 语句来终止该文件中程序的执行并返回调用它的脚本。同样也可以从被包含的文件中返回值。可以像普通函数一样获得 include 调用的返回值。不过这在包含远程文件时却不行,除非远程文件的输出具有合法的 PHP 开始和结束标记(如同任何本地文件一样)。可以在标记内定义所需的变量,该变量在文件被包含的位置之后就可用了。
因为 include() 是一个特殊的语言结构,其参数不需要括号。在比较其返回值时要注意。
注: 在 PHP 3 中,除非是在函数中调用否则被包含的文件中不能出现 return。在此情况下 return() 作用于该函数而不是整个文件。
$bar 的值为 1 是因为 include 成功运行了。注意以上例子中的区别。第一个在被包含的文件中用了 return() 而另一个没有。如果文件不能被包含,则返回 FALSE 并发出一个 E_WARNING 警告。
如果在包含文件中定义有函数,这些函数可以独立于是否在 return() 之前还是之后在主文件中使用。如果文件被包含两次,PHP 5 发出致命错误因为函数已经被定义,但是 PHP 在 return() 之后不会抱怨函数已定义。推荐使用 include_once() 而不是检查文件是否已包含并在包含文件中有条件返回。
另一个将 PHP 文件“包含”到一个变量中的方法是用输出控制函数结合 include() 来捕获其输出,例如:
要在脚本中自动包含文件,参见 php.ini 中的 auto_prepend_file 和 auto_append_file 配置选项。
注: 由于这是一个语言结构而非函数,因此它无法被变量函数调用。
参见 require(),require_once(),include_once(),readfile(),virtual() 和 include_path。
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)的行为可能不是所期望的。
此行为在 PHP 5 中改了,路径先被规格化,因此 C:\PROGRA~1\A.php 和 C:\Program Files\a.php 的实现一样,文件只会被包含一次。
例子 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! ?>
| 警告 |
Windows 版本的 PHP 在 4.3.0 版之前不支持本函数的远程文件访问,即使 allow_url_fopen 选项已被激活。 |
参见 require(),include(),include_once(),get_required_files(),get_included_files(),readfile() 和 virtual()。
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)的行为可能不是所期望的。
此行为在 PHP 5 中改了,路径先被规格化,因此 C:\PROGRA~1\A.php 和 C:\Program Files\a.php 的实现一样,文件只会被包含一次。
例子 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) ?>
| 警告 |
Windows 版本的 PHP 在 4.3.0 版之前不支持本函数的远程文件访问,即使 allow_url_fopen 选项已被激活。 |
参见 include(),require(),require_once(),get_required_files(),get_included_files(),readfile() 和 virtual()。
一个函数可由以下的语法来定义:
任何有效的 PHP 代码都有可能出现在函数内部,甚至包括其它函数和类定义。
在 PHP 3 中,函数必须在被调用之前定义。而 PHP 4 则不再有这样的条件。除非函数如以下两个范例中有条件的定义。
如果一个函数以以下两个范例的方式有条件的定义,其定义必须在调用之前完成。
例子 17-2. 有条件的函数
|
PHP 中的所有函数和类都具有全局域,可以在内部定义外部调用,反之亦然。
PHP 不支持函数重载,也不可能取消定义或者重定义已声明的函数。
注: 函数名是非大小写敏感的,不过在调用函数的时候,通常使用其在定义时相同的形式。
PHP 3 虽然支持默认参数(更多信息请参照默认参数的值),但是却不支持可变的参数个数。PHP 4 支持:见可变长度的参数列表和涉及到的相关函数 func_num_args(), func_get_arg(),以及 func_get_args() 以获取更多的信息。
在 PHP 中可以调用递归函数。但是要避免递归函数/方法调用超过 100-200 层,因为可能会破坏堆栈从而使当前脚本终止。
通过参数列表可以传递信息到函数,即以逗号作为分隔符的表达式列表。
PHP 支持按值传递参数(默认),通过引用传递以及默认参数。可变长度参数列表仅在 PHP 4 和后续版本中支持;更多信息请参照可变长度参数列表和涉及到的相关函数 func_num_args(),func_get_arg() 以及 func_get_args()。PHP 3 中通过传递一个数组参数可以达到类似的效果:
缺省情况下,函数参数通过值传递(因而即使在函数内部改变参数的值,它并不会改变函数外部的值)。如果希望允许函数修改它的参数值,必须通过引用传递参数。
如果想要函数的一个参数总是通过引用传递,可以在函数定义中该参数的前面预先加上符号 &:
函数可以定义 C++ 风格的标量参数默认值,如下:
上面代码段的输出是:
Making a cup of cappuccino. Making a cup of espresso. |
PHP 还允许使用数组和特殊类型 NULL 作为默认参数,例如:
例子 17-8. 使用非标量类型作为默认参数
|
默认值必须是常量表达式,不是(例如)变量,类成员,或者函数调用。
请注意当使用默认参数时,任何默认参数必须放在任何非默认参数的右侧;否则,可能函数将不会按照预期的情况工作。考虑下面的代码片断:
上述例子的输出是:
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 . |
现在,比较上面的例子和这个例子:
这个例子的输出是:
Making a bowl of acidophilus raspberry. |
注: 自 PHP 5 起,默认值可以通过引用传递。
PHP 4 及更高版本已经在用户自定义函数中支持可变长度参数列表。这个真的很简单,用 func_num_args(),func_get_arg(),和 func_get_args() 函数。
无需特别的语法,参数列表仍然能够被明确无误的传递给函数并且正常运转。
值通过使用可选的返回语句返回。任何类型都可以返回,其中包括列表和对象。这导致函数立即结束它的运行,并且将控制权传递回它被调用的行。更多信息见 return()。
例子 17-11. return() 的用法
|
函数不能返回多个值,但为了获得简单的结果,可以返回一个列表。
从函数返回一个引用,必须在函数声明和指派返回值给一个变量时都使用引用操作符 & :
有关引用的更多信息, 请查看引用的解释。
PHP 支持变量函数的概念。这意味着如果一个变量名后有圆括号,PHP 将寻找与变量的值同名的函数,并且将尝试执行它。除了别的事情以外,这个可以被用于实现回调函数,函数表等等。
变量函数不能用于语言结构,例如 echo(),print(),unset(),isset(),empty(),include(),require() 以及类似的语句。需要使用自己的外壳函数来将这些结构用作变量函数。
例子 17-14. 变量函数示例
|
还可以利用变量函数的特性来调用一个对象的方法。
PHP 有很多标准的函数和结构。还有一些函数需要和特定地 PHP 扩展模块一起编译,否则在使用它们的时候就会得到一个致命的“未定义函数”错误。例如,要使用图像函数比如 imagecreatetruecolor(),需要在编译 PHP 的时候加上 GD 的支持。或者,要使用 mysql_connect() 函数,就需要在编译 PHP 的时候加上 MySQL 支持。有很多核心函数已包含在每个版本的 PHP 中如字符串和变量函数。调用 phpinfo() 或者 get_loaded_extensions() 可以得知 PHP 加载了那些扩展库。同时还应该注意,很多扩展库默认就是有效的。PHP 手册按照不同的扩展库组织了它们的文档。请参阅配置,安装以及各自的扩展库章节以获取有关如何设置 PHP 的信息。
手册中如何阅读函数原型讲解了如何阅读和理解一个函数的原型。确认一个函数将返回什么,或者函数是否直接作用于传递的参数是很重要的。例如,str_replace() 函数将返回修改过的字符串,而 usort() 却直接作用于传递的参数变量本身。手册中,每一个函数的页面中都有关于函数参数、行为改变、成功与否的返回值以及使用条件等信息。了解这些重要的(常常是细微的)差别是编写正确的 PHP 代码的关键。
类是变量与作用于这些变量的函数的集合。使用下面的语法定义一个类:
<?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 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 操作符创建一个类的实例时,构造函数将会自动调用。当函数与类同名时,这个函数将成为构造函数。如果一个类没有构造函数,则调用基类的构造函数,如果有的话。
上文定义了一个 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,它指的就是派生类在 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。
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 中对象比较范例
上例将输出:
|
即使对于具有对象成分的类,比较的规则也相同。在以下的范例中建立了一个容器类来储存 Flag 对象的一个相关数组。
例子 18-2. PHP 4 中复合对象的比较
上例将输出:
|
PHP 5 引入了新的对象模型(Object Model)。完全重写了 PHP 处理对象的方式,允许更佳性能和更多特性。
每个类的定义都以关键字 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-3. 对象赋值
上例将输出:
|
很多开发者写面向对象的应用程序时对每个类的定义建立一个 PHP 源文件。一个很大的烦恼是不得不在每个脚本(每个类一个文件)开头写一个常常的包含文件列表。
在 PHP 5 中,不再需要这样了。可以定义一个 __autoload 函数,它会在试图使用尚未被定义的类时自动调用。通过调用此函数,脚本引擎在 PHP 出错失败前有了最后一个机会加载所需的类。
注: 在 __autoload 函数中抛出的异常不能被 catch 语句块捕获并导致致命错误。
PHP 5 允行开发者在一个类中定义一个方法作为构造函数。具有构造函数的类会在每次创建对象时先调用此方法,所以非常适合在使用对象之前做一些初始化工作。
注: 如果子类中定义了构造函数则不会暗中调用其父类的构造函数。要执行父类的构造函数,需要在子类的构造函数中调用 parent::__construct()。
为了实现向后兼容性,如果 PHP 5 在类中找不到 __construct() 函数,它就会尝试寻找旧式的构造函数,也就是和类同名的函数。因此唯一会产生兼容性问题的情况是:类中已有一个名为 __construct() 的方法,但它却又不是构造函数。
PHP 5 引入了析构函数的概念,这类似于其它面向对象的语言,如 C++。析构函数会在到某个对象的所有引用都被删除或者当对象被显式销毁时执行。
和构造函数一样,父类的析构函数不会被引擎暗中调用。要执行父类的析构函数,必须在子类的析构函数体中显式调用 parent::__destruct()。
注: 析构函数在脚本关闭时调用,此时所有的头信息已经发出。
注: 试图在析构函数中抛出一个异常会导致致命错误。
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.
Class members must be defined with public, private, or protected.
例子 19-8. Member declaration
|
注: 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.
Class methods must be defined with public, private, or protected. Methods without any declaration are defined as public.
例子 19-9. Method Declaration
|
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!
Two special keywords self and parent are used to access members or methods from inside the class definition.
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
|
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
|
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).
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
上例将输出:
|
Old code that has no user-defined classes or functions named 'abstract' should run without modifications.
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.
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
|
See also the instanceof operator.
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.
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
上例将输出:
|
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 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
上例将输出:
|
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
上例将输出:
|
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
上例将输出:
|
注: For more examples of iterators, see the SPL Extension.
Patterns are ways to describe best practices and good designs. They show a flexible solution to common programming problems.
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
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:
|
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
This allows a single instance of the Example class to be retrieved.
|
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. |
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.
The __toString method allows a class to decide how it will react when it is converted to a string.
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 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
|
例子 19-28. Final class example
|
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.
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
上例将输出:
|
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 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
上例将输出:
|
ReflectionException extends the standard Exception and is thrown by Reflection API. No specific methods or properties are introduced.
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
|
注: The method invoke() accepts a variable number of arguments which are passed to the function just as in call_user_func().
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
|
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
|
注: 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').
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
|
注: 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.
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
|
注: Trying to get or set private or protected class property's values will result in an exception being thrown.
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
|
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
|
注: 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
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
Failing to satisfy the type hint results in a fatal error.
Type hinting also works with functions:
|
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.
PHP 5 添加了类似于其它语言的异常处理模块,可以在 PHP 内检测(try)、抛出(throw)和捕获(catch)异常。一个 try 至少要有一个与之对应的 catch。定义多个 catch 可以捕获不同的对象。PHP 会按这些 catch 被定义的顺序执行,直到完成最后一个为止。而在这些 catch 内,又可以抛出新的异常。
当一个异常被抛出时,其后(译者注:指抛出异常时所在的代码块)的代码将不会继续执行,而 PHP 就会尝试查找第一个能与之匹配的 catch。如果一个异常没有被捕获,而且又没用使用 set_exception_handler() 作相应的处理的话,那么 PHP 将会产生一个严重的错误,并且输出未能捕获异常的提示信息。
用户可以用自定义的异常处理类来扩展 PHP 内置的异常处理类。以下的代码说明了在内置的异常处理类中,哪些属性和方法在子类中是可访问和可继承的。译者注:以下这段代码只为说明内置异常处理类的结构,它并不是一段有实际意义的可用代码。
例子 20-2. 内置的异常处理类
|
如果使用自定义的类来扩展内置异常处理类,并且要重新定义构造函数的话,建议同时调用 parent::__construct() 来检查所有的变量是否已被赋值。当对象要输出字符串的时候,可以重载 __toString() 并自定义输出的样式。
例子 20-3. 扩展 PHP 内置的异常处理类
|
在 PHP 中引用意味着用不同的名字访问同一个变量内容。这并不像 C 的指针,替代的是,引用是符号表别名。注意在 PHP 中,变量名和变量内容是不一样的,因此同样的内容可以有不同的名字。最接近的比喻是 Unix 的文件名和文件本身――变量名是目录条目,而变量内容则是文件本身。引用可以被看作是 Unix 文件系统中的紧密连接。
PHP 的引用允许用两个变量来指向同一个内容。意思是,当这样做时:
这意味着 $a 和 $b 指向了同一个变量。注: $a 和 $b 在这里是完全相同的,这并不是 $a 指向了 $b 或者相反,而是 $a 和 $b 指向了同一个地方。
注: 如果具有引用的数组被拷贝,其值不会解除引用。对于数组传值给函数也是如此。
同样的语法可以用在函数中,它返回引用,以及用在 new 运算符中(PHP 4.0.4 以及以后版本):
注: 不用 & 运算符导致对象生成了一个拷贝。如果在类中用 $this,它将作用于该类当前的实例。没有用 & 的赋值将拷贝这个实例(例如对象)并且 $this 将作用于这个拷贝上,这并不总是想要的结果。由于性能和内存消耗的问题,通常只想工作在一个实例上面。
尽管可以用 @ 运算符来抑制构造函数中的任何错误信息,例如用 @new,但用 &new 语句时这不起效果。这是 Zend 引擎的一个限制并且会导致一个解析错误。
| 警告 | ||
如果在一个函数内部给一个声明为 global 的变量赋于一个引用,该引用只在函数内部可见。可以通过使用 $GLOBALS 数组避免这一点。
|
注: 如果在 foreach 语句中给一个具有引用的变量赋值,被引用的对象也被改变。
| 警告 | |
复杂数组最好拷贝而不是引用。下面的例子不会如期望中那样工作。 |
引用做的第二件事是用引用传递变量。这是通过在函数内建立一个本地变量并且该变量在呼叫范围内引用了同一个内容来实现的。例如:
将使 $a 变成 6。这是因为在 foo 函数中变量 $var 指向了和 $a 指向的同一个内容。更多详细解释见引用传递。引用做的第三件事是引用返回。
如前所述,引用不是指针。这意味着下面的结构不会产生预期的效果:
这将使 foo 函数中的 $var 变量在函数调用时和 $bar 绑定在一起,但接着又被重新绑定到了 $GLOBALS["baz"] 上面。不可能通过引用机制将 $bar 在函数调用范围内绑定到别的变量上面,因为在函数 foo 中并没有变量 $bar(它被表示为 $var,但是 $var 只有变量内容而没有调用符号表中的名字到值的绑定)。可以使用引用返回来引用被函数选择的变量。
可以将一个变量通过引用传递给函数,这样该函数就可以修改其参数的值。语法如下:
注意在函数调用时没有引用符号――只有函数定义中有。光是函数定义就足够使参数通过引用来正确传递了。在最近版本的 PHP 中如果把 & 用在 foo(&$a); 中会得到一条警告说“Call-time pass-by-reference”已经过时了。以下内容可以通过引用传递:
变量,例如 foo($a)
New 语句,例如 foo(new foobar())
从函数中返回的引用,例如:
详细解释见引用返回。任何其它表达式都不能通过引用传递,结果未定义。例如下面引用传递的例子是无效的:
这些条件是 PHP 4.0.4 以及以后版本有的。引用返回用在当想用函数找到引用应该被绑定在哪一个变量上面时。不要用返回引用来增加性能,引擎足够聪明来自己进行优化。仅在有合理的技术原因时才返回引用!要返回引用,使用此语法:
<?php
function &find_var($param)
{
/* ...code... */
return $found_var;
}
$foo =& find_var($bar);
$foo->x = 2;
?> |
注: 和参数传递不同,这里必须在两个地方都用 & 符号――指出返回的是一个引用,而不是通常的一个拷贝,同样也指出 $foo 是作为引用的绑定,而不是通常的赋值。
注: 如果试图这样从函数返回引用:return ($found_var);,这将不会起作用,因为在试图返回一个表达式的结果而不是一个引用的变量。只能从函数返回引用变量――没别的方法。如果代码试图返回一个动态表达式或 new 运算符的结果,自 PHP 4.4.0 和 PHP 5.1.0 起会发出一条 E_NOTICE 错误。
当 unset 一个引用,只是断开了变量名和变量内容之间的绑定。这并不意味着变量内容被销毁了。例如:
不会 unset $b,只是 $a。再拿这个和 Unix 的 unlink 调用来类比一下可能有助于理解。
PHP 作为一种强大的语言,无论是以模块还是 CGI 的方式安装,它的解释器都可以在服务器上访问文件、运行命令以及创建网络连接等。这些功能也许会给服务器添加很多不安全因素,但是只要正确地安装和配置 PHP,以及编写安全的代码,那么 PHP 相对于 Perl 和 C 来说,是能创建出更安全的 CGI 程序的。而且,也可以在可用性和安全性之间找到一个很好的平衡点。
PHP 可能会被用在很多不同的方面,因此,PHP 内置的选项以方便用户对其进行配置。虽然众多的选项可以使 PHP 完成很多工作,但是对这些选项的设定以及对服务器的配置很可能会产生安全问题。
PHP 的选项与其语法一样,具有很高的灵活性。使用 PHP,可以在只有 shell 用户权限的环境下创建完善的服务器端程序,或者在被严格限制环境下使用它来完成服务器端包含(Server-Side Includes)而无需承但太大的风险。如何建立这样一种环境,其安全性如何,很大程度上取决于 PHP 的开发者。
本章以一些常规的安全建议作开头,讲述如何在不同的环境下尽可能地提高安全性,以及介绍对于不同安全级别的一些编程原则。
绝对安全的系统是不存在的,因此安全业界常用的方法有助于平衡可用性和风险。对用户提交的每一个变量都进行双重验证可能是一个很负责任的行为,但会导致用户必须花很多时间去填写一张复杂无比的表格,从而迫使某些用户尝试绕过安全机制。
最好的安全机制应该能在不防碍用户,并且不过多地增加开发难度的情况下做到能满足需求。实际上,一些安全问题往往会发生在这种过度强化安全机制的系统上。
不要忘记著名的等强原则:一个系统的的强度是由它最薄弱的环节决定的(译者注:相当于木桶原理)。如果所有的事务都基于时间、地点、事务种类进行详细的记录,而用户验证却只依靠一个 cookie,那么用户所对应的事务记录的可信度就被大大剥弱了。
调试代码的时候一定要记住,就算是一个简单的页面也很难对所有可能发生的情况进行检测:对你不满的雇员不一定会输入如你所愿的东西,黑客也有足够的时间研究你的系统,当然,你的宠物猫也会跳到你的键盘上。这就是为什么必须检查所有的代码,去发现哪里可以引入不正当的数据,然后对代码改进、简化或者增强。
互联网上充满了为了成名而破坏你的代码、攻击你的网站并输入不正当数据的人,总之他们会使你的生活充满乐趣。无论是大网站还是小网站,只要能和互联网连接,就会成为一个目标。很多黑客程序并不理会网站的大小,只会机械地扫描 IP 地址并找寻受害者。我们希望那个不要是你。
如果不想把 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_root 和 user_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 语句来设置,请看下一节。
此编译选项可以防止任何人通过如 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 服务器不支持任何方式能够判断请求是直接的还是重定向的,就不能使用这个选项,而应该用其它方法。请看下一节。
在 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 目录外的地方,比如说 /usr/local/bin。这样做唯一不便的地方就是必须在每一个包含 PHP 代码的文件的第一行加入如下语句:
还要将这些文件的属性改成可执行。也就是说,要像处理用 Perl 或 sh 或其它任何脚本语言写的 CGI 脚本一样,使用以 #! 开头的 shell-escape 机制来启动它们。在这种情况下,要使 PHP 能正确处理 PATH_INFO 和 PATH_TRANSLATED 等变量的话,在编译 PHP 解释器时必须加入 --enable-discard-path 参数。
当 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 活动都限制到非用户和非系统文件之中。
PHP 遵从大多数服务器系统中关于文件和目录权限的安全机制。这就使管理员可以控制哪些文件在文件系统内是可读的。必须特别注意的是全局的可读文件,并确保每一个有权限的用户对这些文件的读取动作都是安全的。
PHP 被设计为以用户级别来访问文件系统,所以完全有可能通过编写一段 PHP 代码来读取系统文件如 /etc/passwd,更改网络连接以及发送大量打印任务等等。因此必须确保 PHP 代码读取和写入的是合适的文件。
请看下面的代码,用户想要删除自己主目录中的一个文件。假设此情形是通过 web 界面来管理文件系统,因此 Apache 用户有权删除用户目录下的文件。
只给 PHP 的 web 用户很有限的权限。
检查所有提交上来的变量。
例子 26-3. 更安全的文件名检查
|
根据操作系统的不同,存在着各种各样需要注意的文件,包括联系到系统的设备(/dev/ 或者 COM1)、配置文件(/ect/ 文件和 .ini文件)、常用的存储区域(/home/ 或者 My Documents)等等。由于此原因,建立一个策略禁止所有权限而只开放明确允许的通常更容易些。
今时今日,数据库系统已经成为各个动态网站上 web 应用程序的重要组成部分。由于非常敏感和机密的数据有可能保存在数据库中,所以对数据库实施保护就显得尤为重要了。
要从数据库中提取或者存入数据,就必须经过连接数据库、发送一条合法查询、获取结果、关闭连接等步骤。目前,能完成这一系列动作的最常用的查询语言是结构化查询语言 Structured Query Language (SQL)。可以看看攻击者是如何篡改 SQL 查询语句的。
PHP 本身并不能保护数据库的安全。下面的章节只是讲述怎样用 PHP 脚本对数据库进行基本的访问和操作。
记住一条简单的原则:深入防御。保护数据库的措施越多,攻击者就越难获得和使用数据库内的信息。正确地设计和应用数据库可以减少被攻击的担忧。
第一步一般都是创建数据库,除非是使用第三方的数据库服务。当创建一个数据库的时候,会指定一个所有者来执行和新建语句。通常,只有所有者(或超级用户)才有权对数据库中的对象进行任意操作。如果想让其他用户使用,就必须赋予他们权限。
应用程序永远不要使用数据库所有者或超级用户帐号来连接数据库,因为这些帐号可以执行任意的操作,比如说修改数据库结构(例如删除一个表)或者清空整个数据库的内容。
应该为程序的每个方面创建不同的数据库帐号,并赋予对数据库对象的极有限的权限。仅分配给能完成其功能所需的权限,避免同一个用户可以完成另一个用户的事情。这样即使攻击者利用程序漏洞取得了数据库的访问权限,也最多只能做到和该程序一样的影响范围。
鼓励用户不要把所有的事务逻辑都用 web 应用程序(即用户的脚本)来实现。最好用视图(view)、触发器(trigger)或者规则(rule)在数据库层面完成。当系统升级的时候,需要为数据库开辟新的接口,这时就必须重做所有的数据库客户端。除此之外,触发器还可以透明和自动地处理字段,并在调试程序和跟踪事实时提供有用的信息。
把连接建立在 SSL 加密技术上可以增加客户端和服务器端通信的安全性,或者 SSH 也可以用于加密客户端和数据库之间的连接。如果使用了这些技术的话,攻击者要监视服务器的通信或者得到数据库的信息是很困难的。
SSL/SSH 能保护客户端和服务器端交换的数据,但 SSL/SSH 并不能保护数据库中已有的数据。SSL 只是一个加密网络数据流的协议。
如果攻击者取得了直接访问数据库的许可(绕过 web 服务器),敏感数据就可能暴露或者被滥用,除非数据库自己保护了这些信息。对数据库内的数据加密是减少这类风险的有效途径,但是只有很少的数据库提供这些加密功能。
对于这个问题,有一个简单的解决办法,就是创建自己的加密机制,然后把它用在 PHP 程序内。PHP 有几个扩展库可以完成这个工作,比如说 Mcrypt 和 Mhash 等,它们包含多种加密运算法则。脚本在插入数据库之前先把数据加密,以后提取出来时再解密。有关加密如何工作的例子请参考相关手册。
对某些真正隐蔽的数据,如果不需要以明文的形式存在(即不用显示),可以考虑用散列算法。使用散列算法最常见的例子就是把密码经过 MD5 加密后的散列存进数据库来代替原来的明文密码。参见 crypt() 和 md5()。
例子 27-1. 对密码字段进行散列加密
|
很多 web 开发者没有注意到 SQL 查询是可以被篡改的,因而把 SQL 查询当作可信任的命令。殊不知道,SQL 查询可以绕开访问控制,从而绕过身份验证和权限检查。更有甚者,有可能通过 SQL 查询去运行主机操作系统级的命令。
直接 SQL 命令注入就是攻击者常用的一种创建或修改已有 SQL 语句的技术,从而达到取得隐藏数据,或覆盖关键的值,甚至执行数据库主机操作系统命令的目的。这是通过应用程序取得用户输入并与静态参数组合成 SQL 查询来实现的。下面将会给出一些真实的例子。
由于在缺乏对输入的数据进行验证,并且使用了超级用户或其它有权创建新用户的数据库帐号来连接,攻击者可以在数据库中新建一个超级用户。
0;
insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd)
select 'crack', usesysid, 't','t','crack'
from pg_shadow where usename='postgres';
-- |
注: -- 是 SQL 的注释标记,一般可以使用来它告诉 SQL 解释器忽略后面的语句。
对显示搜索结果的页面下手是一个能得到密码的可行办法。攻击者所要做的只不过是找出哪些提交上去的变量是用于 SQL 语句并且处理不当的。而这类的变量通常都被用于 SELECT 查询中的条件语句,如 WHERE, ORDER BY, LIMIT 和 OFFSET。如果数据库支持 UNION 构造的话,攻击者还可能会把一个完整的 SQL 查询附加到原来的语句上以便从任意数据表中得到密码。因此,对密码字段加密是很重要的。
SQL 中的 UPDATE 也会受到攻击。这种查询也可能像上面的例子那样被插入或附加上另一个完整的请求。但是攻击者更愿意对 SET 子句下手,这样他们就可以更改数据表中的一些数据。这种情况下必须要知道数据库的结构才能修改查询成功进行。可以通过表单上的变量名对字段进行猜测,或者进行暴力破解。对于存放用户名和密码的字段,命名的方法并不多。
<?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 ...;"; ?> |
下面这个可怕的例子将会演示如何在某些数据库上执行系统命令。
<?php
$query = "SELECT * FROM products
WHERE id LIKE '%a%'
exec master..xp_cmdshell 'net user test testpass /ADD'--";
$result = mssql_query($query);
?> |
注: 虽然以上的例子是针对某一特定的数据库系统的,但是这并不代表不能对其它数据库系统实施类似的攻击。使用不同的方法,各种数据库都有可能遭殃。
也许有人会自我安慰,说攻击者要知道数据库结构的信息才能实施上面的攻击。没错,确实如此。但没人能保证攻击者一定得不到这些信息,一但他们得到了,数据库有泄露的危险。如果你在用开放源代码的软件包来访问数据库,比如论坛程序,攻击者就很容得到到相关的代码。如果这些代码设计不良的话,风险就更大了。
这些攻击总是建立在发掘安全意识不强的代码上的。所以,永远不要信任外界输入的数据,特别是来自于客户端的,包括选择框、表单隐藏域和 cookie。就如上面的第一个例子那样,就算是正常的查询也有可能造成灾难。
永远不要使用超级用户或所有者帐号去连接数据库。要用权限被严格限制的帐号。
检查输入的数据是否具有所期望的数据格式。PHP 有很多可以用于检查输入的函数,从简单的变量函数和字符类型函数(比如 is_numeric(),ctype_digit())到复杂的 Perl 兼容正则表达式函数都可以完成这个工作。
如果程序等待输入一个数字,可以考虑使用 is_numeric() 来检查,或者直接使用 settype() 来转换它的类型,也可以用 sprintf() 把它格式化为数字。
使用数据库特定的敏感字符转义函数(比如 mysql_escape_string() 和 sql_escape_string())把用户提交上来的非数字数据进行转义。如果数据库没有专门的敏感字符转义功能的话 addslashes() 和 str_replace() 可以代替完成这个工作。看看第一个例子,此例显示仅在查询的静态部分加上引号是不够的,查询很容易被攻破。
也可以选择使用数据库的存储过程和预定义指针等特性来抽象数库访问,使用户不能直接访问数据表和视图。但这个办法又有别的影响。
除此之外,在允许的情况下,使用代码或数据库系统保存查询日志也是一个好办法。显然,日志并不能防止任何攻击,但利用它可以跟踪到哪个程序曾经被尝试攻击过。日志本身没用,要查阅其中包含的信息才行。毕竟,更多的信息总比没有要好。
对于 PHP 的安全性来说错误报告是一把双刃剑。一方面可以提高安全性,另一方面又有害。
攻击系统时经常使用的手法就是输入不正确的数据,然后查看错误提示的类型及上下文。这样做有利于攻击者收集服务器的信息以便寻找弱点。比如说,如果一个攻击者知道了一个页面所基于的表单信息,那么他就会尝试修改变量:
通常 PHP 所返回的错误提示都能帮助开发者调试程序,它会提出哪个文件的哪些函数或代码出错,并指出错误发生的在文件的第几行,这些就是 PHP 本身所能给出的信息。很多 PHP 开发者会使用 show_source()、highlight_string() 或者 highlight_file() 函数来调试代码,但是在正式运行的网站中,这种做法可能会暴露出隐藏的变量、未检查的语法和其它的可能危及系统安全的信息。在运行一些具有内部调试处理的程序,或者使用通用调试技术是很危险的。如果让攻击者确定了程序是使用了哪种具体的调试技术,他们会尝试发送变量来打开调试功能:
不管错误处理机制如何,可以探测系统错误的能力会给攻击者提供更多信息。
比如说,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 指定用于记录错误信息的文件。
可能 PHP 中最具争议的变化就是从 PHP 4.2.0 版开始配置文件中 register_globals 的默认值从 on 改为 off 了。对此选项的依赖是如此普遍以至于很多人根本不知道它的存在而以为 PHP 本来就是这么工作的。本节会解释用这个指令如何写出不安全的代码,但要知道这个指令本身没有不安全的地方,误用才会。
当 register_globals 打开以后,各种变量都被注入代码,例如来自 HTML 表单的请求变量。再加上 PHP 在使用变量之前是无需进行初始化的,这就使得更容易写出不安全的代码。这是个很艰难的抉择,但 PHP 社区还是决定默认关闭此选项。当打开时,人们使用变量时确实不知道变量是哪里来的,只能想当然。但是 register_globals 的关闭改变了这种代码内部变量和客户端发送的变量混杂在一起的糟糕情况。下面举一个错误使用 register_globals 的例子:
例子 29-1. 错误使用 register_globals = on 的例子
|
当 register_globals = on 的时候,上面的代码就会有危险了。如果是 off,$authorized 就不能通过如 URL 请求等方式来改变,这样就好多了,尽管初始化变量是一个良好的编程习惯。比如说,如果在上面的代码执行之前加入 $authorized = false 的话,无论 register_globals 是 on 还是 off 都可以,因为用户状态被初始化为未经认证。
另一个例子是关于会话的。当 register_globals = on 的时候,$username 也可以用在下面的代码中,但要意识到 $username 也可能会从其它途径进来,比如说通过 URL 的 GET。
采取相应的预防措施以便在伪造变量输入的时候给予警告是完全有可能的。如果事先确切知道变量是哪里来的,就可以检查所提交的数据是否是从不正当的表单提交而来。不过这不能保证变量未被伪造,这需要攻击者去猜测应该怎样去伪造。如果不在乎请求数据来源的话,可以使用 $_REQUEST 数组,它包括了 GET、POST 和 COOKIE 的所有数据。详情可参见本手册的来自 PHP 之外的变量。
例子 29-3. 探测有害变量
|
当然,单纯地关闭 register_globals 并不代表所有的代码都安全了。对于每一段提交上来的数据,都要对其进行具体的检查。永远要验证用户数据和对变量进行初始化!把 error_reporting() 设为 E_NOTICE 级别可以检查未初始化的变量。
更多关于模拟 register_globals 为 on 或 off 的信息,请见此 FAQ。
Superglobals 可用性说明: 自 PHP 4.1.0 起,可以使用超全局数组变量例如 $_GET,$_POST 和 $_SERVER 等等。更多信息请阅读手册中的 superglobals。
很多 PHP 程序所存在的重大弱点并不是 PHP 语言本身的问题,而是编程者的安全意识不高而导致的。因此,必须时时注意每一段代码可能存在的问题,去发现非正确数据提交时可能造成的影响。
此脚本是否只能影响所预期的文件?
非正常的数据被提交后能否产生作用?
此脚本能用于计划外的用途吗?
此脚本能否和其它脚本结合起来做坏事?
是否所有的事务都被充分记录了?
还可以考虑关闭 register_globals,magic_quotes 或者其它使编程更方便但会使某个变量的合法性,来源和其值被搞乱的设置。在开发时,可以使用 error_reporting(E_ALL) 模式帮助检查变量使用前是否有被检查或被初始化,这样就可以防止某些非正常的数据的挠乱了。
魔术引号(Magic Quote)是一个自动将进入 PHP 脚本的数据进行转义的过程。最好在编码时不要转义而在运行时根据需要而转义。
当打开时,所有的 '(单引号),"(双引号),\(反斜线)和 NULL 字符都会被自动加上一个反斜线进行转义。这和 addslashes() 作用完全相同。
一共有三个魔术引号指令:
影响到 HTTP 请求数据(GET,POST 和 COOKIE)。不能在运行时改变。在 PHP 中默认值为 on。
如果打开的话,大部份从外部来源取得数据并返回的函数,包括从数据库和文本文件,所返回的数据都会被反斜线转义。该选项可在运行的时改变,在 PHP 中的默认值为 off。
如果打开的话,将会使用单引号对单引号进行转义而非反斜线。此选项会完全覆盖 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 的范例。更多信息请参见本手册的怎样修改配置设定。
如果不能修改服务器端的配置文件,使用 .htaccess 也可以。范例如下:
|
为了能写出移植性较强的代码(可以运行于任何环境),例如不能修改服务器配置的情况,下面的例子可以在运行时关闭 magic_quotes_gpc。但是这样做比较低效,适当的修改配置才是更好的办法。
例子 31-2. 在运行时关闭魔术引号
|
一般而言,通过隐藏的手段提高安全性被认为是作用不大的做法。但某些情况下,尽可能的多增加一份安全性都是值得的。
一些简单的方法可以帮助隐藏 PHP,这样做可以提高攻击者发现系统弱点的难度。在 php.ini 文件里设置 expose_php = off ,可以减少他们能获得的有用信息。
另一个策略就是让 web 服务器用 PHP 解析不同扩展名。无论是通过 .htaccess 文件还是 Apache 的配置文件,都可以设置能误导攻击者的文件扩展名:
PHP 和其它的大型系统一样,在持续的研究和改进中。每一个版本都会有或多或少的改进,以便提高安全性和修复已发现的问题等,这样做有利于提高整个系统的安生性和稳定性。
和其它系统级的脚本语言一样,最好的途径是经常更新,并时刻留意最新版本及其改变。
PHP 的 HTTP 认证机制仅在 PHP 以 Apache 模块方式运行时才有效,因此该功能不适用于 CGI 版本。在 Apache 模块的 PHP 脚本中,可以用 header() 函数来向客户端浏览器发送“Authentication Required”信息,使其弹出一个用户名/密码输入窗口。当用户输入用户名和密码后,包含有 URL 的 PHP 脚本将会加上预定义变量 PHP_AUTH_USER,PHP_AUTH_PW 和 AUTH_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 认证范例
|
例子 34-2. Digest HTTP 认证范例 本例演示怎样实现一个简单的 Digest HTTP 认证脚本。更多信息请参考 RFC 2617。
|
兼容性问题: 在编写 HTTP 标头代码时请格外小心。为了对所有的客户端保证兼容性,关键字“Basic”的第一个字母必须大写为“B”,分界字符串必须用双引号(不是单引号)引用;并且在标头行 HTTP/1.0 401 中,在 401 前必须有且仅有一个空格。
在以上例子中,仅仅只打印出了 PHP_AUTH_USER 和 PHP_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 认证的范例
|
该行为对于 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 部分。
PHP 透明地支持 HTTP cookie。cookie 是一种在远程浏览器端储存数据并以此来跟踪和识别用户的机制。可以用 setcookie() 或 setrawcookie() 函数来设置 cookie。cookie 是 HTTP 标头的一部分,因此 setcookie() 函数必须在其它信息被输出到浏览器前调用,这和对 header() 函数的限制类似。可以使用输出缓冲函数来延迟脚本的输出,直到按需要设置好了所有的 cookie 或者其它 HTTP 标头。
任何从客户端发送的 cookie 将会像 GET 和 POST 数据一样被自动的转换为 PHP 变量,该过程受 register_globals 和 variables_order 两个配置选项的影响。如果希望对一个 cookie 变量设置多个值,则需在 cookie 的名称后加 [] 符号。
在 PHP 4.1.0 及更高版本,自动全局变量数组 $_COOKIE 将总是包含所有从客户端发来的 cookie 数据。在老版本的 PHP 中,当 track_vars 配置选项打开时(此选项自 PHP 4.0.3 后总是打开的),系统为 cookie 设置的数组变量是 $HTTP_COOKIE_VARS。
关于更多细节以及有关浏览器问题的注意事项,参见 setcookie() 和 setrawcookie() 函数。
XForms 定义了一种传统 web 表单的变种,它可以用于更多的平台和浏览器,甚至非传统的媒体例如 PDF 文档。
XFroms 的第一个关键区别是表单怎样发送到客户端。XForms for HTML Authors 包含有怎样创建 XForms 的详细说明。本节只看一个简单例子。
例子 37-1. 一个简单的 XForms 搜索表单
|
上面的表单显示一个文本输入框(命名为 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
|
注: 在写本文档时,许多浏览器还不支持 XForms。如果上面例子失败请检查自己的浏览器版本。
本特性可以使用户上传文本和二进制文件。用 PHP 的认证和文件操作函数,可以完全控制允许哪些人上传以及文件上传后怎样处理。
PHP 能够接受任何来自符合 RFC-1867 标准的浏览器(包括 Netscape Navigator 3 及更高版本,打了补丁的 Microsoft Internet Explorer 3 或者更高版本)上传的文件。
相关的设置: 请参阅 php.ini 的 file_uploads,upload_max_filesize,upload_tmp_dirpost_max_size 以及 max_input_time 设置选项。
请注意 PHP 也支持 PUT 方法的文件上传,Netscape Composer 和 W3C 的 Amaya 客户端使用这种方法。请参阅对 PUT 方法的支持以获取更多信息。
例子 38-1. 文件上传表单 可以如下建立一个特殊的表单来支持文件上传:
以上范例中的 __URL__ 应该被换掉,指向一个真实的 PHP 文件。 MAX_FILE_SIZE 隐藏字段(单位为字节)必须放在文件输入字段之前,其值为接收文件的最大尺寸。这是对浏览器的一个建议,PHP 也会检查此项。在浏览器端可以简单绕过此设置,因此不要指望用此特性来阻挡大文件。实际上,PHP 设置中的上传文件最大值是不会失效的。但是最好还是在表单中加上此项目,因为它可以避免用户在花时间等待上传大文件之后才发现文件过大上传失败的麻烦。 |
注: 要确保文件上传表单的属性是 enctype="multipart/form-data",否则文件上传不了。
全局变量 $_FILES 自 PHP 4.1.0 起存在(在更早的版本中用 $HTTP_POST_FILES 替代)。此数组包含有所有上传的文件信息。
以上范例中 $_FILES 数组的内容如下所示。我们假设文件上传字段的名称如上例所示,为 userfile。名称可随意命名。
客户端机器文件的原名称。
文件的 MIME 类型,如果浏览器提供此信息的话。一个例子是“image/gif”。不过此 MIME 类型在 PHP 端并不检查,因此不要想当然认为有这个值。
已上传文件的大小,单位为字节。
文件被上传后在服务端储存的临时文件名。
和该文件上传相关的错误代码。此项目是在 PHP 4.2.0 版本中增加的。
文件被上传后,默认地会被储存到服务端的默认临时目录中,除非 php.ini 中的 upload_tmp_dir 设置为其它的路径。服务端的默认临时目录可以通过更改 PHP 运行环境的环境变量 TMPDIR 来重新设置,但是在 PHP 脚本内部通过运行 putenv() 函数来设置是不起作用的。该环境变量也可以用来确认其它的操作也是在上传的文件上进行的。
例子 38-2. 使文件上传生效 请查阅函数 is_uploaded_file() 和 move_uploaded_file() 以获取进一步的信息。以下范例处理由表单提供的文件上传。
|
接受上传文件的 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 数组特性甚至支持文件类型。
|
从 PHP 4.2.0 开始,PHP 将随文件信息数组一起返回一个对应的错误代码。该代码可以在文件上传时生成的文件数组中的 error 字段中被找到,也就是 $_FILES['userfile']['error']。
其值为 0,没有错误发生,文件上传成功。
其值为 1,上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值。
其值为 2,上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。
其值为 3,文件只有部分被上传。
其值为 4,没有文件被上传。
其值为 6,找不到临时文件夹。PHP 4.3.10 和 PHP 5.0.3 引进。
其值为 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 版本添加的。
当以上表单被提交后,数组 $_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]。
PHP 3 和 PHP 4 对 PUT 方法的支持有所不同。在 PHP 4 中,必须使用标准的输入流来读取一个 HTTP PUT 的内容。
例子 38-5. 用 PHP 4 来保存 HTTP PUT 文件
|
注: 以下文档的内容仅对 PHP 3 适用。
PHP 提供对诸如 Netscape Composer 和 W3C Amaya 等客户端使用的 HTTP PUT 方法的支持。PUT 请求比文件上传要简单的多,它们一般的形式为:
这通常意味着远程客户端会将其中的 /path/filename.html 存储到 web 目录树。让 Apache 或者 PHP 自动允许所有人覆盖 web 目录树下的任何文件显然是很不明智的。因此,要处理类似的请求,必须先告诉 web 服务器需要用特定的 PHP 脚本来处理该请求。在 Apache 下,可以用 Script 选项来设置。它可以被放置到 Apache 配置文件中几乎所有的位置。通常我们把它放置在 <Directory> 区域或者 <Virtualhost> 区域。可以用如下一行来完成该设置:
这将告诉 Apache 将所有对 URI 的 PUT 请求全部发送到 put.php 脚本,这些 URI 必须和 PUT 命令中的内容相匹配。当然,这是建立在 PHP 支持 .php 扩展名,并且 PHP 已经在运行的假设之上。
在 put.php 文件中,可以作如下操作:
这将会把文件拷贝到远程客户端请求的位置。可能希望在文件拷贝之前进行一些检查或者对用户认证之类的操作。这里唯一的问题是,当 PHP 接受到 PUT 方法的请求时,它将会把上传的文件储存到和其它用 POST 方法处理过的文件相同的临时目录。在请求结束时,临时文件将被删除。因此,用来处理 PUT 的 PHP 脚本必须将该文件拷贝到其它的地方。该临时文件的文件名被储存在变量 $PHP_PUT_FILENAME 中,也可以通过 $REQUEST_URI 变量获得建议的目标文件名(在非 Apache web 服务器上可能会有较大的变化)。该目标文件名是由远程客户端指定的。也可以不听从改客户端的信息,而把所有上传的文件存储到一个特殊的上传目录下。
只要在 php.ini 文件中激活了 allow_url_fopen 选项,就可以在大多数需要用文件名作为参数的函数中使用 HTTP 和 FTP 的 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. 获取远程文件的标题
|
如果有合法的访问权限,以一个用户的身份和某 FTP 服务器建立了链接,还可以向该 FTP 服务器端的文件进行写操作。仅能用该方法来创建新的文件;如果尝试覆盖已经存在的文件,fopen() 函数的调用将会失败。
要以“anonymous”以外的用户名连接服务器,需要指明用户名(可能还有密码),例如“ftp://user:password@ftp.example.com/path/to/file”(也可以在通过需要 Basic 认证的 HTTP 协议访问远程文件时使用相同的语法)。
注: 以下内容对 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.ini 的 max_execution_time 或 Apache .conf 设置中对应的“php_value max_execution_time”参数或者 set_time_limit() 函数来更改。当计数器超时的时候,脚本将会类似于以上连接中断的情况退出,先前被注册过的关闭触发函数也将在这时被执行。在该关闭触发函数中,可以通过调用 connection_status() 函数来检查超时是否导致关闭触发函数被调用。如果超时导致了关闭触发函数的调用,该函数将返回 2。
需要注意的一点是 ABORTED 和 TIMEOUT 状态可以同时有效。这在告诉 PHP 忽略用户的退出操作时是可能的。PHP 将仍然注意用户已经中断了连接但脚本仍然在运行的情况。如果到了运行的时间限制,脚本将被退出,设置过的关闭触发函数也将被执行。在这时会发现函数 connection_status() 返回 3。
永久的数据库连接是指在脚本结束运行时不关闭的连接。当收到一个永久连接的请求时。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()。
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_dir | NULL | PHP_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_basedir | NULL | PHP_INI_SYSTEM | |
| disable_functions | "" | 仅 php.ini | 自 PHP 4.0.1 起可用 |
| disable_classes | "" | 仅 php.ini | 自 PHP 4.3.2 起可用 |
以下是配置选项的简要解释。
是否启用 PHP 的安全模式。更多信息请阅读安全一章。
默认情况下,安全模式在打开文件时会做 UID 比较检查。如果想将其放宽到 GID 比较,则打开 safe_mode_gid。是否在文件访问时使用 UID(FALSE)或者 GID(TRUE)来做检查。
当从此目录及其子目录(目录必须在 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 的文件将不能被包含。在较早版本中,所有文件都能被包含。
如果 PHP 使用了安全模式,system() 和其它程序执行函数将拒绝启动不在此目录中的程序。必须使用 / 作为目录分隔符,包括 Windows 中。
设置某些环境变量可能是潜在的安全缺口。本指令包含有一个逗号分隔的前缀列表。在安全模式下,用户只能改变那些名字具有在这里提供的前缀的环境变量。默认情况下,用户只能设置以 PHP_ 开头的环境变量(例如 PHP_FOO = BAR)。
注: 如果本指令为空,PHP 将使用户可以修改任何环境变量!
本指令包含有一个逗号分隔的环境变量的列表,最终用户不能用 putenv() 来改变这些环境变量。甚至在 safe_mode_allowed_env_vars 中设置了允许修改时也不能改变这些变量。
将 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 不受安全模式的影响。
本指令只能设置在 php.ini 中。例如不能将其设置在 httpd.conf。
本指令可以使你出于安全的理由禁用某些类。用逗号分隔类名。disable_classes 不受安全模式的影响。
本指令只能设置在 php.ini 中。例如不能将其设置在 httpd.conf。
可用性说明: 本指令自 PHP 4.3.2 起可用。
参见 register_globals,display_errors 和 log_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 |
<?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> |
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_USER、PHP_AUTH_PW 和 PHP_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 的函数 | ?? |
从版本 4.3.0 开始,PHP 提供了一种新类型的 SAPI(Server Application Programming Interface,服务端应用编程端口)支持,名为 CLI,意为 Command Line Interface,即命令行接口。顾名思义,该 SAPI 模块主要用作 PHP 的开发外壳应用。CLI SAPI 和其它 SAPI 模块相比有很多的不同之处,我们将在本章中详细阐述。值得一提的是,CLI 和 CGI 是不同的 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/php 和 sapi/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_errors | FALSE | 无意义的 HTML 标记符会使得出错信息很凌乱,所以在外壳下阅读报错信息是十分困难的。因此将该选项的默认值改为 FALSE。 |
| implicit_flush | TRUE | 在命令行模式下,所有来自 print() 和 echo() 的输出将被立即写到输出端,而不作任何地缓冲操作。如果希望延缓或控制标准输出,仍然可以使用 output buffering 设置项。 |
| max_execution_time | 0(无限值) | 鉴于在外壳环境下使用 PHP 的无穷的可能性,最大运行时间被设置为了无限值。为 web 开发的应用程序可能只需运行几秒钟时间,而外壳应用程序的运行时间可能会长的多。 |
| register_argc_argv | TRUE |
由于该设置为 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 的流。可以用如下方法来调用:
| ||
| STDOUT |
一个已打开的指向 stdout 的流。可以用如下方式来调用:
| ||
| STDERR |
一个已打开的指向 stderr 的流。可以用如下方式来调用:
|
有了以上常量,就无需自己建立指向诸如 stderr 的流,只需简单的使用这些常量来代替流指向:
php -r 'fwrite(STDERR, "stderr\n");' |
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 |
注: 可以在命令行运行时给该 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 代码:
让 PHP 运行指定文件。
php my_script.php php -f my_script.php |
以上两种方法(使用或不使用 -f 参数)都能够运行给定的 my_script.php 文件。可以选择任何文件来运行,指定的 PHP 脚本并非必须要以 .php 为扩展名,它们可以有任意的文件名和扩展名。
在命令行直接运行 PHP 代码。
php -r 'print_r(get_defined_constants());' |
在使用这种方法时,请注意外壳变量的替代及引号的使用。
注: 请仔细阅读以上范例,在运行代码时没有开始和结束的标记符!加上 -r 参数后,这些标记符是不需要的,加上它们会导致语法错误。
通过标准输入(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 文件中。
| |||
| -c | --php-ini |
用该参数,可以指定一个放置 php.ini 文件的目录,或者直接指定一个自定义的 INI 文件(其文件名可以不是 php.ini),例如:
| |||
| -n | --no-php-ini |
完全忽略 php.ini。此参数在 PHP 4.3.0 以后有效。 | |||
| -d | --define |
用该参数可以自行设置任何可以在 php.ini 文件中设置的配置选项的值,其语法为:
例子(因版面原因而折行显示):
| |||
| -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 参数。
| |||
| -m | --modules |
使用该参数,PHP 将打印出内置以及已加载的 PHP 及 Zend 模块:
| |||
| -r | --run |
使用该参数可以在命令行内运行单行 PHP 代码。无需加上 PHP 的起始和结束标识符(<?php 和 ?>),否则将会导致语法解析错误。
| |||
| -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 选项来计算一个项目总行数的例子。
| |||
| -s | --syntax-highlight and --syntax-highlight |
显示有语法高亮色彩的源代码。 该参数使用内建机制来解析文件并为其生成一个 HTML 高亮版本并将结果写到标准输出。请注意该过程所做的只是生成了一个 <code> [...] </code> 的 HTML 标记的块,并不包含任何的 HTML 头。
| |||
| -v | --version |
将 PHP,PHP SAPI 和 Zend 的版本信息写入标准输出。例如:
| |||
| -w | --strip |
显示除去了注释和多余空白的源代码。
| |||
| -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)
|
在以上脚本中,用第一行特殊的代码来指明该文件应该由 PHP 来执行。在这里使用 CLI 的版本,因此不会有 HTTP 头信息输出。在用 PHP 编写命令行应用程序时,可以使用两个参数:$argc 和 $argv。前面一个的值是比参数个数大 1 的整数(运行的脚本本身的名称也被当作一个参数)。第二个是包含有参数的数组,其第一个元素为脚本的名称,下标为数字 0($argv[0])。
以上程序中检查了参数的个数是大于 1 个还是小于 1 个。此外如果参数是 --help,-help,-h 或 -? 时,打印出帮助信息,并同时动态输出脚本的名称。如果还收到了其它参数,将其显示出来。
如果希望在 Unix 下运行以上脚本,需要使其属性为可执行文件,然后简单的运行 script.php echothis 或 script.php -h。在 Windows 下,可以为此编写一个批处理文件:
假设将上述程序命名为 script.php,且 CLI 版的 php.exe 文件放置在 c:\php\cli\php.exe,该批处理文件会帮助将附加的参数传给脚本程序:script.bat echothis 或 script.bat -h。
请参阅 Readline 扩展模块的有关文档,以获取更多的函数的信息。这些函数可以帮助完善 PHP 命令行应用程序。
| 警告 |
本扩展模块是实验性的。本模块的行为,包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本扩展模块风险自担。 |
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) |
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
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| apd.dumpdir | NULL | PHP_INI_ALL | |
| apd.statement_tracing | "0" | PHP_INI_ALL |
以下是配置选项的简要解释。
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().
Specfies whether or not to do per-line tracings. Turning this on (1) will impact the performance of your application.
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.
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
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.
To generate a calltree file that you can import into the KCacheGrind profile analysis application, issue the pprof2calltree comand.
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.
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); |
(no version information, might be only in CVS)
apd_callstack -- Returns the current call stack as an arrayBehaves like perl's Carp::cluck. Throw a warning and a callstack. The default line delimiter is "<BR />\n".
Usually sent via the socket to restart the interpreter.
(no version information, might be only in CVS)
apd_croak -- Throw an error, a callstack and then exitBehaves like perl's Carp::croak. Throw an error, a callstack and then exit. The default line delimiter is "<BR />\n".
(no version information, might be only in CVS)
apd_dump_function_table -- Outputs the current function table(no version information, might be only in CVS)
apd_dump_persistent_resources -- Return all persistent resources as an arrayReturn all persistent resources as an array.
(no version information, might be only in CVS)
apd_dump_regular_resources -- Return all current regular resources as an arrayReturn all current regular resources as an array.
Usually sent via the socket to request information about the running script.
(no version information, might be only in CVS)
apd_get_active_symbols -- Get an array of the current variables names in the local scopeReturns the names of all the variables defined in the active scope, (not their values)
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.
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
(no version information, might be only in CVS)
apd_set_session -- Changes or sets the current debugging levelThis 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 |
(no version information, might be only in CVS)
apd_set_socket_session_trace -- Starts the remote session debuggingConnects 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.
Syntax similar to create_function(). Overrides built-in functions (replaces them in the symbol table).
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
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| apc.enabled | 1 | PHP_INI_ALL | |
| apc.shm_segments | 1 | PHP_INI_SYSTEM | |
| apc.shm_size | 30 | PHP_INI_SYSTEM | |
| apc.optimization | 0 | PHP_INI_ALL | |
| apc.num_files_hint | 1000 | PHP_INI_SYSTEM | |
| apc.ttl | 0 | PHP_INI_SYSTEM | |
| apc.gc_ttl | 3600 | PHP_INI_SYSTEM | |
| apc.cache_by_default | On | PHP_INI_SYSTEM | |
| apc.filters | "" | PHP_INI_SYSTEM | |
| apc.mmap_file_mask | "" | PHP_INI_SYSTEM | |
| apc.slam_defense | 0 | PHP_INI_SYSTEM | |
| apc.file_update_protection | 2 | PHP_INI_SYSTEM | |
| apc.enable_cli | 0 | PHP_INI_SYSTEM | > APC 3.0.6 |
以下是配置选项的简要解释。
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).
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.
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.
The optimization level. Zero disables the optimizer, and higher values use more aggressive optimizations. Expect very modest speed improvements. This is experimental.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
上例的输出类似于:
|
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).
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().
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.
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.
The name of the constant set (that was stored with apc_define_constants()) to be retrieved.
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.
注: Unlike many other mechanisms in PHP, variables stored using apc_store() will persist between requests (until the value is removed from the cache).
Store the variable using this name. keys are cache-unique, so storing a second value with the same key will overwrite the original value.
The variable to store
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.).
本类函数仅在 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。
Apache 的 PHP 模块的行为受 php.ini 的设置影响。在 php.ini 中的设置可以被服务器配置文件或本地的 .htaccess 文件中的 php_flag 设置所覆盖。
表格 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 解析。本指令仅在使用 PHP 的 Apache 模块版本时才有用。可以基于目录或者虚拟主机来打开或者关闭 PHP。将 engine off 放到 httpd.conf 文件中适当的位置就可以激活或禁用 PHP。
指定 PHP 脚本在请求结束后是否可以要求终止子进程。参见 apache_child_terminate()。
在本次请求中发送一个头信息 Last-Modified:,显示 PHP 脚本最后被修改的日期。
不管文件结尾是什么,将文件作为 PHP 以可执行位组来解析。
apache_child_terminate() 将把运行当前 PHP 请求的 Apache 进程注册为终止状态,一旦结束 PHP 代码的运行此进程将终止。可以用在占用大量内存的脚本后面来终止该进程,因为通常内存只在内部释放而不会还给操作系统。
如果 PHP 以 Apache 1 模块方式运行,且 Apache 的版本是非多线程的,以及激活了 PHP 指令 child_terminate,则返回 TRUE。如果不满足上述条件则返回 FALSE 并生成一条 E_WARNING 级的错误信息。
Get an Apache environment variable as specified by variable.
This function requires Apache 2 otherwise it's undefined.
The Apache environment variable
Whether to get the top-level variable available to all Apache layers.
本函数对一个 URL 执行部分请求。取得所有有关给定资源的重要信息后就停手。
此函数仅在 PHP 作为 Apache 模块安装时才可使用。
一个有关 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() 例子
上例的输出类似于:
|
apache_note() 是用于 Apache 的函数,可以取得或者设置请求 notes 表中的值。
如果只有一个参数调用,则返回记录 note_name 的当前值。如果用两个参数调用,则将记录 note_name 的值设为 note_value 并返回记录 note_name 的前一个值。如果未能获取记录,则返回 FALSE。
Fetches all HTTP requests from the current request.
此函数仅在 PHP 作为 Apache 模块安装时才可使用。
例子 1. apache_request_headers() example
上例的输出类似于:
|
注: 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() 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.
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.
The environment variable that's being set.
The new variable value.
Whether to set the top-level variable available to all Apache layers.
注: 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() 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.
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.
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 模块安装时才可使用。
| 版本 | 说明 |
|---|---|
| 4.3.0 | Became an alias for apache_request_headers(). Essentially, it was renamed. This is because this function only works with Apache. |
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 模块安装时才可使用。
| 警告 |
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 中使用本函数。
本类函数允许用多种方法来操作数组和与之交互。数组的本质是储存,管理和操作一组变量。
PHP 支持一维和多维数组,可以是用户创建或由另一个函数创建。有一些特定的数据库处理函数可以从数据库查询中生成数组,还有一些函数返回数组。
以下常量作为 PHP 核心的一部分一直有效。
CASE_LOWER 用在 array_change_key_case() 中将数组的键名转换成小写字母。这也是 array_change_key_case() 的默认值。
CASE_UPPER 用在 array_change_key_case() 中将数组的键名转换成大写字母。
排序顺序标识:
SORT_ASC 用在 array_multisort() 函数中,使其升序排列。
SORT_DESC 用在 array_multisort() 函数中,使其降序排列。
排序类型标识:用于各种排序函数
参见 is_array(),explode(),implode(),split(),preg_split() 和 unset()。
【译者注】本章中出现的“关联数组”或“结合数组”指的是键名为字符串的数组,“索引”和“键名”指的是同一样东西。“索引”多指数组的数字形式的下标。
array_change_key_case() 将 input 数组中的所有键名改为全小写或大写。改变是根据后一个选项 case 参数来进行的。可以在这里用两个常量,CASE_UPPER 和 CASE_LOWER。默认值是 CASE_LOWER。本函数不改变数字索引。
如果一个数组中的多个键名经过本函数后变成一样的话(例如 "keY" 和 "kEY"),最后一个值将覆盖其它的值。
array_chunk() 将一个数组分割成多个数组,其中每个数组的单元数目由 size 决定。最后一个数组的单元数目可能会少几个。得到的数组是一个多维数组中的单元,其索引从零开始。
将可选参数 preserve_keys 设为 TRUE,可以使 PHP 保留输入数组中原来的键名。如果你指定了 FALSE,那每个结果数组将用从零开始的新数字索引。默认值是 FALSE。
例子 1. array_chunk() 例子
上例将输出:
|
返回一个 array,用来自 keys 数组的值作为键名,来自 values 数组的值作为相应的值。
如果两个数组的单元数不同或者数组为空时返回 FALSE。
array_count_values() 返回一个数组,该数组用 input 数组中的值作为键名,该值在 input 数组中出现的次数作为值。
array_diff_assoc() 返回一个数组,该数组包括了所有在 array1 中但是不在任何其它参数数组中的值。注意和 array_diff() 不同的是键名也用于比较。
上面的例子中可以看到键值对 "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() 返回一个数组,该数组包括了所有出现在 array1 中但是未出现在任何其它参数数组中的键名的值。注意关联关系保留不变。本函数和 array_diff() 相同只除了比较是根据键名而不是值来进行的。
在 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() 返回一个数组,该数组包括了所有在 array1 中但是不在任何其它参数数组中的值。注意和 array_diff() 不同的是键名也用于比较。
此比较是通过用户提供的回调函数来进行的。如果认为第一个参数小于,等于,或大于第二个参数时必须分别返回一个小于零,等于零,或大于零的整数。这和 array_diff_assoc() 不同的是还使用了比较索引的内部函数。
例子 1. array_diff_uassoc() 例子
上例将输出:
|
上面的例子中 "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() 返回一个数组,该数组包括了所有出现在 array1 中但是未出现在任何其它参数数组中的键名的值。注意关联关系保留不变。本函数和 array_diff() 相同只除了比较是根据键名而不是值来进行的。
此比较是通过用户提供的回调函数来进行的。如果认为第一个参数小于,等于,或大于第二个参数时必须分别返回一个小于零,等于零,或大于零的整数。
例子 1. array_diff_ukey() 例子
上例将输出:
|
注: 注意本函数只检查了多维数组中的一维。当然,可以用 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() 返回一个数组,该数组包括了所有在 array1 中但是不在任何其它参数数组中的值。注意键名保留不变。
注: 两个单元仅在 (string) $elem1 === (string) $elem2 时被认为是相同的。也就是说,当字符串的表达是一样的时候。
注: 注意本函数只检查了多维数组中的一维。当然可以用 array_diff($array1[0], $array2[0]); 检查更深的维度。
| 警告 |
本函数在 PHP 4.0.4 中是坏的! |
参见 array_diff_assoc(),array_intersect() 和 array_intersect_assoc()。
array_fill() 用 value 参数的值将一个数组填充 num 个条目,键名由 start_index 参数指定的开始。注意 num 必须是一个大于零的数值,否则 PHP 会发出一条警告。
参见 str_repeat() 和 range()。
array_filter() 依次将 input 数组中的每个值传递到 callback 函数。如果 callback 函数返回 TRUE,则 input 数组的当前值会被包含在返回的结果数组中。数组的键名保留不变。
例子 1. array_filter() 例子
上例将输出:
|
用户不应在回调函数中修改数组本身。例如增加/删除单元或者对 array_filter() 正在作用的数组进行 unset。如果数组改变了,此函数的行为没有定义。
如果没有提供 callback 函数,array_filter() 将删除 input 中所有等值为 FALSE 的条目。更多信息见转换为布尔值。
array_flip() 返回一个反转后的 array,例如 trans 中的键名变成了值,而 trans 中的值成了键名。
注意 trans 中的值需要能够作为合法的键名,例如需要是 integer 或者 string。如果值的类型不对将发出一个警告,并且有问题的键/值对将不会反转。
如果同一个值出现了多次,则最后一个键名将作为它的值,所有其它的都丢失了。
array_flip() 如果失败返回 FALSE。
array_intersect_assoc() 返回一个数组,该数组包含了所有在 array1 中也同时出现在所有其它参数数组中的值。注意和 array_intersect() 不同的是键名也用于比较。
上面例子中可以看到只有键值对 "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() 返回一个数组,该数组包含了所有出现在 array1 中并同时出现在所有其它参数数组中的键名的值。
上例中可以看到只有 '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() 返回一个数组,该数组包含了所有在 array1 中也同时出现在所有其它参数数组中的值。注意和 array_intersect() 不同的是键名也用于比较。
此比较是通过用户提供的回调函数来进行的。如果认为第一个参数小于,等于,或大于第二个参数时必须分别返回一个小于零,等于零,或大于零的整数。
参见 array_intersect(),array_intersect_assoc(),array_uintersect_assoc(),array_uintersect_uassoc(),array_intersect_key() 和 array_intersect_ukey()。
array_intersect_ukey() 返回一个数组,该数组包含了所有出现在 array1 中并同时出现在所有其它参数数组中的键名的值。
此比较是通过用户提供的回调函数来进行的。如果认为第一个参数小于,等于,或大于第二个参数时必须分别返回一个小于零,等于零,或大于零的整数。
例子 1. array_intersect_ukey() 例子
上例将输出:
|
上例中可以看到只有 '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() 返回一个数组,该数组包含了所有在 array1 中也同时出现在所有其它参数数组中的值。注意键名保留不变。
注: 两个单元仅在 (string) $elem1 === (string) $elem2 时被认为是相同的。也就是说,当字符串的表达是一样的时候。
参见 array_intersect_assoc(),array_diff() 和 array_diff_assoc()。
array_key_exists() 在给定的 key 存在于数组中时返回 TRUE。key 可以是任何能作为数组索引的值。array_key_exists() 也可用于对象。
注: 在 PHP 4.0.6 中本函数名为 key_exists()。
参见 isset(),array_keys() 和 in_array()。
array_keys() 返回 input 数组中的数字或者字符串的键名。
如果指定了可选参数 search_value,则只返回该值的键名。否则 input 数组中的所有键名都会被返回。自 PHP 5 起,可以用 strict 参数来进行全等比较(===)。
例子 1. array_keys() 例子
上例将输出:
|
array_map() 返回一个数组,该数组包含了 arr1 中的所有单元经过 callback 作用过之后的单元。callback 接受的参数数目应该和传递给 array_map() 函数的数组数目一致。
例子 2. array_map() - 使用更多的数组
上例将输出:
|
通常使用了两个或更多数组时,它们的长度应该相同,因为回调函数是平行作用于相应的单元上的。如果数组的长度不同,则最短的一个将被用空的单元扩充。
本函数一个有趣的用法是构造一个数组的数组,这可以很容易的通过用 NULL 作为回调函数名来实现。
例子 3. 建立一个数组的数组
上例将输出:
|
参见 array_filter(),array_reduce(),array_walk() 和有关 callback 类型的信息。
array_merge_recursive() 将一个或多个数组的单元合并起来,一个数组中的值附加在前一个数组的后面。返回作为结果的数组。
如果输入的数组中有相同的字符串键名,则这些值会被合并到一个数组中去,这将递归下去,因此如果一个值本身是一个数组,本函数将按照相应的条目把它合并为另一个数组。然而,如果数组具有相同的数组键名,后一个值将不会覆盖原来的值,而是附加到后面。
例子 1. array_merge_recursive() 例子
$result 成为:
|
参见 array_merge()。
array_merge() 将一个或多个数组的单元合并起来,一个数组中的值附加在前一个数组的后面。返回作为结果的数组。
如果输入的数组中有相同的字符串键名,则该键名后面的值将覆盖前一个值。然而,如果数组包含数字键名,后面的值将不会覆盖原来的值,而是附加到后面。
如果只给了一个数组并且该数组是数字索引的,则键名会以连续方式重新索引。
例子 1. array_merge() 例子
上例将输出:
|
例子 2. 简单的 array_merge() 例子
别忘了数字键名将会被重新编号!
如果你想完全保留原有数组并只想新的数组附加到后面,用 + 运算符:
数字键名将被保留从而原来的关联保持不变。
|
| 警告 | |
array_merge() 的行为在 PHP 5 中被修改了。和 PHP 4 不同,array_merge() 现在只接受 array 类型的参数。不过可以用强制转换来合并其它类型。请看下面的例子。
|
如果成功则返回 TRUE,失败则返回 FALSE。
array_multisort() 可以用来一次对多个数组进行排序,或者根据某一维或多维对多维数组进行排序。
关联(string)键名保持不变,但数字键名会被重新索引。
输入数组被当成一个表的列并以行来排序――这类似于 SQL 的 ORDER BY 子句的功能。第一个数组是要排序的主要数组。数组中的行(值)比较为相同的话就按照下一个输入数组中相应值的大小来排序,依此类推。
本函数的参数结构有些不同寻常,但是非常灵活。第一个参数必须是一个数组。接下来的每个参数可以是数组或者是下面列出的排序标志。
排序顺序标志:
SORT_ASC - 按照上升顺序排序
SORT_DESC - 按照下降顺序排序
排序类型标志:
SORT_REGULAR - 将项目按照通常方法比较
SORT_NUMERIC - 将项目按照数值比较
SORT_STRING - 将项目按照字符串比较
每个数组之后不能指定两个同类的排序标志。每个数组后指定的排序标志仅对该数组有效 - 在此之前为默认值 SORT_ASC 和 SORT_REGULAR。
例子 1. 对多个数组排序
本例中经过排序后,第一个数组将包含 "10","a",100,100。第二个数组将包含 1,1,"2",3。第二个数组中的项目顺序完全和第一个数组中相应的项目(100 和 100)顺序一致。
|
本例中经过排序后,第一个数组将包含 10,100,100,"a"(作为字符串上升排序),第二个数组将包含 1,3,"2",1(作为数值下降排序)。
例子 3. Sorting multi-dimensional array
本例中在排序后,第一个数组将变成 "10",100,100,11,"a"(被当作字符串以升序排列)。第二个数组将包含 1, 3, "2", 2, 1(被当作数字以降序排列)。
|
例子 4. 对数据库结果进行排序 本例中 data 数组中的每个单元表示一个表中的一行。这是典型的数据库记录的数据集合。 例子中的数据如下:
数据全都存放在名为 data 的数组中。这通常是通过循环从数据库取得的结果,例如 mysql_fetch_assoc()。
本例中将把 volume 降序排列,把 edition 升序排列。 现在有了包含有行的数组,但是 array_multisort() 需要一个包含列的数组,因此用以下代码来取得列,然后排序。
数据集合现在排好序了,结果如下:
|
例子 5. 不区分大小写字母排序 SORT_STRING 和 SORT_REGULAR 都是区分大小写字母的,大写字母会排在小写字母之前。 要进行不区分大小写的排序,就要按照原数组的小写字母拷贝来排序。
上例将输出:
|
【译者注】本函数相当有用,为有助于理解,请再看下面这个例子:
例子 6. 名次排列
上例将输出:
本例中对包含成绩的数组 $grade 按照分数(score)由高到低进行排序,分数相同的人则按照名字(name)由小到大排序。排序后李四 95 分为第一名,赵六 60 分为第五名没有异议。张三、王五和刘七都是 70 分,他们的名次则由其姓名的字母顺序排列,Liu 在前,Wang 在后而 Zhang 在最后。为了区别,三个 70 分分别用了整数,浮点数和字符串来表示,可以在程序输出中清楚地看到它们排序的结果。 |
array_pad() 返回 input 的一个拷贝,并用 pad_value 将其填补到 pad_size 指定的长度。如果 pad_size 为正,则数组被填补到右侧,如果为负则从左侧开始填补。如果 pad_size 的绝对值小于或等于 input 数组的长度则没有任何填补。有可能一次最多填补 1048576 个单元。
参见 array_fill() 和 range()。
array_pop() 弹出并返回 array 数组的最后一个单元,并将数组 array 的长度减一。如果 array 为空(或者不是数组)将返回 NULL。
注: 使用本函数后会重置(reset())数组指针。
array_push() 将 array 当成一个栈,并将传入的变量压入 array 的末尾。array 的长度将根据入栈变量的数目增加。和如下效果相同:
<?php $array[] = $var; ?> |
返回数组新的单元总数。
注: 如果用 array_push() 来给数组增加一个单元,还不如用 $array[] = ,因为这样没有调用函数的额外负担。
注: 如果第一个参数不是数组,array_push() 将发出一条警告。这和 $var[] 的行为不同,后者会新建一个数组。
array_rand() 在你想从数组中取出一个或多个随机的单元时相当有用。它接受 input 作为输入数组和一个可选的参数 num_req,指明了你想取出多少个单元 - 如果没有指定,默认为 1。
如果你只取出一个,array_rand() 返回一个随机单元的键名,否则就返回一个包含随机键名的数组。这样你就可以随机从数组中取出键名和值。
注: 自 PHP 4.2.0 起,不再需要用 srand() 或 mt_srand() 函数给随机数发生器播种,现已自动完成。
参见 shuffle()。
array_reduce() 将回调函数 function 迭代地作用到 input 数组中的每一个单元中,从而将数组简化为单一的值。如果指定了可选参数 initial,该参数将被当成是数组中的第一个值来处理,或者如果数组为空的话就作为最终返回值。如果数组为空并且没有传递 initial 参数,array_reduce() 返回 NULL。
这将使 $b 的值为 15,$c 的值为 1200(= 10*1*2*3*4*5),以及 $d 的值为 1。
参见 array_filter(),array_map(),array_unique() 和 array_count_values()。
array_reverse() 接受数组 array 作为输入并返回一个单元为相反顺序的新数组,如果 preserve_keys 为 TRUE 则保留原来的键名。
例子 1. array_reverse() 例子
这将使 $result 和 $result_keyed 具有相同的单元,但是注意键名的区别。$result 和 $result_keyed 的打印输出显示分别为:
|
注: 第二个参数是 PHP 4.0.3 中新加的。
参见 array_flip()。
在 haystack 中搜索 needle 参数并在找到的情况下返回键名,否则返回 FALSE。
注: 如果 needle 是字符串,则比较以区分大小写的方式进行。
注: 在 PHP 4.2.0 之前,array_search() 在失败时返回 NULL 而不是 FALSE。
如果可选的第三个参数 strict 为 TRUE,则 array_search() 还将在 haystack 中检查 needle 的类型。
如果 needle 在 haystack 中出现不止一次,则返回第一个匹配的键。要返回所有匹配值的键,应该用 array_keys() 加上可选参数 search_value 来代替。
参见 array_keys(),array_values(),array_key_exists() 和 in_array()。
array_shift() 将 array 的第一个单元移出并作为结果返回,将 array 的长度减一并将所有其它单元向前移动一位。所有的数字键名将改为从零开始计数,文字键名将不变。如果 array 为空(或者不是数组),则返回 NULL。
注: 使用本函数后会重置(reset())数组指针。
array_slice() 返回根据 offset 和 length 参数所指定的 array 数组中的一段序列。
如果 offset 非负,则序列将从 array 中的此偏移量开始。如果 offset 为负,则序列将从 array 中距离末端这么远的地方开始。
如果给出了 length 并且为正,则序列中将具有这么多的单元。如果给出了 length 并且为负,则序列将终止在距离数组末端这么远的地方。如果省略,则序列将从 offset 开始一直到 array 的末端。
注意 array_slice() 默认将重置数组的键。自 PHP 5.0.2 起,可以通过将 preserve_keys 设为 TRUE 来改变此行为。
例子 1. array_slice() 例子
上例将输出:
|
参见 array_splice() 和 unset()。
array_splice() 把 input 数组中由 offset 和 length 指定的单元去掉,如果提供了 replacement 参数,则用 replacement 数组中的单元取代。返回一个包含有被移除单元的数组。注意 input 中的数字键名不被保留。
如果 offset 为正,则从 input 数组中该值指定的偏移量开始移除。如果 offset 为负,则从 input 末尾倒数该值指定的偏移量开始移除。
如果省略 length,则移除数组中从 offset 到结尾的所有部分。如果指定了 length 并且为正值,则移除这么多单元。如果指定了 length 并且为负值,则移除从 offset 到数组末尾倒数 length 为止中间所有的单元。小窍门:当给出了 replacement 时要移除从 offset 到数组末尾所有单元时,用 count($input) 作为 length。
如果给出了 replacement 数组,则被移除的单元被此数组中的单元替代。如果 offset 和 length 的组合结果是不会移除任何值,则 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() 例子
|
array_sum() 将数组中的所有值的和以整数或浮点数的结果返回。
注: PHP 4.2.1 之前的版本修改了传入的数组本身,将其中的字符串值转换成数值(大多数情况下都转换成了零,根据具体值而定)。
array_udiff_assoc() 返回一个数组,该数组包括了所有在 array1 中但是不在任何其它参数数组中的值。注意和 array_diff() 与 array_udiff() 不同的是键名也用于比较。数组数据的比较是用用户提供的回调函数进行的。在此方面和 array_diff_assoc() 的行为正好相反,后者是用内部函数进行比较的。
例子 1. array_udiff_assoc() 例子
上例将输出:
|
上例中可以看到键值对 "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() 返回一个数组,该数组包括了所有在 array1 中但是不在任何其它参数数组中的值。注意和 array_diff() 与 array_udiff() 不同的是键名也用于比较。数组数据的比较是用用户提供的回调函数 data_compare_func 进行的。在此方面和 array_diff_assoc() 的行为正好相反,后者是用内部函数进行比较的。对键名(索引)的检查也是由回调函数 key_compare_func 进行的。这和 array_udiff_assoc() 的行为不同,后者是用内部函数比较索引的。
例子 1. array_udiff_uassoc() 例子
上例将输出:
|
在上例中键值对 "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() 返回一个数组,该数组包括了所有在 array1 中但是不在任何其它参数数组中的值。注意键名保持不变。数据的比较是用 data_compare_func 进行的。如果认为第一个参数小于,等于,或大于第二个参数时必须分别返回一个小于零,等于零,或大于零的整数。这和 array_diff() 不同,后者使用了内部函数来比较数据。
例子 1. array_udiff() 例子
上例将输出:
|
注: 注意本函数只检查了多维数组中的一维。当然,可以用 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() 返回一个数组,该数组包含了所有在 array1 中也同时出现在所有其它参数数组中的值。注意和 array_uintersect() 不同的是键名也要比较。数据是用回调函数比较的。
此比较是通过用户提供的回调函数来进行的。如果认为第一个参数小于,等于,或大于第二个参数时必须分别返回一个小于零,等于零,或大于零的整数。
参见 array_uintersect(),array_intersect_assoc(),array_intersect_uassoc() 和 array_uintersect_uassoc()。
array_uintersect_uassoc() 返回一个数组,该数组包含了所有在 array1 中也同时出现在所有其它参数数组中的值。注意和 array_uintersect() 不同的是键名也要比较。数据和索引都是用回调函数比较的。
例子 1. array_uintersect_uassoc() 例子
上例将输出:
|
此比较是通过用户提供的回调函数来进行的。如果认为第一个参数小于,等于,或大于第二个参数时必须分别返回一个小于零,等于零,或大于零的整数。
参见 array_uintersect(),array_intersect_assoc(),array_intersect_uassoc() 和 array_uintersect_assoc()。
array_uintersect() 返回一个数组,该数组包含了所有在 array1 中也同时出现在所有其它参数数组中的值。数据比较是用回调函数进行的。
此比较是通过用户提供的回调函数来进行的。如果认为第一个参数小于,等于,或大于第二个参数时必须分别返回一个小于零,等于零,或大于零的整数。
参见 array_intersect(),array_uintersect_assoc(),array_intersect_uassoc() 和 array_uintersect_uassoc()。
array_unique() 接受 array 作为输入并返回没有重复值的新数组。
注意键名保留不变。array_unique() 先将值作为字符串排序,然后对每个值只保留第一个遇到的键名,接着忽略所有后面的键名。这并不意味着在未排序的 array 中同一个值的第一个出现的键名会被保留。
注: 当且仅当 (string) $elem1 === (string) $elem2 时两个单元被认为相同。就是说,当字符串的表达一样时。
第一个单元将被保留。
array_unshift() 将传入的单元插入到 array 数组的开头。注意单元是作为整体被插入的,因此传入单元将保持同样的顺序。所有的数值键名将修改为从零开始重新计数,所有的文字键名保持不变。
返回 array 数组新的单元数目。
将用户自定义函数 funcname 应用到 array 数组中的每个单元。本函数会递归到更深层的数组中去。典型情况下 funcname 接受两个参数。input 参数的值作为第一个,键名作为第二个。如果提供了可选参数 userdata,将被作为第三个参数传递给 callback funcname。
如果成功则返回 TRUE,失败则返回 FALSE。
注: 如果 funcname 需要直接作用于数组中的值,则给 funcname 的第一个参数指定为引用。这样任何对这些单元的改变也将会改变原始数组本身。
例子 1. array_walk_recursive() 例子
上例将输出:
注意上例中的键 'sweet' 并没有显示出来。任何其值为数组的键都不会被传递到回调函数中去。 |
参见 array_walk() 和有关 callback 类型的信息。
如果成功则返回 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() 例子
上例将输出:
|
参见 array_walk_recursive(),create_function(),list(),foreach,each(),call_user_func_array(),array_map() 和有关 callback 类型的信息。
返回根据参数建立的数组。参数可以用 => 运算符给出索引。关于数组是什么的信息请阅读数组一节。
注: array() 是一个语言结构,用于字面上表示数组,不是常规的函数。
语法“index => values”,用逗号分开,定义了索引和值。索引可以是字符串或数字。如果省略了索引,会自动产生从 0 开始的整数索引。如果索引是整数,则下一个产生的索引将是目前最大的整数索引 + 1。注意如果定义了两个完全一样的索引,则后面一个会覆盖前一个。
在最后一个定义的数组项目之后加一个逗号虽然不常见,却是合法的语法。
下面的例子演示了怎样建立一个二维数组,怎样给相应的数组指定键名,以及怎样在普通数组中略过和继续数字索引。
注意索引 3 被定义了两次,保留了最后的值 13。索引 4 在 索引 8 之后定义,下一个自动生成的索引(值为 19 那个)为 9,因为最大的索引是 8。
本例建立了从 1 开始的数组。
在 Perl 中,可以访问在双引号内的数组的值。但在 PHP 中需要将数组用花括号括起来。
参见 array_pad(),list(),count(),foreach 和 range()。
本函数对数组进行排序,数组的索引保持和单元的关联。主要用于对那些单元顺序很重要的结合数组进行排序。
如果成功则返回 TRUE,失败则返回 FALSE。
fruits 被按照字母顺序逆向排序,并且单元的索引关系不变。
可以用可选的参数 sort_flags 改变排序的行为,详情见 sort()。
本函数对数组进行排序,数组的索引保持和单元的关联。主要用于对那些单元顺序很重要的结合数组进行排序。
如果成功则返回 TRUE,失败则返回 FALSE。
fruits 被按照字母顺序排序,并且单元的索引关系不变。
可以用可选的参数 sort_flags 改变排序的行为,详情见 sort()。
compact() 接受可变的参数数目。每个参数可以是一个包括变量名的字符串或者是一个包含变量名的数组,该数组中还可以包含其它单元内容为变量名的数组, compact() 可以递归处理。
对每个参数,compact() 在当前的符号表中查找该变量名并将它添加到输出的数组中,变量名成为键名而变量的内容成为该键的值。简单说,它做的事和 extract() 正好相反。返回将所有变量添加进去后的数组。
任何没有变量名与之对应的字符串都被略过。
参见 extract()。
返回 var 中的单元数目,通常是一个 array,任何其它类型都只有一个单元。
对于对象,如果安装了 SPL,可以通过实现 Countable 接口来调用 count()。该接口只有一个方法 count(),此方法返回 count() 函数的返回值。
如果 var 不是数组类型或者实现了 Countable 接口的对象,将返回 1,有一个例外,如果 var 是 NULL 则结果是 0。
注: 可选的 mode 参数自 PHP 4.2.0 起可用。
如果可选的 mode 参数设为 COUNT_RECURSIVE(或 1),count() 将递归地对数组计数。对计算多维数组的所有单元尤其有用。mode 的默认值是 0。count() 识别不了无限递归。
| 注意 |
count() 对没有初始化的变量返回 0,但对于空的数组也会返回 0。用 isset() 来测试变量是否已经初始化。 |
请参考手册中数组一节中关于怎样在 PHP 中实现和使用数组的详细解释。
参见 is_array(),isset() 和 strlen()。
每个数组中都有一个内部的指针指向它“当前的”单元,初始指向插入到数组中的第一个单元。
current() 函数返回当前被内部指针指向的数组单元的值,并不移动指针。如果内部指针指向超出了单元列表的末端,current() 返回 FALSE。
| 警告 |
如果数组包含有空的单元(0 或者 "",空字符串)则本函数在碰到这个单元时也返回 FALSE。这使得用 current() 不可能判断是否到了此数组列表的末端。要正确遍历可能含有空单元的数组,用 each() 函数。 |
例子 1. current() 及相关函数的用法示例
|
返回 array 数组中当前指针位置的键/值对并向前移动数组指针。键值对被返回为四个单元的数组,键名为 0,1,key 和 value。单元 0 和 key 包含有数组单元的键名,1 和 value 包含有数据。
如果内部指针越过了数组的末端,则 each() 返回 FALSE。
<?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() 结合使用来遍历数组,例如:
在执行 each() 之后,数组指针将停留在数组中的下一个单元或者当碰到数组结尾时停留在最后一个单元。如果要再用 each 遍历数组,必须使用 reset()。
| 注意 |
因为将一个数组赋值给另一个数组时会重置原来的数组指针,因此在上边的例子中如果我们在循环内部将 $fruit 赋给了另一个变量的话将会导致无限循环。 |
本函数用来将变量从数组中导入到当前的符号表中。接受结合数组 var_array 作为参数并将键名当作变量名,值作为变量的值。对每个键/值对都会在当前的符号表中建立变量,并受到 extract_type 和 prefix 参数的影响。
注: 自版本 4.0.5 起本函数返回被提取的变量数目。
注: EXTR_IF_EXISTS 和 EXTR_PREFIX_IF_EXISTS 是版本 4.2.0 中引进的。
注: EXTR_REFS 是版本 4.3.0 中引进的。
extract() 检查每个键名看是否可以作为一个合法的变量名,同时也检查和符号表中已有的变量名的冲突。对待非法/数字和冲突的键名的方法将根据 extract_type 参数决定。可以是以下值之一:
如果有冲突,覆盖已有的变量。
如果有冲突,不覆盖已有的变量。
如果有冲突,在变量名前加上前缀 prefix。
给所有变量名加上前缀 prefix。自 PHP 4.0.5 起这也包括了对数字索引的处理。
仅在非法/数字的变量名前加上前缀 prefix。本标记是 PHP 4.0.5 新加的。
仅在当前符号表中已有同名变量时,覆盖它们的值。其它的都不处理。可以用在已经定义了一组合法的变量,然后要从一个数组例如 $_REQUEST 中提取值覆盖这些变量的场合。本标记是 PHP 4.2.0 新加的。
仅在当前符号表中已有同名变量时,建立附加了前缀的变量名,其它的都不处理。本标记是 PHP 4.2.0 新加的。
将变量作为引用提取。这有力地表明了导入的变量仍然引用了 var_array 参数的值。可以单独使用这个标志或者在 extract_type 中用 OR 与其它任何标志结合使用。本标记是 PHP 4.3.0 新加的。
如果没有指定 extract_type,则被假定为 EXTR_OVERWRITE。
注意 prefix 仅在 extract_type 的值是 EXTR_PREFIX_SAME,EXTR_PREFIX_ALL,EXTR_PREFIX_INVALID 或 EXTR_PREFIX_IF_EXISTS 时需要。如果附加了前缀后的结果不是合法的变量名,将不会导入到符号表中。
extract() 返回成功导入到符号表中的变量数目。
| 警告 |
不要对不能信任的数据使用 extract(),例如用户的输入($_GET,...)。如果这样做,举例说,要临时运行依赖于 register_globals 的老代码,要确保使用不会覆盖的 extract_type 值,例如 EXTR_SKIP,并且要留意应该按照 php.ini 中由 variables_order 定义的顺序来提取。 |
extract() 的一种可能用法是将 wddx_deserialize() 返回的结合数组中的内容导入到符号表变量中去。
$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()。
在 haystack 中搜索 needle,如果找到则返回 TRUE,否则返回 FALSE。
如果第三个参数 strict 的值为 TRUE 则 in_array() 函数还会检查 needle 的类型是否和 haystack 中的相同。
注: 如果 needle 是字符串,则比较是区分大小写的。
注: 在 PHP 版本 4.2.0 之前,needle 不允许是一个数组。
例子 3. in_array() 中用数组作为 needle
上例将输出:
|
key() 返回数组中当前单元的键名。
例子 1. key() 例子
|
对数组按照键名逆向排序,保留键名到数据的关联。主要用于结合数组。
如果成功则返回 TRUE,失败则返回 FALSE。
可以用可选参数 sort_flags 改变排序的行为,详情见 sort()。
对数组按照键名排序,保留键名到数据的关联。本函数主要用于关联数组。
如果成功则返回 TRUE,失败则返回 FALSE。
可以用可选参数 sort_flags 改变排序的行为,详情见 sort()。
参见 asort(),arsort(),krsort(),uksort(),sort(),natsort() 和 rsort()。
注: 第二个参数是 PHP 4 新加的。
像 array() 一样,这不是真正的函数,而是语言结构。list() 用一步操作给一组变量进行赋值。
注: list() 仅能用于数字索引的数组并假定数字索引从 0 开始。
例子 1. list() 例子
|
例子 2. 使用 list() 的例子
|
| 警告 |
list() 从最右边一个参数开始赋值。如果你用单纯的变量,不用担心这一点。但是如果你用了具有索引的数组,通常你期望得到的结果和在 list() 中写的一样是从左到右的,但实际上不是。是以相反顺序赋值的。 |
本函数实现了一个和人们通常对字母数字字符串进行排序的方法一样的排序算法并保持原有键/值的关联,这被称为“自然排序”。
如果成功则返回 TRUE,失败则返回 FALSE。
natcasesort() 是 natsort() 函数的不区分大小写字母的版本。
例子 1. natcasesort() 例子
上例将输出:
更多信息见 Martin Pool 的 Natural Order String Comparison 页面。 |
本函数实现了一个和人们通常对字母数字字符串进行排序的方法一样的排序算法并保持原有键/值的关联,这被称为“自然排序”。本算法和通常的计算机字符串排序算法(用于 sort())的区别见下面示例。
如果成功则返回 TRUE,失败则返回 FALSE。
例子 1. natsort() 例子
上例将输出:
更多信息见 Martin Pool 的 Natural Order String Comparison 页面。 |
返回数组内部指针指向的下一个单元的值,或当没有更多单元时返回 FALSE。
next() 和 current() 的行为类似,只有一点区别,在返回值之前将内部指针向前移动一位。这意味着它返回的是下一个数组单元的值并将数组指针向前移动了一位。如果移动指针的结果是超出了数组单元的末端,则 next() 返回 FALSE。
| 警告 |
如果数组包含空的单元,或者单元的值是 0 则本函数碰到这些单元也返回 FALSE。要正确遍历可能含有空单元或者单元值为 0 的数组,参见 each() 函数。 |
例子 1. next() 及相关函数的用法示例
|
返回数组内部指针指向的前一个单元的值,或当没有更多单元时返回 FALSE。
| 警告 |
如果数组包含空的单元,或者单元的值是 0 则本函数碰到这些单元也返回 FALSE。要正确遍历可能含有空单元或者单元值为 0 的数组,参见 each() 函数。 |
prev() 和 next() 的行为类似,只除了它将内部指针倒回一位而不是前移一位。
例子 1. prev() 及相关函数用法示例
|
range() 返回数组中从 low 到 high 的单元,包括它们本身。如果 low > high,则序列将从 high 到 low。
新参数: 可选的 step 参数是 PHP 5.0.0 新加的。
如果给出了 step 的值,它将被作为单元之间的步进值。step 应该为正值。如果未指定,step 则默认为 1。
例子 1. range() 例子
|
注: 在版本 4.1.0 之前 range() 函数只产生递增的整数数组。对于字符序列和递减数组的支持是 4.1.0 加入的。字符序列值的长度限定为一。如果输入的长度超过一,则只使用第一个字符。
| 注意 |
在 PHP 版本 4.1.0 到 4.3.2 中,range() 将数字字符串看作字符串而不是整数,因此将会被作为字符序列使用。例如,"4242" 会被当作 "4" 来对待。 |
参见 shuffle(),array_fill() 和 foreach。
reset() 将 array 的内部指针倒回到第一个单元并返回第一个数组单元的值,如果数组为空则返回 FALSE。
例子 1. reset() 例子
|
本函数对数组进行逆向排序(最高到最低)。
注: 本函数为 array 中的单元赋予新的键名。这将删除原有的键名而不仅是重新排序。
如果成功则返回 TRUE,失败则返回 FALSE。
fruits 被按照字母顺序逆向排序。
可以用可选参数 sort_flags 改变排序的行为,详情见 sort()。
本函数打乱(随机排列单元的顺序)一个数组。
注: 本函数为 array 中的单元赋予新的键名。这将删除原有的键名而不仅是重新排序。
注: 自 PHP 4.2.0 起,不再需要用 srand() 或 mt_srand() 函数给随机数发生器播种,现已自动完成。
本函数对数组进行排序。当本函数结束时数组单元将被从最低到最高重新安排。
注: 本函数为 array 中的单元赋予新的键名。这将删除原有的键名而不仅是重新排序。
如果成功则返回 TRUE,失败则返回 FALSE。
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()。
本函数对数组排序并保持索引和单元之间的关联。主要用于对那些单元顺序很重要的结合数组进行排序。比较函数是用户自定义的。
如果成功则返回 TRUE,失败则返回 FALSE。
参见 usort(),uksort(),sort(),asort(),arsort(),ksort() 和 rsort()。
本函数将使用用户提供的比较函数对数组中的键名进行排序。如果要排序的数组需要用一种不寻常的标准进行排序,那么应该使用此函数。
cmp_function 函数应接受两个参数,该参数将被 array 中的一对键名填充。比较函数在第一个参数小于,等于,或大于第二个参数时必须分别返回一个小于零,等于零,或大于零的整数。
如果成功则返回 TRUE,失败则返回 FALSE。
参见 usort(),uasort(),sort(),asort(),arsort(),ksort(),natsort() 和 rsort()。
本函数将用用户自定义的比较函数对一个数组中的值进行排序。如果要排序的数组需要用一种不寻常的标准进行排序,那么应该使用此函数。
比较函数必须在第一个参数被认为小于,等于或大于第二个参数时分别返回一个小于,等于或大于零的整数。
注: 如果两个成员比较结果相同,则它们在排序后的数组中的顺序未经定义。到 PHP 4.0.6 之前,用户自定义函数将保留这些单元的原有顺序。但是由于在 4.1.0 中引进了新的排序算法,结果将不是这样了,因为对此没有一个有效的解决方案。
注: 本函数为 array 中的单元赋予新的键名。这将删除原有的键名而不仅是重新排序。
如果成功则返回 TRUE,失败则返回 FALSE。
注: 很明显在这个小例子中用 sort() 函数更合适。
例子 2. 使用多维数组的 usort() 例子
当排序多维数组时,$a 和 $b 包含到数组第一个索引的引用。 上例将输出:
|
例子 3. 使用对象的成员函数的 usort() 例子
上例将输出:
|
参见 uasort(),uksort(),sort(),asort(),arsort(),ksort(),natsort() 和 rsort()。
可以用 aspell() 函数对某个单词进行拼写检查并给出正确的拼写建议。
注: 该扩展已经被从 PHP 中删除,在 PHP 4.3.0 及以后的版本不再有效。如果想用 PHP 进行拼写检查,请使用 pspell。它使用 pspell 库,并且能够和更新版本的 aspell 一起工作。
aspell 仅工作于非常旧(.27.* 及以前)版本的 aspell 库。无论是该模块,或是那些旧版本的 aspell 均不再被支持。如果需要 aspell 库,可以在 http://aspell.sourceforge.net/ 找到。
(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]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.
aspell_check() checks the spelling of a word and returns TRUE if the spelling is correct, FALSE if not.
aspell_new() opens up a new dictionary and returns the dictionary link identifier for use in other aspell functions. Returns FALSE on error.
PHP 为任意精度数学计算提供了二进制计算器(Binary Calculator),它支持任意大小和精度的数字,以字符串形式描述。
本类函数仅在 PHP 编译时配置了 --enable-bcmath 时可用。在 PHP 3 中,本类函数仅在 PHP 编译时没有配置 --disable-bcmath 时可用。
PHP 的 Windows 版本已经内置该扩展模块的支持。无需加载任何附加扩展库即可使用这些函数。
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.
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.
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.
Get the modulus of the left_operand using modulus.
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.
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.
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.
This function sets the default scale parameter for all subsequent bc math functions that do not explicitly specify a scale parameter. 如果成功则返回 TRUE,失败则返回 FALSE。
Return the square root of the operand. The optional scale parameter sets the number of digits after the decimal place in the result.
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.
Bzip2 函数用来透明的读写 bzip2(.bz2)压缩文件。
该例子打开一临时文件,并写入一测试字符串,然后打印文件内容。
例子 1. Bzip2 例子
|
bzcompress() compresses the given string and returns it as bzip2 encoded data.
The string to compress.
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.
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.
bzdecompress() decompresses the given string containing bzip2 encoded data.
The string to decompress.
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.
Returns the error number of any bzip2 error returned by the given file pointer.
Returns the error number and error string of any bzip2 error returned by the given file pointer.
Returns an associative array, with the error code in the errno entry, and the error message in the errstr entry.
Gets the error string of any bzip2 error returned by the given file pointer.
bzopen() opens a bzip2 (.bz2) file for reading or writing.
The name of the file to open.
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.
bzread() reads from the given bzip2 file pointer.
Reading stops when length (uncompressed) bytes have been read or EOF is reached, whichever comes first.
The file pointer. It must be valid and must point to a file successfully opened by bzopen().
If not specified, bzread() will read 1024 (uncompressed) bytes at a time.
bzwrite() writes a string into the given bzip2 file stream.
The file pointer. It must be valid and must point to a file successfully opened by bzopen().
The written data.
If supplied, writing will stop after length (uncompressed) bytes have been written or the end of data is reached, whichever comes first.
日历扩展是由一系列简单的日历格式转换函数组成。媒介或标准是基于儒略日计数(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 中,或者在运行时被动态加载后才有效。
以下常量自 PHP 4.3.0 起可用:
以下常量自 PHP 5.0.0 起可用:
(PHP 4 >= 4.1.0, PHP 5)
cal_days_in_month -- Return the number of days in a month for a given year and calendarThis function will return the number of days in the month of year for the specified calendar.
See also jdtounix().
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
上例将输出:
|
See also cal_to_jd().
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
上例将输出:
|
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().
(PHP 3 >= 3.0.9, PHP 4, PHP 5)
easter_date -- Get Unix timestamp for midnight on Easter of a given yearReturns 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.
| 警告 |
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.
(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 yearReturns 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).
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().
(PHP 3, PHP 4, PHP 5)
FrenchToJD -- Converts a date from the French Republican Calendar to a Julian Day CountConverts 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.
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.
Returns the day of the week. Can return a string or an integer depending on the 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
| Mode | Meaning | Values |
|---|---|---|
| 0 | Gregorian - abbreviated | Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec |
| 1 | Gregorian | January, February, March, April, May, June, July, August, September, October, November, December |
| 2 | Julian - abbreviated | Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec |
| 3 | Julian | January, February, March, April, May, June, July, August, September, October, November, December |
| 4 | Jewish | Tishri, Heshvan, Kislev, Tevet, Shevat, AdarI, AdarII, Nisan, Iyyar, Sivan, Tammuz, Av, Elul |
| 5 | French Republican | Vendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose, Germinal, Floreal, Prairial, Messidor, Thermidor, Fructidor, Extra |
Converts a Julian Day Count to the French Republican Calendar.
Converts Julian Day Count to a string containing the Gregorian date in the format of "month/day/year".
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.
Converts Julian Day Count to a string containing the Julian Calendar Date in the format of "month/day/year".
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().
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.
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. |
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().
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/.
| 警告 |
本函数暂无文档,仅有参数列表。 |
(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(4.0.2 - 4.2.3 only)
ccvs_count -- Find out how many transactions of a given type are stored in the systemThe 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.
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.
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).
例子 1. A ctype_alnum() example (using the default locale)
上例将输出:
|
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.
例子 1. A ctype_alpha() example (using the default locale)
上例将输出:
|
Checks if all of the characters in the provided string, text, are control characters. Control characters are e.g. line feed, tab, esc.
例子 1. A ctype_cntrl() example
上例将输出:
|
Checks if all of the characters in the provided string, text, are numerical.
例子 1. A ctype_digit() example
上例将输出:
|
Checks if all of the characters in the provided string, text, creates visible output.
Returns TRUE if every character in text is printable and actually creates visible output (no white space), FALSE otherwise.
例子 1. A ctype_graph() example
上例将输出:
|
Checks if all of the characters in the provided string, text, are lowercase letters.
例子 1. A ctype_lower() example (using the default locale)
上例将输出:
|
Checks if all of the characters in the provided string, text, are printable.
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 4 >= 4.0.4, PHP 5)
ctype_punct -- Check for any printable character which is not whitespace or an alphanumeric characterChecks if all of the characters in the provided string, text, are punctuation character.
Returns TRUE if every character in text is printable, but neither letter, digit or blank, FALSE otherwise.
例子 1. A ctype_punct() example
上例将输出:
|
Checks if all of the characters in the provided string, text, creates whitespace.
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
上例将输出:
|
Checks if all of the characters in the provided string, text, are uppercase characters.
例子 1. A ctype_upper() example (using the default locale)
上例将输出:
|
Checks if all of the characters in the provided string, text, are hexadecimal 'digits'.
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
上例将输出:
|
本类函数允许获取类和对象实例的信息。可以取得对象所属的类的名字,以及它的成员属性和方法。通过使用这些函数,不仅可以弄清楚一个对象类的全体成员,而且可以知道它的起源(例如,该对象类是哪个类的扩展)。
在本例子中,先定义一个基础类和一个扩展类。基础类描述的是普通的蔬菜(Vegetable),它是否可食用(is_edible)以及它是什么颜色(what_color)。子类 Spinach 增加了“烹调”的方法(cook_it)和“获知它是否已被烹调了”的方法(is_cooked)。
例子 1. classes.inc
|
接着,从这些对象中创建两个对象实例,打印出它们的相关信息,包括它们的起源。还定义了一些实用函数,它们主要是为了让变量的输出好看些。
例子 2. test_script.php
上边例子中重点要注意的是对象 $leafy 是 Spinach 类的一个实例,而 Spinach 类是 Vegetable 类的一个子类,因此上边脚本的最后部分将会输出:
|
| 警告 |
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 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_name 指定的类中定义的方法名所组成的数组。
注: 从 PHP 4.0.6 开始,可以指定对象本身来代替 class_name,例如:
例子 1. get_class_methods() 示例
|
运行结果:
返回由类的默认属性组成的关联数组,此数组的元素以 varname => value 的形式存在。
注: 在 PHP 4.2.0 之前,get_class_vars() 不会包含未初始化的类变量。
例子 1. get_class_vars() 示例
|
运行结果:
返回对象实例 obj 所属类的名字。如果 obj 不是一个对象则返回 FALSE。
注: get_class() 返回用户定义的类名的小写形式。在 PHP 扩展中定义的类则返回其原有的名字。
返回由当前脚本中已定义类的名字组成的数组。
注: 在 PHP 4.0.1pl2 中,有三个额外的类存在于返回的数组中:stdClass(在 Zend/zend.c 中定义)、OverloadedTestClass(在 ext/standard/basic_functions.c 中定义)和 Directory(在 ext/standard/dir.c 中定义)。
还需要注意的是额外类的出现依赖于你已编译到 PHP 中的库。这意味着你不能使用这些类名定义自己的类。在附录的 预定义类 部分有预定义类的列表。
参见 class_exists()。
This function returns an array of the names of the declared interfaces in the current script.
See also get_declared_classes().
返回由 obj 指定的对象中定义的属性组成的关联数组。
注: 在 PHP 4.2.0 之前的版本中,如果在 obj 对象实例中声明的变量没有被赋值,则它们将不会在返回的数组中。而在 PHP 4.2.0 之后,这些变量作为键名将被赋予 NULL 值。
例子 1. 使用 get_object_vars()
|
Array
(
[x] => 1.233
[y] => 3.445
[label] =>
)
Array
(
[x] => 1.233
[y] => 3.445
[label] => point #1
) |
如果 obj 是对象,则返回对象实例 obj 所属类的父类名。
如果 obj 是字符串,则返回以此字符串为名的类的父类名。此功能是在 PHP 4.0.5 中增加的。
This function returns TRUE if the interface given by interface_name has been defined, FALSE otherwise.
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().
如果对象 object 所属类是类 class_name 的子类,则返回 TRUE,否则返回 FALSE。
参见 get_class()、 get_parent_class() 和 is_a()。
如果 method_name 所指的方法在 object 所指的对象类中已定义,则返回 TRUE,否则返回 FALSE。
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.
A string with the class name or an object of the class to test for
The name of the property
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 以后的发布而改变。使用本函数风险自担。 |
例子 1. classkit_import() example
上例将输出:
|
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
The class to which this method will be added
The name of the method to add
Comma-delimited list of arguments for the newly-created method
The code to be evaluated when methodname is called
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.
例子 1. classkit_method_add() example
上例将输出:
|
| classkit_method_copy() |
| classkit_method_redefine() |
| classkit_method_remove() |
| classkit_method_rename() |
| create_function() |
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
Destination class for copied method
Destination method name
Source class of the method to copy
Name of the method to copy from the source class. If this parameter is omitted, the value of dMethod is assumed.
例子 1. classkit_method_copy() example
上例将输出:
|
注: 本函数不能用于操作当前正在运行(或运行链上)的方法。
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
The class in which to redefine the method
The name of the method to redefine
Comma-delimited list of arguments for the redefined method
The new code to be evaluated when methodname is called
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.
例子 1. classkit_method_redefine() example
上例将输出:
|
注: 本函数不能用于操作当前正在运行(或运行链上)的方法。
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
注: 本函数不能用于操作当前正在运行(或运行链上)的方法。
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
The class in which to rename the method
The name of the method to rename
The new name to give to the renamed method
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].
例子 1. Simple ClibPDF Example
|
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
|
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 的点来度量。
The cpdf_add_outline() function adds a bookmark with text text that points to the current page.
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().
The cpdf_begin_text() function starts a text section. 如果成功则返回 TRUE,失败则返回 FALSE。 The created text section must be ended with cpdf_end_text().
See also cpdf_end_text().
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().
The cpdf_clip() function clips all drawing to the current path. 如果成功则返回 TRUE,失败则返回 FALSE。
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().
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_closepath_fill_stroke -- Close, fill and stroke current pathThe 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().
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().
The cpdf_closepath() function closes the current path. 如果成功则返回 TRUE,失败则返回 FALSE。
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().
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().
The cpdf_end_text() function ends a text section which was started with cpdf_begin_text(). 如果成功则返回 TRUE,失败则返回 FALSE。
See also cpdf_begin_text().
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().
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().
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().
The cpdf_finalize() function ends the document. You still have to call cpdf_close(). 如果成功则返回 TRUE,失败则返回 FALSE。
See also cpdf_close().
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().
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().
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().
The cpdf_moveto() function set the current point to the coordinates x_coor and y_coor. 如果成功则返回 TRUE,失败则返回 FALSE。
可选参数 mode 决定单元的长度。如果为 0 或被省略则使用该页指定的默认单元。否则坐标忽略当前单元而使用 postscript 的点来度量。
The cpdf_newpath() starts a new path on the document given by the pdf_document parameter. 如果成功则返回 TRUE,失败则返回 FALSE。
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().
(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)
cpdf_output_buffer -- Outputs the pdf document in memory bufferThe 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().
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().
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().
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
|
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。
See also cpdf_save().
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().
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().
The cpdf_rotate() function set the rotation in degrees to angle. 如果成功则返回 TRUE,失败则返回 FALSE。
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().
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().
The cpdf_scale() function set the scaling factor in both directions. 如果成功则返回 TRUE,失败则返回 FALSE。
| 警告 |
本函数暂无文档,仅有参数列表。 |
The cpdf_set_char_spacing() function sets the spacing between characters. 如果成功则返回 TRUE,失败则返回 FALSE。
See also cpdf_set_word_spacing() and cpdf_set_leading().
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_set_creator -- Sets the creator field in the pdf documentThe 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().
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().
(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)
cpdf_set_font_directories -- Sets directories to search when using external fonts
| 警告 |
本函数暂无文档,仅有参数列表。 |
(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)
cpdf_set_font_map_file -- Sets fontname to filename translation map when using external fontsThe 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.
The cpdf_set_horiz_scaling() function sets the horizontal scaling to scale percent. 如果成功则返回 TRUE,失败则返回 FALSE。
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_set_keywords -- Sets the keywords field of the pdf documentThe 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().
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().
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.
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_set_subject -- Sets the subject field of the pdf documentThe 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().
The cpdf_set_text_matrix() function sets a matrix which describes a transformation applied on the current text font. 如果成功则返回 TRUE,失败则返回 FALSE。
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().
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.
The cpdf_set_text_rise() function sets the text rising to value units. 如果成功则返回 TRUE,失败则返回 FALSE。
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().
(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)
cpdf_set_viewer_preferences -- How to show the document in the viewerThe cpdf_set_word_spacing() function sets the spacing between words. 如果成功则返回 TRUE,失败则返回 FALSE。
See also cpdf_set_char_spacing() and cpdf_set_leading().
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。
The cpdf_setflat() function set the flatness to a value between 0 and 100. 如果成功则返回 TRUE,失败则返回 FALSE。
The cpdf_setgray_fill() function sets the current gray value to fill a path. 如果成功则返回 TRUE,失败则返回 FALSE。
See also cpdf_setrgbcolor_fill().
The cpdf_setgray_stroke() function sets the current drawing color to the given gray value. 如果成功则返回 TRUE,失败则返回 FALSE。
See also cpdf_setrgbcolor_stroke().
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().
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。
The cpdf_setlinejoin() function set the linejoin parameter between a value of 0 and 2. 0 = miter, 1 = round, 2 = bevel. 如果成功则返回 TRUE,失败则返回 FALSE。
The cpdf_setlinewidth() function set the line width to width. 如果成功则返回 TRUE,失败则返回 FALSE。
The cpdf_setmiterlimit() function set the miter limit to a value greater or equal than 1. 如果成功则返回 TRUE,失败则返回 FALSE。
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_setrgbcolor_fill -- Sets filling color to rgb color valueThe 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().
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_setrgbcolor_stroke -- Sets drawing color to rgb color valueThe 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().
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_setrgbcolor -- Sets drawing and filling color to rgb color valueThe 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().
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().
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().
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().
The cpdf_stroke() function draws a line along current path. 如果成功则返回 TRUE,失败则返回 FALSE。
See also cpdf_closepath() and cpdf_closepath_stroke().
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().
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.
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.
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.
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 将被允许以一个 D-COM(Distributed COM)客户方式操作并允许 PHP 脚本在远程服务器上实例化 COM 对象。
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.
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.
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.
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.
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 中,或者在运行时被动态加载后才有效。
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 类构造函数。参数:
被请求组件的名字或 class-id。
DCOM 服务器的名字,组件在此服务器上被取用。如果是 NULL,则假定是 localhost。想要允许 DCOM,必须将 php.ini 中的 com.allow_dcom 设为 TRUE。
指定用于将 PHP 字符串(php-strings)转换成 UNICODE 字符串(unicode-strings)的代码页,反之亦然。可用的值为 CP_ACP、CP_MACCP、CP_OEMCP、CP_SYMBOL、CP_THREAD_ACP, CP_UTF7 和 CP_UTF8。
例子 1. COM 示例 (1)
|
例子 2. COM 示例 (2)
|
The DOTNET class allows you to instantiate a class from a .Net assembly and call its methods and access its properties.
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.
注: You need to install the .Net runtime on your web server to take advantage of this feature.
VARIANT 类构造函数。参数:
初始值。若省略则创建一个 VT_EMPTY 对象。
指定 VARIANT 对象的内容类型。可用的值为 VT_UI1、VT_UI2、VT_UI4、VT_I1、VT_I2、VT_I4、VT_R4、VT_R8、VT_INT、VT_UINT、VT_BOOL、VT_ERROR、VT_CY、VT_DATE、VT_BSTR、VT_DECIMAL、VT_UNKNOWN、VT_DISPATCH 和 VT_VARIANT。这些值相互排斥,但是可以使用 VT_BYREF 将它们联合起来指定为一个值。若省略,则使用参数 value 的类型。额外信息请查阅 msdn 库。
指定用于将 PHP 字符串(php-strings)转换成 UNICODE 字符串(unicode-strings)的代码页,反之亦然。可用的值为 CP_ACP、CP_MACCP、CP_OEMCP、CP_SYMBOL、CP_THREAD_ACP, CP_UTF7 和 CP_UTF8。
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.
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
|
See also com_print_typeinfo(), com_message_pump().
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_object 所引用的 COM 对象的 property 属性值,出错则返回 FALSE。
注: 本函数在 PHP 5 中不存在,应该使用常规的并更自然的面向对象语法来访问属性或调用方法。
com_invoke() 调用由 com_object 所引用的对象的方法。出错返回 FALSE,成功则返回 function_name 的返回值。
com_load() 创建新的 COM 组件同时返回此组件的引用。失败则返回 FALSE。codepage 可用的值为:CP_ACP、CP_MACCP、CP_OEMCP、CP_SYMBOL、CP_THREAD_ACP, CP_UTF7 和 CP_UTF8。
(PHP 4 >= 4.2.3, PHP 5)
com_message_pump -- Process COM messages, sleeping for up to timeoutms millisecondsThis 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.
(PHP 4 >= 4.2.3, PHP 5)
com_print_typeinfo -- Print out a PHP class definition for a dispatchable interfaceThe 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_object 所引用的对象的 property 属性值。成功则返回新设置的值,出错则返回 FALSE。
注: 本函数在 PHP 5 中不存在,应该使用常规的并更自然的面向对象语法来访问属性或调用方法。
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()。
Adds left to right using the following rules (taken from the MSDN library), which correspond to those of Visual Basic:
表格 1. Variant Addition Rules
| If | Then |
|---|---|
| Both expressions are of the string type | Concatenation |
| One expression is a string type and the other a character | Addition |
| One expression is numeric and the other is a string | Addition |
| Both expressions are numeric | Addition |
| Either expression is NULL | NULL is returned |
| Both expressions are empty | Integer subtype is returned |
See also variant_sub().
注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。
变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。
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 is | If right is | then the result is |
|---|---|---|
| TRUE | TRUE | TRUE |
| TRUE | FALSE | FALSE |
| TRUE | NULL | NULL |
| FALSE | TRUE | FALSE |
| FALSE | FALSE | FALSE |
| FALSE | NULL | FALSE |
| NULL | TRUE | NULL |
| NULL | FALSE | FALSE |
| NULL | NULL | NULL |
See also variant_or().
注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。
变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。
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().
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()。
Compares left with right and returns one of the following values:
表格 1. Variant Comparision Results
| value | meaning |
|---|---|
| VARCMP_LT | left is less than right |
| VARCMP_EQ | left is equal to right |
| VARCMP_GT | left is greater than right |
| VARCMP_NULL | Either 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
| value | meaning |
|---|---|
| NORM_IGNORECASE | Compare case insensitively |
| NORM_IGNORENONSPACE | Ignore nonspacing characters |
| NORM_IGNORESYMBOLS | Ignore symbols |
| NORM_IGNOREWIDTH | Ignore string width |
| NORM_IGNOREKANATYPE | Ignore Kana type |
| NORM_IGNOREKASHIDA | Ignore Arabic kashida characters |
注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。
变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。
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().
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().
Divides left by right and returns the result, subject to the following rules:
表格 1. Variant Division Rules
| If | Then |
|---|---|
| Both expressions are of the string, date, character, boolean type | Double is returned |
| One expression is a string type and the other a character | Division and a double is returned |
| One expression is numeric and the other is a string | Division and a double is returned. |
| Both expressions are numeric | Division and a double is returned |
| Either expression is NULL | NULL is returned |
| right is empty and left is anything but empty | A 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 empty | A 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()。
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()。
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()。
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.
Converts left and right to integer values, and then performs integer division according the following rules:
表格 1. Variant Integer Division Rules
| If | Then |
|---|---|
| Both expressions are of the string, date, character, boolean type | Division and integer is returned |
| One expression is a string type and the other a character | Division |
| One expression is numeric and the other is a string | Division |
| Both expressions are numeric | Division |
| Either expression is NULL | NULL is returned |
| Both expressions are empty | A 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()。
Performs a bitwise implication operation, according to the following truth table:
表格 1. Variant Implication Table
| If left is | If right is | then the result is |
|---|---|---|
| TRUE | TRUE | TRUE |
| TRUE | FALSE | TRUE |
| TRUE | NULL | TRUE |
| FALSE | TRUE | TRUE |
| FALSE | FALSE | TRUE |
| FALSE | NULL | TRUE |
| NULL | TRUE | TRUE |
| NULL | FALSE | NULL |
| NULL | NULL | NULL |
注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。
变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。
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()。
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()。
Multiplies left by right and returns the result, subject to the following rules:
表格 1. Variant Multiplication Rules
| If | Then |
|---|---|
| Both expressions are of the string, date, character, boolean type | Multiplication |
| One expression is a string type and the other a character | Multiplication |
| One expression is numeric and the other is a string | Multiplication |
| Both expressions are numeric | Multiplication |
| Either expression is NULL | NULL is returned |
| Both expressions are empty | Empty 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()。
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()。
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()。
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 is | If right is | then the result is |
|---|---|---|
| TRUE | TRUE | TRUE |
| TRUE | FALSE | TRUE |
| TRUE | NULL | TRUE |
| FALSE | TRUE | TRUE |
| FALSE | FALSE | FALSE |
| FALSE | NULL | NULL |
| NULL | TRUE | TRUE |
| NULL | FALSE | NULL |
| NULL | NULL | NULL |
See also variant_and(), variant_xor().
注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。
变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。
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()。
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()。
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().
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.
(PHP 5)
variant_sub -- subtracts the value of the right variant from the left variant value and returns the resultSubtracts right from left using the following rules:
表格 1. Variant Subtraction Rules
| If | Then |
|---|---|
| Both expressions are of the string type | Subtraction |
| One expression is a string type and the other a character | Subtraction |
| One expression is numeric and the other is a string | Subtraction. |
| Both expressions are numeric | Subtraction |
| Either expression is NULL | NULL is returned |
| Both expressions are empty | Empty string is returned |
See also variant_add().
注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。
变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。
Performs a logical exclusion, according to the following truth table:
表格 1. Variant XOR Rules
| If left is | If right is | then the result is |
|---|---|---|
| TRUE | TRUE | FALSE |
| TRUE | FALSE | TRUE |
| FALSE | TRUE | TRUE |
| FALSE | FALSE | FALSE |
| NULL | NULL | NULL |
See also variant_and(), variant_or().
注: 对于所有的变量算法函数,此函数的参数可以要么是 PHP 自身的类型(整型,字符串,浮点型,布尔型或者 NULL),要么是一个 COM,VARIANT 或 DOTNET 类的实例。PHP 自身类型将被转换为变量,使用与 VARIANT 类的构造函数中相同的规则。COM 和 DOTNET 对象将具有其默认属性的值,取得并作为变量值使用。
变量算法函数是 COM 库中与其名称接近的函数的封装。此类函数的更多信息请参考 MSDN 库。PHP 函数命名有少许不同,例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。
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
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| crack.default_dictionary | NULL | PHP_INI_SYSTEM | Available since PHP 4.0.5. |
This example shows how to open a CrackLib dictionary, test a given password, retrieve any diagnostic messages, and close the dictionary.
例子 1. CrackLib example
|
注: If crack_check() returns TRUE, crack_getlastmessage() will return 'strong password'.
Performs an obscure check with the given password on the specified dictionary.
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
The crack lib dictionary. If not specified, the last opened dictionary is used.
The tested password.
crack_closedict() closes the specified dictionary identifier.
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
crack_getlastmessage() returns the message from the last obscure check.
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
crack_opendict() opens the specified CrackLib dictionary for use with crack_check().
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
注: Only one dictionary may be open at a time.
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() is used to generate the HTML form of request for payment.
(4.0.5 - 4.2.3 only, PECL)
cybermut_creerreponsecm -- Generate the delivery's acknowledgement of the payment's confirmationThe 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.
(4.0.5 - 4.2.3 only, PECL)
cybermut_testmac -- Make sure that there was no data diddling contained in the received message of confirmationcybermut_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.
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 中,或者在运行时被动态加载后才有效。
Available since PHP 5.1.0
Available since PHP 5.1.0
Available since PHP 5.1.0
Available since PHP 5.1.0
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:
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
|
See also: curl_init().
This function copies a cURL handle, returning a new cURL handle with the same preferences.
例子 1. Copying a cURL handle.
|
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.
(PHP 4 >= 4.0.3, PHP 5)
curl_error -- Return a string containing the last error for the current sessionReturns 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.
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
|
注: 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().
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"
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
|
See also: curl_close(), curl_setopt()
| 警告 |
本函数暂无文档,仅有参数列表。 |
See also curl_multi_init(), curl_init(), and curl_multi_remove_handle().
| 警告 |
本函数暂无文档,仅有参数列表。 |
See also curl_multi_init() and curl_close().
| 警告 |
本函数暂无文档,仅有参数列表。 |
See also curl_multi_init() and curl_exec().
(PHP 5)
curl_multi_getcontent -- Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set| 警告 |
本函数暂无文档,仅有参数列表。 |
See also curl_multi_init().
| 警告 |
本函数暂无文档,仅有参数列表。 |
See also curl_init() and curl_multi_close().
| 警告 |
本函数暂无文档,仅有参数列表。 |
See also curl_multi_init(), curl_init(), and curl_multi_add_handle().
(PHP 5)
curl_multi_select -- Get all the sockets associated with the cURL extension, which can then be "selected"| 警告 |
本函数暂无文档,仅有参数列表。 |
See also curl_multi_init().
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:
| Option | Set value to | Notes |
|---|---|---|
| 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.
| |
| 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:
| Option | Set value to | Notes |
|---|---|---|
| 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:
| Option | Set value to | Notes |
|---|---|---|
| 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.
| |
| 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.
| |
| 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:
| Option | Set value to | Notes |
|---|---|---|
| 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:
| Option | Set value to | Notes |
|---|---|---|
| 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:
| Option | Set value to | Notes |
|---|---|---|
| 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
|
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.
The function returns an associative array with the elements "errcode" and, if "errcode" is FALSE, "outbuff" (string), "outLth" (long) and "macbuff" (string).
To enable Cyrus IMAP support and to use these functions you have to compile PHP with the --with-cyrus option.
| 警告 |
本函数暂无文档,仅有参数列表。 |
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
| Handler | Notes |
|---|---|
| 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
| Handler | Configure Switch |
|---|---|
| dbm |
To enable support for dbm add
--with-dbm[=DIR].
|
| ndbm |
To enable support for ndbm add
--with-ndbm[=DIR].
|
| gdbm | To enable support for gdbm add --with-gdbm[=DIR]. |
| db2 |
To enable support for db2 add
--with-db2[=DIR].
|
| db3 |
To enable support for db3 add
--with-db3[=DIR].
|
| db4 |
To enable support for db4 add
--with-db4[=DIR].
|
| cdb |
To enable support for cdb add
--with-cdb[=DIR].
|
| flatfile |
To enable support for flatfile add
--with-flatfile.
|
| inifile |
To enable support for inifile add
--with-inifile.
|
| qdbm |
To enable support for qdbm add
--with-qdbm[=DIR].
|
注: 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.
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.
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.
dba_close() closes the established database and frees all resources of the specified database handle.
dba_delete() deletes the specified entry from the database.
The key of the entry which is deleted.
The database handler, returned by dba_open() or dba_popen().
dba_exists() checks whether the specified key exists in the database.
The key the check is performed for.
The database handler, returned by dba_open() or dba_popen().
dba_fetch() fetches the data specified by key from the database specified with handle.
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().
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.
The database handler, returned by dba_open() or dba_popen().
dba_firstkey() returns the first key of the database and resets the internal key pointer. This permits a linear search through the whole database.
dba_handlers() list all the handlers supported by this extension.
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
上例的输出类似于:
|
dba_insert() inserts the entry described with key and value into the database.
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.
The value to be inserted.
The database handler, returned by dba_open() or dba_popen().
dba_key_split() splits a key (string representation) into an array 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_nextkey() returns the next key of the database and advances the internal key pointer.
dba_open() establishes a database instance for path with mode using handler.
Commonly a regular path in your filesystem.
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 open mode = "rl" mode = "rlt" mode = "wl" mode = "wlt" mode = "rd" mode = "rdt" mode = "wd" mode = "wdt" not open ok ok ok ok ok ok ok ok mode = "rl" ok ok wait false illegal illegal illegal illegal mode = "wl" wait false wait false illegal illegal illegal illegal mode = "rd" illegal illegal illegal illegal ok ok wait false mode = "wd" illegal illegal illegal illegal wait false wait false
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.
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.
| 版本 | 说明 |
|---|---|
| 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_popen() establishes a persistent database instance for path with mode using handler.
Commonly a regular path in your filesystem.
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.
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.
dba_replace() replaces or inserts the entry described with key and value into the database specified by handle.
The key of the entry to be replaced.
The value to be replaced.
The database handler, returned by dba_open() or dba_popen().
可以用这些函数得到 PHP 所运行的服务器的日期和时间。可以用这些函数将日期和时间以很多不同方式格式化输出。
注: 请留意这些函数依赖于服务器的地区设置。确认在使用这些函数时考虑到了夏令时的设置(例如使用 $date = strtotime('+7 days', $date) 而不是 $date += 7*24*60*60)和闰年。
这些函数的行为受 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 起可用 |
以下是配置选项的简要解释。
注: 前四个配置选项目前仅用于 date_sunrise() 和 date_sunset()。
自 PHP 5.1.0 起定义有以下常量来提供标准日期表达方法,可以用于日期格式函数(例如 date())。
原子钟格式(如:2005-08-15T15:52:01+0000)
HTTP Cookies 格式(如:Mon, 15 Aug 2005 15:52:01 UTC)
ISO-8601(如:2005-08-15T15:52:01+0000)
RFC 822(如:Mon, 15 Aug 2005 15:52:01 UTC)
RFC 850(如:Monday, 15-Aug-05 15:52:01 UTC)
RFC 1036(如:Monday, 15-Aug-05 15:52:01 UTC)
RFC 1123(如:Mon, 15 Aug 2005 15:52:01 UTC)
RFC 2822(如:Mon, 15 Aug 2005 15:52:01 +0000)
RSS(如:Mon, 15 Aug 2005 15:52:01 UTC)
World Wide Web Consortium(如:2005-08-15T15:52:01+0000)
如果给出的日期有效则返回 TRUE,否则返回 FALSE。检查由参数构成的日期的合法性。日期在以下情况下被认为有效:
year 的值是从 1 到 32767
month 的值是从 1 到 12
Day 的值在给定的 month 所应该具有的天数范围之内,闰年已经考虑进去了。
参见 mktime() 和 strtotime()。
本函数返回默认时区,使用如下“假定”的顺序:
用 date_default_timezone_set() 函数设定的时区(如果设定了的话)
TZ 环境变量(如果非空)
date.timezone 配置选项(如果设定了的话)
自己推测(如果操作系统支持)
如果以上选择都不成功,则返回 UTC
date_default_timezone_set() 设定用于所有日期时间函数的默认时区。
注: 自 PHP 5.1.0 起(此版本日期时间函数被重写了),如果时区不合法则每个对日期时间函数的调用都会产生一条 E_NOTICE 级别的错误信息。
date_sunrise() 返回给定的日期(以 timestamp 指定)与地点的日出时间。latitude,longitude 和 zenith 参数默认值分别为配置选项中的 date.default_latitude,date.default_longitude 和 date.sunrise_zenith。
latitude 默认是指北纬。因此如果要指定南纬,必须传递一个负值。同样规则也适用于 longitude,其默认是指东经。
gmt_offset 参数的单位是小时。
表格 1. format 常量
| 常量 | 说明 | 取值举例 |
|---|---|---|
| SUNFUNCS_RET_STRING | 以 string 格式返回结果 | 16:46 |
| SUNFUNCS_RET_DOUBLE | 以 float 格式返回结果 | 16.78243132 |
| SUNFUNCS_RET_TIMESTAMP | 以 integer 格式(时间戳)返回结果 | 1095034606 |
参见 date_sunset()。
date_sunset() 返回给定的日期(以 timestamp 指定)与地点的日落时间。latitude,longitude 和 zenith 参数默认值分别为配置选项中的 date.default_latitude,date.default_longitude 和 date.sunrise_zenith。
latitude 默认是指北纬。因此如果要指定南纬,必须传递一个负值。同样规则也适用于 longitude,其默认是指东经。
gmt_offset 参数的单位是小时。
表格 1. format 常量
| 常量 | 说明 | 取值举例 |
|---|---|---|
| SUNFUNCS_RET_STRING | 以 string 格式返回结果 | 16:46 |
| SUNFUNCS_RET_DOUBLE | 以 float 格式返回结果 | 16.78243132 |
| SUNFUNCS_RET_TIMESTAMP | 以 integer 格式(时间戳)返回结果 | 1095034606 |
参见 date_sunrise()。
返回将整数 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 位数字 | 01 到 31 |
| D | 星期中的第几天,文本表示,3 个字母 | Mon 到 Sun |
| j | 月份中的第几天,没有前导零 | 1 到 31 |
| l(“L”的小写字母) | 星期几,完整的文本格式 | Sunday 到 Saturday |
| N | ISO-8601 格式数字表示的星期中的第几天(PHP 5.1.0 新加) | 1(表示星期一)到 7(表示星期天) |
| S | 每月天数后面的英文后缀,2 个字符 | st,nd,rd 或者 th。可以和 j 一起用 |
| w | 星期中的第几天,数字表示 | 0(表示星期天)到 6(表示星期六) |
| z | 年份中的第几天 | 0 到 366 |
| 星期 | --- | --- |
| W | ISO-8601 格式年份中的第几周,每周从星期一开始(PHP 4.1.0 新加的) | 例如:42(当年的第 42 周) |
| 月 | --- | --- |
| F | 月份,完整的文本格式,例如 January 或者 March | January 到 December |
| m | 数字表示的月份,有前导零 | 01 到 12 |
| M | 三个字母缩写表示的月份 | Jan 到 Dec |
| n | 数字表示的月份,没有前导零 | 1 到 12 |
| t | 给定月份所应有的天数 | 28 到 31 |
| 年 | --- | --- |
| L | 是否为闰年 | 如果是闰年为 1,否则为 0 |
| o | ISO-8601 格式年份数字。这和 Y 的值相同,只除了如果 ISO 的星期数(W)属于前一年或下一年,则用那一年。(PHP 5.1.0 新加) | Examples: 1999 or 2003 |
| Y | 4 位数字完整表示的年份 | 例如:1999 或 2003 |
| y | 2 位数字表示的年份 | 例如:99 或 03 |
| 时间 | --- | --- |
| a | 小写的上午和下午值 | am 或 pm |
| A | 大写的上午和下午值 | AM 或 PM |
| B | Swatch Internet 标准时 | 000 到 999 |
| g | 小时,12 小时格式,没有前导零 | 1 到 12 |
| G | 小时,24 小时格式,没有前导零 | 0 到 23 |
| h | 小时,12 小时格式,有前导零 | 01 到 12 |
| H | 小时,24 小时格式,有前导零 | 00 到 23 |
| i | 有前导零的分钟数 | 00 到 59> |
| s | 秒数,有前导零 | 00 到 59> |
| 时区 | --- | --- |
| e | 时区标识(PHP 5.1.0 新加) | 例如:UTC,GMT,Atlantic/Azores |
| I | 是否为夏令时 | 如果是夏令时为 1,否则为 0 |
| O | 与格林威治时间相差的小时数 | 例如:+0200 |
| T | 本机所在的时区 | 例如:EST,MDT(【译者注】在 Windows 下为完整文本格式,例如“Eastern Standard Time”,中文版会显示“中国标准时间”)。 |
| Z | 时差偏移量的秒数。UTC 西边的时区偏移量总是负的,UTC 东边的时区偏移量总是正的。 | -43200 到 43200 |
| 完整的日期/时间 | --- | --- |
| c | ISO 8601 格式的日期(PHP 5 新加) | 2004-02-12T15:19:21+00:00 |
| r | RFC 822 格式的日期 | 例如:Thu, 21 Dec 2000 16:01:07 +0200 |
| U | 从 Unix 纪元(January 1 1970 00:00:00 GMT)开始至今的秒数 | 参见 time() |
格式字串中不能被识别的字符将原样显示。Z 格式在使用 gmdate() 时总是返回 0。
例子 1. date() 例子
|
在格式字串中的字符前加上反斜线来转义可以避免它被按照上表解释。如果加上反斜线后的字符本身就是一个特殊序列,那还要转义反斜线。
可以把 date() 和 mktime() 结合使用来得到未来或过去的日期。
例子 3. date() 和 mktime() 例子
|
注: 由于夏令时的缘故,这种方法比简单地在时间戳上加减一天或者一个月的秒数更可靠。
一些使用 date() 格式化日期的例子。注意要转义所有其它的字符,因为目前有特殊含义的字符会产生不需要的结果,而其余字符在 PHP 将来的版本中可能会被用上。当转义时,注意用单引号以避免类似 \n 的字符变成了换行符。
例子 4. date() 格式举例
|
要格式化其它语种的日期,应该用 setlocale() 和 strftime() 函数。
返回一个根据 timestamp 得出的包含有日期信息的结合数组。如果没有给出时间戳则认为是当前本地时间。数组中的单元如下:
表格 1. 返回的关联数组中的键名单元
| 键名 | 说明 | 返回值例子 |
|---|---|---|
| "seconds" | 秒的数字表示 | 0 到 59 |
| "minutes" | 分钟的数字表示 | 0 到 59 |
| "hours" | 小时的数字表示 | 0 到 23 |
| "mday" | 月份中第几天的数字表示 | 1 到 31 |
| "wday" | 星期中第几天的数字表示 | 0(表示星期天)到 6(表示星期六) |
| "mon" | 月份的数字表示 | 1 到 12 |
| "year" | 4 位数字表示的完整年份 | 例如:1999 或 2003 |
| "yday" | 一年中第几天的数字表示 | 0 到 365 |
| "weekday" | 星期几的完整文本表示 | Sunday 到 Saturday |
| "month" | 月份的完整文本表示 | January> 到 December |
| 0 | 自从 Unix 纪元开始至今的秒数,和 time() 的返回值以及用于 date() 的值类似。 | 系统相关,典型值为从 -2147483648 到 2147483647。 |
参见 date(),time() 和 setlocale()。
本函数是 gettimeofday(2) 的接口。返回一个关联数组,包含有系统调用返回的数据。
自 PHP 5.1.0 起有个可选参数 return_float,当其设为 TRUE 时,gettimeofday() 会返回一个浮点数。
数组中的键为:
"sec" - 自 Unix 纪元起的秒数
"usec" - 微秒数
"minuteswest" - 格林威治向西的分钟数
"dsttime" - 夏令时修正的类型
同 date() 函数完全一样,只除了返回的时间是格林威治标准时(GMT)。例如当在中国(GMT +0800)运行以下程序时,第一行显示“Jan 01 2000 00:00:00”而第二行显示“Dec 31 1999 16:00:00”。
注: 在 PHP 5.1.0 之前,负的时间戳(1970 年之前的日期)在某些系统下(例如 Windows)不能工作。
参见 date(),mktime(),gmmktime() 和 strftime()。
和 mktime() 完全一样,只除了返回值是格林威治标准时的时间戳。
参数总是表示 GMT 日期,因此 is_dst 对结果没有影响。
和 mktime() 一样,参数可以从右到左依次空着,空着的参数会被设为相应的当前 GMT 值。
注: 自 5.1.0 起,is_dst 参数被废弃。因此应该用新的时区处理特性。
注: gmmktime() 内部使用了 mktime(),因此只有转换成本地时间也合法的时间才能用在其中。 so only times valid in derived local time can be used.
和 strftime() 的行为相同,只除了返回时间是格林威治标准时(GMT)。例如,当在东部标准时(EST,GMT -500)运行时,下面第一行显示“Dec 31 1998 20:00:00”,而第二行显示“Jan 01 1999 01:00:00”。
参见 strftime()。
根据给定的格式字符对 timestamp 格式化并返回数字结果。timestamp 为可选项,默认值为本地当前时间,即 time() 的值。
和 date() 不同,idate() 只接受一个字符作为 format 参数。
表格 1. format 参数可识别以下字符
| format 字符 | 说明 |
|---|---|
| B | Swatch 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) |
| W | ISO-8601 格式年份中的第几个星期,每星期从星期一开始 |
| y | 年份(1 或 2 位数字――见下面说明) |
| Y | 年份(4 位数字) |
| z | 年份中的第几天 |
| Z | 以秒为单位的时区偏移量 |
注: 因为 idate() 总是返回 integer,不能以“0”开头,因此 idate() 可能会返回比用户期望中要少的数字。见下面例子:
localtime() 函数返回一个数组,其结构和 C 函数调用返回的完全一样。localtime() 的第一个参数是时间戳,如果没有给出则使用从 time() 返回的当前时间。第二个参数是 is_associative,如果设为 FALSE 或未提供则返回的是普通的数字索引数组。如果该参数设为 TRUE 则 localtime() 函数返回包含有所有从 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() 例子
上例的输出类似于:
|
microtime() 当前 Unix 时间戳以及微秒数。本函数仅在支持 gettimeofday() 系统调用的操作系统下可用。
如果调用时不带可选参数,本函数以 "msec sec" 的格式返回一个字符串,其中 sec 是自 Unix 纪元(0:00:00 January 1, 1970 GMT)起到现在的秒数,msec 是微秒部分。字符串的两部分都是以秒为单位返回的。
如果给出了 get_as_float 参数并且其值等价于 TRUE,microtime() 将返回一个浮点数。
注: get_as_float 参数是 PHP 5.0.0 新加的。
例子 1. 用 microtime() 对脚本的运行计时
|
参见 time()。
根据给出的参数返回 Unix 时间戳。时间戳是一个长整数,包含了从 Unix 纪元(January 1 1970 00:00:00 GMT)到给定时间的秒数。
参数可以从右向左省略,任何省略的参数会被设置成本地日期和时间的当前值。
小时数。
分钟数。
秒数(一分钟之内)。
月份数。
天数。
年份数,可以是两位或四位数字,0-69 对应于 2000-2069,70-100 对应于 1970-2000。在如今系统中普遍把 time_t 作为一个 32 位有符号整数的情况下,year 的合法范围是 1901 到 2038 之间,不过此限制自 PHP 5.1.0 起已被克服了。
本参数可以设为 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 起,本参数已被废弃。应该使用新的时区处理特性来替代。
例子 2. 下个月的最后一天 任何给定月份的最后一天都可以被表示为下个月的第 "0" 天,而不是 -1 天。下面两个例子都会产生字符串 "The last day in Feb 2000 is: 29"。
|
返回用给定的格式字串对给出的 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 网站找到。
注: %G 和 %V,如果数字编号系统未能充分理解,基于 ISO 8601:1988 的星期数可能得出未预期的结果。见上面的 %V 和以下的例子。
例子 2. ISO 8601:1988 week number example
|
参见 setlocale(),mktime(),strptime() 以及 Open Group specification of strftime()。
strptime() 返回一个将 date 解析后的数组,如果出错返回 FALSE。
月份和星期几的名字以及其它与语种有关的字符串对应于 setlocale()设定的当前区域(LC_TIME)。
被解析的字符串(例如从 strftime() 返回的)
date 所使用的格式(例如同 strftime() 中所使用的相同)。
更多有关格式选项的信息见 strftime() 页面。
例子 1. strptime() 例子
上例的输出类似于:
|
本函数预期接受一个包含美国英语日期格式的字符串并尝试将其解析为 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。
| 警告 |
在 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 及更新的版本克服了此限制。
| 警告 |
本扩展模块是实验性的。本模块的行为,包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 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.
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 中,或者在运行时被动态加载后才有效。
表格 1. DB++ Error Codes
| PHP Constant | db++ constant | meaning |
|---|---|---|
| DBPLUS_ERR_NOERR (integer) | ERR_NOERR | Null error condition |
| DBPLUS_ERR_DUPLICATE (integer) | ERR_DUPLICATE | Tried to insert a duplicate tuple |
| DBPLUS_ERR_EOSCAN (integer) | ERR_EOSCAN | End of scan from rget() |
| DBPLUS_ERR_EMPTY (integer) | ERR_EMPTY | Relation is empty (server) |
| DBPLUS_ERR_CLOSE (integer) | ERR_CLOSE | The server can't close |
| DBPLUS_ERR_WLOCKED (integer) | ERR_WLOCKED | The record is write locked |
| DBPLUS_ERR_LOCKED (integer) | ERR_LOCKED | Relation was already locked |
| DBPLUS_ERR_NOLOCK (integer) | ERR_NOLOCK | Relation cannot be locked |
| DBPLUS_ERR_READ (integer) | ERR_READ | Read error on relation |
| DBPLUS_ERR_WRITE (integer) | ERR_WRITE | Write error on relation |
| DBPLUS_ERR_CREATE (integer) | ERR_CREATE | Create() system call failed |
| DBPLUS_ERR_LSEEK (integer) | ERR_LSEEK | Lseek() system call failed |
| DBPLUS_ERR_LENGTH (integer) | ERR_LENGTH | Tuple exceeds maximum length |
| DBPLUS_ERR_OPEN (integer) | ERR_OPEN | Open() system call failed |
| DBPLUS_ERR_WOPEN (integer) | ERR_WOPEN | Relation already opened for writing |
| DBPLUS_ERR_MAGIC (integer) | ERR_MAGIC | File is not a relation |
| DBPLUS_ERR_VERSION (integer) | ERR_VERSION | File is a very old relation |
| DBPLUS_ERR_PGSIZE (integer) | ERR_PGSIZE | Relation uses a different page size |
| DBPLUS_ERR_CRC (integer) | ERR_CRC | Invalid crc in the superpage |
| DBPLUS_ERR_PIPE (integer) | ERR_PIPE | Piped relation requires lseek() |
| DBPLUS_ERR_NIDX (integer) | ERR_NIDX | Too many secondary indices |
| DBPLUS_ERR_MALLOC (integer) | ERR_MALLOC | Malloc() call failed |
| DBPLUS_ERR_NUSERS (integer) | ERR_NUSERS | Error use of max users |
| DBPLUS_ERR_PREEXIT (integer) | ERR_PREEXIT | Caused by invalid usage |
| DBPLUS_ERR_ONTRAP (integer) | ERR_ONTRAP | Caused by a signal |
| DBPLUS_ERR_PREPROC (integer) | ERR_PREPROC | Error in the preprocessor |
| DBPLUS_ERR_DBPARSE (integer) | ERR_DBPARSE | Error in the parser |
| DBPLUS_ERR_DBRUNERR (integer) | ERR_DBRUNERR | Run error in db |
| DBPLUS_ERR_DBPREEXIT (integer) | ERR_DBPREEXIT | Exit condition caused by prexit() * procedure |
| DBPLUS_ERR_WAIT (integer) | ERR_WAIT | Wait a little (Simple only) |
| DBPLUS_ERR_CORRUPT_TUPLE (integer) | ERR_CORRUPT_TUPLE | A 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_FIFO | Can't create a fifo |
| DBPLUS_ERR_PERM (integer) | ERR_PERM | Permission denied |
| DBPLUS_ERR_TCL (integer) | ERR_TCL | TCL_error |
| DBPLUS_ERR_RESTRICTED (integer) | ERR_RESTRICTED | Only 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 |
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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.
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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.
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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.
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
Calling dbplus_close() will close a relation previously opened by dbplus_open().
Returns TRUE on success or DBPLUS_ERR_UNKNOWN on failure.
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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().
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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.
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
dbplus_errno() will return the error code returned by the last db++ operation.
See also dbplus_errcode().
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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().
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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().
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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.
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
dbplus_freealllocks() will free all tuple locks held by this client.
See also dbplus_getlock(), dbplus_freelock(), and dbplus_freerlocks().
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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().
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
dbplus_freerlocks() will free all tuple locks held on the given relation.
See also dbplus_getlock(), dbplus_freelock(), and dbplus_freealllocks().
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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().
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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.
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
| 警告 |
本函数暂无文档,仅有参数列表。 |
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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().
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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.
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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().
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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().
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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().
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
dbplus_rchperm() will change access permissions as specified by mask, user and group. The values for these are operating system specific.
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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.
(4.1.0 - 4.2.3 only, PECL)
dbplus_rcrtexact -- Creates an exact but empty copy of a relation including indices| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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.
(4.1.0 - 4.2.3 only, PECL)
dbplus_rcrtlike -- Creates an empty copy of a relation with default indices| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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.
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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().
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
| 警告 |
本函数暂无文档,仅有参数列表。 |
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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.
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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.
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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.
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
dbplus_rrename() will change the name of relation to name.
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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.
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
dbplus_unlink() will close and remove the relation.
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
dbplus_rzap() will remove all tuples from relation.
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
| 警告 |
本函数暂无文档,仅有参数列表。 |
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
| 警告 |
本函数暂无文档,仅有参数列表。 |
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
| 警告 |
本函数暂无文档,仅有参数列表。 |
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
| 警告 |
本函数暂无文档,仅有参数列表。 |
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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().
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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().
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
| 警告 |
本函数暂无文档,仅有参数列表。 |
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
| 警告 |
本函数暂无文档,仅有参数列表。 |
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
dbplus_unlockrel() will release a write lock previously obtained by dbplus_lockrel().
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
Calling dbplus_unselect() will remove a constraint previously set by dbplus_find() on relation.
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 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.
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
dbplus_xlockrel() will request an exclusive lock on relation preventing even read access from other clients.
See also dbplus_xunlockrel().
| 警告 |
本函数是实验性的。本函数的行为,包括函数名称以及其它任何关于本函数的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本函数风险自担。 |
dbplus_xunlockrel() will release an exclusive lock on relation previously obtained by dbplus_xlockrel().
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
| Field | dBase Type | Format | Additional informations |
|---|---|---|---|
| M | Memo | n/a | This type is not supported by PHP, such field will be ignored |
| D | Date | YYYYMMDD | The field length is limited to 8 |
| N | Number | A number | You must declare a length and a precision (the number of digits after the decimal point) |
| C | String | A string | You must declare a length. When retrieving data, the string will be right-padded with spaces to fit the declared length. |
| L | Boolean | T or Y for TRUE, F or N for FALSE | Stored 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.
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().
The database link identifier, returned by dbase_open() or dbase_create().
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.
dbase_create() creates a dBase database with the given definition.
注: 当安全模式被激活时,PHP 将检查被操作的文件或者目录是否与正在执行的脚本有相同的 UID(所有者)。
注: 本函数受 open_basedir 的影响。
The name of the database. It can be a relative or absolute path to the file where dBase will store your data.
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
|
Marks the given record to be deleted from the database.
注: To actually remove the record from the database, you must also call dbase_pack().
The database link identifier, returned by dbase_open() or dbase_create().
An integer which spans from 1 to the number of records in the database (as returned by dbase_numrecords()).
Returns information on the column structure of the given database link identifier.
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:
The name of the column
The human-readable name for the dbase type of the column (i.e. date, boolean, etc.)
The number of bytes this column can hold
The number of digits of decimal precision for the column
A suggested printf() format specifier for the column
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 3 >= 3.0.4, PHP 4, PHP 5)
dbase_get_record_with_names -- Gets a record from a database as an associative arrayGets a record from a dBase database as an associative array.
The database link identifier, returned by dbase_open() or dbase_create().
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
|
Gets a record from a database as an indexed array.
The database link identifier, returned by dbase_open() or dbase_create().
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.
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).
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_open() opens a dBase database with the given access mode.
注: 当安全模式被激活时,PHP 将检查被操作的文件或者目录是否与正在执行的脚本有相同的 UID(所有者)。
注: 本函数受 open_basedir 的影响。
The name of the database. It can be a relative or absolute path to the file where dBase will store your data.
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.
Returns a database link identifier if the database is successfully opened, or FALSE if an error occurred.
Packs the specified database by permanently deleting all records marked for deletion using dbase_delete_record().
Replaces the given record in the database with the given data.
The database link identifier, returned by dbase_open() or dbase_create().
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.
An integer which spans from 1 to the number of records in the database (as returned by dbase_numrecords()).
例子 1. Updating a record in the database
|
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.
The function dbmopen() returns an database identifier which is used by the other dbm-functions.
Deletes the value for key in the database.
Returns FALSE if the key didn't exist in the database.
Returns TRUE if there is a value associated with the key.
Returns the value associated with key.
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.
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().)
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:
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(所有者)。
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:
FrontBase (available from PHP 4.1.0).
Sybase-CT (available from PHP 4.2.0).
Oracle (oci8) (available from PHP 4.3.0).
SQLite (PHP 5).
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
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| dbx.colnames_case | "unchanged" | PHP_INI_SYSTEM | Available since PHP 4.3.0. |
以下是配置选项的简要解释。
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 中,或者在运行时被动态加载后才有效。
如果成功则返回 TRUE,失败则返回 FALSE。
注: Always refer to the module-specific documentation as well.
See also dbx_connect().
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
DBX_CMP_NATIVE - no type conversion
DBX_CMP_TEXT - compare items as strings
DBX_CMP_NUMBER - compare items numerically
例子 1. dbx_compare() example
|
See also dbx_sort().
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:
It is the name of the currently selected database.
It is a valid handle for the connected database, and as such it can be used in module-specific functions (if required).
It is used internally by dbx only, and is actually the module number mentioned above.
注: Always refer to the module-specific documentation as well.
See also dbx_close().
(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)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.
注: 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).
(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-statementdbx_escape_string() returns the text, escaped where necessary (such as quotes, backslashes etc). It returns NULL on error.
例子 1. dbx_escape_string() example
|
See also dbx_query().
(PHP 5 <= 5.0.4)
dbx_fetch_row -- Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag setdbx_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
|
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() 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
|
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.
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.
It provides info about columns, such as field names and field types.
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.
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.
The case of the returned column names will not be changed.
The case of the returned column names will be changed to uppercase.
The case of the returned column names will be changed to lowercase.
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:
It is a valid handle for the connected database, and as such it can be used in module specific functions (if required).
These contain the number of columns (or fields) and rows (or records) respectively.
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.
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"].
例子 4. How to handle UNBUFFERED queries
|
注: 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().
(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)
dbx_sort -- Sort a result from a dbx_query by a custom sort function如果成功则返回 TRUE,失败则返回 FALSE。
注: It is always better to use ORDER BY SQL clause instead of dbx_sort(), if possible.
例子 1. dbx_sort() example
|
See also dbx_compare().
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
以下常量由本扩展模块定义,因此只有在本扩展模块被编译到 PHP 中,或者在运行时被动态加载后才有效。
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 平台下实现。
The file descriptor returned by dio_open().
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 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)
例子 1. Setting and clearing a lock
|
(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 modedio_open() opens a file and returns a new file descriptor for it.
The opened file.
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.
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.
The function dio_read() reads and returns len bytes from file with descriptor fd.
The file descriptor returned by dio_open().
The number of bytes to read. If not specified, dio_read() reads 1K sized block.
The function dio_seek() is used to change the file position of the given file descriptor.
The file descriptor returned by dio_open().
The new position.
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
|
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
(PHP 4 >= 4.3.0, PHP 5 <= 5.0.4)
dio_tcsetattr -- Sets terminal attributes and baud rate for a serial portdio_tcsetattr() sets the terminal attributes and baud rate of the open fd.
注: 本函数未在 Windows 平台下实现。
The file descriptor returned by dio_open().
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
|
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 平台下实现。
dio_write() writes up to len bytes from data to file fd.
The file descriptor returned by dio_open().
The written data.
The length of data to write in bytes. If not specified, the function writes all the data to the specified file.
将当前进程的根目录改变为 directory。
本函数仅在系统支持且运行于 CLI,CGI 或嵌入 SAPI 版本时才能正确工作。此外本函数还需要 root 权限。
这是个仿冒面向对象的机制来读取一个目录。给定的 directory 被打开。一旦目录被打开,有两个属性可用。handle 属性可以用在其它目录函数例如 readdir(),rewinddir() 和 closedir() 中。path 属性被设为被打开的目录路径。有三个方法可用:read,rewind 和 close。
例子 1. dir() 例子 请留意下面例子中检查 dir() 返回值的风格。我们明确地测试返回值是否全等于(值和类型都相同 - 更多信息参见比较运算符)FALSE,否则任何目录项的名称求值为 FALSE 的都会导致循环停止。
上例的输出类似于:
|
成功则返回当前工作目录,失败返回 FALSE。
在某些 Unix 的变种下,如果任何父目录没有设定可读或搜索模式,即使当前目录设定了,getcwd() 还是会返回 FALSE。有关模式与权限的更多信息见 chmod()。
打开一个目录句柄,可用于之后的 closedir(),readdir() 和 rewinddir() 调用中。
如果成功则返回目录句柄的 resource,失败则返回 FALSE。
如果 path 不是一个合法的目录或者因为权限限制或文件系统错误而不能打开目录,opendir() 返回 FALSE 并产生一个 E_WARNING 级别的 PHP 错误信息。可以在 opendir() 前面加上“@”符号来抑制错误信息的输出。
例子 1. opendir() 例子
上例的输出类似于:
|
例子 1. 列出目录中的所有文件 请留意下面例子中检查 readdir() 返回值的风格。这里明确地测试返回值是否全等于(值和类型都相同――更多信息参见比较运算符)FALSE,否则任何目录项的名称求值为 FALSE 的都会导致循环停止(例如一个目录名为“0”)。
|
返回一个 array,包含有 directory 中的文件和目录。
要被浏览的目录
默认的排序顺序是按字母升序排列。如果使用了可选参数 sorting_order(设为 1),则排序顺序是按字母降序排列。
context 参数的说明见手册中的 Streams API 一章。
例子 2. scandir() 在 PHP 4 中的实现
上例的输出类似于:
|
提示: 如果“fopen wrappers”已经被激活,则在本函数中可以把 URL 作为文件名来使用。请参阅 fopen() 函数来获取怎样指定文件名的详细信息以及支持 URL 封装协议的列表:附录 L。
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.
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.
Extends DOMNode.
DOMCharacterData->appendData() - Append a 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
Extends DOMNode.
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 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 back 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
表格 3.
| Name | Type | Read-only | Description |
|---|---|---|---|
| actualEncoding | string | yes | |
| config | DOMConfiguration | yes | |
| doctype | DOMDocumentType | yes | The Document Type Declaration associated with this document. |
| documentElement | DOMElement | yes | This is a convenience attribute that allows direct access to the child node that is the document element of the document. |
| documentURI | string | no | The location of the document or NULL if undefined. |
| encoding | string | no | |
| formatOutput | bool | no | |
| implementation | DOMImplementation | yes | The DOMImplementation object that handles this document. |
| preserveWhiteSpace | bool | no | Do not remove redundant white space. Default to TRUE. |
| recover | bool | no | |
| resolveExternals | bool | no | Set it to TRUE to load external entities from a doctype declaration. This is useful for including character entities in your XML document. |
| standalone | bool | no | |
| strictErrorChecking | bool | no | Throws DOMException on errors. Default to TRUE. |
| substituteEntities | bool | no | |
| validateOnParse | bool | no | Loads and validates against the DTD. Default to FALSE. |
| version | string | no | |
| xmlEncoding | string | yes | 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. |
| xmlStandalone | bool | no | An attribute specifying, as part of the XML declaration, whether this document is standalone. This is FALSE when unspecified. |
| xmlVersion | string | no | 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". |
Extends DOMNode
Each DOMDocument has a doctype attribute whose value is either NULL or a DOMDocumentType object.
表格 4.
| Name | Type | Read-only | Description |
|---|---|---|---|
| publicId | string | yes | The public identifier of the external subset. |
| systemId | string | yes | The system identifier of the external subset. This may be an absolute URI or not. |
| name | string | yes | The name of DTD; i.e., the name immediately following the DOCTYPE keyword. |
| entities | DOMNamedNodeMap | yes | A DOMNamedNodeMap containing the general entities, both external and internal, declared in the DTD. |
| notations | DOMNamedNodeMap | yes | A DOMNamedNodeMap containing the notations declared in the DTD. |
| internalSubset | string | yes | The internal subset as a string, or null if there is none. This is does not contain the delimiting square brackets. |
Extends DOMNode.
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
Extends DOMNode
This interface represents a known entity, either parsed or unparsed, in an XML document.
表格 6.
| Name | Type | Read-only | Description |
|---|---|---|---|
| publicId | string | yes | The public identifier associated with the entity if specified, and NULL otherwise. |
| systemId | string | yes | The system identifier associated with the entity if specified, and NULL otherwise. This may be an absolute URI or not. |
| notationName | string | yes | For unparsed entities, the name of the notation for the entity. For parsed entities, this is NULL. |
| actualEncoding | string | no | 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. |
| encoding | string | yes | 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. |
| version | string | yes | 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. |
DOM operations raise exceptions under particular circumstances, i.e., when an operation is impossible to perform for logical reasons.
See also µÚ 20 章.
The DOMImplementation interface provides a number of methods for performing operations that are independent of any particular instance of the document object model.
DOMImplementation->createDocument() - Creates a DOM Document 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
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() - Returns namespace URI of the node based on the prefix
DOMNode->lookupPrefix() - Returns name space prefix of the node based on namespaceURI
DOMNode->normalize() - Normalizes the node
DOMNode->removeChild() - Removes child from list of children
DOMNode->replaceChild() - Replaces a child
表格 8.
| Name | Type | Read-only | Description |
|---|---|---|---|
| nodeName | string | yes | Returns the more accurate name for the current node type |
| nodeValue | string | no | The value of this node, depending on its type. |
| nodeType | int | yes | Gets the type of the node. One of the predefined XML_xxx_NODE constants |
| parentNode | DOMNode | yes | The parent of this node. |
| childNodes | DOMNodeList | yes | A DOMNodeList that contains all children of this node. If there are no children, this is an empty DOMNodeList. |
| firstChild | DOMNode | yes | The first child of this node. If there is no such node, this returns NULL. |
| lastChild | DOMNode | yes | The last child of this node. If there is no such node, this returns NULL. |
| previousSibling | DOMNode | yes | The node immediately preceding this node. If there is no such node, this returns NULL. |
| nextSibling | DOMNode | yes | The node immediately following this node. If there is no such node, this returns NULL. |
| attributes | DOMNamedNodeMap | yes | A DOMNamedNodeMap containing the attributes of this node (if it is a DOMElement) or NULL otherwise. |
| ownerDocument | DOMDocument | yes | The DOMDocument object associated with this node. |
| namespaceURI | string | yes | The namespace URI of this node, or NULL if it is unspecified. |
| prefix | string | no | The namespace prefix of this node, or NULL if it is unspecified. |
| localName | string | yes | Returns the local part of the qualified name of this node. |
| baseURI | string | yes | The absolute base URI of this node or NULL if the implementation wasn't able to obtain an absolute URI. |
| textContent | string | no | This attribute returns the text content of this node and its descendants. |
Extends DOMCharacterData.
DOMText->isWhitespaceInElementContent() - Indicates whether this text node contains whitespace
DOMText->splitText() - Breaks the node into two nodes at the specified offset
DOMXPath->registerNamespace() - Registers the namespace with the DOMXpath object
DOMXPath->evaluate() - Evaluates the given XPath expression and returns a typed result if possible
DOMXPath->query() - Evaluates the given XPath expression
Many examples in this reference require an XML file. We will use book.xml that contains the following:
例子 1. chapter.xml
|
以下常量由本扩展模块定义,因此只有在本扩展模块被编译到 PHP 中,或者在运行时被动态加载后才有效。
表格 14. XML constants
| Constant | Value | Description |
|---|---|---|
| XML_ELEMENT_NODE (integer) | 1 | Node is a DOMElement |
| XML_ATTRIBUTE_NODE (integer) | 2 | Node is a DOMAttr |
| XML_TEXT_NODE (integer) | 3 | Node is a DOMText |
| XML_CDATA_SECTION_NODE (integer) | 4 | Node is a DOMCharacterData |
| XML_ENTITY_REF_NODE (integer) | 5 | Node is a DOMEntityReference |
| XML_ENTITY_NODE (integer) | 6 | Node is a DOMEntity |
| XML_PI_NODE (integer) | 7 | Node is a DOMProcessingInstruction |
| XML_COMMENT_NODE (integer) | 8 | Node is a DOMComment |
| XML_DOCUMENT_NODE (integer) | 9 | Node is a DOMDocument |
| XML_DOCUMENT_TYPE_NODE (integer) | 10 | Node is a DOMDocumentType |
| XML_DOCUMENT_FRAG_NODE (integer) | 11 | Node is a DOMDocumentFragment |
| XML_NOTATION_NODE (integer) | 12 | Node 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
| Constant | Value | Description |
|---|---|---|
| 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) | 3 | If 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) | 12 | If an invalid or illegal string is specified. |
| DOM_INVALID_MODIFICATION_ERR (integer) | 13 | If 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. |
(no version information, might be only in CVS)
DOMAttr->__construct() -- Creates a new DOMAttr objectCreates 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().
例子 1. Creating a new DOMAttr
|
(no version information, might be only in CVS)
DOMAttr->isId() -- Checks if attribute is a defined IDThis 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.
例子 1. DOMAttr->isId() Example
|
(no version information, might be only in CVS)
DOMCharacterData->appendData() -- Append the string to the end of the character data of the nodeAppend the string data to the end of the character data of the node.
| DOMCharacterData->deleteData() |
| DOMCharacterData->insertData() |
| DOMCharacterData->replaceData() |
| DOMCharacterData->substringData() |
(no version information, might be only in CVS)
DOMCharacterData->deleteData() -- Remove a range of characters from the nodeDeletes count characters starting from position offset.
The offset from which to start removing.
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.
Raised if offset is negative or greater than the number of 16-bit units in data, or if count is negative.
| DOMCharacterData->appendData() |
| DOMCharacterData->insertData() |
| DOMCharacterData->replaceData() |
| DOMCharacterData->substringData() |
(no version information, might be only in CVS)
DOMCharacterData->insertData() -- Insert a string at the specified 16-bit unit offsetInserts string data at position offset.
Raised if offset is negative or greater than the number of 16-bit units in data.
| DOMCharacterData->appendData() |
| DOMCharacterData->deleteData() |
| DOMCharacterData->replaceData() |
| DOMCharacterData->substringData() |
(no version information, might be only in CVS)
DOMCharacterData->replaceData() -- Replace a substring within the DOMCharacterData nodeReplace count characters starting from position offset with data.
The offset from which to start replacing.
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.
The string with which the range must be replaced.
Raised if offset is negative or greater than the number of 16-bit units in data, or if count is negative.
| DOMCharacterData->appendData() |
| DOMCharacterData->deleteData() |
| DOMCharacterData->insertData() |
| DOMCharacterData->substringData() |
(no version information, might be only in CVS)
DOMCharacterData->substringData() -- Extracts a range of data from the nodeReturns the specified substring.
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.
Raised if offset is negative or greater than the number of 16-bit units in data, or if count is negative.
| DOMCharacterData->appendData() |
| DOMCharacterData->deleteData() |
| DOMCharacterData->insertData() |
| DOMCharacterData->replaceData() |
(no version information, might be only in CVS)
DOMComment->__construct() -- Creates a new DOMComment objectCreates 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().
例子 1. Creating a new DOMComment
|
(no version information, might be only in CVS)
DOMDocument->__construct() -- Creates a new DOMDocument objectCreates a new DOMDocument object.
The version number of the document as part of the XML declaration.
The encoding of the document as part of the XML declaration.
(no version information, might be only in CVS)
DOMDocument->createAttribute() -- Create new attributeThis function creates a new instance of class DOMAttr. 本节点不会出现在文档中,除非是用例如 DOMNode->appendChild() 函数来将其插入。
| DOMNode->appendChild() |
| DOMDocument->createAttributeNS() |
| DOMDocument->createCDATASection() |
| DOMDocument->createComment() |
| DOMDocument->createDocumentFragment() |
| DOMDocument->createElement() |
| DOMDocument->createElementNS() |
| DOMDocument->createEntityReference() |
| DOMDocument->createProcessingInstruction() |
| DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createAttributeNS() -- Create new attribute node with an associated namespaceThis function creates a new instance of class DOMAttr. 本节点不会出现在文档中,除非是用例如 DOMNode->appendChild() 函数来将其插入。
The URI of the namespace.
The tag name and prefix of the attribute, as prefix:tagname.
Raised if qualifiedName contains an invalid character.
Raised if qualifiedName is a malformed qualified name, or if qualifiedName has a prefix and namespaceURI is NULL.
| DOMNode->appendChild() |
| DOMDocument->createAttribute() |
| DOMDocument->createCDATASection() |
| DOMDocument->createComment() |
| DOMDocument->createDocumentFragment() |
| DOMDocument->createElement() |
| DOMDocument->createElementNS() |
| DOMDocument->createEntityReference() |
| DOMDocument->createProcessingInstruction() |
| DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createCDATASection() -- Create new cdata nodeThis function creates a new instance of class DOMCDATASection. 本节点不会出现在文档中,除非是用例如 DOMNode->appendChild() 函数来将其插入。
| DOMNode->appendChild() |
| DOMDocument->createAttribute() |
| DOMDocument->createAttributeNS() |
| DOMDocument->createComment() |
| DOMDocument->createDocumentFragment() |
| DOMDocument->createElement() |
| DOMDocument->createElementNS() |
| DOMDocument->createEntityReference() |
| DOMDocument->createProcessingInstruction() |
| DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createComment() -- Create new comment nodeThis function creates a new instance of class DOMComment. 本节点不会出现在文档中,除非是用例如 DOMNode->appendChild() 函数来将其插入。
| DOMNode->appendChild() |
| DOMDocument->createAttribute() |
| DOMDocument->createAttributeNS() |
| DOMDocument->createCDATASection() |
| DOMDocument->createDocumentFragment() |
| DOMDocument->createElement() |
| DOMDocument->createElementNS() |
| DOMDocument->createEntityReference() |
| DOMDocument->createProcessingInstruction() |
| DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createDocumentFragment() -- Create new document fragmentThis function creates a new instance of class DOMDocumentFragment. 本节点不会出现在文档中,除非是用例如 DOMNode->appendChild() 函数来将其插入。
| DOMNode->appendChild() |
| DOMDocument->createAttribute() |
| DOMDocument->createAttributeNS() |
| DOMDocument->createCDATASection() |
| DOMDocument->createComment() |
| DOMDocument->createElement() |
| DOMDocument->createElementNS() |
| DOMDocument->createEntityReference() |
| DOMDocument->createProcessingInstruction() |
| DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createElement() -- Create new element nodeThis function creates a new instance of class DOMElement. 本节点不会出现在文档中,除非是用例如 DOMNode->appendChild() 函数来将其插入。
The tag name of the element.
The value of the element. By default, an empty element will be created. You can also set the value later with DOMElement->nodeValue.
例子 1. Creating a new element and inserting it as root
上例将输出:
|
| DOMNode->appendChild() |
| DOMDocument->createAttribute() |
| DOMDocument->createAttributeNS() |
| DOMDocument->createCDATASection() |
| DOMDocument->createComment() |
| DOMDocument->createDocumentFragment() |
| DOMDocument->createElementNS() |
| DOMDocument->createEntityReference() |
| DOMDocument->createProcessingInstruction() |
| DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createElementNS() -- Create new element node with an associated namespaceThis function creates a new element node with an associated namespace. 本节点不会出现在文档中,除非是用例如 DOMNode->appendChild() 函数来将其插入。
The URI of the namespace.
The qualified name of the element, as prefix:tagname.
The value of the element. By default, an empty element will be created. You can also set the value later with DOMElement->nodeValue.
Raised if qualifiedName contains an invalid character.
Raised if qualifiedName is a maformed qualified name.
例子 1. Creating a new element and inserting it as root
上例将输出:
|
| DOMNode->appendChild() |
| DOMDocument->createAttribute() |
| DOMDocument->createAttributeNS() |
| DOMDocument->createCDATASection() |
| DOMDocument->createComment() |
| DOMDocument->createDocumentFragment() |
| DOMDocument->createElement() |
| DOMDocument->createEntityReference() |
| DOMDocument->createProcessingInstruction() |
| DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createEntityReference() -- Create new entity reference nodeThis function creates a new instance of class DOMEntityReference. 本节点不会出现在文档中,除非是用例如 DOMNode->appendChild() 函数来将其插入。
The content of the entity reference, e.g. the entity reference minus the leading & and the trailing ; characters.
| DOMNode->appendChild() |
| DOMDocument->createAttribute() |
| DOMDocument->createAttributeNS() |
| DOMDocument->createCDATASection() |
| DOMDocument->createComment() |
| DOMDocument->createDocumentFragment() |
| DOMDocument->createElement() |
| DOMDocument->createElementNS() |
| DOMDocument->createProcessingInstruction() |
| DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createProcessingInstruction() -- Creates new PI nodeThis function creates a new instance of class DOMProcessingInstruction. 本节点不会出现在文档中,除非是用例如 DOMNode->appendChild() 函数来将其插入。
| DOMNode->appendChild() |
| DOMDocument->createAttribute() |
| DOMDocument->createAttributeNS() |
| DOMDocument->createCDATASection() |
| DOMDocument->createComment() |
| DOMDocument->createDocumentFragment() |
| DOMDocument->createElement() |
| DOMDocument->createElementNS() |
| DOMDocument->createEntityReference() |
| DOMDocument->createTextNode() |
This function creates a new instance of class DOMText. 本节点不会出现在文档中,除非是用例如 DOMNode->appendChild() 函数来将其插入。
| DOMNode->appendChild() |
| DOMDocument->createAttribute() |
| DOMDocument->createAttributeNS() |
| DOMDocument->createCDATASection() |
| DOMDocument->createComment() |
| DOMDocument->createDocumentFragment() |
| DOMDocument->createElement() |
| DOMDocument->createElementNS() |
| DOMDocument->createEntityReference() |
| DOMDocument->createProcessingInstruction() |
(no version information, might be only in CVS)
DOMDocument->getElementById() -- Searches for an element with a certain idThis 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.
例子 1. DOMDocument->getElementById() Example
上例将输出:
|
(no version information, might be only in CVS)
DOMDocument->getElementsByTagName() -- Searches for all elements with given tag nameThis function returns a new instance of class DOMNodeList containing the elements with a given tag name.
(no version information, might be only in CVS)
DOMDocument->getElementsByTagNameNS() -- Searches for all elements with given tag name in specified namespaceReturns a DOMNodeList of all elements with a given local name and a namespace URI.
The namespace URI of the elements to match on. The special value * matches all namespaces.
The local name of the elements to match on. The special value * matches all local names.
例子 1. Get all the XInclude elements
上例将输出:
|
(no version information, might be only in CVS)
DOMDocument->importNode() -- Import node into current documentThis function returns a copy of the node to import and associates it with the current document.
The node to import.
If set to TRUE, this method will recursively import the subtree under the importedNode.
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.
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.
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.
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.
(no version information, might be only in CVS)
DOMDocument->relaxNGValidate() -- Performs relaxNG validation on the documentPerforms relaxNG validation on the document based on the given RNG schema.
| DOMDocument->relaxNGValidateSource() |
| DOMDocument->schemaValidate() |
| DOMDocument->schemaValidateSource() |
| DOMDocument->validate() |
(no version information, might be only in CVS)
DOMDocument->relaxNGValidateSource() -- Performs relaxNG validation on the documentPerforms relaxNG validation on the document based on the given RNG source.
| DOMDocument->relaxNGValidate() |
| DOMDocument->schemaValidate() |
| DOMDocument->schemaValidateSource() |
| DOMDocument->validate() |
(no version information, might be only in CVS)
DOMDocument->save() -- Dumps the internal XML tree back into a fileCreates 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.
The path to the saved XML document.
Additional Options. Currently only LIBXML_NOEMPTYTAG is supported.
例子 1. Saving a DOM tree into a file
|
(no version information, might be only in CVS)
DOMDocument->saveHTML() -- Dumps the internal document into a string using HTML formattingCreates 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.
例子 1. Saving a HTML tree into a string
|
(no version information, might be only in CVS)
DOMDocument->saveHTMLFile() -- Dumps the internal document into a file using HTML formattingCreates 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.
例子 1. Saving a HTML tree into a file
|
(no version information, might be only in CVS)
DOMDocument->saveXML() -- Dumps the internal XML tree back into a stringCreates 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.
Use this parameter to output only a specific node without XML declaration rather than the entire document.
Additional Options. Currently only LIBXML_NOEMPTYTAG is supported.
例子 1. Saving a DOM tree into a string
上例将输出:
|
(no version information, might be only in CVS)
DOMDocument->schemaValidate() -- Validates a document based on a schemaValidates a document based on the given schema file.
| DOMDocument->schemaValidateSource() |
| DOMDocument->relaxNGValidate() |
| DOMDocument->relaxNGValidateSource() |
| DOMDocument->validate() |
(no version information, might be only in CVS)
DOMDocument->schemaValidateSource() -- Validates a document based on a schemaValidates a document based on a schema defined in the given string.
| DOMDocument->schemaValidate() |
| DOMDocument->relaxNGValidate() |
| DOMDocument->relaxNGValidateSource() |
| DOMDocument->validate() |
(no version information, might be only in CVS)
DOMDocument->validate() -- Validates the document based on its DTDValidates the document based on its DTD.
You can also use the validateOnParse property of DOMDocument to make a DTD validation.
| DOMDocument->schemaValidate() |
| DOMDocument->schemaValidateSource() |
| DOMDocument->relaxNGValidate() |
| DOMDocument->relaxNGValidateSource() |
(no version information, might be only in CVS)
DOMDocument->xinclude() -- Substitutes XIncludes in a DOMDocument ObjectThis 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.
例子 1. DOMDocument->xinclude() example
上例的输出类似于:
|
(no version information, might be only in CVS)
DOMElement->__construct() -- Creates a new DOMElement objectCreates 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().
The tag name of the element. When also passing in namespaceURI, the element name may take a prefix to be associated with the URI.
The value of the element.
A namespace URI to create the element within a specific namespace.
例子 1. Creating a new DOMElement
|
(no version information, might be only in CVS)
DOMElement->getAttribute() -- Returns value of attributeGets the value of the attribute with name name for the current node.
(no version information, might be only in CVS)
DOMElement->getAttributeNode() -- Returns attribute nodeReturns the attribute node with name name for the current element.
(no version information, might be only in CVS)
DOMElement->getAttributeNodeNS() -- Returns attribute nodeReturns the attribute node in namespace namespaceURI with local name localName for the current node.
(no version information, might be only in CVS)
DOMElement->getAttributeNS() -- Returns value of attributeGets the value of the attribute in namespace namespaceURI with local name localName for the current node.
The value of the attribute, or an empty string if no attribute with the given localName and namespaceURI is found.
(no version information, might be only in CVS)
DOMElement->getElementsByTagName() -- Gets elements by tagnameThis 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.
(no version information, might be only in CVS)
DOMElement->getElementsByTagNameNS() -- Get elements by namespaceURI and localNameThis function fetch all the descendant elements with a given localName and namespaceURI.
The namespace URI.
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.
(no version information, might be only in CVS)
DOMElement->hasAttribute() -- Checks to see if attribute existsIndicates whether attribute named name exists as a member of the element.
| DOMElement->hasAttributeNS() |
| DOMElement->getAttribute() |
| DOMElement->setAttribute() |
| DOMElement->removeAttribute() |
(no version information, might be only in CVS)
DOMElement->hasAttributeNS() -- Checks to see if attribute existsIndicates whether attribute in namespace namespaceURI named localName exists as a member of the element.
| DOMElement->hasAttribute() |
| DOMElement->getAttributeNS() |
| DOMElement->setAttributeNS() |
| DOMElement->removeAttributeNS() |
Removes attribute named name from the element.
(no version information, might be only in CVS)
DOMElement->removeAttributeNode() -- Removes attributeRemoves attribute oldnode from the element.
Raised if the node is readonly.
Raised if oldnode is not an attribute of the element.
Removes attribute is namespace namespaceURI named localName from the element.
Sets an attribute with name name to the given value. If the attribute does not exist, it will be created.
(no version information, might be only in CVS)
DOMElement->setAttributeNode() -- Adds new attribute node to elementAdds new attribute node attr to element.
(no version information, might be only in CVS)
DOMElement->setAttributeNodeNS() -- Adds new attribute node to elementAdds new attribute node attr to element.
Sets an attribute with namespace namespaceURI and name name to the given value. If the attribute does not exist, it will be created.
The namespace URI.
The qualified name of the attribute, as prefix:tagname.
The value of the attribute.
Raised if the node is readonly.
Raised if qualifiedName is a malformed qualified name, or if qualifiedName has a prefix and namespaceURI is NULL.
(no version information, might be only in CVS)
DOMAttr->__construct() -- Creates a new DOMEntityReference object
例子 1. Creating a new DOMEntityReference
|
(no version information, might be only in CVS)
DOMImplementation->__construct() -- Creates a new DOMImplementation object(no version information, might be only in CVS)
DOMImplementation->createDocument() -- Creates a DOMDocument object of the specified type with its document elementCreates a DOMDocument object of the specified type with its document element.
The namespace URI of the document element to create.
The qualified name of the document element to create.
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
Raised if doctype has already been used with a different document or was created from a different implementation.
Raised if there is an error with the namespace, as determined by namespaceURI and qualifiedName.
(no version information, might be only in CVS)
DOMImplementation->createDocumentType() -- Creates an empty DOMDocumentType objectCreates an empty DOMDocumentType object. Entity declarations and notations are not made available. Entity reference expansions and default attribute additions do not occur.
The qualified name of the document type to create.
The external subset public identifier.
The external subset system identifier.
例子 1. Creating a document with an attached DTD
上例将输出:
|
Raised if there is an error with the namespace, as determined by qualifiedName.
(no version information, might be only in CVS)
DOMImplementation->hasFeature() -- Test if the DOM implementation implements a specific featureTest if the DOM implementation implements a specific feature.
You can find a list of all features in the Conformance section of the DOM specification.
The feature to test.
The version number of the feature to test. In level 2, this can be either 2.0 or 1.0.
例子 1. Testing your DOM Implementation
|
(no version information, might be only in CVS)
DOMNamedNodeMap->getNamedItem() -- Retrieves a node specified by nameRetrieves a node specified by its nodeName.
(no version information, might be only in CVS)
DOMNamedNodeMap->getNamedItemNS() -- Retrieves a node specified by local name and namespace URIRetrieves a node specified by localName and namespaceURI.
The namespace URI of the node to retrieve.
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.
(no version information, might be only in CVS)
DOMNamedNodeMap->item() -- Retrieves a node specified by indexRetrieves a node specified by index within the DOMNamedNodeMap object.
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).
(no version information, might be only in CVS)
DOMNode->appendChild() -- Adds new child at the end of the childrenThis 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.
Raised if this node is readonly or if the previous parent of the node being inserted is readonly.
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.
Raised if newnode was created from a different document than the one that created this node.
(no version information, might be only in CVS)
DOMNode->hasAttributes() -- Checks if node has attributesThis method checks if the node has attributes. The tested node have to be an XML_ELEMENT_NODE.
(no version information, might be only in CVS)
DOMNode->hasChildNodes() -- Checks if node has children(no version information, might be only in CVS)
DOMNode->insertBefore() -- Adds a new child before a reference nodeThis 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.
The new node.
The reference node. If not supplied, newnode is appended to the children.
Raised if this node is readonly or if the previous parent of the node being inserted is readonly.
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.
Raised if newnode was created from a different document than the one that created this node.
Raised if refnode is not a child of this node.
(no version information, might be only in CVS)
DOMNode->isSameNode() -- Indicates if two nodes are the same nodeThis function indicates if two nodes are the same node. The comparison is not based on content
(no version information, might be only in CVS)
DOMNode->isSupported() -- Checks if feature is supported for specified versionChecks if the asked feature is supported for the specified version.
The feature to test. See the example of DOMImplementation->hasFeature() for a list of features.
The version number of the feature to test.
(no version information, might be only in CVS)
DOMNode->lookupNamespaceURI() -- Gets the namespace URI of the node based on the prefixGets the namespace URI of the node based on the prefix.
(no version information, might be only in CVS)
DOMNode->lookupPrefix() -- Gets the namespace prefix of the node based on the namespace URIGets the namespace prefix of the node based on the namespace URI.
(no version information, might be only in CVS)
DOMNode->removeChild() -- Removes child from list of childrenThis functions removes a child from a list of children.
Raised if this node is readonly.
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
上例将输出:
|
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.
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().
The old node.
Raised if this node is readonly or if the previous parent of the node being inserted is readonly.
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.
Raised if newnode was created from a different document than the one that created this node.
Raised if oldnode is not a child of this node.
(no version information, might be only in CVS)
DOMNodelist->item() -- Retrieves a node specified by indexRetrieves 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.
例子 1. Traversing all the entries of the table
Alternatively, you can use foreach, which is a much more convenient way:
上例将输出:
|
(no version information, might be only in CVS)
DOMProcessingInstruction->__construct() -- Creates a new DOMProcessingInstruction objectCreates 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().
例子 1. Creating a new DOMProcessingInstruction
上例将输出:
|
(no version information, might be only in CVS)
DOMText->__construct() -- Creates a new DOMText object(no version information, might be only in CVS)
DOMText->isWhitespaceInElementContent() -- Indicates whether this text node contains whitespaceIndicates whether this text node contains whitespace. The text node is determined to contain whitespace in element content during the load of the document.
(no version information, might be only in CVS)
DOMText->splitText() -- Breaks this node into two nodes at the specified offsetBreaks 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.
(no version information, might be only in CVS)
DOMXPath->__construct() -- Creates a new DOMXPath object(no version information, might be only in CVS)
DOMXPath->evaluate() -- Evaluates the given XPath expression and returns a typed result if possible.Executes the given XPath expression and returns a typed result if possible.
The XPath expression to execute.
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
上例将输出:
|
(no version information, might be only in CVS)
DOMXPath->query() -- Evaluates the given XPath expressionExecutes the given XPath expression.
The XPath expression to execute.
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
上例将输出:
We can also use the contextnode parameter to shorten our expression:
|
(no version information, might be only in CVS)
DOMXPath->registerNamespace() -- Registers the namespace with the DOMXPath objectRegisters the namespaceURI and prefix with the DOMXPath object.
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.
例子 1. Import SimpleXML into DOM with dom_import_simplexml()
|
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 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.
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 function | New function |
|---|---|
| xmldoc | domxml_open_mem() |
| xmldocfile | domxml_open_file() |
| domxml_new_xmldoc | domxml_new_doc() |
| domxml_dump_mem | DomDocument_dump_mem() |
| domxml_dump_mem_file | DomDocument_dump_file() |
| DomDocument_dump_mem_file | DomDocument_dump_file() |
| DomDocument_add_root | DomDocument_create_element() followed by DomNode_append_child() |
| DomDocument_dtd | DomDocument_doctype() |
| DomDocument_root | DomDocument_document_element() |
| DomDocument_children | DomNode_child_nodes() |
| DomDocument_imported_node | No replacement. |
| DomNode_add_child | Create a new node with e.g. DomDocument_create_element() and add it with DomNode_append_child(). |
| DomNode_children | DomNode_child_nodes() |
| DomNode_parent | DomNode_parent_node() |
| DomNode_new_child | Create a new node with e.g. DomDocument_create_element() and add it with DomNode_append_child(). |
| DomNode_set_content | Create a new node with e.g. DomDocument_create_text_node() and add it with DomNode_append_child(). |
| DomNode_get_content | Content is just a text node and can be accessed with DomNode_child_nodes(). |
| DomNode_set_content | Content is just a text node and can be added with DomNode_append_child(). |
以下常量由本扩展模块定义,因此只有在本扩展模块被编译到 PHP 中,或者在运行时被动态加载后才有效。
表格 2. XML constants
| Constant | Value | Description |
|---|---|---|
| XML_ELEMENT_NODE (integer) | 1 | Node is an element |
| XML_ATTRIBUTE_NODE (integer) | 2 | Node is an attribute |
| XML_TEXT_NODE (integer) | 3 | Node is a piece of text |
| XML_CDATA_SECTION_NODE (integer) | 4 | |
| XML_ENTITY_REF_NODE (integer) | 5 | |
| XML_ENTITY_NODE (integer) | 6 | Node is an entity like |
| XML_PI_NODE (integer) | 7 | Node is a processing instruction |
| XML_COMMENT_NODE (integer) | 8 | Node is a comment |
| XML_DOCUMENT_NODE (integer) | 9 | Node 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) |
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 name | Parent classes |
|---|---|
| DomAttribute | DomNode |
| DomCData | DomNode |
| DomComment | DomCData : DomNode |
| DomDocument | DomNode |
| DomDocumentType | DomNode |
| DomElement | DomNode |
| DomEntity | DomNode |
| DomEntityReference | DomNode |
| DomProcessingInstruction | DomNode |
| DomText | DomCData : DomNode |
| Parser | Currently still called DomParser |
| XPathContext |
表格 4. DomDocument class (DomDocument : DomNode)
| Method name | Function name | Remark |
|---|---|---|
| doctype | DomDocument_doctype() | |
| document_element | DomDocument_document_element() | |
| create_element | DomDocument_create_element() | |
| create_text_node | DomDocument_create_text_node() | |
| create_comment | DomDocument_create_comment() | |
| create_cdata_section | DomDocument_create_cdata_section() | |
| create_processing_instruction | DomDocument_create_processing_instruction() | |
| create_attribute | DomDocument_create_attribute() | |
| create_entity_reference | DomDocument_create_entity_reference() | |
| get_elements_by_tagname | DomDocument_get_elements_by_tagname() | |
| get_element_by_id | DomDocument_get_element_by_id() | |
| dump_mem | DomDocument_dump_mem() | not DOM standard |
| dump_file | DomDocument_dump_file() | not DOM standard |
| html_dump_mem | DomDocument_html_dump_mem() | not DOM standard |
| xpath_init | xpath_init | not DOM standard |
| xpath_new_context | xpath_new_context | not DOM standard |
| xptr_new_context | xptr_new_context | not DOM standard |
表格 5. DomElement class (DomElement : DomNode)
| Method name | Function name | Remark |
|---|---|---|
| tagname | DomElement_tagname() | |
| get_attribute | DomElement_get_attribute() | |
| set_attribute | DomElement_set_attribute() | |
| remove_attribute | DomElement_remove_attribute() | |
| get_attribute_node | DomElement_get_attribute_node() | |
| get_elements_by_tagname | DomElement_get_elements_by_tagname() | |
| has_attribute | DomElement_has_attribute() |
表格 6. DomNode class
| Method name | Remark |
|---|---|
| DomNode_node_name() | |
| DomNode_node_value() | |
| DomNode_node_type() | |
| DomNode_last_child() | |
| DomNode_first_child() | |
| DomNode_child_nodes() | |
| DomNode_previous_sibling() | |
| DomNode_next_sibling() | |
| DomNode_parent_node() | |
| DomNode_owner_document() | |
| DomNode_insert_before() | |
| DomNode_append_child() | |
| DomNode_append_sibling() | Not in DOM standard. This function emulates the former behaviour of DomNode_append_child(). |
| DomNode_remove_child() | |
| DomNode_has_child_nodes() | |
| DomNode_has_attributes() | |
| DomNode_clone_node() | |
| DomNode_attributes() | |
| DomNode_unlink_node() | Not in DOM standard |
| DomNode_replace_node() | Not in DOM standard |
| DomNode_set_content() | Not in DOM standard, deprecated |
| DomNode_get_content() | Not in DOM standard, deprecated |
| DomNode_dump_node() | Not in DOM standard |
| DomNode_is_blank_node() | Not in DOM standard |
表格 7. DomAttribute class (DomAttribute : DomNode)
| Method name | Remark | |
|---|---|---|
| name | DomAttribute_name() | |
| value | DomAttribute_value() | |
| specified | DomAttribute_specified() |
表格 8. DomProcessingInstruction class (DomProcessingInstruction : DomNode)
| Method name | Function name | Remark |
|---|---|---|
| target | DomProcessingInstruction_target() | |
| data | DomProcessingInstruction_data() |
表格 10. XPathContext class
| Method name | Function name | Remark |
|---|---|---|
| eval | XPathContext_eval() | |
| eval_expression | XPathContext_eval_expression() | |
| register_ns | XPathContext_register_ns() |
表格 11. DomDocumentType class (DomDocumentType : DomNode)
| Method name | Function name | Remark |
|---|---|---|
| name | DomDocumentType_name() | |
| entities | DomDocumentType_entities() | |
| notations | DomDocumentType_notations() | |
| public_id | DomDocumentType_public_id() | |
| system_id | DomDocumentType_system_id() | |
| internal_subset | DomDocumentType_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
|
(no version information, might be only in CVS)
DomAttribute->set_value -- Sets the value of an attributeThis function sets the value of an attribute.
(no version information, might be only in CVS)
DomAttribute->specified -- Checks if attribute is specifiedChecks if the attribute was explicitly given a value in the original document.
注: This method is not implemented yet.
例子 1. Getting all the attributes of a node
上例将输出:
|
(no version information, might be only in CVS)
DomDocument->add_root -- Adds a root node [deprecated]Adds a root element node to a dom document and returns the new node. The element name is given in the passed parameter.
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().
(no version information, might be only in CVS)
DomDocument->create_cdata_section -- Create new cdata nodeThis 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().
(no version information, might be only in CVS)
DomDocument->create_comment -- Create new comment nodeThis 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().
(no version information, might be only in CVS)
DomDocument->create_element_ns -- Create new element node with an associated namespaceThis 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().
(no version information, might be only in CVS)
DomDocument->create_element -- Create new element nodeThis 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().
(no version information, might be only in CVS)
DomDocument->create_entity_reference -- Create an entity referenceThis 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().
(no version information, might be only in CVS)
DomDocument->create_processing_instruction -- Creates new PI nodeThis 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().
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().
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.
(no version information, might be only in CVS)
DomDocument->document_element -- Returns root element nodeThis 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.
(no version information, might be only in CVS)
DomDocument->dump_file -- Dumps the internal XML tree back into a fileCreates 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
|
See also domdocument_dump_mem(), and domdocument_html_dump_mem().
(no version information, might be only in CVS)
DomDocument->dump_mem -- Dumps the internal XML tree back into a stringCreates 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
|
注: The first parameter was added in PHP 4.3.0.
See also domdocument_dump_file(), and domdocument_html_dump_mem().
(no version information, might be only in CVS)
DomDocument->get_element_by_id -- Searches for an element with a certain idThis 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.
(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(no version information, might be only in CVS)
DomDocument->html_dump_mem -- Dumps the internal XML tree back into a string as HTMLCreates 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
上例将输出:
|
See also domdocument_dump_file(), and domdocument_html_dump_mem().
(no version information, might be only in CVS)
DomDocument->xinclude -- Substitutes XIncludes in a DomDocument ObjectThis function substitutes XIncludes in a DomDocument object.
例子 1. Substituting Xincludes
上例将输出:
If include.xml doesn't exist, you'll see:
|
(no version information, might be only in CVS)
DomDocumentType->entities() -- Returns list of entities(no version information, might be only in CVS)
DomDocumentType->internal_subset() -- Returns internal subset(no version information, might be only in CVS)
DomDocumentType->name() -- Returns name of document typeThis function returns the name of the document type.
(no version information, might be only in CVS)
DomDocumentType->notations() -- Returns list of notations(no version information, might be only in CVS)
DomDocumentType->public_id() -- Returns public id of document typeThis function returns the public id of the document type.
(no version information, might be only in CVS)
DomDocumentType->system_id() -- Returns the system id of document type(no version information, might be only in CVS)
DomElement->get_attribute_node() -- Returns the node of the given attributeReturns the node of the given attribute in the current element.
Returns the node of the attribute as a DomAttribute or FALSE if no attribute with the given name is found.
(no version information, might be only in CVS)
DomElement->get_attribute() -- Returns the value of the given attributeReturns 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.
Returns the name of the attribute as a string or an empty string if no attribute with the given name is found.
(no version information, might be only in CVS)
DomElement->get_elements_by_tagname() -- Gets elements by tagnameGets all the sub elements with the specific name within the current element.
(no version information, might be only in CVS)
DomElement->has_attribute() -- Checks to see if an attribute exists in the current nodeThis functions checks to see if an attribute named name exists in the current node.
例子 1. Testing the existence of an attribute
|
Removes an attribute from the current DomElement node.
(no version information, might be only in CVS)
DomElement->set_attribute() -- Sets the value of an attributeSets an attribute with name name to the given value.
The name of the attribute. If this attribute doesn't exist, it will be created.
The value of the attribute.
Returns the old DomAttribute node, or the new one if you are creating the attribute for the first time.
(no version information, might be only in CVS)
DomElement->tagname() -- Returns the name of the current elementReturns 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.
(no version information, might be only in CVS)
DomNode->add_namespace -- Adds a namespace declaration to a nodeThis method adds a namespace declaration to a node.
注: This method is not part of the DOM specification.
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.
(no version information, might be only in CVS)
DomNode->append_child -- Adds a new child at the end of the childrenThis functions appends a child to an existing list of children or creates a new list of children.
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.
| 版本 | 说明 |
|---|---|
| 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.
The above example could also be written as the following:
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
|
The above example could also be done with DomNode->insert_before instead of DomNode->append_child.
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().
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.
Returns all children of the node.
See also domnode_next_sibling(), and domnode_previous_sibling().
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().
This function returns the content of the actual node.
例子 1. Getting a content
|
(no version information, might be only in CVS)
DomNode->has_attributes -- Checks if node has attributesThis function checks if the node has attributes.
See also domnode_has_child_nodes().
(no version information, might be only in CVS)
DomNode->has_child_nodes -- Checks if node has childrenThis function checks if the node has children.
See also domnode_child_nodes().
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
|
See also domnode_append_child().
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().
(no version information, might be only in CVS)
DomNode->next_sibling -- Returns the next sibling of nodeThis 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
|
See also domnode_previous_sibling().
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
| Type | Meaning |
|---|---|
| DomAttribute | value of attribute |
| DomAttribute | |
| DomCDataSection | #cdata-section |
| DomComment | #comment |
| DomDocument | #document |
| DomDocumentType | document type name |
| DomElement | tag name |
| DomEntity | name of entity |
| DomEntityReference | name of entity reference |
| DomNotation | notation name |
| DomProcessingInstruction | target |
| DomText | #text |
Returns the type of the node. All possible types are listed in the table in the introduction.
Returns value of the node. The value has different meanings for the different types of nodes as illustrated in the following table.
(no version information, might be only in CVS)
DomNode->owner_document -- Returns the document this node belongs toThis function returns the document the current node belongs to.
The following example will create two identical lists of children.
See also domnode_insert_before().
(no version information, might be only in CVS)
DomNode->parent_node -- Returns the parent of the nodeThis 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.
(no version information, might be only in CVS)
DomNode->previous_sibling -- Returns the previous sibling of nodeThis 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().
(no version information, might be only in CVS)
DomNode->remove_child -- Removes child from list of childrenThis 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
|
See also domnode_append_child().
(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()
(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()
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()
(no version information, might be only in CVS)
DomProcessingInstruction->data -- Returns the data of ProcessingInstruction nodeThis method gets the data of the ProcessingInstruction node.
(no version information, might be only in CVS)
DomProcessingInstruction->target -- Returns the target of a ProcessingInstruction nodeThis method gets the target of the ProcessingInstruction node.
(no version information, might be only in CVS)
DomXsltStylesheet->process() -- Applies the XSLT-Transformation on a DomDocument ObjectApplies an XSLT Transformation on the given DomDocument object.
The XML document being transformed, as a DomDocument object.
An associative array that takes pairs of parameter names and values.
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.
Set this to the path of a filename, if you want profiling information.
(no version information, might be only in CVS)
DomXsltStylesheet->result_dump_file() -- Dumps the result from a XSLT-Transformation into a fileSince 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.
(no version information, might be only in CVS)
DomXsltStylesheet->result_dump_mem() -- Dumps the result from a XSLT-Transformation back into a stringSince 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.
Creates a new Dom document from scratch and returns it.
The function parses the XML document in the given file.
The path to the XML file. The file is accessed in read-only 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.
If used, it will contain the error messages. error must be passed in by reference.
The function parses the XML document in the given string.
The contents of the XML file.
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.
If used, it will contain the error messages. error must be passed in by reference.
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.
(PHP 4 >= 4.2.0, PECL)
domxml_xslt_stylesheet_doc -- Creates a DomXsltStylesheet Object from a DomDocument ObjectCreates a DomXsltStylesheet object from the given XSL document.
(PHP 4 >= 4.2.0, PECL)
domxml_xslt_stylesheet_file -- Creates a DomXsltStylesheet Object from an XSL document in a fileCreates a DomXsltStylesheet object from the given XSL file.
Call XSLTProcessor->importStylesheet() with DOMDocument::load($xsl_file) as parameter.
(PHP 4 >= 4.2.0, PECL)
domxml_xslt_stylesheet -- Creates a DomXsltStylesheet object from an XSL document in a stringCreates a DomXsltStylesheet object from the given XSL buffer.
Call XSLTProcessor->importStylesheet() with DOMDocument::loadXML($xsl_buf) as parameter.
(PHP 4 >= 4.0.4, PECL)
xpath_eval_expression -- Evaluates the XPath Location Path in the given string
例子 1. xpath_eval_expression() Example
上例将输出:
|
See also xpath_eval().
The optional contextnode can be specified for doing relative XPath queries.
See also xpath_new_context().
| 警告 |
本函数暂无文档,仅有参数列表。 |
| 警告 |
本函数暂无文档,仅有参数列表。 |
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.ini 的影响。
表格 1. Errors and Logging Configuration Options
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| error_reporting | NULL | PHP_INI_ALL | |
| display_errors | "1" | PHP_INI_ALL | |
| display_startup_errors | "0" | PHP_INI_ALL | Available since PHP 4.0.3. |
| log_errors | "0" | PHP_INI_ALL | |
| log_errors_max_len | "1024" | PHP_INI_ALL | Available since PHP 4.3.0. |
| ignore_repeated_errors | "0" | PHP_INI_ALL | Available since PHP 4.3.0. |
| ignore_repeated_source | "0" | PHP_INI_ALL | Available since PHP 4.3.0. |
| report_memleaks | "1" | PHP_INI_ALL | Available since PHP 4.3.0. |
| track_errors | "0" | PHP_INI_ALL | |
| html_errors | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP <= 4.2.3. Available since PHP 4.0.2. |
| docref_root | "" | PHP_INI_ALL | Available since PHP 4.3.0. |
| docref_ext | "" | PHP_INI_ALL | Available since PHP 4.3.2. |
| error_prepend_string | NULL | PHP_INI_ALL | |
| error_append_string | NULL | PHP_INI_ALL | |
| error_log | NULL | PHP_INI_ALL | |
| warn_plus_overloading | NULL | PHP_INI?? |
以下是配置选项的简要解释。
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.
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.
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.
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.
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.
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 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.
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
If enabled, the last error message will always be present in the variable $php_errormsg.
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.
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).
See docref_root.
注: The value of docref_ext must begin with a dot '.'.
String to output before an error message.
String to output after an error message.
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().
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
| Value | Constant | Description | Note |
|---|---|---|---|
| 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
|
Returns an associative array. The possible returned elements are as follows:
表格 1. Possible returned elements from debug_backtrace()
| Name | Type | Description |
|---|---|---|
| function | string | The current function name. See also __FUNCTION__. |
| line | integer | The current line number. See also __LINE__. |
| file | string | The current file name. See also __FILE__. |
| class | string | The current class name. See also __CLASS__ |
| type | string | The current call type. If a method call, "->" is returned. If a static method call, "::" is returned. If a function call, nothing is returned. |
| args | array | 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
Results similar to the following when executing /tmp/b.php:
|
debug_print_backtrace() prints a PHP backtrace. It prints the function calls, included/required files and eval()ed stuff.
例子 1. debug_print_backtrace() example
上例的输出类似于:
|
Sends an error message to the web server's error log, a TCP port or to a file.
The error message that should be logged.
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. |
The destination. Its meaning depends on the message parameter as described above.
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
|
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.
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
| value | constant |
|---|---|
| 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 |
例子 1. error_reporting() examples
|
| 警告 |
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. |
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).
例子 1. restore_error_handler() example Decide if unserialize() caused an error, then restore the original error handler.
上例将输出:
|
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).
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.
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]]] )
The first parameter, errno, contains the level of the error raised, as an integer.
The second parameter, errstr, contains the error message, as a string.
The third parameter is optional, errfile, which contains the filename that the error was raised in, as a string.
The fourth parameter is optional, errline, which contains the line number the error was raised at, as an integer.
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.
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:
上例的输出类似于:
|
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.
Returns the name of the previously defined exception handler, or FALSE on error. If no previous handler was defined, an empty string is returned.
restore_exception_handler(), restore_error_handler(), error_reporting(), 有关 callback 类型的信息, 和 PHP 5 Exceptions.
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.
The designated error message for this error. It's limited to 1024 characters in length. Any additional characters beyond 1024 will be truncated.
The designated error type for this error. It only works with the E_USER family of constants, and will default to E_USER_NOTICE.
例子 1. trigger_error() example See set_error_handler() for a more extensive example.
|
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 起可用。 |
以下是配置选项的简要解释。
exif.encode_unicode 定义了 UNICODE 用户注释被处理的字符集。默认为 ISO-8859-15,可用于大多数非亚洲国家。本设置可以为空或者必须为一个 mbstring 所支持的编码。如果为空,则使用当前 mbstring 内部使用的编码。
exif.decode_unicode_motorola 定义了 Unicode 编码的用户注释的图像内部字符集,如果图像是摩托罗拉字节顺序(big-endian)的话。本设置不能为空但可以指定一个 mbstring 支持的编码列表。默认为 UCS-2BE。
exif.decode_unicode_intel 定义了 Unicode 编码的用户注释的图像内部字符集,如果图像是英特尔字节顺序(little-endian)的话。本设置不能为空但可以指定一个 mbstring 支持的编码列表。默认为 UCS-2LE。
exif.encode_jis 定义了 JIS 用户注释被处理的字符集。默认为空值,迫使函数使用当前 mbstring 使用的内部编码。
exif.decode_jis_motorola 定义了 JIS 编码的用户注释的图像内部字符集,如果图像是摩托罗拉字节顺序(big-endian)的话。本设置不能为空但可以指定一个 mbstring 支持的编码列表。默认为 JIS。
exif.decode_jis_intel 定义了 JIS 编码的用户注释的图像内部字符集,如果图像是英特尔字节顺序(litle-endian)的话。本设置不能为空但可以指定一个 mbstring 支持的编码列表。默认为 JIS。
以下常量由本扩展模块定义,因此只有在本扩展模块被编译到 PHP 中,或者在运行时被动态加载后才有效。
The exif_imagetype() lists several related built-in constants.
exif_imagetype() 读取一个图像的第一个字节并检查其签名。
本函数可用来避免调用其它 exif 函数用到了不支持的文件类型上或和 $_SERVER['HTTP_ACCEPT'] 结合使用来检查浏览器是否可以显示某个指定的图像。
exif_read_data() 函数从 JPEG 或 TIFF 图像文件中读取 EXIF 头信息。这样就可以读取数码相机产生的元数据。
Exif 头信息往往存在于数码相机生成的 JPEG/TIFF 图像中,但不幸的是每个数码相机制造商的标记都不同,因此(编写代码时)不能依赖于某个特定的 Exif 头信息。
Height 和 Width 是用和 getimagesize() 一样的方法计算的,因此它们的值不能是任何返回的头信息的部分。此外 html 是一个 height/width 的文本字符串可以用于普通的 HTML 中。
当一个 Exif 头信息包含有一个 Copyright 时注意它本身可以包含两个值。解决方案和 Exif 2.10 标准不一致,COMPUTED 区段会同时返回 Copyright.Photographer 和 Copyright.Editor,但是 IFD0 区段则包含有一个字节数组用 NULL 字符分隔开两个项目。或者只有第一项如果数据类型错误的话(Exif 的正常行为)。COMPUTED 也会包含 Copyright,要么是原始的版权字符串,要么是逗号分隔的摄像与编辑的版权信息。
UserComment 标记和 Copyright 有同样的问题。它也可以存储两个值,第一个是使用的编码方式,第二个是其值本身。如果这样则 IFD0 区段仅包含编码方式或者一个字节数组。COMPUTED 区段将存储两个值到 UserCommentEncoding 和 UserComment。UserComment 在两种情况下都可用因此应该优先使用它而不是 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。
被读取的图像文件名。不能是 URL。
是需要存在于文件中的逗号分隔的区段列表用来产生结果数组。如果未找到所请求的区段则返回值为 FALSE。
| FILE | FileName, FileSize, FileDateTime, SectionsFound |
| COMPUTED | html,Width,Height,IsColor,可能有更多其它的。Height 和 Width 是用和 getimagesize() 一样的方法计算的,因此它们的值不能是任何返回的头信息的部分。此外 html 是一个 height/width 的文本字符串可以用于普通的 HTML 中。 |
| ANY_TAG | 任何包含有标记的信息,例如 IFD0,EXIF,... |
| IFD0 | 所有 IFD0 的标记数据。在标准的图像文件中这包含了图像大小及其它。 |
| THUMBNAIL | 如果有第二个 IFD,文件应该包含有缩略图。所有有关嵌入缩略图的标记信息都存储在本区。 |
| COMMENT | JPEG 图像的注释头信息。 |
| EXIF | EXIF 区段是 IFDO 的子区,包含有图像的更多详细信息。大多数内容都是数码相机相关的。 |
指定了是否每个区段都成为一个数组。sections COMPUTED,THUMBNAIL 和COMMENT 区段总是成为数组,因为它们里面包含的名字和其它区段冲突。
当设定为 TRUE 时,读取缩略图本身。否则只读取标记数据。
| 版本 | 说明 |
|---|---|
| 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() 例子
第一个调用失败了,因为图像没有头信息。 上例的输出类似于:
|
exif_thumbnail() 读取 TIFF 或 JPEG 图像中的嵌入缩略图。如果图像不包含缩略图则返回 FALSE。
参数 width,height 和 imagetype 自 PHP 4.3.0 起可用,返回缩略图的大小和类型。有可能 exif_thumbnail() 不能创建图像但可以测定其大小,此情况下返回值是 FALSE,但是 width 和 height 的值已经传回了。
如果想用此函数发送缩略图,应该用 header() 函数发送 mime 类型信息。下面的例子演示了此方法:
例子 1. exif_thumbnail() 例子
|
自 PHP 4.3.0 起,exif_thumbnail() 函数可以以 TIFF 格式返回缩略图。
注: 本函数仅在 PHP 编译时使用了 --enable-exif 选项时可用。其功能和行为在 PHP 4.2 改变了。
注: 本函数不需要 GD 图像库。
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 中,或者在运行时被动态加载后才有效。
表格 1. FAM event constants
| Constant | Description |
|---|---|
| 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() 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() closes a connection to the FAM service previously opened using fam_open().
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() 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() 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() 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() 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() returns non-zero if events are available to be fetched using fam_next_event().
See also fam_next_event().
fam_resume_monitor() resumes monitoring of a resource previously suspend using fam_suspend_monitor().
See also fam_suspend_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().
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.
Returns the number of fields (columns) in the opened filePro database.
See also filepro().
Returns the name of the field corresponding to field_number.
Returns the edit type of the field corresponding to field_number.
Returns the width of the field corresponding to 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(所有者)。
Returns the number of rows in the opened filePro database.
注: 当安全模式被激活时,PHP 将检查被操作的文件或者目录是否与正在执行的脚本有相同的 UID(所有者)。
See also filepro().
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(所有者)。
无需外部库文件就可以加入本扩展模块的支持。但如要使 PHP 在 Linux 上支持 LFS(大文件)的话,必须有最新的 glibc 并在编译时加入参数:-D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64。
这些函数的行为受 php.ini 的影响。
表格 1. 文件系统和流配置选项
| 名称 | 默认值 | 可修改范围 | 更新记录 |
|---|---|---|---|
| allow_url_fopen | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.3.4. PHP 4.0.4 版以后可用。 |
| user_agent | NULL | PHP_INI_ALL | PHP 4.3.0 版以后可用。 |
| default_socket_timeout | "60" | PHP_INI_ALL | PHP 4.3.0 版以后可用。 |
| from | "" | PHP_INI_ALL | |
| auto_detect_line_endings | "0" | PHP_INI_ALL | PHP 4.3.0 版以后可用。 |
以下是配置选项的简要解释。
本选项激活了 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 函数。 |
定义 PHP 发送的 User-Agent。
基于 socket 的流的默认超时时间(秒)。
注: 本配置参数是 PHP 4.3.0 引进的。
定义匿名 ftp 的密码(email 地址)。
当设为 On 时,PHP 将检查通过 fgets() 和 file() 取得的数据中的行结束符号是符合 Unix,MS-Dos,还是 Macintosh 的习惯。
这使得 PHP 可以和 Macintosh 系统交互操作,但是默认值是 Off,因为在检测第一行的 EOL 习惯时会有很小的性能损失,而且在 Unix 系统下使用回车符号作为项目分隔符的人们会遭遇向下不兼容的行为。
注: 本配置参数是 PHP 4.3.0 引进的。
以下常量由本扩展模块定义,因此只有在本扩展模块被编译到 PHP 中,或者在运行时被动态加载后才有效。
给出一个包含有指向一个文件的全路径的字符串,本函数返回基本的文件名。如果文件名是以 suffix 结束的,那这一部分也会被去掉。
在 Windows 中,斜线(/)和反斜线(\)都可以用作目录分隔符。在其它环境下是斜线(/)。
注: suffix 参数是 PHP 4.1.0 新加的。
参见 dirname()。
尝试将文件 filename 所属的组改成 group(通过组名或组 ID 指定)。只有超级用户可以任意修改文件的组,其它用户可能只能将文件的组改成该用户自己所在的组。
如果成功则返回 TRUE,失败则返回 FALSE。
注: 本函数不能作用于远程文件,被检查的文件必须通过服务器的文件系统访问。
注: 当安全模式被激活时,PHP 将检查被操作的文件或者目录是否与正在执行的脚本有相同的 UID(所有者)。
尝试将 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。
尝试将文件 filename 的所有者改成用户 user(由用户名或用户 ID 指定)。只有超级用户可以改变文件的所有者。
如果成功则返回 TRUE,失败则返回 FALSE。
注: 本函数不能作用于远程文件,被检查的文件必须通过服务器的文件系统访问。
注: 当安全模式被激活时,PHP 将检查被操作的文件或者目录是否与正在执行的脚本有相同的 UID(所有者)。
参见 chmod()。
当使用 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()。
将文件从 source 拷贝到 dest。如果成功则返回 TRUE,失败则返回 FALSE。
如果要移动文件的话,请使用 rename() 函数。
注: 从 PHP 4.3.0 开始,如果启用了“fopen wrappers”的话,source 和 dest 都可以是 URL。更多细节见 fopen()。如果 dest 是一个 URL,则如果封装协议不支持覆盖已有的文件时拷贝操作会失败。
| 警告 |
如果目标文件已存在,将会被覆盖。 |
Windows 兼容: 如果复制一个零字节的文件,copy() 将返回 FALSE ,但文件也会被正确复制。
参见 move_uploaded_file(),rename() 和手册中关于文件上传处理一节。
给出一个包含有指向一个文件的全路径的字符串,本函数返回去掉文件名后的目录名。
在 Windows 中,斜线(/)和反斜线(\)都可以用作目录分隔符。在其它环境下是斜线(/)。
注: 在 PHP 4.0.3 中,dirname() 被修正为 POSIX 兼容。本质上就意味着如果在 path 中没有斜线,则返回一个点('.'),表示当前目录。否则返回的是把 path 中结尾的 /component(最后一个斜线以及后面部分)去掉之后的字符串。注意这意味着在老的函数返回一个空字符串的情形下你通常从 dirname() 得到的是斜线或者一个点。
dirname() 从 PHP 4.3.0 开始有所改变 请看以下例子:
dirname() 的操作从 PHP 5.0.0 版开始是二进制安全的。
参见 basename(),pathinfo() 和 realpath()。
给出一个包含有一个目录的字符串,本函数将根据相应的文件系统或磁盘分区返回可用的字节数。
注: 本函数不能作用于远程文件,被检查的文件必须通过服务器的文件系统访问。
给出一个包含有一个目录的字符串,本函数将根据相应的文件系统或磁盘分区返回所有的字节数。
注: 本函数不能作用于远程文件,被检查的文件必须通过服务器的文件系统访问。
【译者注】本函数返回的是该目录所在的磁盘分区的总大小,因此在给出同一个磁盘分区的不同目录作为参数所得到的结果完全相同。在 Unix 和 Windows 200x/XP 中都支持将一个磁盘分区加载为一个子目录,这时正确使用本函数就很有意义。
将 handle 指向的文件关闭。
如果成功则返回 TRUE,失败则返回 FALSE。
文件指针必须有效,并且是通过 fopen() 或 fsockopen() 成功打开的。
如果文件指针到了 EOF 或者出错时则返回 TRUE,否则返回一个错误(包括 socket 超时),其它情况则返回 FALSE。
| 警告 |
如果服务器没有关闭由 fsockopen() 所打开的连接,feof() 会一直等待直到超时而返回 TRUE。默认的超时限制是 60 秒,可以使用 stream_set_timeout() 来改变这个值。 |
文件指针必须是有效的,并且必须指向一个由 fopen() 或 fsockopen() 成功打开的文件。
本函数强制将所有缓冲的输出写入 handle 文件句柄所指向的资源。 如果成功则返回 TRUE,失败则返回 FALSE。
文件指针必须是有效的,并且必须指向一个由 fopen() 或 fsockopen() 成功打开的文件。
返回一个包含有一个字符的字符串,该字符从 handle 指向的文件中得到。碰到 EOF 则返回 FALSE。
文件指针必须是有效的,并且必须指向一个由 fopen() 或 fsockopen() 成功打开的文件。
注: 本函数可安全用于二进制对象。
参见 fread(),fopen(),popen(),fsockopen() 和 fgets()。
一个由 fopen()、popen() 或 fsockopen() 产生的有效文件指针。
必须大于 CVS 文件内最长的一行。在 PHP 5 中该参数是可选的。如果忽略(在 PHP 5.0.4 以后的版本中设为 0)该参数的话,那么长度就没有限制,不过可能会影响执行效率。
设置字段分界符(只允许一个字符),默认值为逗号。
设置字段环绕符(只允许一个字符),默认值为双引号。该参数是在 PHP 4.3.0 中添加的。
和 fgets() 类似,只除了 fgetcsv() 解析读入的行并找出 CSV 格式的字段然后返回一个包含这些字段的数组。
fgetcsv() 出错时返回 FALSE,包括碰到文件结束时。
注: CSV 文件中的空行将被返回为一个包含有单个 null 字段的数组,不会被当成错误。
从 PHP 4.3.5 起,fgetcsv() 的操作是二进制安全的。
注: 该函数对区域设置是敏感的。比如说 LANG 设为 en_US.UTF-8 的话,单字节编码的文件就会出现读取错误。
注: 如果碰到 PHP 在读取文件时不能识别 Macintosh 文件的行结束符,可以激活 auto_detect_line_endings 运行时配置选项。
从 handle 指向的文件中读取一行并返回长度最多为 length - 1 字节的字符串。碰到换行符(包括在返回值中)、EOF 或者已经读取了 length - 1 字节后停止(看先碰到那一种情况)。如果没有指定 length,则默认为 1K,或者说 1024 字节。
出错时返回 FALSE。
通常的缺陷:
习惯了 C 语言中 fgets() 语法的人应该注意到 EOF 是怎样被返回的。
文件指针必须是有效的,并且必须指向一个由 fopen() 或 fsockopen() 成功打开的文件。
以下是一个简单例子:
注: 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()。
和 fgets() 相同,只除了 fgetss 尝试从读取的文本中去掉任何 HTML 和 PHP 标记。
可以用可选的第三个参数指定哪些标记不被去掉。
注: allowable_tags 是 PHP 3.0.13,PHP 4.0.0 新加的。
参数 length 从 PHP 5 起开始可选。
注: 如果碰到 PHP 在读取文件时不能识别 Macintosh 文件的行结束符,可以激活 auto_detect_line_endings 运行时配置选项。
如果由 filename 指定的文件或目录存在则返回 TRUE,否则返回 FALSE。
在 Windows 中要用 //computername/share/filename 或者 \\computername\share\filename 来检查网络中的共享文件。
注: 本函数的结果会被缓存。更多信息参见 clearstatcache()。
| 警告 |
如果因为安全模式的限制而导致不能访问文件的话,该函数会返回 FALSE。然而,如果文件在 safe_mode_include_dir 所指定的目录内的话,仍然可以使用 include 来包含。 |
和 file() 一样,只除了 file_get_contents() 把文件读入一个字符串。将在参数 offset 所指定的位置开始读取长度为 maxlen 的内容。如果失败,file_get_contents() 将返回 FALSE。
file_get_contents() 函数是用来将文件的内容读入到一个字符串中的首选方法。如果操作系统支持还会使用内存映射技术来增强性能。
注: 如果要打开有特殊字符的 URL (比如说有空格),就需要使用 urlencode() 进行 URL 编码。
注: context 参数可以用 NULL 来忽略。
注: 本函数可安全用于二进制对象。
提示: 如果“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:// 套接字,则需要自己检测并抑制警告信息。 |
和依次调用 fopen(),fwrite() 以及 fclose() 功能一样。
参数 data 可以是数组(但不能为多元数组),这就相当于 file_put_contents($filename, join('', $array))
自 PHP 5.1.0 起,data 参数也可以被指定为 stream 资源,这里 stream 中所保存的缓存数据将被写入到指定文件中,这种用法就相似于使用 stream_copy_to_stream() 函数。
注: 本函数可安全用于二进制对象。
注: 对 context 的支持是 PHP 5.0.0 添加的。有关 context 的说明请参考参考 CXLI, Stream Functions。
提示: 如果“fopen wrappers”已经被激活,则在本函数中可以把 URL 作为文件名来使用。请参阅 fopen() 函数来获取怎样指定文件名的详细信息以及支持 URL 封装协议的列表:附录 L。
和 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()。
返回文件上次被访问的时间,如果出错则返回 FALSE。时间以 Unix 时间戳的方式返回。
注意:一个文件的 atime 应该在不论何时读取了此文件中的数据块时被更改。当一个应用程序定期访问大量文件或目录时很影响性能。有些 Unix 文件系统可以在加载时关闭 atime 的更新以提高这类程序的性能。USENET 新闻组假脱机是一个常见的例子。在这种文件系统下本函数没有用处。
注: 本函数的结果会被缓存。更多信息参见 clearstatcache()。
参见 filemtime(),fileinode() 和 date()。
返回文件上次 inode 被修改的时间,如果出错则返回 FALSE。时间以 Unix 时间戳的方式返回。
注意:在大多数 Unix 文件系统中,当一个文件的 inode 数据被改变时则该文件被认为是修改了。也就是说,当文件的权限,所有者,所有组或其它 inode 中的元数据被更新时。参见 filemtime()(这才是你想用于在 web 页面中建立“最后更新时间”脚注的函数)和 fileatime()。
注意某些 Unix 说明文本中把 ctime 说成是该文件建立的时间,这是错的。在大多数 Unix 文件系统中没有 Unix 文件的建立时间。
注: 本函数的结果会被缓存。更多信息参见 clearstatcache()。
例子 1. 一个 fileatime() 的例子
|
参见 filemtime()。
取得该文件所属组的 ID。如果出错则返回 FALSE。组 ID 以数字格式返回,用 posix_getgrgid() 来将其解析为组名。如果失败返回 FALSE 以及一个 E_WARNING 级别的错误。
本函数的结果会被缓存。详细信息见 clearstatcache()。
注: 本函数的结果会被缓存。更多信息参见 clearstatcache()。
参见 fileowner() 和 safe_mode_gid。
返回文件的 inode 节点号,出错时返回 FALSE。
注: 本函数的结果会被缓存。更多信息参见 clearstatcache()。
参见 stat()。
返回文件上次被修改的时间,出错时返回 FALSE。时间以 Unix 时间戳的方式返回,可用于 date()。
注: 本函数的结果会被缓存。更多信息参见 clearstatcache()。
本函数返回文件中的数据块上次被写入的时间,也就是说,文件的内容上次被修改的时间。
参见 filectime(),stat(),touch() 和 getlastmod()。
返回文件所有的用户 ID,如果出错则返回 FALSE。用户 ID 以数字格式返回,用 posix_getpwuid() 来将其解析为用户名。
注: 本函数的结果会被缓存。更多信息参见 clearstatcache()。
参见 stat()。
返回文件的访问权限,如果出错则返回 FALSE。
注: 本函数的结果会被缓存。更多信息参见 clearstatcache()。
例子 2. 输出全部权限
上例将输出:
|
参见 is_readable() 和 stat()。
返回文件大小的字节数,如果出错返回 FALSE (在错误报告级别为 E_WARNING的情况下)。
注: 因为 PHP 的整数类型是有符号的,并且大多数平台使用 32 位整数,filesize() 函数在碰到大于 2GB 的文件时可能会返回非预期的结果。对于 2GB 到 4GB 之间的文件通常可以使用 sprintf("%u", filesize($file)) 来克服此问题。
注: 本函数的结果会被缓存。更多信息参见 clearstatcache()。
参见 file_exists()。
返回文件的类型。可能的值有 fifo,char,dir,block,link,file 和 unknown。
如果出错则返回 FALSE。如果 stat 调用失败或者文件类型未知的话 filetype() 还会产生一个 E_NOTICE 消息。
注: 本函数的结果会被缓存。更多信息参见 clearstatcache()。
参见 is_dir(),is_file(),is_link(),file_exists(),stat() 和 mime_content_type()。
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。
注: 由于 flock() 需要一个文件指针, 因此你可能需要一个锁定文件来保护到你打算通过写模式打开来截断的文件的访问(在 fopen() 函数中加入 "w" 或 "w+")。
| 警告 |
flock() 不能在 NFS 以及其他的一些网络文件系统中正常工作。详细资料请检查你的操作系统文档。 在部分操作系统中,flock() 以处理级执行。当用一个多线程服务器 API(比如 ISAPI)时,您可能不可以依靠 flock() 来保护文件,因为在同一服务器内运行在其它线程的 PHP 脚本可以对该文件进行处理。 flock() 不支持旧的文件系统,如 FAT 以及它的派生系统。因此,它在这种情况下经常会返回一个 FALSE 值(尤其是指 Windows 98 的用户)。 |
fnmatch() 检查传入的 string 是否匹配给出的 shell 统配符 pattern。
此函数对于文件名尤其有用,但也可以用于普通的字符串。普通用户可能习惯于 shell 模式或者至少其中最简单的形式 '?' 和 '*' 通配符,因此使用 fnmatch() 来代替 ereg() 或者 preg_match() 来进行前端搜索表达式输入对于非程序员用户更加方便。
| 警告 |
目前该函数无法在 Windows 或其它非 POSIX 兼容的系统上使用 |
参见 glob(),ereg(),preg_match() 和 UNIX 中 fnmatch(3) 的手册中的标志名(只要本文档中还未包括它们)。
fopen() 将 filename 指定的名字资源绑定到一个流上。如果 filename 是 "scheme://..." 的格式,则被当成一个 URL,PHP 将搜索协议处理器(也被称为封装协议)来处理此模式。如果该协议尚未注册封装协议,PHP 将发出一条消息来帮助检查脚本中潜在的问题并将 filename 当成一个普通的文件名继续执行下去。
如果 PHP 认为 filename 指定的是一个本地文件,将尝试在该文件上打开一个流。该文件必须是 PHP 可以访问的,因此需要确认文件访问权限允许该访问。如果激活了 安全模式 或者 open_basedir 则会应用进一步的限制。
如果 PHP 认为 filename 指定的是一个已注册的协议,而该协议被注册为一个网络 URL,PHP 将检查并确认 allow_url_fopen 已被激活。如果关闭了,PHP 将发出一个警告,而 fopen 的调用则失败。
注: 所支持的协议列表见附录 L。某些协议(也被称为 wrappers)支持 context 和 php.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。
如果在用服务器模块版本的 PHP 时在打开和写入文件上遇到问题,记住要确保所使用的文件是服务器进程所能够访问的。
在 Windows 平台上,要小心转义文件路径中的每个反斜线,或者用斜线。
| 警告 |
当使用 SSL 时,Microsoft IIS 将违反协议不发送 close_notify 标记就关闭连接。PHP 将在到达数据尾端时报告 "SSL: Fatal Protocol Error"。要绕过此问题,应将 error_reporting 级别降低为不包括警告。PHP 4.3.7 及更高版本可以在当使用 https:// 封装协议打开流的时候检测出有此问题的 IIS 服务器并抑制警告。如果使用 fsockopen() 来创建一个 ssl:// 套接字,则需要自己检测并抑制警告信息。 |
注: 当安全模式被激活时,PHP 将检查被操作的目录是否和正在执行的脚本有相同的 UID(所有者)。
参见附录 L,fclose(),fgets(),fread(),fwrite(),fsockopen(),file(),file_exists(),is_readable(),stream_set_timeout() 和 popen()。
将给定的文件指针从当前的位置读取到 EOF 并把结果写到输出缓冲区。
如果发生错误, fpassthru() 返回 FALSE。 否则 fpassthru() 返回从 handle 读取并传递到输出的字符数目。
文件指针必须是有效的,并且必须指向一个由 fopen() 或 fsockopen() 成功打开的文件。
如果已经向文件写入数据,就必须调用 rewind() 来将文件指针指向文件头。
如果既不修改文件也不在特定位置检索,只想将文件的内容下载到输出缓冲区,应该使用 readfile(),这样可以省去 fopen() 调用。
注: 当在 Windows 系统中将 fpassthru() 用于二进制文件时,要确保在用 fopen() 打开文件时在 mode 中附加了 b 来将文件以二进制方式打开。
鼓励在处理二进制文件时使用 b 标志,即使系统并不需要,这样可以使脚本的移植性更好。
参见 readfile(),fopen(),popen() 和 fsockopen()。
fputcsv() 将一行(用 fields 数组传递)格式化为 CSV 格式并写入由 handle 指定的文件。返回写入字符串的长度,出错则返回 FALSE。
可选的 delimiter 参数设定字段分界符(只允许一个字符)。默认为逗号:,。
可选的 enclosure 参数设定字段字段环绕符(只允许一个字符)。默认为双引号:"。
注: 如果碰到 PHP 在读取文件时不能识别 Macintosh 文件的行结束符,可以激活 auto_detect_line_endings 运行时配置选项。
参见 fgetcsv()。
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() 函数和 sscanf() 相似,但是它从与 handle 关联的文件中接受输入并根据指定的 format(定义于 sprintf() 的文档中)来解释输入。如果只给此函数传递了两个参数,解析后的值会被作为数组返回。否则,如果提供了可选参数,此函数将返回被赋值的数目。可选参数必须用引用传递。
格式字符串中的任何空白会与输入流中的任何空白匹配。这意味着甚至格式字符串中的制表符 \t 也会与输入流中的一个空格字符匹配。
注: 在 PHP 4.3.0 之前,从文件中读入的最大字符数是 512(或者第一个 \n,看先碰到哪种情况)。从 PHP 4.3.0 起可以读取任意长的行。
在与 handle 关联的文件中设定文件指针位置。新位置,从文件头开始以字节数度量,是以 whence 指定的位置加上 offset。whence 的值定义为:
| SEEK_SET - 设定位置等于 offset 字节。 |
| SEEK_CUR - 设定位置为当前位置加上 offset。 |
| SEEK_END - 设定位置为文件尾加上 offset。(要移动到文件尾之前的位置,需要给 offset 传递一个负值。) |
如果没有指定 whence,默认为 SEEK_SET。
成功则返回 0;否则返回 -1。注意移动到 EOF 之后的位置不算错误。
可能不能用于在 fopen() 中以 "http://" 或 "ftp://" 格式打开所返回的文件指针。在附加模式(加参数 "a" 打开文件)中 ftell() 会返回未定义错误。
注: whence 参数是 PHP 4.0.0 之后增加的。
注: 如果你使用附加模试("a" 或 "a+"),任何写入文件数据都会被附加上去,而文件的位置将会被忽略。
获取由文件指针 handle 所打开文件的统计信息。本函数和 stat() 函数相似,除了它是作用于已打开的文件指针而不是文件名。
返回一个数组具有该文件的统计信息,该数组的格式详细说明于手册中 stat() 页面里。
例子 1. fstat() 例子
上例的输出类似于:
|
注: 本函数不能作用于远程文件,被检查的文件必须通过服务器的文件系统访问。
返回由 handle 指定的文件指针的位置,也就是文件流中的偏移量。
如果出错,返回 FALSE。
文件指针必须是有效的,且必须指向一个通过 fopen() 或 popen() 成功打开的文件。 在附加模式(加参数 "a" 打开文件)中 ftell() 会返回未定义错误。
接受文件指针 handle 作为参数,并将文件大小截取为 size。如果成功则返回 TRUE,失败则返回 FALSE。
注: 文件只会在 append 模式下改变。在 write 模式下,必须加上 fseek() 操作。
fwrite() 把 string 的内容写入 文件指针 handle 处。 如果指定了 length,当写入了 length 个字节或者写完了 string 以后,写入就会停止,视乎先碰到哪种情况。
fwrite() 返回写入的字符数,出现错误时则返回 FALSE 。
注意如果给出了 length 参数,则 magic_quotes_runtime 配置选项将被忽略,而 string 中的斜线将不会被抽去。
注: 在区分二进制文件和文本文件的系统上(如 Windows) 打开文件时,fopen() 函数的 mode 参数要加上 'b'。
例子 1. 一个简单的 fwrite() 例子
|
参见 fread(),fopen(),fsockopen(),popen() 和 file_put_contents()。
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() 和相关函数
上例的输出类似于:
|
注: 本函数不能作用于远程文件,被检查的文件必须通过服务器的文件系统访问。
如果文件名存在并且为目录则返回 TRUE。如果 filename 是一个相对路径,则按照当前工作目录检查其相对路径。
注: 本函数的结果会被缓存。更多信息参见 clearstatcache()。
如果文件存在且可执行则返回 TRUE。
is_executable() 自 PHP 5.0.0 版起可用于 Windows。
注: 本函数的结果会被缓存。更多信息参见 clearstatcache()。
如果文件存在并且是一个符号连接则返回 TRUE。
注: 本函数的结果会被缓存。更多信息参见 clearstatcache()。
参见 is_dir(),is_file() 和 readlink()。
如果文件存在并且可读则返回 TRUE。
记住 PHP 也许只能以运行 webserver 的用户名(通常为 'nobody')来访问文件。不计入安全模式的限制。
例子 1. is_writable() 例子
|
注: 本函数的结果会被缓存。更多信息参见 clearstatcache()。
如果 filename 所给出的文件是通过 HTTP POST 上传的则返回 TRUE。这可以用来确保恶意的用户无法欺骗脚本去访问本不能访问的文件,例如 /etc/passwd。
这种检查显得格外重要,如果上传的文件有可能会造成对用户或本系统的其他用户显示其内容的话。
为了能使 is_uploaded_file() 函数正常工作,必段指定类似于 $_FILES['userfile']['tmp_name'] 的变量,而在从客户端上传的文件名 $_FILES['userfile']['name'] 不能正常运作。
例子 1. is_uploaded_file() 例子
|
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 的例子
|
参见 move_uploaded_file(),以及文件上传处理一章中的简单使用例子。
如果文件存在并且可写则返回 TRUE。filename 参数可以是一个允许进行是否可写检查的目录名。
记住 PHP 也许只能以运行 webserver 的用户名(通常为 'nobody')来访问文件。不计入安全模式的限制。
注: 本函数的结果会被缓存。更多信息参见 clearstatcache()。
See also is_readable(), file_exists(), and fwrite().
link() 建立一个硬连接。如果成功则返回 TRUE,失败则返回 FALSE。
注: 本函数不能作用于远程文件,被检查的文件必须通过服务器的文件系统访问。
注: 本函数未在 Windows 平台下实现。
参见 symlink() 来建立软连接,以及 readlink() 和 linkinfo()。
linkinfo() 返回 lstat 系统调用所返回的 UNIX C stat 结构中的 st_dev 字段。本函数用来验证一个连接(由 path 所指向的)是否确实存在(使用 stat.h 中的 S_ISLNK 宏同样的方法)。如果出错则返回 0 或 FALSE。
注: 本函数未在 Windows 平台下实现。
参见 symlink(),link() 和 readlink()。
获取由 filename 指定的文件或符号连接的统计信息。本函数和 stat() 函数相同,只除了如果 filename 参数是符号连接的话,则该符号连接的状态被返回,而不是该符号连接所指向的文件的状态。
有关 lstat() 返回的数组结构见手册中 stat() 函数的页面。
注: 本函数的结果会被缓存。更多信息参见 clearstatcache()。
参见 stat()。
尝试新建一个由 pathname 指定的目录。
注意也许想用八进制数指定模式,也就是说该数应以零打头。模式也会被当前的 umask 修改,可以用 umask() 来改变。
注: Mode 在 Windows 下被忽略。自 PHP 4.2.0 起成为可选项。
默认的 mode 是 0777,意味着最大可能的访问权。有关 mode 的更多信息请阅读 chmod() 页面。
注: recursive 参数是 PHP 5.0.0 添加的。
如果成功则返回 TRUE,失败则返回 FALSE。
参见 rmdir()。
本函数检查并确保由 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() 载入一个由 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 的值会被求值。例如:
例子 2. parse_ini_file() 例子
上例将输出:
|
由数字组成的键名和小节名会被 PHP 当作整数来处理,因此以 0 开头的数字会被当作八进制而以 0x 开头的会被当作十六进制。
pathinfo() 返回一个联合数组包含有 path 的信息。包括以下的数组单元:dirname,basename 和 extension。
可以通过参数 options 指定要返回哪些单元。它们包括:PATHINFO_DIRNAME,PATHINFO_BASENAME 和 PATHINFO_EXTENSION。默认是返回全部的单元。
注: 有关取得当前路径信息的说明,请阅读预定义变量一节。
关闭用 popen() 打开的指向管道的文件指针。
文件指针必须有效,且必须是成功调用 popen() 所返回的。
返回运行的进程的终止状态。
参见 popen()。
打开一个指向进程的管道,该进程由派生给定的 command 命令执行而产生。
返回一个和 fopen() 所返回的相同的文件指针,只不过它是单向的(只能用于读或写)并且必须用 pclose() 来关闭。此指针可以用于 fgets(),fgetss() 和 fwrite()。
如果出错返回 FALSE。
注: 如果需要双向支持,使用 proc_open()。
注: 如果未找到要执行的命令,会返回一个合法的资源。这看上去很怪,但有道理。它允许你访问 shell 返回的任何错误信息:
注: 在打开了安全模式时,只能执行在 safe_mode_exec_dir 之内的程序。为实用起见目前不能在指向程序的路径中包含 .. 成分。
| 警告 |
在打开了安全模式时,初始命令字符串之后的所有词都被看成一个单一的参数。因此,echo y | echo x 就成了 echo "y | echo x"。 |
参见 pclose(),fopen() 和 proc_open()。
读入一个文件并写入到输出缓冲。
返回从文件中读入的字节数。如果出错返回 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() 和同名的 C 函数做同样的事,返回符号连接的内容。如果出错返回 FALSE。
注: 本函数未在 Windows 平台下实现。
参见 is_link(),symlink() 和 linkinfo()。
realpath() 扩展所有的符号连接并且处理输入的 path 中的 '/./', '/../' 以及多余的 '/' 并返回规范化后的绝对路径名。返回的路径中没有符号连接,'/./' 或 '/../' 成分。
realpath() 失败时返回 FALSE,比如说文件不存在的话。在 BSD 系统上,如果仅仅是 path 不存在的话,PHP 并不会像其它系统那样返回 FALSE。
参见 basename(),dirname() 和 pathinfo()。
尝试把 oldname 重命名为 newname。
如果成功则返回 TRUE,失败则返回 FALSE。
注: 在 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。
将 handle 的文件位置指针设为文件流的开头。
如果成功则返回 TRUE,失败则返回 FALSE。
文件指针必须合法,并且指向由 fopen() 成功打开的文件。
注: 如果将文件以附加("a" 或者 "a+")模式打开,写入文件的任何数据总是会被附加在后面,不管文件指针的位置。
尝试删除 dirname 所指定的目录。 该目录必须是空的,而且要有相应的权限。如果成功则返回 TRUE,失败则返回 FALSE。
注: 自 PHP 5.0.0 起 rmdir() 也可用于某些 URL 封装协议。参见附录 L 的列表看看 rmdir() 支持哪些 URL 封装协议。
注: 对 context 的支持是 PHP 5.0.0 添加的。有关 context 的说明请参考参考 CXLI, Stream Functions。
注: 当安全模式被激活时,PHP 将检查被操作的目录是否和正在执行的脚本有相同的 UID(所有者)。
获取由 filename 指定的文件的统计信息。如果 filename 是符号连接,则统计信息是关于被连接文件本身的,而不是符号连接。lstat() 和 stat() 相同,只除了它会返回符号连接的状态。
如果出错,stat() 返回 FALSE,并且发出一条警告。
返回一个数组包含有文件的统计信息,该数组具有以下列出的单元,数组下标从零开始。除了数字索引之外自 PHP 4.0.6 起还可以通过关联索引来访问。
表格 1. stat() 和 fstat() 返回格式
| 数字下标 | 关联键名(自 PHP 4.0.6) | 说明 |
|---|---|---|
| 0 | dev | device number - 设备名 |
| 1 | ino | inode number - inode 号码 |
| 2 | mode | inode protection mode - inode 保护模式 |
| 3 | nlink | number of links - 被连接数目 |
| 4 | uid | userid of owner - 所有者的用户id |
| 5 | gid | groupid of owner- 所有者的组 id |
| 6 | rdev | device type, if inode device * - 设备类型,如果是 inode 设备的话 |
| 7 | size | size in bytes - 文件大小的字节数 |
| 8 | atime | time of last access (unix timestamp) - 上次访问时间(Unix 时间戳) |
| 9 | mtime | time of last modification (unix timestamp) - 上次修改时间(Unix 时间戳) |
| 10 | ctime | time of last change (unix timestamp) - 上次改变时间(Unix 时间戳) |
| 11 | blksize | blocksize of filesystem IO * - 文件系统 IO 的块大小 |
| 12 | blocks | number of blocks allocated - 所占据块的数目 |
注: 本函数的结果会被缓存。更多信息参见 clearstatcache()。
提示: 自 PHP 5.0.0 起本函数也可被某些 URL wrapper 使用。参考附录 L 来看哪些 wrapper 支持 stat() 系列函数的功能。
参见 lstat(),fstat(),filemtime() 和 filegroup()。
symlink() 对于已有的 target 建立一个名为 link 的符号连接。
如果成功则返回 TRUE,失败则返回 FALSE。
注: 本函数未在 Windows 平台下实现。
参见 link() 来建立硬连接,以及 readlink() 和 linkinfo()。
在指定目录中建立一个具有唯一文件名的文件。如果该目录不存在,tempnam() 会在系统临时目录中生成一个文件,并返回其文件名。
在 PHP 4.0.6 之前,tempnam() 函数的行为取决于系统。在 Windows 下 TMP 环境变量会越过 dir 参数,在 Linux 下 TMPDIR 环境变量优先,而在 SVR4 下总是使用 dir 参数,如果其指向的目录存在的话。如果有疑问请参考系统文档中的 tempnam(3) 函数。
注: 如果 PHP 不能在指定的 dir 参数中创建文件,则退回到系统默认值。
返回新的临时文件名,出错返回 FALSE。
注: 本函数的行为在 4.0.3 版中改变了。也会建立一个临时文件以避免竞争情形,即有可能会在产生出作为文件名的字符串与脚本真正建立该文件之间会在文件系统中存在同名文件。注意,如果不再需要该文件则要删除此文件,不会自动删除的。
以读写 (w+) 模式建立一个具有唯一文件名的临时文件,返回一个与 fopen() 所返回相似的文件句柄。文件会在关闭后(用 fclose())自动被删除,或当脚本结束后。
详细信息请参考系统手册中的 tmpfile(3) 函数,以及 stdio.h 头文件。
参见 tempnam()。
尝试将由 filename 给出的文件的访问和修改时间设定为给出的时间。如果没有给出可选参数 time,则使用当前时间。这和 utime(有时也叫做 utimes)所作的等价。如果给出了第三个参数 atime,则给定文件的访问时间会被设为 atime。注意访问时间总是会被修改的,不论有几个参数。
如果文件不存在,则会被创建。如果成功则返回 TRUE,失败则返回 FALSE。
umask() 将 PHP 的 umask 设定为 mask & 0777 并返回原来的 umask。当 PHP 被作为服务器模块使用时,在每个请求结束后 umask 会被恢复。
无参数调用 umask() 会返回当前的 umask。
注: 在多线程的服务器上尽量避免使用这个函数。创建文件后要改变其权限最好还是使用 chmod()。使用 umask() 会导致并发程序和服务器发生不可预知的情况,因为它们是使用相同的 umask 的。
删除 filename。和 Unix C 的 unlink() 函数相似。如果成功则返回 TRUE,失败则返回 FALSE。
注: 自 PHP 5.0.0 起 unlink() 也可以用于某些 URL 封装协议。参考附录 L 中的列表看哪些封装协议支持 unlink()。
注: 对 context 的支持是 PHP 5.0.0 添加的。有关 context 的说明请参考参考 CXLI, Stream Functions。
参见目录删除函数 rmdir()。
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:
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
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| ibase.allow_persistent | "1" | PHP_INI_SYSTEM | |
| ibase.max_persistent | "-1" | PHP_INI_SYSTEM | |
| ibase.max_links | "-1" | PHP_INI_SYSTEM | |
| ibase.default_db | NULL | PHP_INI_SYSTEM | Available since PHP 5.0.0. |
| ibase.default_user | NULL | PHP_INI_ALL | |
| ibase.default_password | NULL | PHP_INI_ALL | |
| ibase.default_charset | NULL | PHP_INI_ALL | Available 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 |
以下是配置选项的简要解释。
Whether to allow persistent connections to Firebird/InterBase.
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.
The maximum number of Firebird/InterBase connections per process, including persistent connections.
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.
The user name to use when connecting to a database if no user name is specified.
The password to use when connecting to a database if no password is specified.
The character set to use when connecting to a database if no character set is specified.
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
| Constant | Description |
|---|---|
| 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_READ | Starts a read-only transaction. |
| IBASE_WRITE | Starts a read-write transaction. |
| IBASE_CONSISTENCY | Starts 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_CONCURRENCY | Starts 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_COMMITTED | Starts 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_WAIT | Indicated that a transaction should wait and retry when a conflict occurs. |
| IBASE_NOWAIT | Indicated 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
| Constant | Description |
|---|---|
| IBASE_FETCH_BLOBS | Also available as IBASE_TEXTfor backward compatibility. Causes BLOB contents to be fetched inline, instead of being fetched as BLOB identifiers. |
| IBASE_FETCH_ARRAYS | Causes 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_UNIXTIME | Causes 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.
Options to ibase_backup()
Options to ibase_restore()
Options to ibase_maintain_db()
Options to ibase_db_info()
Options to ibase_server_info()
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().
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_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().
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().
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() 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().
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().
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]);
?> |
注: 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().
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
|
See also ibase_blob_add(), ibase_blob_cancel(), ibase_blob_close() and ibase_blob_create().
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() 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().
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().
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。
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。
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
|
注: 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().
| 警告 |
本函数暂无文档,仅有参数列表。 |
(PHP 4 >= 4.2.0, PHP 5)
ibase_delete_user -- Delete a user from a security database (only for IB6 or later)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().
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().
Returns the error code that resulted from the most recent InterBase function call. Returns FALSE if no error occurred.
See also ibase_errmsg().
Returns the error message that resulted from the most recent InterBase function call. Returns FALSE if no error occurred.
See also ibase_errcode().
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.
注: 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() 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().
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().
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().
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().
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().
Free a query prepared by ibase_prepare(). 如果成功则返回 TRUE,失败则返回 FALSE。
Frees a result set that has been created by ibase_query() or ibase_execute(). 如果成功则返回 TRUE,失败则返回 FALSE。
| 警告 |
本函数暂无文档,仅有参数列表。 |
Returns new generator value as integer, or as string if the value is too big.
| 警告 |
本函数暂无文档,仅有参数列表。 |
(PHP 4 >= 4.2.0, PHP 5)
ibase_modify_user -- Modify a user to a security database (only for IB6 or later)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().
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().
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().
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().
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().
(PHP 3 >= 3.0.6, PHP 4, PHP 5)
ibase_pconnect -- Open a persistent connection to an InterBase databaseibase_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.
(PHP 3 >= 3.0.6, PHP 4, PHP 5)
ibase_prepare -- Prepare a query for later binding of parameter placeholders and executionPrepare a query for later binding of parameter placeholders and execution (via ibase_execute()).
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.
注: 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().
| 警告 |
本函数暂无文档,仅有参数列表。 |
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。
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。
| 警告 |
本函数暂无文档,仅有参数列表。 |
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().
(PHP 3 >= 3.0.6, PHP 4)
ibase_timefmt -- Sets the format of timestamp, date and time type columns returned from queriesSets 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.
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().
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().
| 警告 |
本扩展模块是实验性的。本模块的行为,包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。使用本扩展模块风险自担。 |
(no version information, might be only in CVS)
PDO_FIREBIRD DSN -- Connecting to Firebird and Interbase databasesThe PDO_FIREBIRD Data Source Name (DSN) is composed of the following elements:
The DSN prefix is firebird:.
The hostname on which the database server resides.
The port number for the server on which the database is running.
The name of the database.
The name of the user that will connect to the database.
The password for the user.