PHP 手册

PHP 手册

Stig Sæther Bakken
Alexander Aulbach
Egon Schmid
Jim Winstead
Lars Torben Wilson
Rasmus Lerdorf
Andrei Zmievski
Jouni Ahto

中文文档翻译小组

Verdana
肖盛文
宋琪
Thomaslio Li
黄啸宇
王远之
孙翯

文件生成时间: Sat Sep 21 03:33:26 2002
请访问 http://www.php.net/docs.php 获取最新的版本

Copyright © 1997, 1998, 1999, 2000, 2001, 2002 the PHP Documentation Group


PHP 手册

目录

序文
I. 入门指引
1. 简介
2. 简明教程
3. 安装
4. Configuration
5. Security
II. 语言参考
6. 基本语法
7. 类型
8. 变量
9. 常量
10. 表达式
11. 运算符
12. 流程控制
13. 函数
14. 类与对象
15. 引用的解释
III. 特点
16. 错误处理
17. 图形的建立与操作
18. 用 PHP 进行 HTTP 认证
19. Cookies
20. 文件上传处理
21. 使用远程文件
22. 连接处理
23. 数据库永久连接
24. 安全模式
25. PHP 的命令行模式
IV. 函数参考
I. Apache 专用函数
II. 数组函数库
III. Aspell functions [deprecated]
IV. BCMath Arbitrary Precision Mathematics Functions
V. Bzip2 Compression Functions
VI. Calendar functions
VII. CCVS API Functions
VIII. COM support functions for Windows
IX. Class/Object Functions
X. ClibPDF functions
XI. Crack functions
XII. CURL, Client URL Library Functions
XIII. Cybercash payment functions
XIV. Crédit Mutuel CyberMUT functions
XV. Cyrus IMAP administration functions
XVI. Character type functions
XVII. Database (dbm-style) abstraction layer functions
XVIII. 时间日期函数库
XIX. dBase functions
XX. DBM Functions
XXI. dbx functions
XXII. DB++ Functions
XXIII. Direct IO functions
XXIV. Directory functions
XXV. DOM XML functions
XXVI. .NET functions
XXVII. Error Handling and Logging Functions
XXVIII. FrontBase Functions
XXIX. filePro functions
XXX. Filesystem functions
XXXI. Forms Data Format functions
XXXII. FriBiDi functions
XXXIII. FTP functions
XXXIV. Function Handling functions
XXXV. Gettext
XXXVI. GMP functions
XXXVII. HTTP functions
XXXVIII. Hyperwave functions
XXXIX. Hyperwave API functions
XL. iconv functions
XLI. Image functions
XLII. IMAP, POP3 and NNTP functions
XLIII. Informix functions
XLIV. InterBase functions
XLV. Ingres II functions
XLVI. IRC Gateway Functions
XLVII. PHP / Java Integration
XLVIII. LDAP functions
XLIX. Mail functions
L. mailparse functions
LI. Mathematical Functions
LII. Multi-Byte String Functions
LIII. MCAL functions
LIV. Mcrypt Encryption Functions
LV. Mhash Functions
LVI. Mimetype Functions
LVII. Microsoft SQL Server functions
LVIII. Ming functions for Flash
LIX. Miscellaneous functions
LX. mnoGoSearch Functions
LXI. mSQL functions
LXII. MySQL 函数库
LXIII. Mohawk Software session handler functions
LXIV. muscat functions
LXV. Network Functions
LXVI. Ncurses terminal screen control functions
LXVII. Lotus Notes functions
LXVIII. Unified ODBC functions
LXIX. Object Aggregation/Composition Functions
LXX. Oracle 8 functions
LXXI. OpenSSL functions
LXXII. Oracle functions
LXXIII. Ovrimos SQL functions
LXXIV. Output Control Functions
LXXV. Object property and method call overloading
LXXVI. PDF functions
LXXVII. Verisign Payflow Pro functions
LXXVIII. PHP Options&Information
LXXIX. POSIX functions
LXXX. PostgreSQL 数据库函数库
LXXXI. Process Control Functions
LXXXII. Program Execution functions
LXXXIII. Printer functions
LXXXIV. Pspell Functions
LXXXV. GNU Readline
LXXXVI. GNU Recode functions
LXXXVII. Regular Expression Functions (Perl-Compatible)
LXXXVIII. qtdom functions
LXXXIX. Regular Expression Functions (POSIX Extended)
XC. Semaphore, Shared Memory and IPC Functions
XCI. SESAM database functions
XCII. Session handling functions
XCIII. Shared Memory Functions
XCIV. Shockwave Flash functions
XCV. SNMP functions
XCVI. Socket functions
XCVII. String functions
XCVIII. Sybase functions
XCIX. Tokenizer functions
C. URL Functions
CI. Variable Functions
CII. vpopmail functions
CIII. W32api functions
CIV. WDDX Functions
CV. XML 语法解析函数
CVI. XML-RPC functions
CVII. XSLT functions
CVIII. YAZ functions
CIX. YP/NIS Functions
CX. Zip File Functions (Read Only Access)
CXI. Zlib Compression Functions
V. Extending PHP 4.0
26. Overview
27. Extension Possibilities
28. Source Layout
29. PHP's Automatic Build System
30. Creating Extensions
31. Using Extensions
32. Troubleshooting
33. Source Discussion
34. Accepting Arguments
35. Creating Variables
36. Duplicating Variable Contents: The Copy Constructor
37. Returning Values
38. Printing Information
39. Startup and Shutdown Functions
40. Calling User Functions
41. Initialization File Support
42. Where to Go from Here
43. Reference: Some Configuration Macros
44. API Macros
45. Streams API for PHP Extension Authors
Overview
Streams Basics
Streams Common API Reference
Streams Dir API Reference
Streams File API Reference
Streams Socket API Reference
Streams Structures
Streams Constants
VI. FAQ: 常见问题
46. 一般信息
47. 邮件列表
48. 获取 PHP
49. 数据库问题
50. 安装
51. 编译问题
52. 使用 PHP
53. PHP 和 HTML
54. PHP 和 COM
55. PHP 和其它语言
56. 从 PHP/FI 2 移植到 PHP 3
57. 从 PHP 3 移植到 PHP 4
58. 杂类问题
VII. 附录
A. PHP 及其相关工程的历史
B. 从 PHP 3 移植到 PHP 4
C. 从 PHP/FI 2 移植到 PHP 3
D. 排除 PHP 程序的错误
E. 扩展 PHP
F. 函数别名列表
G. 保留字列表
H. 资源类型列表
I. List of Supported Protocols/Wrappers
J. 解析器代号列表
K. 关于本手册
L. 函数索引
M. 补充说明
VIII. 微软 HTML 帮助版本
59. 关于此版本
60. Using PHP Manual CHM Edition
61. The Full Text Search
62. Specialities of this Edition
63. Integrating the PHP Manual
64. Skin development
65. CHM Edition Credits

前进
序文


序文

PHP，即“PHP: Hypertext Preprocessor”，是一种广泛用于 Open Source（开放源代码）的尤其适合 Web 开发并可以嵌入 HTML 的多用途脚本语言。它的语法接近 C，Java 和 Perl，而且容易学习。该语言的主要目标是让 Web 开发人员快速的书写动态生成的网页，然而，PHP 的功能并不局限于此。

本手册基本上由函数参考组成，此外包括语言参考、PHP 主要特点以及其它补充信息。

您可以在 http://www.php.net/docs.php 下载这个手册的几种格式的版本。 供下载的手册将随其内容的变化而更新。关于手册发展的更多信息， 请参阅附录：“关于本手册”。

后退 | 起点 | 前进
PHP 手册 |  | 入门指引


入门指引

PHP 手册
后退 前进

I. 入门指引

目录
1. 简介
2. 简明教程
3. 安装
4. Configuration
5. Security

后退 | 起点 | 前进
序文 |  | 简介


简介

PHP 手册
后退 前进

章 1. 简介

目录
PHP 是什么？
PHP 能做什么？

PHP 是什么？

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

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

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

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

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

    </body>
</html>

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

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

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

尽管 PHP 的开发是以服务端脚本为目的地，但事实上其功能远不局限与此。请继续读后面的章节，在“PHP 能做什么？”一节中您将获得更多的信息。

后退 | 起点 | 前进
入门指引 | 上一级 | PHP 能做什么？


PHP 能做什么？

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

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

  • 服务端脚本。这是 PHP 最传统，也是最主要的目标领域。开展这项工作您需要具备以下三点：PHP 解析器（CGI 或者服务器模块）、WEB 服务器和 WEB 浏览器。您需要在运行 WEB 服务器时，安装并配置 PHP，然后，可以用 WEB 浏览器来访问 PHP 程序的输出，即浏览服务端的 PHP 页面。请查阅“安装须知”一章以获取更多信息。

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

  • 编写客户端的 GUI 应用程序。对于基于窗口式的应用程序来说，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 目前的版本还没有支持 OOP 所有的标准，但很多代码仓库和大型的应用程序（包括 PEAR 库）仅使用 OOP 代码来开发。

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

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

Adabas D | Ingres | Oracle (OCI7 and OCI8)
dBase | InterBase | Ovrimos
Empress | FrontBase | PostgreSQL
FilePro (read-only) | mSQL | Solid
Hyperwave | Direct MS-SQL | Sybase
IBM DB2 | MySQL | Velocis
Informix | ODBC | Unix dbm

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

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

PHP 具有极其有效的文本处理特性，支持从 POSIX 扩展或者 Perl 正则表达式到 XML 文档解析。为了解析和访问 XML 文档，我们支持了 SAX 和 DOM 标准。您可以使用我们的 XSLT 扩展库来转换 XML 文档。

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

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

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

后退 | 起点 | 前进
简介 | 上一级 | 简明教程


简明教程

PHP 手册
后退 前进

章 2. 简明教程

目录
我需要些什么？
您的第一个 PHP 页面
实用的脚本
处理表单
在新版本的 PHP 中使用旧的 PHP 代码
下一步做什么？

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

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

我需要些什么？

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

后退 | 起点 | 前进
PHP 能做什么？ | 上一级 | 您的第一个 PHP 页面


您的第一个 PHP 页面

在您的 WEB 服务器根目录下建立一个文件名为 hello.php，然后完成如下内容：

例子 2-1. 我们的第一个 PHP 脚本： hello.php

<html>
 <head>
  <title>PHP Tes</title>
 </head>
 <body>
 <?php echo "Hello World<p>"; ?>
 </body>
</html>

该脚本的输出应该为：
<html>
 <head>
  <title>PHP Test</title>
 </head>
 <body>
 Hello World<p>
 </body>
</html>

请注意这和 CGI 脚本不同，该文件不用制作成可执行脚本，它没有任何特殊的地方。您只需把它当作一个普通的 HTML 文档，只是里面多了一重新的标识符，使得您可以用它来做很多有趣的事情。

该程序非常的简单，它仅仅只是利用了 PHP 的 echo() 语句显示了 Hello World。您一定不会满足与此。

如果您试过了这个例子，但是没有得到任何地输出，或者您的浏览器弹出了下载框，或者浏览器以文本方式显示了源文件，可能的原因是您的服务器还没有支持 PHP。您需要请您服务器的管理员根据本手册“安装”一章的内容使得服务器支持 PHP。如果您希望在本地机器上开发 PHP 脚本，请查阅“下载”一节。您可以在任何操作系统下进行本地开发，只需安装合适的 WEB 服务器。

以上例子的目的是为了显示 PHP 特殊标识符的格式。在这个例子中，我们用 <?php 来表示 PHP 标识符的起始，然后我们放入 PHP 语句并通过加上一个终止标识符 ?> 来退出 PHP 模式。您可以根据您的需要在 HTML 文件中像这样开启或关闭 PHP 模式。

关于文本编辑器: 有很多文本编辑器以及集成开发环境（IDEs）可以被用来建立、编辑和管理 PHP 文件。这些工具中的一部分被列在 PHP 编辑器列表中。如果您希望推荐其它的编辑器，请访问以上页面，并要求该页面的维护者将您推荐的编辑器加入到该列表中。

关于文字处理器: 诸如 StarOffice Writer、Microsoft Word 和 Abiword 的文字处理器不是编辑 PHP 文件的良好选择。

如果您希望用以上这些工具的某一种来处理脚本，您必须保证将结果存成了纯文本（PLAIN TEXT）格式，否则 PHP 将无法读取并运行这些脚本。

关于 Windows 记事本: 如果您使用 Windows 记事本来编写 PHP 脚本，您需要注意在您保存文件时，文件的后缀名应该为 .php。（记事本将自动在文件名后面加上 .txt 后缀，除非您采取以下措施之一来避免这种情况。）

当您保存文件时，系统会让你指定文件的文件名，这时请将您的文件名加上引号。（例如，“hello.php”。）

或者，您也可以点击保存对话框中的“保存类型”下拉菜单，并将设置改为“所有文件”。这样您在输入文件名的时候就不用加引号了。

后退 | 起点 | 前进
简明教程 | 上一级 | 实用的脚本


实用的脚本

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

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

要显示该变量，我们只需简单地进行如下操作：

例子 2-2. 打印一个变量（数组元素）

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

该脚本的输出可能是：
Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)

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

$_SERVER 只是 PHP 自动全局化的变量之一。您可以查阅“保留变量”一节来查看这些变量的列表，或者也可以建立如下的文件来得到一个完整的列表：

例子 2-3. 利用 phpinfo() 来显示所有预定义变量

<?php phpinfo(); ?>

如果您在您的浏览器中打开这个文件，您将看到关于 PHP 完整的信息，以及所有您可以使用的变量列表。

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

例子 2-4. 结构控制与函数的使用

<?php
if (strstr($_SERVER["HTTP_USER_AGENT"], "MSIE")) {
    echo "You are using Internet Explorer<br />";
}
?>

该脚本的输出可能是：
You are using Internet Explorer<br />

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

我们需要介绍的第二个原理，是对 strstr() 函数的调用。strstr() 是 PHP 的一个内建函数，其功能是在一个字符串中搜索另外一个字符串。例如我们现在需要在 $_SERVER["HTTP_USER_AGENT"] 变量中寻找 "MSIE"。如果该字符串被找到，则函数返回 TRUE，如果没有，则返回 FALSE。如果该函数返回了 TRUE，则 if 会将条件判断为 TRUE 并运行其大括号 {} 内的代码；否则，则不运行。您可以自己尝试利用if、else以及其它的函数，例如 strtoupper() 和 strlen()，来建立类似的脚本。在本手册中，相关的页面也包含有范例。

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

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

<?php
if (strstr($_SERVER["HTTP_USER_AGENT"], "MSIE")) {
?>
<h3>strstr must have returned true</h3>
<center><b>You are using Internet Explorer</b></center>
<?php
} else {
?>
<h3>strstr must have returned false</h3>
<center><b>You are not using Internet Explorer</b></center>
<?php
}
?>

该脚本的输出可能是：
<h3>strstr must have returned true</h3>
<center><b>You are using Internet Explorer</b></center>

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

后退 | 起点 | 前进
您的第一个 PHP 页面 | 上一级 | 处理表单


处理表单

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

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

<form action="action.php" method="POST">
 Your name: <input type="text" name="name" />
 Your age: <input type="text" name="age" />
 <input type="submit">
</form>

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

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

Hi <?php echo $_POST["name"]; ?>.
You are <?php echo $_POST["age"]; ?> years old.

该脚本的输出可能是：
Hi Joe.
You are 22 years old.

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

后退 | 起点 | 前进
实用的脚本 | 上一级 | 在新版本的 PHP 中使用旧的 PHP 代码


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

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

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

  • 取消了旧的 $HTTP_*_VARS 数组（在函数或者方法中他们原本是全局变量）。PHP 4.1.0 版本引入了如下自动全局数组变量： $_GET、$_POST、 $_COOKIE、$_SERVER、 $_ENV、$_REQUEST 以及 $_SESSION。 老的 $HTTP_*_VARS 数组，诸如 $HTTP_POST_VARS 等，从 PHP 3 就已经开始使用，它们仍然存在。

  • 外部变量不再默认得被注册为全局变量。也就是说，从 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 中使用旧的 PHP 代码 | 上一级 | 安装


安装

PHP 手册
后退 前进

章 3. 安装

目录
General Installation Considerations
Unix/HP-UX installs
Unix/Linux installs
Unix/Mac OS X installs
Unix/OpenBSD installs
Unix/Solaris installs
Installation on UNIX systems
Windows 系统下的安装
Servers-CGI/Commandline
Apache 服务器
Caudium 服务器
Servers-fhttpd
IIS/PWS 服务器
Servers-Netscape and iPlanet
Servers-OmniHTTPd Server
Servers-Oreilly Website Pro
Servers-Xitami
Servers-Other web servers
Problems?
Complete list of configure options

General Installation Considerations

Before installing first, you need to know what do you want to use PHP for. There are three main fields you can use PHP, as described in the What can PHP do? section:

  • Server-side scripting

  • Command line scripting

  • Client-side GUI applications

For the first and most common form, you need three things: PHP itself, a web server and a web browser. You probably already have a web browser, and depending on your operating system setup, you may also have a web server (eg. Apache on Linux or IIS on Windows). You may also rent webspace at a company. This way, you don't need to set up anything on your own, only write your PHP scripts, upload it to the server you rent, and see the results in your browser. You can find a list of hosting companies at http://hosts.php.net/.

While setting up the server and PHP on your own, you have two choices for the method of connecting PHP to the server. For many servers PHP has a direct module interface (also called SAPI). These servers include Apache, Microsoft Internet Information Server, Netscape and iPlanet servers. Many other servers have support for ISAPI, the Microsoft module interface (OmniHTTPd for example). If PHP has no module support for your web server, you can always use it as a CGI processor. This means you set up your server to use the command line executable of PHP (php.exe on Windows) to process all PHP file requests on the server.

If you are also interested to use PHP for command line scripting (eg. write scripts autogenerating some images for you offline, or processing text files depending on some arguments you pass to them), you always need the command line executable. For more information, read the section about writing command line PHP applications. In this case, you need no server and no browser.

With PHP you can also write client side GUI applications using the PHP-GTK extension. This is a completely different approach than writing web pages, as you do not output any HTML, but manage windows and objects within them. For more information about PHP-GTK, please visit the site dedicated to this extension. PHP-GTK is not included in the official PHP distribution.

From now on, this section deals with setting up PHP for web servers on Unix and Windows with server module interfaces and CGI executables.

Downloading PHP, the source code, and binary distributions for Windows can be found at http://www.php.net/. We recommend you to choose a mirror nearest to you for downloading the distributions.

后退 | 起点 | 前进
下一步做什么？ | 上一级 | Unix/HP-UX installs


Unix/HP-UX installs

This section contains notes and hints specific to installing PHP on HP-UX systems.

例子 3-1. Installation Instructions for HP-UX 10

From: paul_mckay@clearwater-it.co.uk
04-Jan-2001 09:49
(These tips are for PHP 4.0.4 and Apache v1.3.9)

So you want to install PHP and Apache on a HP-UX 10.20 box?

1. You need gzip, download a binary distribution from
http://hpux.connect.org.uk/ftp/hpux/Gnu/gzip-1.2.4a/gzip-1.2.4a-sd-10.20.depot.Z
uncompress the file and install using swinstall

2. You need gcc, download a binary distribution from
http://gatekeep.cs.utah.edu/ftp/hpux/Gnu/gcc-2.95.2/gcc-2.95.2-sd-10.20.depot.gz
gunzip this file and install gcc using swinstall.

3. You need the GNU binutils, you can download a binary distribution from
http://hpux.connect.org.uk/ftp/hpux/Gnu/binutils-2.9.1/binutils-2.9.1-sd-10.20.depot.gz
gunzip and install using swinstall.

4. You now need bison, you can download a binary distribution from
http://hpux.connect.org.uk/ftp/hpux/Gnu/bison-1.28/bison-1.28-sd-10.20.depot.gz
install as above.

5. You now need flex, you need to download the source from one of the
http://www.gnu.org mirrors. It is in the <filename>non-gnu</filename> directory of the ftp site.
Download the file, gunzip, then tar -xvf it. Go into the newly created flex
directory and do a ./configure, then a make, and then a make install

If you have errors here, it's probably because gcc etc. are not in your
PATH so add them to your PATH.

Right, now into the hard stuff.

6. Download the PHP and apache sources.

7. gunzip and tar -xvf them.

We need to hack a couple of files so that they can compile ok.

8. Firstly the configure file needs to be hacked because it seems to lose
track of the fact that you are a hpux machine, there will be a
better way of doing this but a cheap and cheerful hack is to put
    lt_target=hpux10.20
on line 47286 of the configure script.

9. Next, the Apache GuessOS file needs to be hacked. Under
apache_1.3.9/src/helpers change line 89 from
    "echo "hp${HPUXMACH}-hpux${HPUXVER}"; exit 0"
to:
    "echo "hp${HPUXMACH}-hp-hpux${HPUXVER}"; exit 0"

10. You cannot install PHP as a shared object under HP-UX so you must compile
it as a static, just follow the instructions at the Apache page.

11. PHP and apache should have compiled OK, but Apache won't start. you need
to create a new user for Apache, eg www, or apache. You then change lines 252
and 253 of the conf/httpd.conf in Apache so that instead of
    User nobody
    Group nogroup
you have something like
    User www
    Group sys

This is because you can't run Apache as nobody under hp-ux.
Apache and PHP should then work.

Hope this helps somebody,
Paul Mckay.

后退 | 起点 | 前进
安装 | 上一级 | Unix/Linux installs


Unix/Linux installs

This section contains notes and hints specific to installing PHP on Linux distributions.

Using Packages

Many Linux distributions have some sort of package installation system, such as RPM. This can assist in setting up a standard configuration, but if you need to have a different set of features (such as a secure server, or a different database driver), you may need to build PHP and/or your webserver. If you are unfamiliar with building and compiling your own software, it is worth checking to see whether somebody has already built a packaged version of PHP with the features you need.

后退 | 起点 | 前进
Unix/HP-UX installs | 上一级 | Unix/Mac OS X installs


Unix/Mac OS X installs

This section contains notes and hints specific to installing PHP on Mac OS X Server.

Using Packages

There are a few pre-packaged and pre-compiled versions of PHP for Mac OS X. This can help in setting up a standard configuration, but if you need to have a different set of features (such as a secure server, or a different database driver), you may need to build PHP and/or your web server yourself. If you are unfamiliar with building and compiling your own software, it's worth checking whether somebody has already built a packaged version of PHP with the features you need.

Compiling for OS X server

There are two slightly different versions of Mac OS X, client and server. The following is for OS X Server.

例子 3-2. Mac OS X server install

1. Get the latest distributions of Apache and PHP
2. Untar them, and run the configure program on Apache like so.
    ./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

4. You may also want to add this line:
    setenv OPTIM=-O2
    If you want the compiler to do some optimization.

5. Next, go to the PHP 4 source directory and configure it.
    ./configure --prefix=/usr \
    --sysconfdir=/etc \
    --localstatedir=/var \
    --mandir=/usr/share/man \
    --with-xml \
    --with-apache=/src/apache_1.3.12

    If you have any other additions (MySQL, GD, etc.), be sure to add
    them here. For the --with-apache string, put in the path to your
    apache source directory, for example "/src/apache_1.3.12".
6. make
7. make install
    This will add a directory to your Apache source directory under
    src/modules/php4.

8. Now, reconfigure Apache to build in 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

    You may get a message telling you that libmodphp4.a is out of date.
    If so, go to the src/modules/php4 directory inside your apache
    source directory and run this command:

    ranlib libmodphp4.a

    Then go back to the root of the apache source directory and run the
    above configure command again. That'll bring the link table up to
    date.

9. make

10. make install

11. copy and rename the php.ini-dist file to your "bin" directory from your
    PHP 4 source directory:
    cp php.ini-dist /usr/local/bin/php.ini

    or (if your don't have a local directory)

    cp php.ini-dist /usr/bin/php.ini

Other examples for Mac OS X client and Mac OS X server are available at Stepwise.

Compiling for MacOS X client

Those tips are graciously provided by Marc Liyanage.

The PHP module for the Apache web server included in Mac OS X. This version includes support for the MySQL and PostgreSQL databases.

NOTE: Be careful when you do this, you could screw up your Apache web server!

Do this to install:

  • 1. Open a terminal window

  • 2. Type "wget http://www.diax.ch/users/liyanage/software/macosx/libphp4.so.gz", wait for download to finish

  • 3. Type "gunzip libphp4.so.gz"

  • 4. Type "sudo apxs -i -a -n php4 libphp4.so"

Now type "sudo open -a TextEdit /etc/httpd/httpd.conf" TextEdit will open with the web server configuration file. Locate these two lines towards the end of the file: (Use the Find command)
#AddType application/x-httpd-php .php
   #AddType application/x-httpd-php-source .phps
Remove the two hash marks (#), then save the file and quit TextEdit.

Finally, type "sudo apachectl graceful" to restart the web server.

PHP should now be up and running. You can test it by dropping a file into your "Sites" folder which is called "test.php". Into that file, write this line: "<?php phpinfo() ?>".

Now open up 127.0.0.1/~your_username/test.php in your web browser. You should see a status table with information about the PHP module.

后退 | 起点 | 前进
Unix/Linux installs | 上一级 | Unix/OpenBSD installs


Unix/OpenBSD installs

This section contains notes and hints specific to installing PHP on OpenBSD.

Using Ports

This is the recommended method of installing PHP on OpenBSD, as it will have the latest patches and security fixes applied to it by the maintainers. To use this method, ensure that you have a recent ports tree. Then simply find out which flavors you wish to install, and issue the make install command. Below is an example of how to do this.

例子 3-3. OpenBSD Ports Install Example

$ cd /usr/ports/www/php4
$ make show VARNAME=FLAVORS
 (choose which flavors you want from the list)
$ env FLAVOR="imap gettext ldap mysql gd" make install
$ /usr/local/sbin/php4-enable

Using Packages

There are pre-compiled packages available for your release of OpenBSD. These integrate automatically with the version of Apache installed with the OS. However, since there are a large number of options (called flavors) available for this port, you may find it easier to compile it from source using the ports tree. Read the packages(7) manual page for more information in what packages are available.

后退 | 起点 | 前进
Unix/Mac OS X installs | 上一级 | Unix/Solaris installs


Unix/Solaris installs

This section contains notes and hints specific to installing PHP on Solaris systems.

Required software

Solaris installs often lack C compilers and their related tools. The required software is as follows:

  • gcc (recommended, other C compilers may work)

  • make

  • flex

  • bison

  • m4

  • autoconf

  • automake

  • perl

  • gzip

  • tar

In addition, you will need to install (and possibly compile) any additional software specific to your configuration, such as Oracle or MySQL.

Using Packages

You can simplify the Solaris install process by using pkgadd to install most of your needed components.

后退 | 起点 | 前进
Unix/OpenBSD installs | 上一级 | Installation on UNIX systems


Installation on UNIX systems

This section will guide you through the general configuration and installation of PHP on Unix systems. Be sure to investigate any sections specific to your platform or web server before you begin the process.

Prerequisite knowledge and software:

  • Basic UNIX skills (being able to operate "make" and a C compiler, if compiling)

  • An ANSI C compiler (if compiling)

  • flex (for compiling)

  • bison (for compiling)

  • A web server

  • Any module specific components (such as gd, pdf libs, etc.)

There are several ways to install PHP for the Unix platform, either with a compile and configure process, or through various pre-packaged methods. This documentation is mainly focused around the process of compiling and configuring PHP.

The initial PHP setup and configuration process is controlled by the use of the commandline options of the configure script. This page outlines the usage of the most common options, but there are many others to play with. Check out the Complete list of configure options for an exhaustive rundown. There are several ways to install PHP:

  • As an Apache module

  • As an fhttpd module

  • For use with AOLServer, NSAPI, phttpd, Pi3Web, Roxen, thttpd, or Zeus.

  • As a CGI executable

Apache Module Quick Reference

PHP can be compiled in a number of different ways, but one of the most popular is as an Apache module. The following is a quick installation overview.

例子 3-4. Quick Installation Instructions for PHP 4 (Apache Module Version)

1.  gunzip apache_1.3.x.tar.gz
2.  tar xvf apache_1.3.x.tar
3.  gunzip php-x.x.x.tar.gz
4.  tar xvf php-x.x.x.tar
5.  cd apache_1.3.x
6.  ./configure --prefix=/www
7.  cd ../php-x.x.x
8.  ./configure --with-mysql --with-apache=../apache_1.3.x --enable-track-vars
9.  make
10. make install
11. cd ../apache_1.3.x
12. ./configure --activate-module=src/modules/php4/libphp4.a
13. make
14. make install
15. cd ../php-x.x.x
16. cp php.ini-dist /usr/local/lib/php.ini
17. Edit your httpd.conf or srm.conf file and add:
      AddType application/x-httpd-php .php

18. Use your normal procedure for restarting the Apache server. (You must
    stop and restart the server, not just cause the server to reload by
    use a HUP or USR1 signal.)

Building

When PHP is configured, you are ready to build the CGI executable. The command make should take care of this. If it fails and you can't figure out why, see the Problems section.

后退 | 起点 | 前进
Unix/Solaris installs | 上一级 | Windows 系统下的安装


Windows 系统下的安装

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

有两种方法安装 PHP for Windows：手工安装或者使用 InstallShield 安装。

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

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

Windows InstallShield

Windows版的 PHP 安装程序可以从 http://www.php.net/ 获得，此程序将安装 PHP 的 CGI 版本，并且自动配置好 IIS，PWS 和 Xitami 三种 Web 服务器。注意，InstallShield Installer 是一种简单易用的安装方法，在很多方面都受到限制，例如不支持自动配置扩展库。

安装好你选用的 HTTP 服务器并且确定工作正常。

运行可执行的安装程序并按照安装向导的提示进行安装。安装程序支持两种安装方法 － 标准，尽量提供最佳默认参数，高级，在安装过程中提问。

安装向导收集足够的信息来配置 php.ini 文件并且配置 Web 服务器来使用 PHP。在 NT Workstation 下的 IIS 和 PWS 中，会列出服务器上所有节点的脚本映射，你可以在这些节点中选择哪些加入 PHP 的脚本映射。

一旦安装结束，安装程序会提示是否需要重新启动系统。重启动服务器或者开始使用 PHP。

警告

注意，这样安装的 PHP 并不安全。如果你想要更安全的安装 PHP，最好手工进行，并且小心地配置每个选项。自动进行的安装程序只是提供一个可以马上使用的 PHP，并不意味着可以用在在线的服务器上。

手工安装步骤

本安装指南帮你手工安装和配置 PHP 到你的 Windows Webserver。你需要从 http://www.php.net/ 下载一个包含可执行版本的 zip 包。本指南的原始版本由 Bob Silva 编辑，位于：http://www.umesd.k12.or.us/php/win32install.html。

本指南提供以下的手工安装支持：

  • Personal Web Server 3，4 或更新版本

  • Internet Information Server 3，4 或更新版本

  • Apache 1.3.x

  • OmniHTTPd 2.0b1 及以上版本

  • Oreilly Website Pro

  • Xitami

  • Netscape Enterprise Server，iPlanet

PHP 4 for Windows 有两种方式 － CGI 版的可执行文件（php.exe），以及一些 SAPI 模块（例如：php4isapi.dll）。后一种是 PHP 4 新提供的方式，提供了显著的性能增长以及一些新功能。

警告

SAPI 模块在 4.1 版中有了显著的增强，但是，在一些老系统中，你也许会遇到可能的服务器错误或者其他的模块例如 ASP 失败。

如果你选择了其中一个 SAPI 模块并且是在 Windows 95 下使用，要确认从微软的 DCOM 页面下载安装了 DCOM 更新。对于 ISAPI 模块，需要 ISAPI 4.0 兼容的Web 服务器（在 IIS 4.0，PWS 4.0 以及 IIS 5.0 下测试通过）。不支持 IIS 3.0。如果需要本地 PHP 支持，你需要下载和安装 Windows NT 4.0 Option Pack With IIS 4.0。

不论何种 Web 服务器，都需要先进行以下步骤：

  • 将 PHP 压缩包释放到你选择的目录中。c:\php\ 就不错。你可能不想用中间有空格的路径（例如：C:\Program Files\PHP 就不太好），如果这样做有些 Web 服务器会崩溃。

  • 你需要确认 PHP 使用的 DLL 文件能被找到。具体涉及到哪些 DLL 文件是根据你用哪种 Web 服务器和你是用 CGI 方式还是服务器模块方式使用 PHP 来决定的。php4ts.dll 是一定要用的。如果你用服务器模块（例如 ISAPI 或者 Apache）那你需要 sapi 目录下相关的 DLL 文件。如果你用了任何 PHP 扩展库那你也需要那些 DLL 文件。为了确保 DLL 文件能被找到，你可以要么把这些文件拷贝到 system 目录下（例如 winnt\system32 或者 windows\system），要么确认这些文件和 PHP 的主要执行文件或者 Web 服务器使用的 DLL 文件在同一个目录下（例如 php.exe，php4apache.dll）。

    PHP 可执行文件，SAPI 模块和一些扩展库要依靠外部的 DLL 文件来执行。需要确认这些 DLL 文件所在目录在 Windows 的路径中。最好把以下文件拷贝到你的 system 目录中，system 目录通常为：

    c:\windows\system for Windows 9x/ME
    c:\winnt\system32 for Windows NT/2000
    c:\windows\system32 for Windows XP

    需要拷贝的文件是：

    php4ts.dll，如果已经存在，则覆盖之。
    PHP发行包中 'dlls' 目录下的所有文件。如果这些文件已经安装在你的系统中，仅在不能正确运行时才覆盖它们（在覆盖前，最好备份原来的文件，或者把原来的文件移动到别的文件夹中 － 以防出错）。

    下载最新版的 Microsoft Data Access Components（MDAC），尤其是使用 Windows 9x/NT4 时。MDAC 位于 http://www.microsoft.com/data/。

  • 拷贝你选中的 ini 文件（见下面）到你的 '%WINDOWS%' 目录下，如果使用的是 Windows 9x/Me，或者到 '%SYSTEMROOT%' 目录下，如果使用的是 Windows NT/2000/XP 并且改名为 php.ini。典型的 '%WINDOWS%' 或者 '%SYSTEMROOT%' 目录为：

    c:\windows for Windows 9x/ME/XP
    c:\winnt 或 c:\winnt40 for NT/2000 servers

    在 PHP 的 zip 包中提供了两个版本的 ini 文件，php.ini-dist 和 php.ini-optimized。我们建议你使用 php.ini-optimized，因为我们优化了此文件中的默认设置以达到更佳性能与安全。最好仔细研究所有的 ini 设置并且自己手工设置每一项参数。如果你想达到最佳的安全性，那这正是为你准备的。当然了，PHP 在默认的 ini 文件下也一样运行得很好。

  • 编辑你的新 php.ini 文件：

    • 你需要修改 'extension_dir' 设置以指向你安装 PHP 的目录，或者你放置那些 php_*.dll 文件的目录，例如：c:\php\extensions

    • 如果你使用 OmniHTTPd，不要进行这一步。设置 'doc_root' 指向你 Webserver 的 document_root。例如：c:\apache\htdocs 或者 c:\webroot

    • 选择哪些扩展库你希望在 PHP 启动时加载。阅读 Windows 扩展库部分学习如何加载，以及哪些是已经加载了的。注意在新安装 PHP 时，建议先不要加载任何扩展库，先确认 PHP 运行正常之后再在 php.ini 中加载它们。

    • PHP 发行包的 browscap 目录下提供了一个 browscap.ini 文件，你可以用它覆盖系统中原有的。在 PWS 和 IIS 中，该文件在 Windows 9x/Me 下位于 c:\windows\system\inetsrv\browscap.ini，在 NT/2000 下位于 c:\winnt\system32\inetsrv\browscap.ini，在 XP 下位于 c:\windows\system32\inetsrv\browscap.ini。

    • 注意 Windows 版中的 mibs 目录包括了 SNMP 的支持文件。该目录应该被移动到：DRIVE:\usr\mibs（DRIVE 是安装了 PHP 的盘符）。

    • 如果你在 Windows NT，2000 或者 XP 下使用了 NTFS，确认运行 Webserver 的用户对于 php.ini 有读的权限（例如使其对所有人可读）。

  • 在 PWS 下给 webroot 执行的权限：

    • 启动“个人 Web 管理器”（PWS Web Manager）

    • 选中“<Home>”，点击“编辑属性(E)”

    • 选中“执行”（Execute）多选框

编译源程序

开始之前，很值得回答一下这个问题：“为什么在 Windows 下编译这么难？”两个原因：

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

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

准备

在开始之前，需要下载很多东西...

  • 对初学者，从最近的 cygwin 镜像站点下载 Cygwin 工具包。这将提供在编译中用到的大多数流行的 GNU 工具。

  • 从 PHP 站点下载其余需要的编译工具：http://www.php.net/extra/win32build.zip。

  • 下载 PHP 使用的 DNS 解析器的源代码：http://www.php.net/extra/bindlib_w32.zip。用这个替代 win32build.zip 中的 resolv.lib。

  • 如果你还没有 unzip 工具，那你需要一个。可以从 InfoZip 下载一个免费的。

  • 如果你计划把 PHP 编译成 Apache 的静态模块那你还需要你用的 Apache 相应版本的源程序。

最后，你还需要 PHP 4 的源代码。你可以通过 匿名 CVS 得到最新的开发版本。如果你有了 snapshot 或者源代码的 tar.gz 文件，你不仅需要 untar 和 unzip 它们，还要在 Microsoft Visual C++ 处理之前把 *.dsp 和 *.dsw 文件中的换行符转换成回车换行。

注: 把 Zend 和 TSRM 目录放到 PHP 4 目录之中，以便在编译过程中能够找到项目文件。

放到一起

  • 遵循你选择的解压缩工具的用法。

  • 运行 setup.exe，按照安装说明进行。如果你选择的安装目录不是 c:\cygnus，设置 Cygwin 环境变量让编译程序知道。在 Windows 95/98 下设置环境变量可以通过在 autoexec.bat 中加入一行做到。在 Windows NT 中，打开我的电脑 => 控制面板 => 系统，并且选择环境变量标签。

警告

建立一个临时目录给 Cygwin 使用，否则很多命令（尤其是 bison）将出错。在 Windows 95/98 下，mkdir C:\TMP。在 Windows NT 下，mkdir %SystemDrive%\tmp。

  • 建一个目录把 win32build.zip 解压缩到里面。

  • 运行 Microsoft Visual C++，选择 Tools => Options 菜单，在对话框中选择 Directories 标签。依次在下拉框中选择 Executable，Include 和 Library files，确认 cygwin\bin，win32build\include 和 win32build\lib 在每个列表框中都包括。（要加入一项，选择列表框最下面的空行并且输入路径)。典型的列表看上如同：

    • c:\cygnus\bin

    • c:\php-win32build\include

    • c:\php-win32build\lib

    点击 OK，退回到 Visual C++。

  • 另外建一个目录并且把 bindlib_w32.zip 解压缩到里面。决定你是需要调试符号（bindlib - Win32 Debug）还是不需要（bindlib - Win32 Release）。建立适当配置：

    • 图形界面用户，运行 VC++，选择 File => Open Workspace 菜单并选择 bindlib。接着选择 Build => Set Active Configuration 菜单并选择需要的配置。最后选择 Build => Rebuild All。

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

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

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

    • 到这一步，你应该得到一个 resolv.lib 在你的 Debug 或者 Release 目录下。拷贝此文件到 win32build\lib 目录下并且覆盖同名的文件。

编译

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

  • 图形界面用户，运行 VC++，选择 File => Open Workspace 菜单并选择 php4ts。接着选择 Build => Set Active Configuration 菜单并选择需要的配置。最后选择 Build => Rebuild All。

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

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

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

    • 到这一步，你应该得到一个可用的 php.exe 在你的 Debug_TS 或者 Release_TS 目录下。

重复以上步骤处理 php4isapi.dsp（在 sapi\isapi 目录下）来编译使 PHP 能够和 Microsoft IIS 集成的代码。

有可能通过编辑 main/config.win32.h.in 文件来对编译过程做一些较小的定制。

Windows 扩展库的安装

在安装好 PHP 和 Webserver 之后，你可能想安装一些扩展库以增加功能。下表说明了一些可用的扩展库。你可以通过去掉 php.ini 中 'extension=php_*.dll' 前面的注释来选择哪些扩展库在 PHP 启动时被加载。你也可以在程序中用 dl() 函数动态加载。

PHP 4 扩展库的 DLL 文件开头都是 'php_'（PHP 3 中是 'php3_' ）。这避免了 PHP 扩展库和它们的支持库混淆。

注: 在PHP 4.0.6 版中 BCMath，Calendar，COM，FTP，MySQL，ODBC，PCRE，Session，WDDX 和 XML 的支持都是内置的。不需要加载任何扩展库就可以使用这些函数。你可以查看自己的版本中的 README.txt 或者 install.txt 文件哪些模块是内置的。

注: 一些扩展库需要其它的 DLL 文件支持才能运行。有几个在发行包的 'dlls' 目录下。但是有一些，例如 Oracla（php_oci8.dll）所需要的 DLL 文件并没有包括在发行包中。

把 'DLLs' 目录下绑定的 DLL 文件拷贝到 Windows 路径中的目录中。安全的地方有：

c:\windows\system for Windows 9x/Me
c:\winnt\system32 for Windows NT/2000
c:\windows\system32 for Windows XP

如果这些文件已经安装在你的系统中，仅在不能正确运行时才覆盖它们（在覆盖前，最好备份原来的文件，或者把原来的文件移动到别的文件夹中 － 以防出错)。

表格 3-1. PHP 扩展库

库名 | 说明 | 注意
php_bz2.dll | bzip2 压缩函数库 | 无
php_calendar.dll | Calendar 转换函数库 | 自 PHP 4.0.3 起内置
php_cpdf.dll | ClibPDF 函数库 | 无
php_crack.dll | Crack 函数库 | 无
php3_crypt.dll | 加密函数库 | 未知
php_ctype.dll | ctype 族函数库 | 无
php_curl.dll | CURL，客户端 URL 函数库 | 需要：libeay32.dll，ssleay32.dll（已包含）
php_cybercash.dll | Cybercash 支付函数库 | 无
php_db.dll | DBM 函数库 | 不赞成使用。用 DBA 代替（php_dba.dll）
php_dba.dll | DBA：数据库（dbm-style）抽象层函数库 | 无
php_dbase.dll | dBase 函数库 | 无
php3_dbm.dll | Berkeley DB2 库 | 未知
php_domxml.dll | DOM XML 函数库 | 需要：libxml2.dll（已包含）
php_dotnet.dll | .NET 函数库 | 无
php_exif.dll | 从 JPEG 读取 EXIF 头信息 | 无
php_fbsql.dll | FrontBase 函数库 | 无
php_fdf.dll | FDF：表单数据格式化函数库. | 需要：fdftk.dll （已包含）
php_filepro.dll | filePro 函数库 | 只读访问
php_ftp.dll | FTP 函数库 | 自 PHP 4.0.3 起内置
php_gd.dll | GD 库图像处理函数库 | 无
php_gettext.dll | Gettext 函数库 | 需要：gnu_gettext.dll（已包含）
php_hyperwave.dll | HyperWave 函数库 | 无
php_iconv.dll | ICONV 字符集转换 | 需要：iconv-1.3.dll（已包含）
php_ifx.dll | Informix 函数库 | 需要：Informix 库文件
php_iisfunc.dll | IIS 管理函数库 | 无
php_imap.dll | IMAP POP3 和 NNTP 函数库 | PHP 3：php3_imap4r1.dll
php_ingres.dll | Ingres II 函数库 | 需要：Ingres II 库文件
php_interbase.dll | InterBase 函数库 | 需要：gds32.dll（已包含）
php_java.dll | Java 扩展 | 需要：jvm.dll（已包含）
php_ldap.dll | LDAP 函数库 | 需要：libsasl.dll（已包含）
php_mhash.dll | Mhash 函数库 | 无
php_ming.dll | Ming 函数库 － Flash 支持 | 无
php_msql.dll | mSQL 函数库 | 需要：msql.dll（已包含）
php3_msql1.dll | mSQL 1 客户端 | 未知
php3_msql2.dll | mSQL 2 客户端 | 未知
php_mssql.dll | MSSQL 函数库 | 需要：ntwdblib.dll（已包含）
php3_mysql.dll | MySQL 函数库 | 自 PHP 4 起内置
php3_nsmail.dll | Netscape 邮件函数库 | 未知
php3_oci73.dll | Oracle 函数库 | 未知
php_oci8.dll | Oracle 8 函数库 | 需要：Oracle 8 客户端库文件
php_openssl.dll | OpenSSL 函数库 | 需要：libeay32.dll（已包含）
php_oracle.dll | Oracle 函数库 | 需要：Oracle 7 客户端库文件
php_pdf.dll | PDF 函数库 | 无
php_pgsql.dll | PostgreSQL 函数库 | 无
php_printer.dll | Printer 函数库 | 无
php_xslt.dll | XSLT 函数库 | 需要：sablot.dll（已包含）
php_snmp.dll | SNMP 函数库 | 仅在 NT 下使用！
php_sybase_ct.dll | Sybase 函数库 | 需要：Sybase 客户端库文件
php_yaz.dll | YAZ 函数库 | 无
php_zlib.dll | ZLib 压缩函数库 | 无

后退 | 起点 | 前进
Installation on UNIX systems | 上一级 | Servers-CGI/Commandline


Servers-CGI/Commandline

The default is to build PHP as a CGI program. This creates a commandline interpreter, which can be used for CGI processing, or for non-web-related PHP scripting. If you are running a web server PHP has module support for, you should generally go for that solution for performance reasons. However, the CGI version enables Apache users to run different PHP-enabled pages under different user-ids. Please make sure you read through the Security chapter if you are going to run PHP as a CGI.

Testing

If you have built PHP as a CGI program, you may test your build by typing make test. It is always a good idea to test your build. This way you may catch a problem with PHP on your platform early instead of having to struggle with it later.

Benchmarking

If you have built PHP 3 as a CGI program, you may benchmark your build by typing make bench. Note that if Safe Mode is on by default, the benchmark may not be able to finish if it takes longer then the 30 seconds allowed. This is because the set_time_limit() can not be used in safe mode. Use the max_execution_time configuration setting to control this time for your own scripts. make bench ignores the configuration file.

注: make bench is only available for PHP 3.

Using Variables

Some server supplied enviroment variables are not defined in the current CGI/1.1 specification. Only the following variables are defined there; everything else should be treated as 'vendor extensions': 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 and SERVER_SOFTWARE

后退 | 起点 | 前进
Windows 系统下的安装 | 上一级 | Apache 服务器


Apache 服务器

本节包括 Apache 下安装 PHP 的说明和提示，包括 Unix 和 Windows 版本。

Unix 下的 Apache 中安装 PHP 的详细资料

你可以根据完整配置选项列表在以下第 10 行中加入你选择的参数。这里把具体版本号略去了以确保本说明的不会出错。你需要把下面的 'xxx' 替换成你得到的文件中确切的数值。

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

1.  gunzip apache_xxx.tar.gz
2.  tar -xvf apache_xxx.tar
3.  gunzip php-xxx.tar.gz
4.  tar -xvf php-xxx.tar
5.  cd apache_xxx
6.  ./configure --prefix=/www --enable-module=so
7.  make
8.  make install
9.  cd ../php-xxx
10. ./configure --with-mysql --with-apxs=/www/bin/apxs
11. make
12. make install

  如果在安装之后你决定修改配置选项，那么只需重复以上最后三步。
  只须重新启动 Apache 就可以使新模块生效。不需要重新编译 Apache。

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

  你可以编辑 php.ini 来设置 PHP 选项。如果你想把 php.ini 放在
  其它目录，在第 10 步加上以下选项：
  --with-config-file-path=/path

14. 编辑 httpd.conf 或者 srm.conf 文件，确认以下两行存在并且没有被注释：

   AddType application/x-httpd-php .php

   LoadModule php4_module        libexec/libphp4.so

  你可以在这里使用任何后缀。.php 只是我们建议的一个。你甚至可以

  加上 .html 以及 .php3 以确保向下兼容。

  在 LoadModule 语句右边的路径必须指向你的 PHP 模块所在的路径。

  如果按照以上步骤进行那么上面的语句是正确的。

15. 用你通常的过程启动 Apache。(你必须完全停止 Apache 再重新启动，

    而不是用 HUP 或者 USR1 信号使 Apache 重新加载。)

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

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

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

3. httpdctl 和 httpsdctl（使用了 OpenSSL），类似 apachectl：
/path/to/httpsdctl stop
/path/to/httpsdctl start

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

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

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

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

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

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

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

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

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

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

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

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

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

User nobody
Group "#-1"

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

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

Windows 下在 Apache 1.3.x 中安装 PHP

有两种方式使 PHP 工作于 Windows 下的 Apache 1.3.x。一种是 CGI 方式（php.exe），另一种是使用 Apache 模块 DLL。不管哪种方式都需要停止 Apache，编辑 srm.conf 或者 httpd.conf 来配置 Apache 以加入PHP支持。

值得在这里指出现在 Windows 下的 SAPI 模块更加稳定了，我们推荐使用模块方式，因为更加透明和安全。

尽管有几种不同方法在 Apache 下配置 PHP，但是对新手来说还是非常简单易用的。有关更多的 httpd.conf 配置指令请参考 Apache 文档。

如果你按照手工安装步骤一节中的说明把 PHP 解压缩到了 c:\php\ 目录下，那么需要加入以下三行到 Apache 配置文件中以 CGI 方式安装：

  • ScriptAlias /php/ "c:/php/"

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

  • Action application/x-httpd-php "/php/php.exe"

注意上面的第二行在原来的 httpd.conf 中就有的，不过被注释了。还有记住用你自己放置 PHP 的路径替换 c:/php/。

警告

在 CGI 方式下，你的服务器可能会受到几种攻击的影响。阅读 CGI 安全一节学习如何防止攻击。

如果你想在 Apache 中用模块方式使用 PHP，确认把 php4ts.dll 拷贝到 windows/system（Windows 9x/Me）或者 winnt/system32（Windows NT/2000/XP）目录下，覆盖原来的文件。然后在 Apache 配置文件中加入以下两行：

  • LoadModule php4_module c:/php/sapi/php4apache.dll

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

修改了配置文件之后记住重新启动 Apache，例如如果你的 Apache 是作为 Windows 的服务安装的，NET STOP APACHE 后面接上 NET START APACHE。或者用你通常使用的快捷方式。

注: 在用 Apache 的 Windows installer 安装之后，你可能发现需要在配置文件（httpd.conf）中用 AddModule 指令定义 mod_php4.c。在配置文件接近开头的地方有一些 AddModule 指令，在其中加入 AddModule mod_php4.c 一行。如果定义了 ClearModuleList 指令的话这一步尤其重要。如果不这么做可能会导致 PHP 不能被注册为 Apache 的模块。

有两种方式使用源程序语法彩色显示特色，但是取决于你的安装方法。如果你配置了 Apache 的 SAPI 模块方式使用 PHP，那么加入下面一行就可以使用本特色：AddType application/x-httpd-php-source .phps

如果你用 CGI 方式使用 PHP，那你需要用 show_source() 函数。建立一个 PHP 文件，加入以下代码：<?php show_source ("original_php_script.php"); ?>。用你想要显示源代码的文件名替换掉 original_php_script.php。

注: 在 Windows-Apache 组合中，所有路径中的反斜线例如 "c:\directory\file.ext" 都必须转换成斜线，如 "c:/directory/file.ext"。

后退 | 起点 | 前进
Servers-CGI/Commandline | 上一级 | Caudium 服务器


Caudium 服务器

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

例子 3-6. Caudium 安装说明

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

您当然可以将各种 PHP 4 的扩展模块编译到 Caudium 服务器中。请参阅 configure 选项完全列表 以获得完整的信息。

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

后退 | 起点 | 前进
Apache 服务器 | 上一级 | Servers-fhttpd


Servers-fhttpd

To build PHP as an fhttpd module, answer "yes" to "Build as an fhttpd module?" (the --with-fhttpd=DIR option to configure) and specify the fhttpd source base directory. The default directory is /usr/local/src/fhttpd. If you are running fhttpd, building PHP as a module will give better performance, more control and remote execution capability.

后退 | 起点 | 前进
Caudium 服务器 | 上一级 | IIS/PWS 服务器


IIS/PWS 服务器

本节包括 IIS（Microsoft Internet Information Server）的说明和提示。以及 PWS/IIS 3，PWS 4 以及更新版本 和 IIS 4 以及更新版本 上 PHP 的安装说明。

Windows 和 PWS/IIS 3

推荐使用PHP发行包中包含的注册表文件（pws-php4cgi.reg）来配置服务器。你可能需要编辑这个文件，确认扩展库和 PHP 的安装目录符合你的设置。或者你可以按照以下步骤手工进行。

警告

以下步骤涉及到直接修改 Windows 注册表，如果出错会使你的系统不稳定。我们强烈推荐你先备份注册表文件。PHP 开发小组将不对你损坏了注册表负责。

  • 运行 Regedit。

  • 找到：HKEY_LOCAL_MACHINE /System /CurrentControlSet /Services /W3Svc /Parameters /ScriptMap。

  • 在编辑菜单下选择：新建->字符串值（New->String Value）。

  • 输入你想 PHP 脚本使用的文件后缀，例如 .php。

  • 双击这个新的字符串值，并且在数据栏中输入 php.exe 的路径，例如：c:\php\php.exe。

  • 如果你希望其他后缀（例如 .php3）也和 PHP 关联，重复以上步骤。

以下步骤并不影响 Web 服务器安装，并且仅适用于你的 PHP 脚本运行于命令行方式下（例如运行 c:\myscripts\test.php）或者在资源管理器中双击 PHP 文件。你可能更希望双击 PHP 文件时用文本编辑器打开，那么可以跳过这一步。

  • 找到：HKEY_CLASSES_ROOT。

  • 在编辑菜单中选择：新建->主键（New->Key）。

  • 给该主键命名为你前一节中设置的后缀，例如：.php。

  • 选中该主键，在右边一栏中双击“默认”（"Default"）并输入 phpfile。

  • 对于你前一节中设置的其它后缀，重复以上步骤。

  • 现在再在 HKEY_CLASSES_ROOT 下面新建一个主键（New->Key），命名为 phpfile。

  • 选中主键 phpfile，在右边一栏中双击“默认”（"Default"）并输入 PHP Script。

  • 右键点击主键 phpfile，选择新建->主键（New->Key），命名为 Shell。

  • 右键点击主键 Shell，选择新建->主键（New->Key），命名为 open。

  • 右键点击主键 open，选择新建->主键（New->Key），命名为 command。

  • 选中主键 command，在右边一栏中双击“默认”（"Default"）并且输入 php.exe 的路径，例如 c:\php\php.exe -q %1（别忘了 %1）。

  • 退出 Regedit。

  • 如果使用 PWS for Windows，重新启动计算机使注册表生效。

PWS和IIS 3 的用户现在就拥有一个完全操作正常的 PHP 系统了。IIS 3 用户还可以使用由 Steven Genusa 提供的一个极好的工具来配置脚本映射。

Windows 和 PWS 4 或更新版本

在 PWS 4 或者更新版本中安装 PHP 有两个选择。一种是 CGI 方式，还有一种是使用 ISAPI 模块的 DLL。

如果你选择 CGI 方式，按照以下步骤：

  • 编辑 PHP 发行包中 SAPI 目录下的 pws-php4cgi.reg文件，在里面输入正确的 php.exe 的路径。反斜线必须双写，例如： [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\w3svc\parameters\Script Map] ".php"="c:\\php\\php.exe"，然后双击此文件将其合并（Merge）到注册表中。

  • 在个人 Web 管理器中，右键点击你希望加入 PHP 支持的目录，选择“属性”（Properties），选中“执行“（Execute）多选框，并确认。

如果你选择 ISAPI 模块，按照以下步骤：

  • 编辑 PHP 发行包中 SAPI 目录下的 pws-php4isapi.reg 文件，在里面输入正确的 php4isapi.dll 的路径。反斜线必须双写，例如： [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\w3svc\parameters\Script Map] ".php"="c:\\php\\sapi\\php4isapi.dll"，然后双击此文件将其合并（Merge）到注册表中。

  • 在个人 Web 管理器中，右键点击你希望加入 PHP 支持的目录，选择“属性”（Properties），选中“执行”（Execute）多选框，并确认。

无论哪种方式都需要重新启动计算机以使改变设置生效。

Windows NT/2000/XP 和 IIS 4 或更新版本

要在 NT/2000/XP 中的 IIS 4 或更新版本中安装 PHP，按照以下说明进行。有两种选择安装 PHP，CGI 方式（php.exe）或者 ISAPI 模块方式。

无论哪种方式，都需要打开管理中心（Microsoft Management Console，NT 4.0 Option Pack 中的 'Internet Services Manager'，或者 2000/XP 中的控制面板 -> 管理工具（Control Panel->Administrative Tools））。用右键点击你的 Web Server 节点（多半是 'Default Web Site'），选择“属性”（Properties）。

如果你选择 CGI 方式，按照以下步骤：

  • 在“主目录”（Home Directory），“虚拟目录”（Virtual Directory）或者“目录”（Directory）标签栏中，点击“配置”（Configuration）按钮，然后选择“应用程序映射”（App Mappings）标签栏。

  • 点击“添加”（Add）按钮，在“可执行文件”（Executable）框中输入：c:\php\php.exe（假定你将 PHP 解压缩到了 c:\php\）。

  • 在“文件后缀”（Extension）框中输入你要使用的 PHP 后缀。'Method exclusions' 空着，选中“脚本引擎”（Script engine）。你也可以选中“检查文件是否存在”（check that file exists）－ 略微损失一点性能，IIS 会先检查脚本文件是否存在。这样会输出 404 的错误信息而不是 PHP 没有输出任何数据的 cgi 错误。

    对于其它你想使用的 PHP 后缀重复以上两个步骤。通常使用的有 .php 和 .phtml，对于一些老的程序还需要 .php3。

  • 设置适当的安全级别（在Internet Service Manager 中完成）。如果你使用了 NTFS，还需要在 php.exe 所在的目录中给 I_USR_ 用户加上“执行”的权限。

如果你选择ISAPI模块，按照以下步骤：

  • 如果你不用 PHP 进行 HTTP 认证的话，你可以（也应该）跳过这一步。在 ISAPI Filters 中，加入一个新的 ISAPI filter。用 PHP 作为过滤器的名字，并且提供 php4isapi.dll 所在的路径。

  • 在“主目录”（Home Directory）中点击“配置”（Configuration）按钮，在应用程序映射（Application Mappings）中添加一个新的条目。用 php4isapi.dll 的路径作为可执行文件（Executable），用 .php 作为文件后缀，选中“脚本引擎”（Script Engine），而 'Method exclusions' 为空。

  • 完全停止 IIS 服务（NET STOP iisadmin）

  • 重新启动IIS服务（NET START w3svc）

后退 | 起点 | 前进
Servers-fhttpd | 上一级 | Servers-Netscape and iPlanet


Servers-Netscape and iPlanet

This section contains notes and hints specific to Netscape and iPlanet installs of PHP, both for Sun Solaris and Windows versions.

You can find more information about setting up PHP for the Netscape Enterprise Server here: http://benoit.noss.free.fr/php/install-php4.html

Installing PHP with Netscape on Sun Solaris

To build PHP with NES or iPlanet web servers, enter the proper install directory for the --with-nsapi = DIR option. The default directory is usually /opt/netscape/suitespot/. Please also read /php-xxx-version/sapi/nsapi/nsapi-readme.txt.

例子 3-7. Installation Example for Netscape Enterprise on Solaris

Instructions for Sun Solaris 2.6 with Netscape Enterprise Server 3.6
From: bhager@invacare.com

1. Install the following packages from www.sunfreeware.com or another
download site:

    flex-2_5_4a-sol26-sparc-local
    gcc-2_95_2-sol26-sparc-local
    gzip-1.2.4-sol26-sparc-local
    perl-5_005_03-sol26-sparc-local
    bison-1_25-sol26-sparc-local
    make-3_76_1-sol26-sparc-local
    m4-1_4-sol26-sparc-local
    autoconf-2.13
    automake-1.4
    mysql-3.23.24-beta (if you want mysql support)
    tar-1.13 (GNU tar)

2. Make sure your path includes the proper directories
    PATH=.:/usr/local/bin:/usr/sbin:/usr/bin:/usr/ccs/bin
    export PATH

3. gunzip php-x.x.x.tar.gz (if you have a .gz dist, otherwise go to 4)
4. tar xvf php-x.x.x.tar
5. cd ../php-x.x.x

6. For the following step, make sure /opt/netscape/suitespot/ is where
   your netscape server is installed. Otherwise, change to correct path:
    /configure --with-mysql=/usr/local/mysql --with-nsapi=/opt/netscape/suitespot/ --enable-track-vars --enable-libgcc
7. make
8. make install
After performing the base install and reading the appropriate readme file, you may need to performs some additional configuration steps.

Firstly you may need to add some paths to the LD_LIBRARY_PATH environment for Netscape to find all the shared libs. This can best done in the start script for your Netscape server. Windows users can probably skip this step. The start script is often located in: /path/to/server/https-servername/start

You may also need to edit the configuration files that are located in:/path/to/server/https-servername/config/.

例子 3-8. Configuration Example for Netscape Enterprise

Configuration Instructions for Netscape Enterprise Server
From: bhager@invacare.com

1. Add the following line to mime.types:
    type=magnus-internal/x-httpd-php exts=php

2. Add the following to obj.conf, shlib will vary depending on
    your OS, for unix it will be something like
    /opt/netscape/suitespot/bin/libphp4.so.

    You should place the following lines after mime types init.
    Init fn="load-modules" funcs="php4_init,php4_close,php4_execute,php4_auth_trans" shlib="/php4/nsapiPHP4.dll"
    Init fn=php4_init errorString="Failed to initialize PHP!"

    <object name="default">
    .
    .
    .
    .#NOTE this next line should happen after all 'ObjectType' and before all 'AddLog' lines
    Service fn="php4_execute" type="magnus-internal/x-httpd-php"
    .
    .
    </Object>

    <Object name="x-httpd-php">
    ObjectType fn="force-type" type="magnus-internal/x-httpd-php"
    Service fn=php4_execute
    </Object>

    Authentication configuration

    PHP authentication cannot be used with any other authentication. ALL AUTHENTICATION IS
    PASSED TO YOUR PHP SCRIPT. To configure PHP Authentication for the entire server, add
    the following line:

    <Object name="default">
    AuthTrans fn=php4_auth_trans
    .
    .
    .
    .
    </Object>

    To use PHP Authentication on a single directory, add the following:

    <Object ppath="d:\path\to\authenticated\dir\*">
    AuthTrans fn=php4_auth_trans
    </Object>

If you are running Netscape Enterprise 4.x, then you should use the following:

例子 3-9. Configuration Example for Netscape Enterprise 4.x

Place these lines after the mime types init, and everything else is similar
to the example configuration above.
From: Graeme Hoose (GraemeHoose@BrightStation.com)

Init fn="load-modules" shlib="/path/to/server4/bin/libphp4.so" funcs="php4_init,php4_close,php4_execute,php4_auth_trans"
Init fn="php4_init" LateInit="yes"

Installing PHP with Netscape on Windows

To Install PHP as CGI (for Netscape Enterprise Server, iPlanet, perhaps Fastrack), do the following:

  • Copy php4ts.dll to your systemroot (the directory where you installed windows)

  • Make a file association from the command line. Type the following two lines:
    assoc .php=PHPScript
ftype PHPScript=c:\php\php.exe %1 %*

  • In the Netscape Enterprise Administration Server create a dummy shellcgi directory and remove it just after (this step creates 5 important lines in obj.conf and allow the web server to handle shellcgi scripts).

  • In the Netscape Enterprise Administration Server create a new mime type (Category: type, Content-Type: magnus-internal/shellcgi, File Suffix:php).

  • Do it for each web server instance you want php to run

More details about setting up PHP as a CGI executable can be found here: http://benoit.noss.free.fr/php/install-php.html

To Install PHP as NSAPI (for Netscape Enterprise Server, iPlanet, perhaps Fastrack, do the following:

  • Copy php4ts.dll to your systemroot (the directory where you installed windows)

  • Make a file association from the command line. Type the following two lines:
    assoc .php=PHPScript
ftype PHPScript=c:\php\php.exe %1 %*

  • In the Netscape Enterprise Administration Server create a new mime type (Category: type, Content-Type: magnus-internal/x-httpd-php, File Suffix:php).

  • Stop your web service and edit obj.conf. At the end of the Init section, place these two lines (necessarily after mime type init!):
    Init fn="load-modules" funcs="php4_init,php4_close,php4_execute,php4_auth_trans" shlib="c:/php/sapi/php4nsapi.dll"
Init fn="php4_init" errorString="Failed to initialise PHP!"

  • In The < Object name="default" > section, place this line necessarily after all 'ObjectType' and before all 'AddLog' lines:
    Service fn="php4_execute" type="magnus-internal/x-httpd-php"

  • At the end of the file, create a new object called x-httpd-php, by inserting these lines:
    <Object name="x-httpd-php">
ObjectType fn="force-type" type="magnus-internal/x-httpd-php"
Service fn=php4_execute
</Object>

  • Restart your web service and apply changes

  • Do it for each web server instance you want PHP to run

More details about setting up PHP as an NSAPI filter can be found here: http://benoit.noss.free.fr/php/install-php4.html

后退 | 起点 | 前进
IIS/PWS 服务器 | 上一级 | Servers-OmniHTTPd Server


Servers-OmniHTTPd Server

This section contains notes and hints specific to OmniHTTPd.

OmniHTTPd 2.0b1 and up for Windows

You need to complete the following steps to make PHP work with OmniHTTPd. This is a CGI executable setup. SAPI is supported by OmniHTTPd, but some tests have shown that it is not so stable to use PHP as an ISAPI module.

  • Step 1: Install OmniHTTPd server.

  • Step 2: Right click on the blue OmniHTTPd icon in the system tray and select Properties

  • Step 3: Click on Web Server Global Settings

  • Step 4: On the 'External' tab, enter: virtual = .php | actual = c:\path-to-php-dir\php.exe, and use the Add button.

  • Step 5: On the Mime tab, enter: virtual = wwwserver/stdcgi | actual = .php, and use the Add button.

  • Step 6: Click OK

Repeat steps 2 - 6 for each extension you want to associate with PHP.

注: Some OmniHTTPd packages come with built in PHP support. You can choose at setup time to do a custom setup, and uncheck the PHP component. We recommend you to use the latest PHP binaries. Some OmniHTTPd servers come with PHP 4 beta distributions, so you should choose not to set up the built in support, but install your own. If the server is already on your machine, use the Replace button in Step 4 and 5 to set the new, correct information.

后退 | 起点 | 前进
Servers-Netscape and iPlanet | 上一级 | Servers-Oreilly Website Pro


Servers-Oreilly Website Pro

This section contains notes and hints specific to Oreilly Website Pro.

Oreilly Website Pro 2.5 and up for Windows

This list describes how to set up the PHP CGI binary or the ISAPI module to work with Oreilly Website Pro on Windows.

  • Edit the Server Properties and select the tab "Mapping".

  • From the List select "Associations" and enter the desired extension (.php) and the path to the CGI exe (ex. c:\php\php.exe) or the ISAPI DLL file (ex. c:\php\sapi\php4isapi.dll).

  • Select "Content Types" add the same extension (.php) and enter the content type. If you choose the CGI executable file, enter 'wwwserver/shellcgi', if you choose the ISAPI module, enter 'wwwserver/isapi' (both without quotes).

后退 | 起点 | 前进
Servers-OmniHTTPd Server | 上一级 | Servers-Xitami


Servers-Xitami

This section contains notes and hints specific to Xitami.

Xitami for Windows

This list describes how to set up the PHP CGI binary to work with Xitami on Windows.

  • Make sure the webserver is running, and point your browser to xitamis admin console (usually http://127.0.0.1/admin), and click on Configuration.

  • Navigate to the Filters, and put the extension which PHP should parse (i.e. .php) into the field File extensions (.xxx).

  • In Filter command or script put the path and name of your php executable i.e. c:\php\php.exe.

  • Press the 'Save' icon.

  • Restart the server to reflect changes.

后退 | 起点 | 前进
Servers-Oreilly Website Pro | 上一级 | Servers-Other web servers


Servers-Other web servers

PHP can be built to support a large number of web servers. Please see Server-related options for a full list of server-related configure options. The PHP CGI binaries are compatible with almost all webservers supporting the CGI standard.

后退 | 起点 | 前进
Servers-Xitami | 上一级 | Problems?


Problems?

Read the FAQ

Some problems are more common than others. The most common ones are listed in the PHP FAQ, part of this manual.

Other problems

If you are still stuck, someone on the PHP installation mailing list may be able to help you. You should check out the archive first, in case someone already answered someone else who had the same problem as you. The archives are available from the support page on http://www.php.net/. To subscribe to the PHP installation mailing list, send an empty mail to php-install-subscribe@lists.php.net. The mailing list address is php-install@lists.php.net.

If you want to get help on the mailing list, please try to be precise and give the necessary details about your environment (which operating system, what PHP version, what web server, if you are running PHP as CGI or a server module, etc.), and preferably enough code to make others able to reproduce and test your problem.

Bug reports

If you think you have found a bug in PHP, please report it. The PHP developers probably don't know about it, and unless you report it, chances are it won't be fixed. You can report bugs using the bug-tracking system at http://bugs.php.net/. Please do not send bug reports in mailing list or personal letters. The bug system is also suitable to submit feature requests.

Read the How to report a bug document before submitting any bug reports!

后退 | 起点 | 前进
Servers-Other web servers | 上一级 | Complete list of configure options


Complete list of configure options

注: These are only used at compile time. If you want to alter PHP's runtime configuration, please see the chapter on Configuration.

The following is a complete list of options supported by PHP 4 configure scripts (as of 4.1.0), used when compiling in Unix-like environments. Some are available in PHP 3, some in PHP 4, and some in both. This is not noted yet.

There are general configuration options for the configure script, consult the appropriate manual pages for GNU autoconf or use the command configure --help for a full, up-to-date list.

  • Database

  • Graphics

  • Miscellaneous

  • PHP Behaviour

  • Server

  • XML

Configure Options in PHP 4

注: These options are only used in PHP 4 as of PHP 4.1.0. Some are available in older versions of PHP 4, some even in PHP 3, some only in PHP 4.1.0. If you want to compile an older version, some options will probably not be available.

Database options

--with-db

Include old xDBM support (deprecated).

--enable-dba=shared

Build DBA as a shared module.

--with-gdbm[=DIR]

Include GDBM support.

--with-ndbm[=DIR]

Include NDBM support.

--with-db2[=DIR]

Include Berkeley DB2 support.

--with-db3[=DIR]

Include Berkeley DB3 support.

--with-dbm[=DIR]

Include DBM support.

--with-cdb[=DIR]

Include CDB support.

--enable-dbase

Enable the bundled dbase library.

--with-dbplus

Include dbplus support.

--enable-dbx

Enable dbx.

--with-fbsql[=DIR]

Include FrontBase support. DIR is the FrontBase base directory.

--enable-filepro

Enable the bundled read-only filePro support.

--with-fribidi[=DIR]

Include fribidi support (requires FriBidi >=0.1.12). DIR is the fribidi installation directory - default /usr/local/.

--with-informix[=DIR]

Include Informix support. DIR is the Informix base install directory, defaults to nothing.

--with-ingres[=DIR]

Include Ingres II support. DIR is the Ingres base directory (default /II/ingres).

--with-interbase[=DIR]

Include InterBase support. DIR is the InterBase base install directory, defaults to /usr/interbase.

--with-msql[=DIR]

Include mSQL support. DIR is the mSQL base install directory, defaults to /usr/local/Hughes.

--with-mysql[=DIR]

Include MySQL support. DIR is the MySQL base directory. If unspecified, the bundled MySQL library will be used.

--with-oci8[=DIR]

Include Oracle-oci8 support. Default DIR is ORACLE_HOME.

--with-adabas[=DIR]

Include Adabas D support. DIR is the Adabas base install directory, defaults to /usr/local.

--with-sapdb[=DIR]

Include SAP DB support. DIR is SAP DB base install directory, defaults to /usr/local.

--with-solid[=DIR]

Include Solid support. DIR is the Solid base install directory, defaults to /usr/local/solid.

--with-ibm-db2[=DIR]

Include IBM DB2 support. DIR is the DB2 base install directory, defaults to /home/db2inst1/sqllib.

--with-empress[=DIR]

Include Empress support. DIR is the Empress base install directory, defaults to $EMPRESSPATH. From PHP4, this option only supports Empress Version 8.60 and above.

--with-empress-bcs[=DIR]

Include Empress Local Access support. DIR is the Empress base install directory, defaults to $EMPRESSPATH. From PHP4, this option only supports Empress Version 8.60 and above.

--with-birdstep[=DIR]

Include Birdstep support. DIR is the Birdstep base install directory, defaults to /usr/local/birdstep.

--with-custom-odbc[=DIR]

Include a user defined ODBC support. The DIR is ODBC install base directory, which defaults to /usr/local. Make sure to define CUSTOM_ODBC_LIBS and have some odbc.h in your include dirs. E.g., you should define following for Sybase SQL Anywhere 5.5.00 on QNX, prior to run configure script: CPPFLAGS="-DODBC_QNX -DSQLANY_BUG" LDFLAGS=-lunix CUSTOM_ODBC_LIBS="-ldblib -lodbc".

--with-iodbc[=DIR]

Include iODBC support. DIR is the iODBC base install directory, defaults to /usr/local.

--with-esoob[=DIR]

Include Easysoft OOB support. DIR is the OOB base install directory, defaults to /usr/local/easysoft/oob/client.

--with-unixODBC[=DIR]

Include unixODBC support. DIR is the unixODBC base install directory, defaults to /usr/local.

--with-openlink[=DIR]

Include OpenLink ODBC support. DIR is the OpenLink base install directory, defaults to /usr/local. This is the same as iODBC.

--with-dbmaker[=DIR]

Include DBMaker support. DIR is the DBMaker base install directory, defaults to where the latest version of DBMaker is installed (such as /home/dbmaker/3.6).

--with-oracle[=DIR]

Include Oracle-oci7 support. Default DIR is ORACLE_HOME.

--with-ovrimos[=DIR]

Include Ovrimos SQL Server support. DIR is the Ovrimos' libsqlcli install directory.

--with-pgsql[=DIR]

Include PostgreSQL support. DIR is the PostgreSQL base install directory, defaults to /usr/local/pgsql. Set DIR to shared to build as a dl, or shared,DIR to build as a dl and still specify DIR.

--with-sybase[=DIR]

Include Sybase-DB support. DIR is the Sybase home directory, defaults to /home/sybase.

--with-sybase-ct[=DIR]

Include Sybase-CT support. DIR is the Sybase home directory. Defaults to /home/sybase.

--disable-unified-odbc

Disable unified ODBC support. Only applicable if iODBC, Adabas, Solid, Velocis or a custom ODBC interface is enabled. PHP 3 only!

Graphics options

--with-gd[=DIR]

Include GD support (DIR is GD's install dir). Set DIR to shared to build as a dl, or shared,DIR to build as a dl and still specify DIR.

--enable-gd-native-ttf

GD: Enable TrueType string function in gd.

--with-jpeg-dir=DIR

GD: Set the path to libjpeg install prefix.

--with-png-dir=DIR

GD: Set the path to libpng install prefix.

--with-xpm-dir=DIR

GD: Set the path to libXpm install prefix.

--with-freetype-dir=DIR

GD: Set the path to freetype2 install prefix.

--with-ttf[=DIR]

GD: Include FreeType 1.x support.

--with-t1lib[=DIR]

GD: Include T1lib support.

--with-cpdflib[=DIR]

Include cpdflib support (requires cpdflib >= 2). DIR is the cpdfllib install directory, defaults to /usr.

--with-jpeg-dir[=DIR]

jpeg dir for cpdflib 2.x.

--with-tiff-dir[=DIR]

tiff dir for cpdflib 2.x.

--with-pdflib[=DIR]

Include PDFlib support. DIR is the pdflib base install directory, defaults to /usr/local. Set DIR to shared to build as dl, or shared,DIR to build as dl and still specify DIR.

--with-jpeg-dir[=DIR]

PDFLIB: define libjpeg install directory.

--with-png-dir[=DIR]

PDFLIB: define libpng install directory.

--with-tiff-dir[=DIR]

PDFLIB: define libtiff install directory.

--with-swf[=DIR]

Include swf support.

--without-gd

Disable GD support. PHP 3 only!

--with-imagick

Include ImageMagick support. DIR is the install directory, and if left out, PHP will try to find it on its own. [experimental]. PHP 3 only!

--with-ming[=DIR]

Include ming support.

Misc options

--enable-force-cgi-redirect

Enable the security check for internal server redirects. You should use this if you are running the CGI version with Apache.

--enable-discard-path

If this is enabled, the PHP CGI binary can safely be placed outside of the web tree and people will not be able to circumvent .htaccess security.

--with-fastcgi=SRCDIR

Build PHP as FastCGI application.

--enable-debug

Compile with debugging symbols.

--with-layout=TYPE

Sets how installed files will be laid out. Type is one of PHP (default) or GNU.

--with-pear=DIR

Install PEAR in DIR (default PREFIX/lib/php).

--without-pear

Do not install PEAR.

--with-openssl[=DIR]

Include OpenSSL support (requires OpenSSL >= 0.9.5).

--enable-sigchild

Enable PHP's own SIGCHLD handler.

--disable-rpath

Disable passing additional runtime library search paths.

--enable-libgcc

Enable explicitly linking against libgcc.

--enable-dmalloc

Enable dmalloc.

--enable-php-streams

Include experimental php streams. Do not use unless you are testing the code!

--with-zlib-dir=<DIR>

Define the location of zlib install directory.

--with-zlib[=DIR]

Include zlib support (requires zlib >= 1.0.9). DIR is the zlib install directory.

--with-aspell[=DIR]

Include ASPELL support.

--enable-bcmath

Enable bc style precision math functions.

--with-bz2[=DIR]

Include BZip2 support.

--enable-calendar

Enable support for calendar conversion.

--with-ccvs[=DIR]

Include CCVS support.

--with-crack[=DIR]

Include crack support.

--enable-ctype

Enable ctype support.

--with-curl[=DIR]

Include CURL support.

--with-cybercash[=DIR]

Include CyberCash support. DIR is the CyberCash MCK install directory.

--with-cybermut[=DIR]

Include CyberMut (French Credit Mutuel telepaiement).

--with-cyrus

Include cyrus IMAP support.

--enable-exif

Enable exif support.

--with-fdftk[=DIR]

Include fdftk support.

--enable-ftp

Enable FTP support.

--with-gettext[=DIR]

Include GNU gettext support. DIR is the gettext install directory, defaults to /usr/local.

--with-gmp

Include gmp support.

--with-hyperwave

Include Hyperwave support.

--with-icap[=DIR]

Include ICAP support.

--with-iconv[=DIR]

Include iconv support.

--with-imap[=DIR]

Include IMAP support. DIR is the c-client install prefix.

--with-kerberos[=DIR]

IMAP: Include Kerberos support. DIR is the Kerberos install dir.

--with-imap-ssl[=DIR]

IMAP: Include SSL support. DIR is the OpenSSL install dir.

--with-ircg-config

Path to the ircg-config script.

--with-ircg

Include ircg support.

--with-java[=DIR]

Include Java support. DIR is the base install directory for the JDK. This extension can only be built as a shared dl.

--with-ldap[=DIR]

Include LDAP support. DIR is the LDAP base install directory.

--enable-mailparse

Enable mailparse support.

--enable-mbstring

Enable multibyte string support.

--enable-mbstr-enc-trans

Enable japanese encoding translation.

--with-mcal[=DIR]

Include MCAL support.

--with-mcrypt[=DIR]

Include mcrypt support. DIR is the mcrypt install directory.

--with-mhash[=DIR]

Include mhash support. DIR is the mhash install directory.

--with-mnogosearch[=DIR]

Include mnoGoSearch support. DIR is the mnoGoSearch base install directory, defaults to /usr/local/mnogosearch.

--with-muscat[=DIR]

Include muscat support.

--with-ncurses

Include ncurses support.

--enable-pcntl

Enable experimental pcntl support (CGI ONLY!)

--without-pcre-regex

Do not include Perl Compatible Regular Expressions support. Use --with-pcre-regex=DIR to specify DIR where PCRE's include and library files are located, if not using bundled library.

--with-pfpro[=DIR]

Include Verisign Payflow Pro support.

--disable-posix

Disable POSIX-like functions.

--with-pspell[=DIR]

Include PSPELL support.

--with-qtdom

Include QtDOM support (requires Qt >= 2.2.0).

--with-libedit[=DIR]

Include libedit readline replacement.

--with-readline[=DIR]

Include readline support. DIR is the readline install directory.

--with-recode[=DIR]

Include recode support. DIR is the recode install directory.

--with-satellite[=DIR]

Enable CORBA support via Satellite (EXPERIMENTAL) DIR is the base directory for ORBit.

--with-mm[=DIR]

Include mm support for session storage.

--enable-trans-sid

Enable transparent session id propagation.

--disable-session

Disable session support.

--enable-shmop

Enable shmop support.

--with-snmp[=DIR]

Include SNMP support. DIR is the SNMP base install directory, defaults to searching through a number of common locations for the snmp install. Set DIR to shared to build as a dl, or shared,DIR to build as a dl and still specify DIR.

--enable-ucd-snmp-hack

Enable UCD SNMP hack.

--enable-sockets

Enable sockets support.

--with-regex=TYPE

regex library type: system, apache, php.

--with-system-regex

Use system regex library (deprecated).

--enable-sysvsem

Enable System V semaphore support.

--enable-sysvshm

Enable the System V shared memory support.

--with-vpopmail[=DIR]

Include vpopmail support.

--with-tsrm-pthreads

Use POSIX threads (default).

--enable-shared[=PKGS]

Build shared libraries [default=yes].

--enable-static[=PKGS]

Build static libraries [default=yes].

--enable-fast-install[=PKGS]

Optimize for fast installation [default=yes].

--with-gnu-ld

Assume the C compiler uses GNU ld [default=no].

--disable-libtool-lock

Avoid locking (might break parallel builds).

--with-pic

Try to use only PIC/non-PIC objects [default=use both].

--with-yaz[=DIR]

Include YAZ support (ANSI/NISO Z39.50). DIR is the YAZ bin install directory.

--enable-memory-limit

Compile with memory limit support.

--disable-url-fopen-wrapper

Disable the URL-aware fopen wrapper that allows accessing files via HTTP or FTP.

--enable-versioning

Export only required symbols. See INSTALL for more information.

--disable-bcmath

Compile without bc style precision math functions. PHP 3 only!

--with-imsp[=DIR]

Include IMSp support (DIR is IMSP's include dir and libimsp.a dir). PHP 3 only!

--with-ftp

Include FTP support. PHP 3 only!

--with-mck[=DIR]

Include Cybercash MCK support. DIR is the cybercash mck build directory, defaults to /usr/src/mck-3.2.0.3-linux for help look in extra/cyberlib. PHP 3 only!

--disable-overload

Disable user-space object overloading support. PHP 3 only!

--enable-yp

Include YP support. PHP 3 only!

--with-zip

Include ZIP support (requires zziplib >= 0.10.6). PHP 3 only!

--with-mod-dav=DIR

Include DAV support through Apache's mod_dav, DIR is mod_dav's installation directory (Apache module version only!) PHP 3 only!

--enable-debugger

Compile with remote debugging functions. PHP 3 only!

--enable-versioning

Take advantage of versioning and scoping provided by Solaris 2.x and Linux. PHP 3 only!

PHP options

--enable-maintainer-mode

Enable make rules and dependencies not useful (and sometimes confusing) to the casual installer.

--with-config-file-path=PATH

Sets the path in which to look for php.ini, defaults to PREFIX/lib.

--enable-safe-mode

Enable safe mode by default.

--with-exec-dir[=DIR]

Only allow executables in DIR when in safe mode defaults to /usr/local/php/bin.

--enable-magic-quotes

Enable magic quotes by default.

--disable-short-tags

Disable the short-form <? start tag by default.

Server options

--with-aolserver=DIR

Specify path to the installed AOLserver.

--with-apxs[=FILE]

Build shared Apache module. FILE is the optional pathname to the Apache apxs tool; defaults to apxs. Make sure you specify the version of apxs that is actually installed on your system and NOT the one that is in the apache source tarball.

--with-apache[=DIR]

Build Apache module. DIR is the top-level Apache build directory, defaults to /usr/local/apache.

--with-mod_charset

Enable transfer tables for mod_charset (Rus Apache).

--with-apxs2[=FILE]

Build shared Apache 2.0 module. FILE is the optional pathname to the Apache apxs tool; defaults to apxs.

--with-fhttpd[=DIR]

Build fhttpd module. DIR is the fhttpd sources directory, defaults to /usr/local/src/fhttpd.

--with-isapi=DIR

Build PHP as an ISAPI module for use with Zeus.

--with-nsapi=DIR

Specify path to the installed Netscape Server.

--with-phttpd=DIR

No information yet.

--with-pi3web=DIR

Build PHP as a module for use with Pi3Web.

--with-roxen=DIR

Build PHP as a Pike module. DIR is the base Roxen directory, normally /usr/local/roxen/server.

--enable-roxen-zts

Build the Roxen module using Zend Thread Safety.

--with-servlet[=DIR]

Include servlet support. DIR is the base install directory for the JSDK. This SAPI prereqs the java extension must be built as a shared dl.

--with-thttpd=SRCDIR

Build PHP as thttpd module.

--with-tux=MODULEDIR

Build PHP as a TUX module (Linux only).

XML options

--with-dom[=DIR]

Include DOM support (requires libxml >= 2.4.2). DIR is the libxml install directory, defaults to /usr.

--disable-xml

Disable XML support using bundled expat lib.

--with-expat-dir=DIR

XML: external libexpat install dir.

--with-xmlrpc[=DIR]

Include XMLRPC-EPI support.

--enable-wddx

Enable WDDX support.

后退 | 起点 | 前进
Problems? | 上一级 | Configuration


Configuration

PHP 手册
后退 前进

章 4. Configuration

目录
The configuration file

The configuration file

The configuration file (called php3.ini in PHP 3.0, and simply php.ini as of PHP 4.0) is read when PHP starts up. For the server module versions of PHP, this happens only once when the web server is started. For the CGI and CLI version, it happens on every invocation.

The default location of php.ini is a compile time option (see the FAQ entry), but can be changed for the CGI and CLI version with the -c command line switch, see the chapter about using PHP from the command line. You can also use the environment variable PHPRC for an additional path to search for a php.ini file.

Not every PHP directive is documented below. For a list of all directives, please read your well commented php.ini file. You may want to view the latest php.ini here from CVS.

注: The default value for the PHP directive register_globals changed from on to off in PHP 4.2.0.

例子 4-1. php.ini example

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

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

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

When using PHP as an Apache module, you can also change the configuration settings using directives in Apache configuration files and .htaccess files (You will need "AllowOverride Options" or "AllowOverride All" privileges)

With PHP 3.0, there are Apache directives that correspond to each configuration setting in the php3.ini name, except the name is prefixed by "php3_".

With PHP 4.0, there are several Apache directives that allow you to change the PHP configuration from within the Apache configuration file itself.

php_value name value

This sets the value of the specified variable.

php_flag name on|off

This is used to set a Boolean configuration option.

php_admin_value name value

This sets the value of the specified variable. "Admin" configuration settings can only be set from within the main Apache configuration files, and not from .htaccess files.

php_admin_flag name on|off

This is used to set a Boolean configuration option.

例子 4-2. Apache configuration example

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

注: PHP constants do not exist outside of PHP. For example, in httpd.conf do not use PHP constants such as E_ALL or E_NOTICE to set the error_reporting directive as they will have no meaning and will evaluate to 0. Use the associated bitmask values instead. These constants can be used in php.ini

You can view the settings of the configuration values in the output of phpinfo(). You can also access the values of individual configuration settings using ini_get() or get_cfg_var().

General Configuration Directives

allow_url_fopen boolean

This option enables the URL-aware fopen wrappers that enable accessing URL object like files. Default wrappers are provided for the access of remote files using the ftp or http protocol, some extensions like zlib may register additional wrappers.

注: This option was introduced immediately after the release of version 4.0.3. For versions up to and including 4.0.3 you can only disable this feature at compile time by using the configuration switch --disable-url-fopen-wrapper.

警告

On Windows, the following functions do not support remote file
accesing: include(),
include_once(), require() and
require_once().

asp_tags boolean

Enables the use of ASP-like <% %> tags in addition to the usual <?php ?> tags. This includes the variable-value printing shorthand of <%= $value %>. For more information, see Escaping from HTML.

注: Support for ASP-style tags was added in 3.0.4.

auto_append_file string

Specifies the name of a file that is automatically parsed after the main file. The file is included as if it was called with the include() function, so include_path is used.

The special value none disables auto-appending.

注: If the script is terminated with exit(), auto-append will not occur.

auto_prepend_file string

Specifies the name of a file that is automatically parsed before the main file. The file is included as if it was called with the include() function, so include_path is used.

The special value none disables auto-prepending.

disable_functions string

This directive allows you to disable certain functions for security reasons. It takes on a comma-dilimited list of function names. disable_functions is not affected by Safe Mode.

This directive must be set in php.ini For example, you cannot set this in httpd.conf.

display_errors boolean

This determines whether errors should be printed to the screen as part of the HTML output or not.

doc_root string

PHP's "root directory" on the server. Only used if non-empty. If PHP is configured with safe mode, no files outside this directory are served.

engine boolean

This directive is really only useful in the Apache module version of PHP. It is used by sites that would like to turn PHP parsing on and off on a per-directory or per-virtual server basis. By putting engine off in the appropriate places in the httpd.conf file, PHP can be enabled or disabled.

error_log string

Name of file where script errors should be logged. 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.

error_reporting integer

Set the error reporting level. The parameter is either an integer representing a bit field, or named constants. The error_reporting levels and constants are described in the Error Handling section of the manual, and in php.ini. To set at runtime, use the error_reporting() function. See also the display_errors directive.

The default value does not show E_NOTICE level errors. You may want to show them during development.

file_uploads boolean

Whether or not to allow HTTP file uploads. See also the upload_max_filesize, upload_tmp_dir, and post_max_size directives.

html_errors boolean

Turn off HTML tags in error messages. The new format for html errors produces clickable messages that direct the user to a page describing the error or function in causing the error. These references are affected by docref_root and docref_ext.

docref_root string

The new error format contains a reference to a page describing the error or function in 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/.

注: The value of docref_root must end with a slash '/'.

docref_ext string

See docref_root.

注: The value of docref_ext must begin with a dot '.'.

open_basedir string

Limit the files that can be opened by PHP to the specified directory-tree.

When a script tries to open a file with, for example, fopen or gzopen, the location of the file is checked. When the file is outside the specified directory-tree, PHP will refuse to open it. All symbolic links are resolved, so it's not possible to avoid this restriction with a symlink.

The special value . indicates that the directory in which the script is stored will be used as base-directory.

Under Windows, separate the directories with a semicolon. On all other systems, separate the directories with a colon. As an Apache module, open_basedir paths from parent directories are now automatically inherited.

The restriction specified with open_basedir is actually a prefix, not a directory name. This means that "open_basedir = /dir/incl" also allows access to "/dir/include" and "/dir/incls" if they exist. When you want to restrict access to only the specified directory, end with a slash. For example: "open_basedir = /dir/incl/"

注: Support for multiple directories was added in 3.0.7.

The default is to allow all files to be opened.

gpc_order string

Set the order of GET/POST/COOKIE variable parsing. The default setting of this directive is "GPC". Setting this to "GP", for example, will cause PHP to completely ignore cookies and to overwrite any GET method variables with POST-method variables of the same name.

Note, that this option is not available in PHP 4. Use variables_order instead.

variables_order string

Set the order of the EGPCS (Environment, GET, POST, Cookie, Server) variable parsing. The default setting of this directive is "EGPCS". Setting this to "GP", for example, will cause PHP to completely ignore environment variables, cookies and server variables, and to overwrite any GET method variables with POST-method variables of the same name.

See also register_globals.

ignore_user_abort boolean

TRUE by default. If changed to FALSE scripts will be terminated as soon as they try to output something after a client has aborted their connection.

See also ignore_user_abort().

implicit_flush boolean

FALSE by default. Changing this to TRUE tells PHP to tell the output layer to flush itself automatically after every output block. This is equivalent to calling the PHP function flush() after each and every call to print() or echo() and each and every HTML block.

When using PHP within an web environment, turning this option on has serious performance implications and is generally recommended for debugging purposes only. This value defaults to TRUE when operating under the CLI SAPI.

include_path string

Specifies a list of directories where the require(), include() and fopen_with_path() functions look for files. The format is like the system's PATH environment variable: a list of directories separated with a colon in UNIX or semicolon in Windows.

例子 4-3. UNIX include_path

include_path=.:/home/httpd/php-lib

例子 4-4. Windows include_path

include_path=".;c:\www\phplib"
The default value for this directive is . (only the current directory).

log_errors boolean

Tells whether script error messages should be logged to the server's error log. This option is thus server-specific.

magic_quotes_gpc boolean

Sets the magic_quotes state for GPC (Get/Post/Cookie) operations. When magic_quotes are on, all ' (single-quote), " (double quote), \ (backslash) and NUL's are escaped with a backslash automatically. If magic_quotes_sybase is also on, a single-quote is escaped with a single-quote instead of a backslash.

magic_quotes_runtime boolean

If magic_quotes_runtime is enabled, most functions that return data from any sort of external source including databases and text files will have quotes escaped with a backslash. If magic_quotes_sybase is also on, a single-quote is escaped with a single-quote instead of a backslash.

magic_quotes_sybase boolean

If magic_quotes_sybase is also on, a single-quote is escaped with a single-quote instead of a backslash if magic_quotes_gpc or magic_quotes_runtime is enabled.

max_execution_time integer

This sets the maximum time in seconds a script is allowed to run before it is terminated by the parser. This helps prevent poorly written scripts from tying up the server. The default setting is 30.

The maximum execution time is not affected by system calls, the sleep() function, etc. Please see the set_time_limit() function for more details.

memory_limit integer

This sets the maximum amount of memory in bytes that a script is allowed to allocate. This helps prevent poorly written scripts for eating up all available memory on a server.

precision integer

The number of significant digits displayed in floating point numbers.

register_argc_argv boolean

Tells PHP whether to declare the argv & argc variables (that would contain the GET information).

See also command line. Also, this directive became available in PHP 4.0.0 and was always "on" before that.

post_max_size integer

Sets max size of post data allowed. This setting also affects file upload. To upload large files, this value must be larger than upload_max_filesize.

If memory limit is enabled by configure script, memory_limit also affects file uploading. Generally speaking, memory_limit should be larger than post_max_size.

register_globals boolean

Tells whether or not to register the EGPCS (Environment, GET, POST, Cookie, Server) variables as global variables. For example; if register_globals = on, the url http://www.example.com/test.php?id=3 will produce $id. Or, $DOCUMENT_ROOT from $_SERVER['DOCUMENT_ROOT']. You may want to turn this off if you don't want to clutter your scripts' global scope with user data. As of PHP 4.2.0, this directive defaults to off. It's preferred to go through PHP Predefined Variables instead, such as the superglobals: $_ENV, $_GET, $_POST, $_COOKIE, and $_SERVER. Please read the security chapter on Using register_globals for related information.

Please note that register_globals cannot be set at runtime (ini_set()). Although, you can use .htaccess if your host allows it as described above. An example .htaccess entry: php_flag register_globals on.

注: register_globals is affected by the variables_order directive.

short_open_tag boolean

Tells whether the short form (<? ?>) of PHP's open tag should be allowed. If you want to use PHP in combination with XML, you can disable this option in order to use <?xml ?> inline. Otherwise, you can print it with PHP, for example: <?php echo '<?xml version="1.0"'; ?>. Also if disabled, you must use the long form of the PHP open tag (<?php ?>).

注: This directive also affects the shorthand <?=, which is identical to <? echo. Use of this shortcut requires short_open_tag to be on.

sql.safe_mode boolean

track_errors boolean

If enabled, the last error message will always be present in the global variable $php_errormsg.

track_vars boolean

If enabled, then Environment, GET, POST, Cookie, and Server variables can be found in the global associative arrays $_ENV, $_GET, $_POST, $_COOKIE, and $_SERVER.

Note that as of PHP 4.0.3, track_vars is always turned on.

upload_tmp_dir string

The temporary directory used for storing files when doing file upload. Must be writable by whatever user PHP is running as.

upload_max_filesize integer

The maximum size of an uploaded file. The value is in bytes.

user_dir string

The base name of the directory used on a user's home directory for PHP files, for example public_html.

warn_plus_overloading boolean

If enabled, this option makes PHP output a warning when the plus (+) operator is used on strings. This is to make it easier to find scripts that need to be rewritten to using the string concatenator instead (.).

Safe Mode Configuration Directives

safe_mode boolean

Whether to enable PHP's safe mode. Read the Security and Safe Mode chapters for more information.

safe_mode_gid boolean

Whether to use UID (FALSE) or GID (TRUE) checking upon file access. See Safe Mode for more information.

safe_mode_exec_dir string

If PHP is used in safe mode, system() and the other functions executing system programs refuse to start programs that are not in this directory.

safe_mode_include_dir string

UID/GID checks are bypassed when including files from this directory and its subdirectories (directory must also be in include_path or full path must including).

As of PHP 4.2.0, this directive can take on a semi-colon separated path in a similar fashion to the include_path directive, rather than just a single directory.

Debugger Configuration Directives

debugger.host string

DNS name or IP address of host used by the debugger.

debugger.port string

Port number used by the debugger.

debugger.enabled boolean

Whether the debugger is enabled.

Extension Loading Directives

enable_dl boolean

This directive is really only useful in the Apache module version of PHP. You can turn dynamic loading of PHP extensions with dl() on and off per virtual server or per directory.

The main reason for turning dynamic loading off is security. With dynamic loading, it's possible to ignore all the safe_mode and open_basedir restrictions.

The default is to allow dynamic loading, except when using safe-mode. In safe-mode, it's always imposible to use dl().

extension_dir string

In what directory PHP should look for dynamically loadable extensions.

extension string

Which dynamically loadable extensions to load when PHP starts up.

SESAM Configuration Directives

sesam_oml string

Name of BS2000 PLAM library containing the loadable SESAM driver modules. Required for using SESAM functions. The BS2000 PLAM library must be set ACCESS=READ,SHARE=YES because it must be readable by the apache server's user id.

sesam_configfile string

Name of SESAM application configuration file. Required for using SESAM functions. The BS2000 file must be readable by the apache server's user id.

The application configuration file will usually contain a configuration like (see SESAM reference manual):

CNF=B
NAM=K
NOTYPE

sesam_messagecatalog string

Name of SESAM message catalog file. In most cases, this directive is not neccessary. Only if the SESAM message file is not installed in the system's BS2000 message file table, it can be set with this directive.

The message catalog must be set ACCESS=READ,SHARE=YES because it must be readable by the apache server's user id.

Browser Capability Configuration Directives

browscap string

Name of browser capabilities file. See also get_browser().

后退 | 起点 | 前进
Complete list of configure options | 上一级 | Security


Security

PHP 手册
后退 前进

章 5. Security

目录
General considerations
Installed as CGI binary
Installed as an Apache module
Filesystem Security
Database Security
Error Reporting
Using Register Globals
User Submitted Data
Hiding PHP
Keeping Current

PHP is a powerful language and the interpreter, whether included in a web server as a module or executed as a separate CGI binary, is able to access files, execute commands and open network connections on the server. These properties make anything run on a web server insecure by default. PHP is designed specifically to be a more secure language for writing CGI programs than Perl or C, and with correct selection of compile-time and runtime configuration options, and proper coding practices, it can give you exactly the combination of freedom and security you need.

As there are many different ways of utilizing PHP, there are many configuration options controlling its behaviour. A large selection of options guarantees you can use PHP for a lot of purposes, but it also means there are combinations of these options and server configurations that result in an insecure setup.

The configuration flexibility of PHP is equally rivalled by the code flexibility. PHP can be used to build complete server applications, with all the power of a shell user, or it can be used for simple server-side includes with little risk in a tightly controlled environment. How you build that environment, and how secure it is, is largely up to the PHP developer.

This chapter starts with some general security advice, explains the different configuration option combinations and the situations they can be safely used, and describes different considerations in coding for different levels of security.

General considerations

A completely secure system is a virtual impossibility, so an approach often used in the security profession is one of balancing risk and usability. If every variable submitted by a user required two forms of biometric validation (such as a retinal scan and a fingerprint), you would have an extremely high level of accountability. It would also take half an hour to fill out a fairly complex form, which would tend to encourage users to find ways of bypassing the security.

The best security is often inobtrusive enough to suit the requirements without the user being prevented from accomplishing their work, or over-burdening the code author with excessive complexity. Indeed, some security attacks are merely exploits of this kind of overly built security, which tends to erode over time.

A phrase worth remembering: A system is only as good as the weakest link in a chain. If all transactions are heavily logged based on time, location, transaction type, etc. but the user is only verified based on a single cookie, the validity of tying the users to the transaction log is severely weakened.

When testing, keep in mind that you will not be able to test all possibilities for even the simplest of pages. The input you may expect will be completely unrelated to the input given by a disgruntled employee, a cracker with months of time on their hands, or a housecat walking across the keyboard. This is why it's best to look at the code from a logical perspective, to discern where unexpected data can be introduced, and then follow how it is modified, reduced, or amplified.

The Internet is filled with people trying to make a name for themselves by breaking your code, crashing your site, posting inappropriate content, and otherwise making your day interesting. It doesn't matter if you have a small or large site, you are a target by simply being online, by having a server that can be connected to. Many cracking programs do not discern by size, they simply trawl massive IP blocks looking for victims. Try not to become one.

后退 | 起点 | 前进
Configuration | 上一级 | Installed as CGI binary


Installed as CGI binary

Possible attacks

Using PHP as a CGI binary is an option for setups that for some reason do not wish to integrate PHP as a module into server software (like Apache), or will use PHP with different kinds of CGI wrappers to create safe chroot and setuid environments for scripts. This setup usually involves installing executable PHP binary to the web server cgi-bin directory. CERT advisory CA-96.11 recommends against placing any interpreters into cgi-bin. Even if the PHP binary can be used as a standalone interpreter, PHP is designed to prevent the attacks this setup makes possible:

  • Accessing system files: http://my.host/cgi-bin/php?/etc/passwd

    The query information in a url after the question mark (?) is passed as command line arguments to the interpreter by the CGI interface. Usually interpreters open and execute the file specified as the first argument on the command line.

    When invoked as a CGI binary, PHP refuses to interpret the command line arguments.

  • Accessing any web document on server: http://my.host/cgi-bin/php/secret/doc.html

    The path information part of the url after the PHP binary name, /secret/doc.html is conventionally used to specify the name of the file to be opened and interpreted by the CGI program. Usually some web server configuration directives (Apache: Action) are used to redirect requests to documents like http://my.host/secret/script.php to the PHP interpreter. With this setup, the web server first checks the access permissions to the directory /secret, and after that creates the redirected request http://my.host/cgi-bin/php/secret/script.php. Unfortunately, if the request is originally given in this form, no access checks are made by web server for file /secret/script.php, but only for the /cgi-bin/php file. This way any user able to access /cgi-bin/php is able to access any protected document on the web server.

    In PHP, compile-time configuration option --enable-force-cgi-redirect and runtime configuration directives doc_root and user_dir can be used to prevent this attack, if the server document tree has any directories with access restrictions. See below for full the explanation of the different combinations.

Case 1: only public files served

If your server does not have any content that is not restricted by password or ip based access control, there is no need for these configuration options. If your web server does not allow you to do redirects, or the server does not have a way to communicate to the PHP binary that the request is a safely redirected request, you can specify the option --enable-force-cgi-redirect to the configure script. You still have to make sure your PHP scripts do not rely on one or another way of calling the script, neither by directly http://my.host/cgi-bin/php/dir/script.php nor by redirection http://my.host/dir/script.php.

Redirection can be configured in Apache by using AddHandler and Action directives (see below).

Case 2: using --enable-force-cgi-redirect

This compile-time option prevents anyone from calling PHP directly with a url like http://my.host/cgi-bin/php/secretdir/script.php. Instead, PHP will only parse in this mode if it has gone through a web server redirect rule.

Usually the redirection in the Apache configuration is done with the following directives:

Action php-script /cgi-bin/php
AddHandler php-script .php

This option has only been tested with the Apache web server, and relies on Apache to set the non-standard CGI environment variable REDIRECT_STATUS on redirected requests. If your web server does not support any way of telling if the request is direct or redirected, you cannot use this option and you must use one of the other ways of running the CGI version documented here.

Case 3: setting doc_root or user_dir

To include active content, like scripts and executables, in the web server document directories is sometimes consider an insecure practice. If, because of some configuration mistake, the scripts are not executed but displayed as regular HTML documents, this may result in leakage of intellectual property or security information like passwords. Therefore many sysadmins will prefer setting up another directory structure for scripts that are accessible only through the PHP CGI, and therefore always interpreted and not displayed as such.

Also if the method for making sure the requests are not redirected, as described in the previous section, is not available, it is necessary to set up a script doc_root that is different from web document root.

You can set the PHP script document root by the configuration directive doc_root in the configuration file, or you can set the environment variable PHP_DOCUMENT_ROOT. If it is set, the CGI version of PHP will always construct the file name to open with this doc_root and the path information in the request, so you can be sure no script is executed outside this directory (except for user_dir below).

Another option usable here is user_dir. When user_dir is unset, only thing controlling the opened file name is doc_root. Opening an url like http://my.host/~user/doc.php does not result in opening a file under users home directory, but a file called ~user/doc.php under doc_root (yes, a directory name starting with a tilde [~]).

If user_dir is set to for example public_php, a request like http://my.host/~user/doc.php will open a file called doc.php under the directory named public_php under the home directory of the user. If the home of the user is /home/user, the file executed is /home/user/public_php/doc.php.

user_dir expansion happens regardless of the doc_root setting, so you can control the document root and user directory access separately.

Case 4: PHP parser outside of web tree

A very secure option is to put the PHP parser binary somewhere outside of the web tree of files. In /usr/local/bin, for example. The only real downside to this option is that you will now have to put a line similar to:

#!/usr/local/bin/php

as the first line of any file containing PHP tags. You will also need to make the file executable. That is, treat it exactly as you would treat any other CGI script written in Perl or sh or any other common scripting language which uses the #! shell-escape mechanism for launching itself.

To get PHP to handle PATH_INFO and PATH_TRANSLATED information correctly with this setup, the php parser should be compiled with the --enable-discard-path configure option.

后退 | 起点 | 前进
Security | 上一级 | Installed as an Apache module


Installed as an Apache module

When PHP is used as an Apache module it inherits Apache's user permissions (typically those of the "nobody" user). This has several impacts on security and authorization. For example, if you are using PHP to access a database, unless that database has built-in access control, you will have to make the database accessable to the "nobody" user. This means a malicious script could access and modify the database, even without a username and password. It's entirely possible that a web spider could stumble across a database administrator's web page, and drop all of your databases. You can protect against this with Apache authorization, or you can design your own access model using LDAP, .htaccess files, etc. and include that code as part of your PHP scripts.

Often, once security is established to the point where the PHP user (in this case, the apache user) has very little risk attached to it, it is discovered that PHP is now prevented from writing any files to user directories. Or perhaps it has been prevented from accessing or changing databases. It has equally been secured from writing good and bad files, or entering good and bad database transactions.

A frequent security mistake made at this point is to allow apache root permissions, or to escalate apache's abilitites in some other way.

Escalating the Apache user's permissions to root is extremely dangerous and may compromise the entire system, so sudo'ing, chroot'ing, or otherwise running as root should not be considered by those who are not security professionals.

There are some simpler solutions. By using open_basedir you can control and restrict what directories are allowed to be used for PHP. You can also set up apache-only areas, to restrict all web based activity to non-user, or non-system, files.

后退 | 起点 | 前进
Installed as CGI binary | 上一级 | Filesystem Security


Filesystem Security

PHP is subject to the security built into most server systems with respect to permissions on a file and directory basis. This allows you to control which files in the filesystem may be read. Care should be taken with any files which are world readable to ensure that they are safe for reading by all users who have access to that filesystem.

Since PHP was designed to allow user level access to the filesystem, it's entirely possible to write a PHP script that will allow you to read system files such as /etc/passwd, modify your ethernet connections, send massive printer jobs out, etc. This has some obvious implications, in that you need to ensure that the files that you read from and write to are the appropriate ones.

Consider the following script, where a user indicates that they'd like to delete a file in their home directory. This assumes a situation where a PHP web interface is regularly used for file management, so the Apache user is allowed to delete files in the user home directories.

例子 5-1. Poor variable checking leads to....

<?php
// remove a file from the user's home directory
$username = $_POST['user_submitted_name'];
$homedir = "/home/$username";
$file_to_delete = "$userfile";
unlink ($homedir/$userfile);
echo "$file_to_delete has been deleted!";
?>
Since the username is postable from a user form, they can submit a username and file belonging to someone else, and delete files. In this case, you'd want to use some other form of authentication. Consider what could happen if the variables submitted were "../etc/" and "passwd". The code would then effectively read:

例子 5-2. ... A filesystem attack

<?php
// removes a file from anywhere on the hard drive that
// the PHP user has access to. If PHP has root access:
$username = "../etc/";
$homedir = "/home/../etc/";
$file_to_delete = "passwd";
unlink ("/home/../etc/passwd");
echo "/home/../etc/passwd has been deleted!";
?>
There are two important measures you should take to prevent these issues.

  • Only allow limited permissions to the PHP web user binary.

  • Check all variables which are submitted.

Here is an improved script:

例子 5-3. More secure file name checking

<?php
// removes a file from the hard drive that
// the PHP user has access to.
$username = $_SERVER['REMOTE_USER']; // using an authentication mechanisim

$homedir = "/home/$username";

$file_to_delete = basename("$userfile"); // strip paths
unlink ($homedir/$file_to_delete);

$fp = fopen("/home/logging/filedelete.log","+a"); //log the deletion
$logstring = "$username $homedir $file_to_delete";
fputs ($fp, $logstring);
fclose($fp);

echo "$file_to_delete has been deleted!";
?>
However, even this is not without it's flaws. If your authentication system allowed users to create their own user logins, and a user chose the login "../etc/", the system is once again exposed. For this reason, you may prefer to write a more customized check:

例子 5-4. More secure file name checking

<?php
$username = $_SERVER['REMOTE_USER']; // using an authentication mechanisim
$homedir = "/home/$username";

if (!ereg('^[^./][^/]*$', $userfile))
     die('bad filename'); //die, do not process

if (!ereg('^[^./][^/]*$', $username))
     die('bad username'); //die, do not process
//etc...
?>

Depending on your operating system, there are a wide variety of files which you should be concerned about, including device entries (/dev/ or COM1), configuration files (/etc/ files and the .ini files), well known file storage areas (/home/, My Documents), etc. For this reason, it's usually easier to create a policy where you forbid everything except for what you explicitly allow.

后退 | 起点 | 前进
Installed as an Apache module | 上一级 | Database Security


Database Security

Nowadays, databases are cardinal components of any web based application by enabling websites to provide varying dynamic content. Since very sensitive or secret informations can be stored in such database, you should strongly consider to protect them somehow.

To retrieve or to store any information you need to connect to the database, send a legitimate query, fetch the result, and close the connecion. Nowadays, the commonly used query language in this interaction is the Structured Query Language (SQL). See how an attacker can tamper with an SQL query.

As you can realize, PHP cannot protect your database by itself. The following sections aim to be an introduction into the very basics of how to access and manipulate databases within PHP scripts.

Keep in mind this simple rule: defence in depth. In the more place you take the more action to increase the protection of your database, the less probability of that an attacker succeeds, and exposes or abuse any stored secret information. Good design of the database schema and the application deals with your greatest fears.

Designing Databases

The first step is always to create the database, unless you want to use an existing third party's one. When a database is created, it is assigned to an owner, who executed the creation statement. Usually, only the owner (or a superuser) can do anything with the objects in that database, and in order to allow other users to use it, privileges must be granted.

Applications should never connect to the database as its owner or a superuser, because these users can execute any query at will, for example, modifying the schema (e.g. dropping tables) or deleting its entire content.

You may create different database users for every aspect of your application with very limited rights to database objects. The most required privileges should be granted only, and avoid that the same user can interact with the database in different use cases. This means that if intruders gain access to your database using one of these credentials, they can only effect as many changes as your application can.

You are encouraged not to implement all the business logic in the web application (i.e. your script), instead to do it in the database schema using views, triggers or rules. If the system evolves, new ports will be intended to open to the database, and you have to reimplement the logic in each separate database client. Over and above, triggers can be used to transparently and automatically handle fields, which often provides insight when debugging problems with your application or tracing back transactions.

Connecting to Database

You may want to estabilish the connections over SSL to encrypt client/server communications for increased security, or you can use ssh to encrypt the network connection between clients and the database server. If either of them is done, then monitoring your traffic and gaining informations in this way will be a hard work.

Encrypted Storage Model

SSL/SSH protects data travelling from the client to the server, SSL/SSH does not protect the persistent data stored in a database. SSL is an on-the-wire protocol.

Once an attacker gains access to your database directly (bypassing the webserver), the stored sensitive data may be exposed or misused, unless the information is protected by the database itself. Encrypting the data is a good way to mitigate this threat, but very few databases offer this type of data encryption.

The easiest way to work around this problem is to first create your own encryption package, and then use it from within your PHP scripts. PHP can assist you in this case with its several extensions, such as Mcrypt and Mhash, covering a wide variety of encryption algorithms. The script encrypts the data be stored first, and decrypts it when retrieving. See the references for further examples how encryption works.

In case of truly hidden data, if its raw representation is not needed (i.e. not be displayed), hashing may be also taken into consideration. The well-known example for the hashing is storing the MD5 hash of a password in a database, instead of the password itself. See also crypt() and md5().

例子 5-5. Using hashed password field

// storing password hash
$query  = sprintf("INSERT INTO users(name,pwd) VALUES('%s','%s');",
            addslashes($username), md5($password));
$result = pg_exec($connection, $query);

// querying if user submitted the right password
$query = sprintf("SELECT 1 FROM users WHERE name='%s' AND pwd='%s';",
            addslashes($username), md5($password));
$result = pg_exec($connection, $query);

if (pg_numrows($result) > 0) {
    echo "Welcome, $username!";
}
else {
    echo "Authentication failed for $username.";
}

SQL Injection

Many web developers are unaware of how SQL queries can be tampered with, and assume that an SQL query is a trusted command. It means that SQL queries are able to circumvent access controls, thereby bypassing standard authentication and authorization checks, and sometimes SQL queries even may allow access to host operating system level commands.

Direct SQL Command Injection is a technique where an attacker creates or alters existing SQL commands to expose hidden data, or to override valuable ones, or even to execute dangerous system level commands on the database host. This is accomplished by the application taking user input and combining it with static parameters to build a SQL query. The following examples are based on true stories, unfortunately.

Owing to the lack of input validation and connecting to the database on behalf of a superuser or the one who can create users, the attacker may create a superuser in your database.

例子 5-6. Splitting the result set into pages ... and making superusers (PostgreSQL and MySQL)

$offset = argv[0]; // beware, no input validation!
$query  = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
// with PostgreSQL
$result = pg_exec($conn, $query);
// with MySQL
$result = mysql_query($query);
Normal users click on the 'next', 'prev' links where the $offset is encoded into the URL. The script expects that the incoming $offset is decimal number. However, someone tries to break in with appending urlencode()'d form of the following to the URL

// in case of PostgreSQL
0;
insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd)
    select 'crack', usesysid, 't','t','crack'
    from pg_shadow where usename='postgres';
--

// in case of MySQL
0;
UPDATE user SET Password=PASSWORD('crack') WHERE user='root';
FLUSH PRIVILEGES;

If it happened, then the script would present a superuser access to him. Note that 0; is to supply a valid offset to the original query and to terminate it.

注: It is common technique to force the SQL parser to ignore the rest of the query written by the developer with -- which is the comment sign in SQL.

A feasible way to gain passwords is to circumvent your search result pages. What the attacker needs only is to try if there is any submitted variable used in SQL statement which is not handled properly. These filters can be set commonly in a preceding form to customize WHERE, ORDER BY, LIMIT and OFFSET clauses in SELECT statements. If your database supports the UNION construct, the attacker may try to append an entire query to the original one to list passwords from an arbitrary table. Using encrypted password fields is strongly encouraged.

例子 5-7. Listing out articles ... and some passwords (any database server)

$query  = "SELECT id, name, inserted, size FROM products
                  WHERE size = '$size'
                  ORDER BY $order LIMIT $limit, $offset;";
$result = odbc_exec($conn, $query);
The static part of the query can be combined with another SELECT statement which reveals all passwords:

'
union select '1', concat(uname||'-'||passwd) as name, '1971-01-01', '0' from usertable;
--

If this query (playing with the ' and --) were assigned to one of the variables used in $query, the query beast awakened.

SQL UPDATEs are also subject to attacking your database. These queries are also threatened by chopping and appending an entirely new query to it. But the attacker might fiddle with the SET clause. In this case some schema information must be possessed to manipulate the query successfully. This can be acquired by examing the form variable names, or just simply brute forcing. There are not so many naming convention for fields storing passwords or usernames.

例子 5-8. From resetting a password ... to gaining more privileges (any database server)

$query = "UPDATE usertable SET pwd='$pwd' WHERE uid='$uid';";
But a malicious user sumbits the value ' or uid like'%admin%'; -- to $uid to change the admin's password, or simply sets $pwd to "hehehe', admin='yes', trusted=100 " (with a trailing space) to gain more privileges. Then, the query will be twisted:

// $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 ...;"

A frightening example how operating system level commands can be accessed on some database hosts.

例子 5-9. Attacking the database host's operating system (MSSQL Server)

$query  = "SELECT * FROM products WHERE id LIKE '%$prod%'";
$result = mssql_query($query);
If attacker submits the value a%' exec master..xp_cmdshell 'net user test testpass /ADD' -- to $prod, then the $query will be:

$query  = "SELECT * FROM products
                    WHERE id LIKE '%a%'
                    exec master..xp_cmdshell 'net user test testpass /ADD'--";
$result = mssql_query($query);

MSSQL Server executes the SQL statements in the batch including a command to add a new user to the local accounts database. If this application were running as sa and the MSSQLSERVER service is running with sufficient privileges, the attacker would now have an account with which to access this machine.

注: Some of the examples above is tied to a specific database server. This does not mean that a similar attack is impossible against other products. Your database server may be so vulnerable in other manner.

Avoiding techniques

You may plead that the attacker must possess a piece of information about the database schema in most examples. You are right, but you never know when and how it can be taken out, and if it happens, your database may be exposed. If you are using an open source, or publicly available database handling package, which may belong to a content management system or forum, the intruders easily produce a copy of a piece of your code. It may be also a security risk if it is a poorly designed one.

These attacks are mainly based on exploiting the code not being written with security in mind. Never trust on any kind of input, especially which comes from the client side, even though it comes from a select box, a hidden input field or a cookie. The first example shows that such a blameless query can cause disasters.

  • Never connect to the database as a superuser or as the database owner. Use always customized users with very limited privileges.

  • Check if the given input has the expected data type. PHP has a wide range of input validating functions, from the simplest ones found in Variable Functions and in Character Type Functions (e.g. is_numeric(), ctype_digit() respectively) onwards the Perl compatible Regular Expressions support.

  • If the application waits for numerical input, consider to verify data with is_numeric(), or silently change its type using settype(), or use its numeric representation by sprintf().

    例子 5-10. A more secure way to compose a query for paging

    settype($offset, 'integer');
$query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";

// please note %d in the format string, using %s would be meaningless
$query = sprintf("SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET %d;",
                 $offset);

  • Quote each non numeric user input which is passed to the database with addslashes() or addcslashes(). See the first example. As the examples shows, quotes burnt into the static part of the query is not enough, and can be easily hacked.

  • Do not print out any database specific information, especially about the schema, by fair means or foul. See also Error Reporting and Error Handling and Logging Functions.

  • You may use stored procedures and previously defined cursors to abstract data access so that users do not directly access tables or views, but this solution has another impacts.

Besides these, you benefit from logging queries either within your script or by the database itself, if it supports. Obviously, the logging is unable to prevent any harmful attempt, but it can be helpful to trace back which application has been circumvented. The log is not useful by itself, but through the information it contains. The more detail is generally better.

后退 | 起点 | 前进
Filesystem Security | 上一级 | Error Reporting


Error Reporting

With PHP security, there are two sides to error reporting. One is beneficial to increasing security, the other is detrimental.

A standard attack tactic involves profiling a system by feeding it improper data, and checking for the kinds, and contexts, of the errors which are returned. This allows the system cracker to probe for information about the server, to determine possible weaknesses. For example, if an attacker had gleaned information about a page based on a prior form submission, they may attempt to override variables, or modify them:

例子 5-11. Attacking Variables with a custom HTML page

<form method="post" action="attacktarget?username=badfoo&password=badfoo">
<input type="hidden" name="username" value="badfoo">
<input type="hidden" name="password" value="badfoo">
</form>

The PHP errors which are normally returned can be quite helpful to a developer who is trying to debug a script, indicating such things as the function or file that failed, the PHP file it failed in, and the line number which the failure occured in. This is all information that can be exploited. It is not uncommon for a php developer to use show_source(), highlight_string(), or highlight_file() as a debugging measure, but in a live site, this can expose hidden variables, unchecked syntax, and other dangerous information. Especially dangerous is running code from known sources with built-in debugging handlers, or using common debugging techniques. If the attacker can determine what general technique you are using, they may try to brute-force a page, by sending various common debugging strings:

例子 5-12. Exploiting common debugging variables

<form method="post" action="attacktarget?errors=Y&amp;showerrors=1"&debug=1">
<input type="hidden" name="errors" value="Y">
<input type="hidden" name="showerrors" value="1">
<input type="hidden" name="debug" value="1">
</form>

Regardless of the method of error handling, the ability to probe a system for errors leads to providing an attacker with more information.

For example, the very style of a generic PHP error indicates a system is running PHP. If the attacker was looking at an .html page, and wanted to probe for the back-end (to look for known weaknesses in the system), by feeding it the wrong data they may be able to determine that a system was built with PHP.

A function error can indicate whether a system may be running a specific database engine, or give clues as to how a web page or programmed or designed. This allows for deeper investigation into open database ports, or to look for specific bugs or weaknesses in a web page. By feeding different pieces of bad data, for example, an attacker can determine the order of authentication in a script, (from the line number errors) as well as probe for exploits that may be exploited in different locations in the script.

A filesystem or general PHP error can indicate what permissions the webserver has, as well as the structure and organization of files on the web server. Developer written error code can aggravate this problem, leading to easy exploitation of formerly "hidden" information.

There are three major solutions to this issue. The first is to scrutinize all functions, and attempt to compensate for the bulk of the errors. The second is to disable error reporting entirely on the running code. The third is to use PHP's custom error handling functions to create your own error handler. Depending on your security policy, you may find all three to be applicable to your situation.

One way of catching this issue ahead of time is to make use of PHP's own error_reporting(), to help you secure your code and find variable usage that may be dangerous. By testing your code, prior to deployment, with E_ALL, you can quickly find areas where your variables may be open to poisoning or modification in other ways. Once you are ready for deployment, by using E_NONE, you insulate your code from probing.

例子 5-13. Finding dangerous variables with E_ALL

<?php
if ($username) {  // Not initialized or checked before usage
    $good_login = 1;
}
if ($good_login == 1) { // If above test fails, not initialized or checked before usage
    fpassthru ("/highly/sensitive/data/index.html");
}
?>

后退 | 起点 | 前进
Database Security | 上一级 | Using Register Globals


Using Register Globals

One feature of PHP that can be used to enhance security is configuring PHP with register_globals = off. By turning off the ability for any user-submitted variable to be injected into PHP code, you can reduce the amount of variable poisoning a potential attacker may inflict. They will have to take the additional time to forge submissions, and your internal variables are effectively isolated from user submitted data.

While it does slightly increase the amount of effort required to work with PHP, it has been argued that the benefits far outweigh the effort.

例子 5-14. Working with register_globals=on

<?php
if ($username) {  // can be forged by a user in get/post/cookies
    $good_login = 1;
}

if ($good_login == 1) { // can be forged by a user in get/post/cookies,
    fpassthru ("/highly/sensitive/data/index.html");
}
?>

例子 5-15. Working with register_globals = off

<?php
if($_COOKIE['username']){
    // can only come from a cookie, forged or otherwise
    $good_login = 1;
    fpassthru ("/highly/sensitive/data/index.html");
}
?>
By using this wisely, it's even possible to take preventative measures to warn when forging is being attempted. If you know ahead of time exactly where a variable should be coming from, you can check to see if submitted data is coming from an inappropriate kind of submission. While it doesn't guarantee that data has not been forged, it does require an attacker to guess the right kind of forging.

例子 5-16. Detecting simple variable poisoning

<?php
if ($_COOKIE['username'] &&
    !$_POST['username'] &&
    !$_GET['username'] ) {
    // Perform other checks to validate the user name...
    $good_login = 1;
    fpassthru ("/highly/sensitive/data/index.html");
} else {
   mail("admin@example.com", "Possible breakin attempt", $_SERVER['REMOTE_ADDR']);
   echo "Security violation, admin has been alerted.";
   exit;
}
?>
Of course, simply turning off register_globals does not mean code is secure. For every piece of data that is submitted, it should also be checked in other ways.

后退 | 起点 | 前进
Error Reporting | 上一级 | User Submitted Data


User Submitted Data

The greatest weakness in many PHP programs is not inherent in the language itself, but merely an issue of code not being written with security in mind. For this reason, you should always take the time to consider the implications of a given piece of code, to ascertain the possible damage if an unexpected variable is submitted to it.

例子 5-17. Dangerous Variable Usage

<?php
// remove a file from the user's home directory... or maybe
// somebody else's?
unlink ($evil_var);

// Write logging of their access... or maybe an /etc/passwd entry?
fputs ($fp, $evil_var);

// Execute something trivial.. or rm -rf *?
system ($evil_var);
exec ($evil_var);

?>
You should always carefully examine your code to make sure that any variables being submitted from a web browser are being properly checked, and ask yourself the following questions:

  • Will this script only affect the intended files?

  • Can unusual or undesirable data be acted upon?

  • Can this script be used in unintended ways?

  • Can this be used in conjunction with other scripts in a negative manner?

  • Will any transactions be adequately logged?

By adequately asking these questions while writing the script, rather than later, you prevent an unfortunate re-write when you need to increase your security. By starting out with this mindset, you won't guarantee the security of your system, but you can help improve it.

You may also want to consider turning off register_globals, magic_quotes, or other convenience settings which may confuse you as to the validity, source, or value of a given variable. Working with PHP in error_reporting(E_ALL) mode can also help warn you about variables being used before they are checked or initialized (so you can prevent unusual data from being operated upon).

后退 | 起点 | 前进
Using Register Globals | 上一级 | Hiding PHP


Hiding PHP

In general, security by obscurity is one of the weakest forms of security. But in some cases, every little bit of extra security is desirable.

A few simple techniques can help to hide PHP, possibly slowing down an attacker who is attempting to discover weaknesses in your system. By setting expose_php = off in your php.ini file, you reduce the amount of information available to them.

Another tactic is to configure web servers such as apache to parse different filetypes through PHP, either with an .htaccess directive, or in the apache configuration file itself. You can then use misleading file extensions:

例子 5-18. Hiding PHP as another language

# Make PHP code look like other code types
AddType application/x-httpd-php .asp .py .pl
Or obscure it completely:

例子 5-19. Using unknown types for PHP extensions

# Make PHP code look like unknown types
AddType application/x-httpd-php .bop .foo .133t
Or hide it as html code, which has a slight performance hit because all html will be parsed through the PHP engine:

例子 5-20. Using html types for PHP extensions

# Make all PHP code look like html
AddType application/x-httpd-php .htm .html
For this to work effectively, you must rename your PHP files with the above extensions. While it is a form of security through obscurity, it's a minor preventative measure with few drawbacks.

后退 | 起点 | 前进
User Submitted Data | 上一级 | Keeping Current


Keeping Current

PHP, like any other large system, is under constant scrutiny and improvement. Each new version will often include both major and minor changes to enhance and repair security flaws, configuration mishaps, and other issues that will affect the overall security and stability of your system.

Like other system-level scripting languages and programs, the best approach is to update often, and maintain awareness of the latest versions and their changes.

后退 | 起点 | 前进
Hiding PHP | 上一级 | 语言参考


语言参考

PHP 手册
后退 前进

II. 语言参考

目录
6. 基本语法
7. 类型
8. 变量
9. 常量
10. 表达式
11. 运算符
12. 流程控制
13. 函数
14. 类与对象
15. 引用的解释

后退 | 起点 | 前进
Keeping Current |  | 基本语法


基本语法

PHP 手册
后退 前进

章 6. 基本语法

目录
从 HTML 中分离
指令分隔符
注释

从 HTML 中分离

PHP 的脚本由文件中一对特殊的标记所引起的内容，当解释器分析一个文件时，所有特殊标记 外的普通文件，解释器不对其做任何处理，而特殊标记内文件将作为 PHP 代码被解释器分析 执行。该运行机制将允许您在 HTML 中嵌入 PHP 代码：PHP 标记外的内容将被完全独立开， 不做任何处理，而内部的将作为 PHP 代码解析。

用来标记 PHP 代码块的标记共有四套，其中只有两套总是有效（<?php. . .?> 和 <script language="php">. . .</script>）；另外两套可以在 php.ini 配置文件中 开启或者关闭。虽然短格式的标记和 ASP 风格的标记可能比较省力，但是某些情况下您可能 必须要使用长格式的标记。比如，您打算在 XML 或者 XHTML 中嵌入 PHP 代码，您将需要 使用 <?php. . .?> 形式的标记以适应 XML 的标准。

PHP 支持的标记为：

例子 6-1. 从 HTML 中分离的方式

1.  <?php echo("if you want to serve XHTML or XML documents, do like this\n"); ?>

2.  <? echo ("this is the simplest, an SGML processing instruction\n"); ?>
    <?= expression ?> This is a shortcut for "<? echo expression ?>"

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

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

优先选用的方式为第一种方式 <?php. . .?>，因为它允许您在 XML 结构， 如 XHTML 的代码中使用 PHP。

第二种方式并非总是可用的。只有当您在 php.ini 配置文件中激活 short_open_tag 选项，才是可用的。 您也可以通过使用 short_tags() 函数（仅用于 PHP 3），或者 使用 --enable-short-tags 选项 configure PHP 来激活短格式标记。 在 php.ini-dist 配置文件中，默认是开启短格式标记的，但是建议您不要使用该标记。

在 PHP 配置文件中开启选项 asp_tags 将激活 第四种方式。

注: ASP 风格的标记添加于 PHP 3.0.4

注: 当开发大型应用程序或者用于分发的函数库，或者在不受您控制的 PHP 服务器上面开发 程序时，请不要使用短格式的标记，因为目标服务器可能并不支持短格式的标记。为了 便于移植，请保证用于再分发的代码中不使用短格式的标记。

PHP 代码块结束标记奖自动包含最近的一个结尾的新行（如果存在的话）。而且， 结束标记自动隐含一个分号; 您不需要为 PHP 代码块的最后行追加一个分号。

PHP 允许您使用如下的结构：

例子 6-2. 更高级的脱离

<?php
if ($expression) {
    ?>
    <strong>This is true.</strong>
    <?php
} else {
    ?>
    <strong>This is false.</strong>
    <?php
}
?>
PHP 将直接输出结束标记和下一个开始标记中的任何非 PHP 代码。当需要输出大量的文本时， 退出 PHP 解析模式将比使用 echo() 或者 print() 或者此类的函数打印所有文本要更加的有效。

后退 | 起点 | 前进
语言参考 | 上一级 | 指令分隔符


指令分隔符

指令分隔方式与 C 或者 Perl 类似 -- 每个语句由分号格开。

结束标记（?>）同样隐含语句的结束，因此下面的代码是等价的：

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

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

后退 | 起点 | 前进
基本语法 | 上一级 | 注释


注释

PHP 支持 'C'，'C++' 和 Unix Shell 风格的注释。例如:

<?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 代码块，无论哪个首先出现。

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

小心不要嵌套 'C' 风格的注释，当注释大量代码时，可能犯该错误。

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

"单行" 注释仅仅注释到行末或者当前的 PHP 代码块，无论哪个首先出现。这意味着 // ?> 后面的 HTML 代码将被打印出来，?> 跳出了 PHP 模式并且返回 HTML 模式，而且 // 注释 符并不会影响到模式的转换。

后退 | 起点 | 前进
指令分隔符 | 上一级 | 类型


类型

PHP 手册
后退 前进

章 7. 类型

目录
介绍
布尔型
整型
浮点型
字符串
数组
对象
资源
NULL
类型戏法

介绍

PHP 支持八种原始类型。

四种标量类型：

  • 布尔型（boolean）

  • 整型（integer）

  • 浮点型（float）

  • 字符串（string）

两种复合类型：

  • 数组（array）

  • 对象（object）

最后是两种特殊类型：

  • 资源（resource）

  • NULL

注: 本手册中你经常会碰到 mixed 参数。这个伪类型表示该参数有多种可能的类型。

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

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

如果你只是想得到一个易读懂的类型的表达方式用于调试，用 gettype()。要查看某个类型，不要用 gettype()，而用 is_type 函数。

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

注意变量根据其当时的类型在特定场合下会表现出不同的风格。更多信息见类型戏法。

后退 | 起点 | 前进
注释 | 上一级 | 布尔型


布尔型

这是最简单的类型。boolean 表达了真值，可以为 TRUE 或 FALSE。

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

语法

要指定一个布尔值，使用关键字 TRUE 或 FALSE。两个都是大小写不敏感的。

$foo = True; // assign the value TRUE to $foo

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

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

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

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

转换为布尔值

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

参见类型戏法。

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

  • 布尔值 FALSE

  • 整型值 0（零）

  • 浮点型值 0.0（零）

  • 空白字符串和字符串 "0"

  • 没有单元的数组

  • 没有单元的对象

  • 特殊类型NULL（包括尚未设定的变量）

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

警告

-1 和其它非零值（不论正负）一样，被认为是 TRUE！

后退 | 起点 | 前进
类型 | 上一级 | 整型


整型

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

参见任意长度整数和浮点数。

语法

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

如果用八进制符号，数字前必须加上 0（零），用十六进制符号数字前必须加上 0x。

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

$a = 1234; # 十进制数
$a = -123; # 一个负数
$a = 0123; # 八进制数（等于十进制的 83）
$a = 0x1A; # 十六进制数（等于十进制的 26）
整型数的字长和平台有关，尽管通常最大值是大约二十亿（32 位有符号）。PHP 不支持无符号整数。

整数溢出

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

$large_number =  2147483647;
var_dump($large_number);
// 输出为：int(2147483647)

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

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

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

警告

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

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

PHP 中没有整除的运算符。1/2 产生出 float 0.5。

var_dump( 25/7 );
// 输出为：float(3.5714285714286)

转换为整形

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

参见类型戏法。

从布尔值转换

FALSE 将产生出 0（零），TRUE 将产生出 1（壹）。

从浮点数转换

当从浮点数转换成整数时，数字将被取整（丢弃小数位）。

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

（译者注：）在 Linux 下返回结果是最小负数（-2147483648），而在 Windows 下返回结果是零（0）。

警告

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

echo (int) ( (0.1+0.7) * 10 ); // echoes 7!

更多信息见浮点数精度。

从字符串转换

参见字符串转换。

从其它类型转换

注意

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

后退 | 起点 | 前进
布尔型 | 上一级 | 浮点型


浮点型

浮点数（也叫“floats”，“doubles”或“real numbers”）可以用以下任何语法定义：
$a = 1.234; $a = 1.2e3; $a = 7E-10;
浮点数的字长和平台相关，尽管通常最大值是 1.8e308 并具有 14 位十进制数字的精度（64 位 IEEE 格式）。

浮点数精度

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

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

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

后退 | 起点 | 前进
整型 | 上一级 | 字符串


字符串

string 是一系列字符。在 PHP 中，字符和字节一样，也就是说，一共有 256 种不同字符的可能性。这也暗示 PHP 对 Unicode 没有本地支持。

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

语法

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

  • 单引号

  • 双引号

  • 定界符

单引号

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

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

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

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

echo 'this is a simple string';
echo 'You can also have embedded newlines in strings,
like this way.';
echo 'Arnold once said: "I\'ll be back"';
// output: ... "I'll be back"
echo 'Are you sure you want to delete C:\\*.*?';
// output: ... delete C:\*.*?
echo 'Are you sure you want to delete C:\*.*?';
// output: ... delete C:\*.*?
echo 'I am trying to include at this point: \n a newline';
// output: ... this point: \n a newline

双引号

如果用双引号（"）括起字符串，PHP 懂得更多特殊字符的转义序列：

表格 7-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 中其它任何标签的命名规则：只能包含字母数字下划线，而且必须以下划线或非数字字符开始。

警告

很重要的一点必须指出，结束标识符所在的行不能包含任何其它字符，可能除了一个分号（;）之外。这尤其意味着该标识符不能被缩进，而且在分号之前和之后都不能有任何空格或制表符。

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

例子 7-2. 定界符字符串例子

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

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

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

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

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

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

变量解析

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

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

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

简单语法

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

$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

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

$fruits = array( 'strawberry' => 'red' , 'banana' => 'yellow' );

// note that this works differently outside string-quotes.
echo "A banana is $fruits[banana].";

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.";

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

复杂（花括号）语法

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

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

$great = 'fantastic';
echo "This is { $great}"; // 不行，输出为：This is { fantastic}
echo "This is {$great}";  // 可以，输出为：This is fantastic
echo "This square is {$square->width}00 centimeters broad.";
echo "This works: {$arr[4][3]}";

// This is wrong for the same reason
// as $foo[bar] is wrong outside a string.
echo "This is wrong: {$arr[foo][3]}";

echo "You should do it this way: {$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 中不赞成使用。

例子 7-3. 一些字符串例子

<?php
/* Assigning a string. */
$str = "This is a string";

/* Appending to it. */
$str = $str . " with some more text";

/* Another way to append, includes an escaped newline. */
$str .= " and a newline at the end.\n";

/* This string will end up being '<p>Number: 9</p>' */
$num = 9;
$str = "<p>Number: $num</p>";

/* This one will be '<p>Number: $num</p>' */
$num = 9;
$str = '<p>Number: $num</p>';

/* Get the first character of a string  */
$str = 'This is a test.';
$first = $str{0};

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

实用函数

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

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

普通函数见字符串函数库一节，高级搜索和替换见正则表达式函数（两种口味：Perl 和 POSIX 扩展）。

还有 URL 字符串函数，以及加密／解密字符串的函数（mcrypt 和 mhash）。

最后，如果还是找不到你要的函数，参见字符类型函数库。

字符串转换

当一个字符串被当作数字来求值时，根据以下规则来决定结果的类型和值。

如果包括“.”，“e”或“E”其中任何一个字符的话，字符串被当作 float 来求值。否则就被当作整数。

该值由字符串最前面的部分决定。如果字符串以合法的数字数据开始，就用该数字作为其值，否则其值为 0（零）。合法数字数据由可选的正负号开始，后面跟着一个或多个数字（可选地包括十进制分数），后面跟着可选的指数。指数是一个“e”或者“E”后面跟着一个或多个数字。

$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) 的部分。

如果你想测试本节中的任何例子，可以拷贝和粘贴这些例子并且加上下面这一行自己看看会发生什么：

echo "\$foo==$foo; type is " . gettype ($foo) . "<br />\n";

后退 | 起点 | 前进
浮点型 | 上一级 | 数组


数组

PHP 中的数组实际上是一个有序图。图是一种把 values 映射到 keys 的类型。此类型在很多方面做了优化，因此你可以把它当成真正的数组来使用，或列表（矢量），散列表（是图的一种实现），字典，集合，栈，队列以及更多可能性。因为可以用另一个 PHP 数组作为值，也可以很容易地模拟树。

解释这些结构超出了本手册的范围，但对于每种结构你至少会发现一个例子。要得到这些结构的更多信息，我们建议你参考有关此广阔主题的外部著作。

语法

定义 array()

可以用 array() 语言结构来新建一个 array。它接受一定数量用逗号分隔的 key => value 参数对。

key 可以是 integer 或者 string。如果键名是一个 integer 的标准表达方法，则被解释为整数（例如 "8" 将被解释为 8，而 "08" 将被解释为 "08"）。

值可以是任何值。

如果省略键名，则取当前最大的整数索引，而新的键名将是该值加一。整数可以为负，所以对于负的索引也是这样。例如最大的索引是 -6 将导致新的键名是 -5。如果还不存在整数索引，则键名将为 0（零）。如果你指定的键名已经有了值，则该值会被覆盖。

使用 true 作为键名将使 integer 1 成为键名。使用 false 作为键名将使 integer 0 成为键名。使用 NULL 作为键名将等同于使用空字符串。使用空字符串作为键名将新建（或覆盖）一个用空字符串作为键名的值，这和用空的方括号不一样。

不能用数组和对象作为键名。这样做会导致一个警告：Illegal offset type。

array( [key =>] value
     , ...
     )
// key is either string or nonnegative integer
// value can be anything

用方括号的语法新建／修改

可以通过明示地设定值来改变一个现有的数组。

这是通过在方括号内指定键名来给数组赋值实现的。也可以省略键名，在这种情况下给变量名加上一对空的方括号（“[]”）。
$arr[key] = value;
$arr[] = value;
// key is either string or nonnegative integer
// value can be anything
如果 $arr 还不存在，将会新建一个。这也是一种定义数组的替换方法。要改变一个值，只要给它赋一个新值。如果要删除一个键名／值对，要对它用 unset()。

实用函数

有相当多的实用函数作用于数组，参见数组函数库一节。

注: unset() 函数允许取消一个数组中的键名。要注意数组将不会重建索引。

$a = array( 1 => 'one', 2 => 'two', 3 => 'three' );
unset( $a[2] );
/* 将产生一个数组，定义为
   $a = array( 1=>'one', 3=>'three');
   而不是
   $a = array( 1 => 'one', 2 => 'three');
*/

foreach 控制结构是专门用于数组的。它提供了一个简单的方法来遍历数组。

数组做什么和不做什么

为什么 $foo[bar] 错了？

应该始终在数组的索引上加上引号。例如用 $foo['bar'] 而不是 $foo[bar]。但是为什么 $foo[bar] 错了呢？你可能在老的脚本中见过如下语法：

$foo[bar] = 'enemy';
echo $foo[bar];
// etc

这样是错的，但可以起作用。那么为什么错了呢？原因是此代码中有一个未定义的常量（bar）而不是字符串（'bar'－注意引号），而 PHP 可能会在以后定义此常量，不幸的是你的代码中有同样的名字。它可以起作用，因为未定义常量会被转换为同样名字的字符串。

和在语法一节中规定的一样，在方括号（“[”和“]”）之间必须有一个表达式。这意味着你可以这样写：

echo $arr[ foo(true) ];

这是一个用函数返回值作为数组索引的例子。PHP 也可以用已知常量，你可能之前已经见过 E_*。

$error_descriptions[E_ERROR] = "A fatal error has occured";
$error_descriptions[E_WARNING] = "PHP issued a warning";
$error_descriptions[E_NOTICE] = "This is just an informal notice";

注意 E_ERROR 也是个合法的标识符，就和第一个例子中的 bar 一样。但是上一个例子实际上和如下写法是一样的：

$error_descriptions[1] = "A fatal error has occured";
$error_descriptions[2] = "PHP issued a warning";
$error_descriptions[8] = "This is just an informal notice";

因为 E_ERROR 等于 1，等等。

那么 $foo[bar] 怎么可能起作用的呢？它起作用是因为根据语法的预期，bar 被当成了一个常量表达式。然而，在这个例子中不存在名为 bar 的常量。PHP 就假定你指的是字面上的 bar，也就是字符串 "bar"，但你忘记写引号了。

那么为什么这样做不好？

在未来的某一时刻，PHP 开发小组可能会想新增一个常量或者关键字，那你就有麻烦了。例如你已经不能这样用 empty 和 default 这两个词了，因为他们是保留字。

注: 当你把 error_reporting 设为 E_ALL 时，你将会看到无论何时使用了未定义的 index 时，PHP 都会产生通知（在你的脚本中加入一行 error_reporting(E_ALL);）。

注: 在双引号 string 中，另一种语法是合法的。细节见字符串中的变量解析。

例子

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')

例子 7-4. 使用 array()

// Array as (property-)map
$map = array( 'version'    => 4
            , 'OS'         => 'Linux'
            , 'lang'       => 'english'
            , 'short_tags' => true
            );

// strictly numerical keys
$array = array( 7
              , 8
              , 0
              , 156
              , -10
              );
// this is the same as array( 0 => 7, 1 => 8, ...)

$switching = array(         10 // key = 0
                  , 5    =>  6
                  , 3    =>  7
                  , 'a'  =>  4
                  ,         11 // key = 6 (maximum of integer-indices was 5)
                  , '8'  =>  2 // key = 8 (integer!)
                  , '02' => 77 // key = '02'
                  , 0    => 12 // the value 10 will be overwritten by 12
                  );

// empty array
$empty = array();

例子 7-5. 集合

$colors = array('red','blue','green','yellow');

foreach ( $colors as $color ) {
    echo "Do you like $color?\n";
}

/* output:
Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?
*/

注意目前不可能在这样一个循环中直接改变数组的值。可以改变的例子如下：

例子 7-6. 集合

foreach ($colors as $key => $color) {
    // won't work:
    //$color = strtoupper($color);

    //works:
    $colors[$key] = strtoupper($color);
}
print_r($colors);

/* output:
Array
(
    [0] => RED
    [1] => BLUE
    [2] => GREEN
    [3] => YELLOW
)
*/

本例产生一个基于一的数组。

例子 7-7. 基于一的数组

$firstquarter  = array(1 => 'January', 'February', 'March');
print_r($firstquarter);

/* output:
Array
(
    [1] => 'January'
    [2] => 'February'
    [3] => 'March'
)
*/

例子 7-8. 填充真正的数组

// fill an array with all items from a directory
$handle = opendir('.');
while ($file = readdir($handle))
{
    $files[] = $file;
}
closedir($handle);

数组是有序的。你也可以使用不同的排序函数来改变顺序。更多信息参见数组函数库。

例子 7-9. 数组排序

sort($files);
print_r($files);

因为数组中的值可以为任意值，也可是另一个数组。这样你可以产生递归或多维数组。

例子 7-10. 递归和多维数组

$fruits = array ( "fruits"  => array ( "a" => "orange"
                                     , "b" => "banana"
                                     , "c" => "apple"
                                     )
                , "numbers" => array ( 1
                                     , 2
                                     , 3
                                     , 4
                                     , 5
                                     , 6
                                     )
                , "holes"   => array (      "first"
                                     , 5 => "second"
                                     ,      "third"
                                     )
                );

后退 | 起点 | 前进
字符串 | 上一级 | 对象


对象

对象初始化

要初始化一个对象，用 new 语句将对象实例到一个变量中。

<?php
class foo
{
    function do_foo()
    {
        echo "Doing foo.";
    }
}

$bar = new foo;
$bar->do_foo();
?>

完整的讨论见类与对象一章。

后退 | 起点 | 前进
数组 | 上一级 | 资源


资源

一个资源是一个特殊变量，保存了到外部资源的一个引用。资源是通过专门的函数来建立和使用的。所有这些函数及其相应资源类型见附录。

注: 资源类型是 PHP 4 引进的。

释放资源

由于 PHP4 Zend 引擎引进了资源计数系统，可以自动检测到一个资源不再被引用了（和 Java 一样）。这种情况下此资源使用的所有外部资源都会被垃圾回收系统释放。由此原因，很少需要用某些 free-result 函数来手工释放内存。

注: 持久数据库连接比较特殊，它们不会被垃圾回收系统破坏。参见数据库永久连接一章。

后退 | 起点 | 前进
对象 | 上一级 | NULL


NULL

特殊的 NULL 值表示一个变量没有值。NULL 类型唯一可能的值就是 NULL。

注: NULL 类型是 PHP 4 引进的。

在下列情况下一个变量被认为是 NULL：

  • 被赋值为 NULL。

  • 尚未被赋值。

  • 被 unset()。

语法

NULL 类型只有一个值，就是大小写敏感的关键字 NULL。

$var = NULL;

参见 is_null() 和 unset()。

后退 | 起点 | 前进
资源 | 上一级 | 类型戏法


类型戏法

PHP 在变量定义中不需要（或不支持）明示的类型定义；变量类型是根据使用该变量的上下文所决定的。也就是说，如果你把一个字符串值赋给变量 var，var 就成了一个字符串。如果你又把一个整型值赋给 var，那它就成了一个整数。

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() 函数。

注: 数组的自动转换行为目前没有定义。

$a = "1";     // $a 是字符串
$a[0] = "f";  // 是字符串偏移量吗？结果会是什么？

由于 PHP 支持通过偏移量进行的字符串索引，这和数组索引的语法一样。以上的例子就产生了一个问题：$a 应该变成一个第一个元素是“f”的数组呢，还是“f”成了字符串 $a 的第一个字符？

由于此原因，在 PHP 3.0.12 和 PHP 4.0b3-RC4 中这种自动转换的结果被当成未定义。解决方案仍在讨论之中。

（译者注：）PHP 4 中上面的一个例子出错，第二个例子的结果将是字符串 $a = 'f'。

类型强制转换

PHP 中的类型强制转换和 C 中的非常像：在要转换的变量之前加上用括号括起来的目标类型。

$foo = 10;   // $foo is an integer
$bar = (float) $foo;   // $bar is a float

允许的强制转换有：

  • (int), (integer) - 转换成整型

  • (bool), (boolean) - 转换成布尔型

  • (float), (double), (real) - 转换成浮点型

  • (string) - 转换成字符串

  • (array) - 转换成数组

  • (object) - 转换成对象

注: 除了用强制转换将变量转换成字符串之外，还可以将变量用双引号引起来。

注意在括号内允许有空格和制表符，所以下面两个例子功能相同：

$foo = (int) $bar;
$foo = ( int ) $bar;

当在某些类型之间强制转换时确切地会发生什么可能不是很明显。更多信息见如下小节：

  • 转换为布尔值

  • 转换为整型

当强制将数组转换为字符串时，结果将是 Array 这个词。当强制将对象转换为字符串时，结果将是 Object 这个词。

当强制将一个标量或字符串转换为数组时，变量将成为数组的第一个元素：

$var = 'ciao';
$arr = (array) $var;
echo $arr[0];  // outputs 'ciao'

当强制将一个标量或字符串转换为对象时，变量会成为对象的属性，属性名为“scalar”：

$var = 'ciao';
$obj = (object) $var;
echo $obj->scalar;  // outputs 'ciao'

后退 | 起点 | 前进
NULL | 上一级 | 变量


变量

PHP 手册
后退 前进

章 8. 变量

目录
基础
预定义变量
变量范围
可变变量
PHP 的外部变量

基础

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";      // outputs "Bob, Joe"

$4site = 'not yet';     // invalid; starts with a number
$_4site = 'not yet';    // valid; starts with an underscore
$t澌te = 'mansikka';    // valid; '洄 is ASCII 228.
?>

PHP 3 中，变量总是传值赋值。那也就是说，当你将一个表达式的值赋予一个变量时， 整个原始表达式的值被赋值到目标变量。这意味着，例如，当一个变量的值赋予另外一个 变量时，改变其中一个变量的值，将不会影响到另外一个变量。有关这种类型的赋值操作， 请参阅 表达式 一章。

PHP 4 提供了另外一种方式给变量赋值： 传地址赋值。 这意味着新的变量简单的引用（换言之，“成为其别名” 或者 “指向”）了原始变量。 改动新的变量将影响到原始变量，反之亦然。这同样意味着其中没有执行复制操作；因而， 这种赋值操作更加快速。尽管如此，任何提速的操作只有在紧密循环或者大 数组 或者 对象 才可能被注意到。

使用传地址赋值，简单地追加一个（&）符号到将要赋值的变量前（源变量）。例如， 下列代码片断两次输出‘My name is Bob’：

<?php
$foo = 'Bob';              // Assign the value 'Bob' to $foo
$bar = &$foo;              // Reference $foo via $bar.
$bar = "My name is $bar";  // Alter $bar...
echo $bar;
echo $foo;                 // $foo is altered too.
?>

需要注意的是只有命名变量才可以传地址赋值，这一点非常重要。

<?php
$foo = 25;
$bar = &$foo;      // This is a valid assignment.
$bar = &(24 * 7);  // Invalid; references an unnamed expression.

function test()
{
   return 25;
}

$bar = &test();    // Invalid.
?>

后退 | 起点 | 前进
类型戏法 | 上一级 | 预定义变量


预定义变量

PHP 提供了大量的预定义变量。由于许多变量依赖于运行的服务器的版本和设置，及其它 因素，所以并没有详细的说明文档。一些预定义变量在 PHP 以 命令行 形式运行时并不生效。 有关这些变量的详细列表，请参阅 保留的预定义变量 一章。

警告

PHP 4.2.0 以及后续版本中， PHP 指令 register_globals 的默认值为 off. 这是 PHP 的一个主要变化。让 register_globals 的值 为 off 将影响到预定义变量集在全局范围内的有效性。例如， 为了得到 DOCUMENT_ROOT 的值，你将必须使用 $_SERVER['DOCUMENT_ROOT'] 代替 $DOCUMENT_ROOT， 又如，使用 $_GET['id'] 来代替 $id 从 URL http://www.example.com/test.php?id=3 中获取 id 值，亦或 使用 $_ENV['HOME'] 来代替 $HOME 获取 环境变量 HOME 的值。

更多相关信息，请阅读配置项目 register_globals， 有关安全性的一章 使用 Register Globals， 以及 PHP 4.1.0 和 4.2.0 的发行通告.

请优先使用可用的 PHP 预定义变量，如 超级全局数组。

从 PHP 4.1.0 开始，PHP 提供了一套附加的预定数组，这些数组变量包含了来自 Web 服务器（如果可用）， 运行环境，和用户输入的数据。这些数组非常特别，她们在全局范围内自动生效，例如，在任何范围内自动生效。 为此，她们常因是 "autoglobals" 或者 "superglobals" 而闻名。（PHP 中尚且没有一种可使用户 自定义超级全局变量的机制）超级全局变量罗列于下文中；但是为了得到她们的内容和关于 PHP 预定 义变量的进一步的讨论以及她们的本质，请参阅 预定义变量。 而且，你也将注意到旧的地预定义数组（$HTTP_*_VARS）仍旧存在。

如果某些 variables_order 中的变量没有设定，她们的 对应的 PHP 预定义数组也是空的。

PHP 超全局变量

$GLOBALS

包含一个引用指向每个当前脚本的全局范围内有效的变量。该数组的键标为全局变量的 名称。从 PHP 3 开始存在 $GLOBALS 数组。

$_SERVER

变量由 Web 服务器设定或者直接与当前脚本的执行环境相关联。类似于旧数组 $HTTP_SERVER_VARS 数组（依然有效，但反对使用）。

$_GET

经由 HTTP GET 方法提交至脚本的变量。类似于旧数组 $HTTP_GET_VARS 数组（依然有效，但反对使用）。

$_POST

经由 HTTP POST 方法提交至脚本的变量。类似于旧数组 $HTTP_POST_VARS 数组（依然有效，但反对使用）。

$_COOKIE

经由 HTTP Cookies 方法提交至脚本的变量。类似于旧数组 $HTTP_COOKIE_VARS 数组（依然有效，但反对使用）。

$_FILES

经由 HTTP POST 文件上传而提交至脚本的变量。类似于旧数组 $HTTP_POST_FILES 数组（依然有效，但反对使用）。详细信息请参阅 POST 方法上传。

$_ENV

执行环境提交至脚本的变量。类似于旧数组 $HTTP_ENV_VARS 数组（依然有效，但反对使用）。

$_REQUEST

经由任何用户输入机制提交至脚本的变量，因此该数组并不值得信任。所有包含在该数组中的变量的存在与否 以及变量的顺序均按照 php.ini 中的 variables_order 配置指示来定义。该数组没有直接模拟 PHP 4.1.0 的早期版本。参照 import_request_variables()。

注: 当运行于 命令行 模式时，这个数组将 不会 包含 argv 和 argc 入口；她们已经存在于数组 $_SERVER 中。

$_SESSION

当前注册给脚本会话的变量。类似于旧数组 $HTTP_SESSION_VARS 数组（依然有效，但反对使用）。详细信息，请参照 Session 处理函数 章节。

后退 | 起点 | 前进
变量 | 上一级 | 变量范围


变量范围

变量的范围即它定义的上下文背景（译者:说白了，也就是它的生效范围）。大部分的 PHP 变量只有一个单独的范围。这个单独的范围跨度同样包含了 include 和 require 引入的文件。范例:

<?php
$a = 1;
include "b.inc";
?>

这里变量 $a 将会在包含文件 b.inc 中生效。但是，在用户自定义函数中，一个局部函数范围将被引入。任何用于函数内部的变量按缺省情况将被限制在局部函数范围内。范例：

<?php
$a = 1; /* global scope */

function Test()
{
    echo $a; /* reference to local scope variable */
}

Test();
?>

这个脚本不会有任何输出因为 echo 语句引用了一个局部版本的变量 $a， 而且在这个范围内，它并没有被赋值。你可能注意到 PHP 的全局变量和 C 语言有一点点不同，在 C 语言中，全局变量在函数中自动生效，除非被局部变量覆盖。这可能引起一些问题，有些人可能漫不经心的改变一个全局变量。 PHP 中全局变量在函数中使用时必须申明为全局。例如：

<?php
$a = 1;
$b = 2;

function Sum()
{
    global $a, $b;

    $b = $a + $b;
}

Sum();
echo $b;
?>

The above script will output "3". By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function. 上面的脚本将会输出 "3"。

A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array. The previous example can be rewritten as:

<?php
$a = 1;
$b = 2;

function Sum()
{
    $GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"];
}

Sum();
echo $b;
?>

The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. Notice how $GLOBALS exists in any scope, this is because $GLOBALS is a superglobal. Here's an example demonstrating the power of superglobals:

<?php
function test_global()
{
    // Most predefined variables aren't "super" and require
    // 'global' to be available to the functions local scope.
    global $HTTP_POST_VARS;

    print $HTTP_POST_VARS['name'];

    // Superglobals are available in any scope and do
    // not require 'global'.  Superglobals are available
    // as of PHP 4.1.0
    print $_POST['name'];
}
?>

Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Consider the following example:

<?php
function Test ()
{
    $a = 0;
    echo $a;
    $a++;
}
?>

This function is quite useless since every time it is called it sets $a to 0 and prints "0". The $a++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static:

<?php
function Test()
{
    static $a = 0;
    echo $a;
    $a++;
}
?>

Now, every time the Test() function is called it will print the value of $a and increment it.

Static variables also provide one way to deal with recursive functions. A recursive function is one which calls itself. Care must be taken when writing a recursive function because it is possible to make it recurse indefinitely. You must make sure you have an adequate way of terminating the recursion. The following simple function recursively counts to 10, using the static variable $count to know when to stop:

<?php
function Test()
{
    static $count = 0;

    $count++;
    echo $count;
    if ($count < 10) {
        Test ();
    }
    $count--;
}
?>

The Zend Engine 1, driving PHP4, implements the static and global modifier for variables in terms of references. For example, a true global variable imported inside a function scope with the global statement actually creates a reference to the global variable. This can lead to unexpected behaviour which the following example addresses:

<?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);
?>

Executing this example will result in the following output:

NULL
object(stdClass)(0) {
}

A similar behaviour applies to the static statement. References are not stored statically:

<?php
function &get_instance_ref() {
    static $obj;

    echo "Static object: ";
    var_dump($obj);
    if (!isset($obj)) {
        // Assign a reference to the static variable
        $obj = &new stdclass;
    }
    $obj->property++;
    return $obj;
}

function &get_instance_noref() {
    static $obj;

    echo "Static object: ";
    var_dump($obj);
    if (!isset($obj)) {
        // Assign the object to the static variable
        $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();
?>

Executing this example will result in the following output:

Static object: NULL
Static object: NULL

Static object: NULL
Static object: object(stdClass)(1) {
  ["property"]=>
  int(1)
}

This example demonstrates that when assigning a reference to a static variable, it's not remembered when you call the &get_instance_ref() function a second time.

后退 | 起点 | 前进
预定义变量 | 上一级 | 可变变量


可变变量

Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as:

<?php
$a = "hello";
?>

A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, hello, can be used as the name of a variable by using two dollar signs. i.e.

<?php
$$a = "world";
?>

At this point two variables have been defined and stored in the PHP symbol tree: $a with contents "hello" and $hello with contents "world". Therefore, this statement:

<?php
echo "$a ${$a}";
?>

produces the exact same output as:

<?php
echo "$a $hello";
?>

i.e. they both produce: hello world.

In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.

Please note that variable variables cannot be used with PHP's Superglobal arrays. This means you cannot do things like ${$_GET}. If you are looking for a way to handle availability of superglobals and the old HTTP_*_VARS, you might want to try referencing them.

后退 | 起点 | 前进
变量范围 | 上一级 | PHP 的外部变量


PHP 的外部变量

HTML 表单 (GET 和 POST)

When a form is submitted to a PHP script, the information from that form is automatically made available to the script. There are many ways to access this information, for example:

例子 8-1. 一个简单的 HTML 表单

<form action="foo.php" method="post">
    Name:  <input type="text" name="username"><br>
    Email: <input type="text" name="email"><br>
    <input type="submit" name="submit" value="Submit me!">
</form>

Depending on your particular setup and personal preferences, there are many ways to access data from your HTML forms. Some examples are:

例子 8-2. 从一个简单的 POST HTML 表单访问数据

<?php
// Available since PHP 4.1.0

   print $_POST['username'];
   print $_REQUEST['username'];

   import_request_variables('p', 'p_');
   print $p_username;

// Available since PHP 3.

   print $HTTP_POST_VARS['username'];

// Available if the PHP directive register_globals = on.  As of
// PHP 4.2.0 the default value of register_globals = off.
// Using/relying on this method is not preferred.

   print $username;
?>

Using a GET form is similar except you'll use the appropriate GET predefined variable instead. GET also applies to the QUERY_STRING (the information after the '?' in an URL). So, for example, http://www.example.com/test.php?id=3 contains GET data which is accessible with $_GET['id']. See also $_REQUEST and import_request_variables().

注: Superglobal arrays, like $_POST and $_GET, became available in PHP 4.1.0

As shown, before PHP 4.2.0 the default value for register_globals was on. And, in PHP 3 it was always on. The PHP community is encouraging all to not rely on this directive as it's preferred to assume it's off and code accordingly.

注: The magic_quotes_gpc configuration directive affects Get, Post and Cookie values. If turned on, value (It's "PHP!") will automagically become (It\'s \"PHP!\"). Escaping is needed for DB insertion. See also addslashes(), stripslashes() and magic_quotes_sybase.

PHP also understands arrays in the context of form variables (see the related faq). You may, for example, group related variables together, or use this feature to retrieve values from a multiple select input. For example, let's post a form to itself and upon submission display the data:

例子 8-3. 更复杂的表单变量

<?php
if ($HTTP_POST_VARS['action'] == 'submitted') {
    print '<pre>';

    print_r($HTTP_POST_VARS);
    print '<a href="'. $HTTP_SERVER_VARS['PHP_SELF'] .'">Please try again</a>';

    print '</pre>';
} else {
?>
<form action="<?php echo $HTTP_SERVER_VARS['PHP_SELF']; ?>" method="post">
    Name:  <input type="text" name="personal[name]"><br>
    Email: <input type="text" name="personal[email]"><br>
    Beer: <br>
    <select multiple name="beer[]">
        <option value="warthog">Warthog</option>
        <option value="guinness">Guinness</option>
        <option value="stuttgarter">Stuttgarter Schwabenbr漉</option>
    </select><br>
    <input type="hidden" name="action" value="submitted">
    <input type="submit" name="submit" value="submit me!">
</form>
<?php
}
?>

In PHP 3, the array form variable usage is limited to single-dimensional arrays. In PHP 4, no such restriction applies.

IMAGE SUBMIT 变量名

When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:

<input type="image" src="image.gif" name="sub">

When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables, sub_x and sub_y. These contain the coordinates of the user click within the image. The experienced may note that the actual variable names sent by the browser contains a period rather than an underscore, but PHP converts the period to an underscore automatically.

HTTP Cookies

PHP transparently supports HTTP cookies as defined by Netscape's Spec. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the setcookie() function. Cookies are part of the HTTP header, so the SetCookie function must be called before any output is sent to the browser. This is the same restriction as for the header() function. Cookie data is then available in the appropriate cookie data arrays, such as $_COOKIE, $HTTP_COOKIE_VARS as well as in $_REQUEST. See the setcookie() manual page for more details and examples.

If you wish to assign multiple values to a single cookie variable, you may assign it as an array. For example:

<?php
  setcookie("MyCookie[foo]", "Testing 1", time()+3600);
  setcookie("MyCookie[bar]", "Testing 2", time()+3600);
?>

That will create two seperate cookies although MyCookie will now be a single array in your script. If you want to set just one cookie with multiple values, consider using serialize() or explode() on the value first.

Note that a cookie will replace a previous cookie by the same name in your browser unless the path or domain is different. So, for a shopping cart application you may want to keep a counter and pass this along. i.e.

例子 8-4. 一个 setcookie() 的示例

<?php
$count++;
setcookie("count", $count, time()+3600);
setcookie("Cart[$count]", $item, time()+3600);
?>

变量名中点

Typically, PHP does not alter the names of variables when they are passed into a script. However, it should be noted that the dot (period, full stop) is not a valid character in a PHP variable name. For the reason, look at it:
<?php
$varname.ext;  /* invalid variable name */
?>
Now, what the parser sees is a variable named $varname, followed by the string concatenation operator, followed by the barestring (i.e. unquoted string which doesn't match any known key or reserved words) 'ext'. Obviously, this doesn't have the intended result.

For this reason, it is important to note that PHP will automatically replace any dots in incoming variable names with underscores.

确定变量类型

Because PHP determines the types of variables and converts them (generally) as needed, it is not always obvious what type a given variable is at any one time. PHP includes several functions which find out what type a variable is, such as: gettype(), is_array(), is_float(), is_int(), is_object(), and is_string(). See also the chapter on Types.

后退 | 起点 | 前进
可变变量 | 上一级 | 常量


常量

PHP 手册
后退 前进

章 9. 常量

目录
语法
预定义常量

常量是一个简单值的标识符（名字）。如同其名称所暗示的，在脚本执行期间该值不能改变。（所谓的“magic constants” __FILE__ 和 __LINE__ 看上去是个例外，但是它们实际上不是常量。）常量默认为大小写敏感。按照惯例常量标识符总是大写的。

常量名和其它任何 PHP 标签遵循同样的命名规则。合法的常量名以字母或下划线开始，后面跟着任何字母，数字或下划线。用正则表达式是这样表达的：[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

注: 在这里，字母是 a-z，A-Z，以及从 127 到 255（0x7f-0xff）的 ASCII 字符。

常量的范围是全局的 － 不用管范围就可以在代码的任何地方访问。

语法

可以用 define() 函数来定义常量。一个常量一旦被定义，就不能再改变或者取消定义。

常量只能包含标量数据（boolean，integer，float 和 string）。

可以简单的通过指定其名字来取得常量的值，不要在常量前面加上 $ 符号。如果常量名是动态的，也可以用函数 constant() 来读取常量的值。用 get_defined_constants() 可以获得所有已定义的常量列表。

注: 常量和（全局）变量在不同的名字空间中。这意味着例如 TRUE 和 $TRUE 是不同的。

如果使用了一个未定义的常量，PHP 假定你想要的是该常量本身的名字。此时将发出一个 notice。用 defined() 函数来判断一个常量是否已被定义。

常量和变量不同：

  • 常量前面没有美元符号（$）；

  • 常量只能用 define() 函数定义，而不能通过赋值语句；

  • 常量可以不用理会变量范围的规则而在任何地方定义和访问；

  • 常量一旦定义就不能被重新定义或者取消定义；

  • 常量的值只能是标量。

例子 9-1. 定义常量

<?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
echo Constant; // outputs "Constant" and issues a notice.
?>

后退 | 起点 | 前进
PHP 的外部变量 | 上一级 | 预定义常量


预定义常量

PHP 向它运行的任何脚本提供了大量的预定义常量。不过很多常量都是由不同的扩展库定义的，只有在加载了这些扩展库时才会出现，或者动态加载后，或者在编译时已经包括进去了。

预定义常量的列表见预定义常量一节。

后退 | 起点 | 前进
常量 | 上一级 | 表达式


表达式

PHP 手册
后退 前进

章 10. 表达式

表达式是 PHP 最重要的基石。在 PHP 中，几乎你所写的任何东西都是一个表达式。 简单但却最精确的定义一个表达式的方式就是“anything that has a value”。

最基本的表达式形式是常量和变量。当你键入“$a = 5”，即将值'5'分配给变量 $a。 '5'，很明显，值为5，换句话说'5'是一个值为5的表达式（既然如此，'5'是一个整型常量）。

赋值之后，你所盼望的情况是 $a 的值为5，因而如果你写下 $b = $a， 期望的是它犹如 $b = 5 一样。换句话说，$a 是一个值也为5的表达式。 如果一切运行正确，那这正是将要发生的正确结果。

稍微复杂的表达式例子就是函数。例如，考虑下面的函数：

function foo ()
{
    return 5;
}

假定你已经熟悉了函数的概念（如果不是的话，请看一下函数的相关章节），那么键入
$c = foo() 从本质上来说就如写下 $c = 5，
而且你是正确的。 函数也是表达式，表达式的值即为它们的返回值。既然 foo() 返回5，
表达式 ‘foo()’ 的值也是5。通常函数不会仅仅返回一个静态值，而可能会计算一些东西。

当然，PHP 中的值常常并非是整型的。PHP 支持三种标量值类型：整型值，浮点值和字符串值 （标量值不能拆分为更小的单元，比如：数组）。PHP 也支持两种复合类型：数组和对象。 这两种类型具可以赋值给变量或者从函数返回。

到目前为止，PHP/FI 2 的用户不应该感到任何的变化。然而，当许多其它语言 为之努力的时候，PHP 在相同道路上促进了表达式的成长。PHP 是一种面向表达式 的语言，从这一方面来讲几乎一切都是表达式。考虑刚才我们已经研究过的例子， ‘$a = 5’。可以轻松的看到这里有两个相关的值，整型常量 '5'，而且变量 $a 的值也被更新为5。但是事实是：这里只有一个相关的附加值，即被分配的值本身。 赋值操作计算需分配的值，即5。实际上，意味着‘$a = 5’，不必管它是做什么的， 是一个值为5的表达式。因而，一些像这样的代码‘$b = ($a = 5)’和‘$a =5; $b=5’ （分号标志着语句的结束）。因为赋值操作的顺序是由右到左的，你也可以这么写 ‘$b = $a =5’。

另外一个很好的面向表达式的例子就是前、后递增和递减。 PHP/FI 2 和多数其它语言的用户应该比较熟悉变量++和变量--符号。即递增和递减 操作符。在 PHP/FI 2 中，语句‘$a++’没有值（不是表达式），这样的话你便不能为 其赋值或者以任何其它方式来使用它。PHP 通过将其变为了表达式，如 C 语言，增强了 递增/递减的能力。在 PHP 和 C 语言 中，有两种类型的递增前递增和后递增，本质 上来讲，前递增和后递增均增加了变量的值，并且对于变量的影响是相同的。不同的是 递增表达式的值。前递增，写做‘++$variable’，求增加后的值（PHP 在读取变量的值 之前，增加变量的值，因而称之为‘前递增’）。后递增，写做‘$variable++’，求变量 未递增之前的原始值（PHP 在读取变量的值之后，增加变量的值，因而叫做‘后递增’）。 【译者注:前递增，++$a, 则该表达式的值加1；后递增, $a++, 则该表达式的值不变。】

一个常用到表达式类型是比较表达式。这些表达式求值0或者1，即 FALSE 或者 TRUE (分别的)。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 += 3’的值是什么呢？ 不是3，也不是 $a 的原始值，而是完成 +3 操作后变量 $a 的值】。 任何两位操作符都可以使用在复制操作符模式，例如‘$a -= 5’（从变量 $a 的值中减去5）， ‘$b *= 7’ （变量 $b 乘以 7），等等。

有一些表达式，如果你没有在别的语言中看到过的话，可能认为它们是多余的，如三重操作符：

$first ? $second : $third

如果第一个子表达式的值是 TRUE （非零），那么计算第二个子表达式的值， 其值即为整个表达式的值。否则，将是第三个子表达式的值。

下面的例子一般来说应该可以稍微帮你理解前、后递增和表达式：

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 <emphasis>before</emphasis>
                       the increment, 2*6 = 12 to $f */
$g = double(++$e);  /* assign twice the value of $e <emphasis>after</emphasis>
                       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 表达式。

后退 | 起点 | 前进
预定义常量 | 上一级 | 运算符


运算符

PHP 手册
后退 前进

章 11. 运算符

目录
运算符优先级
算术运算符
赋值运算符
位运算符
比较运算符
错误控制运算符
执行运算符
加一／减一运算符
逻辑运算符
字符串运算符
数组运算符

运算符优先级

运算符优先级指定了两个表达式绑定得有多“紧密”。例如，表达式 1 + 5 * 3 的结果是 16 而不是 18 是因为乘号（“*”）的优先级比加号（“+”）高。必要时可以用括号来强制改变优先级。例如：(1 + 5) * 3 的值为 18。

下表从低到高列出了运算符的优先级。

表格 11-1. 运算符优先级

结合方向 | 运算符
左 | ,
左 | or
左 | xor
左 | and
右 | print
左 | = += -= *= /= .= %= &= |= ^= ~= <<= >>=
左 | ? :
左 | ||
左 | &&
左 | |
左 | ^
左 | &
无 | == != === !==
无 | < <= > >=
左 | << >>
左 | + - .
左 | * / %
右 | ! ~ ++ -- (int) (float) (string) (array) (object) @
右 | [
无 | new

后退 | 起点 | 前进
表达式 | 上一级 | 算术运算符


算术运算符

还记得学校里学到的基本数学知识吗？就和它们一样。

表格 11-2. 算术运算符

例子 | 名称 | 结果
$a + $b | 加法 | $a 和 $b 的和。
$a - $b | 减法 | $a 和 $b 的差。
$a * $b | 乘法 | $a 和 $b 的积。
$a / $b | 除法 | $a 除以 $b 的商。
$a % $b | 取模 | $a 除以 $b 的余数。

除号（“/”）总是返回浮点数，即使两个运算数是整数（或由字符串转换成的整数）也是这样。

后退 | 起点 | 前进
运算符 | 上一级 | 赋值运算符


赋值运算符

基本的赋值运算符是“=”。你一开始可能会以为它是“等于”，其实不是的。它实际上意味着把右边表达式的值赋给左运算数。

赋值运算表达式的值也就是所赋的值。也就是说，“$a = 3”的值是 3。这样就可以使你做一些小技巧：

$a = ($b = 4) + 5; // $a is equal to 9 now, and $b has been set to 4.

在基本赋值运算符之外，还有适合于所有二元算术和字符串运算符的“组和运算符”，这可以让你在一个表达式中使用它的值并把表达式的结果赋给它，例如：

$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 中不可能这样做。“引用赋值”意味着两个变量都指向同一个数据，没有任何数据的拷贝。有关引用的更多信息见引用的说明。

后退 | 起点 | 前进
算术运算符 | 上一级 | 位运算符


位运算符

位运算符允许对整型数中指定的位进行置位。如果左右参数都是字符串，则位运算符将操作这个字符串中的字符。

<?php
    echo 12 ^ 9; // Outputs '5'

    echo "12" ^ "9"; // Outputs the Backspace character (ascii 8)
                     // ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8

    echo "hallo" ^ "hello"; // Outputs the ascii values #0 #4 #0 #0 #0
                            // 'a' ^ 'e' = #4
?>

表格 11-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”）。

后退 | 起点 | 前进
赋值运算符 | 上一级 | 比较运算符


比较运算符

比较运算符，如同它们名称所暗示的，允许你对两个值进行比较。

表格 11-4. 比较运算符

例子 | 名称 | 结果
$a == $b | 等于 | TRUE，如果 $a 等于 $b。
$a === $b | 全等 | TRUE，如果 $a 等于 $b，并且它们的类型也相同。(PHP 4 only)
$a != $b | 不等 | TRUE，如果 $a 不等于 $b。
$a <> $b | 不等 | TRUE，如果 $a 不等于 $b。
$a !== $b | 非全等 | TRUE，如果 $a 不等于 $b，或者它们的类型不同。(PHP 4 only)
$a < $b | 小与 | TRUE，如果 $a 严格小于 $b。
$a > $b | 大于 | TRUE，如果 $a 严格 $b。
$a <= $b | 小于等于 | TRUE，如果 $a 小于或者等于 $b。
$a >= $b | 大于等于 | TRUE，如果 $a 大于或者等于 $b。

另外一个条件运算符是“?:”（或三元）运算符，它和 C 以及很多其它语言的操作一样。

(expr1) ? (expr2) : (expr3);

如果 expr1 的值为 TRUE，则此表达式的值为 expr2，如果 expr1 的值为 FALSE，则此表达式的值为 expr3。

后退 | 起点 | 前进
位运算符 | 上一级 | 错误控制运算符


错误控制运算符

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 将尝试将反引号中的内容作为外壳命令来执行，并将其输出信息返回（例如，可以赋给一个变量而不是简单地丢弃到标准输出）。

$output = `ls -al`;
echo "<pre>$output</pre>";

注: 反引号运算符在激活了 safe mode 或者关闭了 shell_exec() 时是无效的。

参见 escapeshellcmd()，exec()，passthru()，popen()，shell_exec() 和 system()。

后退 | 起点 | 前进
错误控制运算符 | 上一级 | 加一／减一运算符


加一／减一运算符

PHP 支持 C 风格的前／后加一与减一运算符。

表格 11-5. 加一／减一运算符

例子 | 名称 | 效果
++$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";
?>

后退 | 起点 | 前进
执行运算符 | 上一级 | 逻辑运算符


逻辑运算符

表格 11-6. 逻辑运算符

例子 | 名称 | 结果
$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。

“与”和“或”有两种不同形式运算符的原因是它们操作的优先级不同。（见运算符优先级。）

后退 | 起点 | 前进
加一／减一运算符 | 上一级 | 字符串运算符


字符串运算符

有两个字符串运算符。第一个是连接运算符（“.”），它返回其左右参数连接后的字符串。第二个是连接赋值运算符（“.=”），它将右边参数附加到左边的参数后。更多信息见赋值运算符。

$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"

$a = "Hello ";
$a .= "World!";     // now $a contains "Hello World!"

后退 | 起点 | 前进
逻辑运算符 | 上一级 | 数组运算符


数组运算符

PHP 仅有的一个数组运算符是 + 运算符。它把右边的数组附加到左边的数组后，但是重复的键值不会被覆盖。

$a = array("a" => "apple", "b" => "banana");
$b = array("a" =>"pear", "b" => "strawberry", "c" => "cherry");

$c = $a + $b;

var_dump($c);
array(3) {
  ["a"]=>
  string(5) "apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  string(6) "cherry"
}

后退 | 起点 | 前进
字符串运算符 | 上一级 | 流程控制


流程控制

PHP 手册
后退 前进

章 12. 流程控制

目录
if
else
elseif
流程控制的替代语法
while
do..while
for
foreach
break
continue
switch
declare
return
require()
include()
require_once()
include_once()

任何 PHP 脚本都是由一系列语句构成的。一条语句可以是一个赋值语句，一个函数调用，一个循环，甚至一个什么也不做的（空语句）条件语句。语句通常以分号结束。此外，还可以用花括号将一组语句封装成一个语句组。语句组本身可以当作是一行语句。本章讲述了各种语句类型。

if

if 结构是很多语言包括 PHP 在内最重要的特性之一，它允许按照条件执行代码片段。PHP 的 if 结构和 C 语言相似：

if (expr)
    statement

如同在表达式一章中定义的，expr 按照布尔求值。如果 expr 的值为 TRUE，PHP 将执行 statement，如果值为 FALSE － 将忽略 statement。有关哪些值被视为 FALSE 的更多信息参见“转换为布尔值”一节。

如果 $a 大于 $b，则以下例子将显示 a is bigger than b：

if ($a > $b)
    print "a is bigger than b";

经常需要按照条件执行不止一条语句，当然并不需要给每条语句都加上一个 if 子句。可以将这些语句放入语句组中。例如，如果 $a 大于 $b，以下代码将显示 a is bigger than b 并且将 $a 的值赋给 $b：

if ($a > $b) {
    print "a is bigger than b";
    $b = $a;
}

if 语句可以无限层地嵌套在其它 if 语句中，这给程序的不同部分的条件执行提供了充分的弹性。

后退 | 起点 | 前进
数组运算符 | 上一级 | else


else

经常需要在满足某个条件时执行一条语句，而在不满足该条件时执行其它语句，这正是 else 的功能。else 延伸了 if 语句，可以在 if 语句中的表达式的值为 FALSE 时执行语句。例如以下代码在 $a 大于 $b 时显示 a is bigger than b，反之则显示 a is NOT bigger than b：

if ($a > $b) {
    print "a is bigger than b";
} else {
    print "a is NOT bigger than b";
}

else 语句仅在 if 以及 elseif（如果有的话）语句中的表达式的值为 FALSE 时执行（参见 elseif）。

后退 | 起点 | 前进
流程控制 | 上一级 | elseif


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：

if ($a > $b) {
    print "a is bigger than b";
} elseif ($a == $b) {
    print "a is equal to b";
} else {
    print "a is smaller than b";
}

在同一个 if 结构中可以有多个 elseif 语句。第一个表达式值为 TRUE 的 elseif 语句（如果有的话）将会执行。在 PHP 中，也可以写成“else if”（两个单词），它和“elseif”（一个单词）的行为完全一样。句法分析的含义有少许区别（如果你熟悉 C 语言的话，这是同样的行为），但是底线是两者会产生完全一样的行为。

elseif 的语句仅在之前的 if 或 elseif 的表达式值为 FALSE，而当前的 elseif 表达式值为 TRUE 时执行。

后退 | 起点 | 前进
else | 上一级 | 流程控制的替代语法


流程控制的替代语法

PHP 提供了一些流程控制的替代语法，包括 if，while，for，foreach 和 switch。替代语法的基本形式是把左花括号（{）换成冒号（:），把右花括号（}）分别换成 endif;，endwhile;，endfor;，endforeach; 以及 endswitch;。

<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>

在上面的例子中，HTML 内容“A is equal to 5”用替代语法嵌套在 if 语句中。该 HTML 的内容仅在 $a 等与 5 时显示。

替代语法同样可以用在 else 和 elseif 中。下面是一个包括 elseif 和 else 的 if 结构用替代语法格式写的例子：

if ($a == 5):
    print "a equals 5";
    print "...";
elseif ($a == 6):
    print "a equals 6";
    print "!!!";
else:
    print "a is neither 5 nor 6";
endif;

更多例子参见 while，for 和 if。

后退 | 起点 | 前进
elseif | 上一级 | while


while

while 循环是 PHP 中最简单的循环类型。它和 C 语言中的 while 表现得一样。while 语句的基本格式是：

while (expr) statement

while 语句的含意很简单，它告诉 PHP 只要while 表达式的值为 TRUE 就重复执行嵌套中的循环语句。表达式的值在每次开始循环时检查，所以即使这个值在循环语句中改变了，语句也不会停止执行，直到本次循环结束。有时候如果 while 表达式的值一开始就是 FALSE，则循环语句一次都不会执行。

和 if 语句一样，可以在 while 循环中用花括号括起一个语句组，或者用替代语法：

while (expr): statement ... endwhile;

下面两个例子完全一样，都显示数字 1 到 10：

/* example 1 */

$i = 1;
while ($i <= 10) {
    print $i++;  /* the printed value would be
                    $i before the increment
                    (post-increment) */
}

/* example 2 */

$i = 1;
while ($i <= 10):
    print $i;
    $i++;
endwhile;

后退 | 起点 | 前进
流程控制的替代语法 | 上一级 | do..while


do..while

do..while 和 while 循环非常相似，区别在于表达式的值是在每次循环结束时检查而不是开始时。和正规的 while 循环主要的区别是 do..while 的循环语句保证会执行一次（表达式的真值在每次循环结束后检查），然而在正规的 while 循环中就不一定了（表达式真值在循环开始时检查，如果一开始就为 FALSE 则整个循环立即终止）。

do..while 循环只有一种语法：

$i = 0;
do {
   print $i;
} while ($i>0);

以上循环将正好运行一次，因为经过第一次循环后，当检查表达式的真值时，其值为 FALSE（$i 不大于 0）而导致循环终止。

资深的 C 语言用户可能熟悉另一种不同的 do..while 循环用法，把语句放在 do..while(0) 之中，在循环内部用 break 语句来结束执行循环。以下代码片段示范了此方法：

do {
    if ($i < 5) {
        print "i is not big enough";
        break;
    }
    $i *= $factor;
    if ($i < $minimum_limit) {
        break;
    }
    print "i is ok";

     ...process i...

} while(0);

如果你还不能立刻理解也不用担心。即使不用此“特性”你也照样可以写出强大的代码来。

后退 | 起点 | 前进
while | 上一级 | for


for

for 循环是 PHP 中最复杂的循环结构。它的行为和 C 语言的相似。 for 循环的语法是：

for (expr1; expr2; expr3) statement

第一个表达式（expr1）在循环开始前无条件求值一次。

expr2 在每次循环开始前求值。如果值为 TRUE，则继续循环，执行嵌套的循环语句。如果值为 FALSE，则终止循环。

expr3 在每次循环之后被求值（执行）。

每个表达式都可以为空。expr2 为空意味着将无限循环下去（和 C 一样，PHP 认为其值为 TRUE）。这可能不想你想象中那样没有用，因为你经常会希望用 break 语句来结束循环而不是用 for 的表达式真值判断。

考虑以下的例子。它们都显示数字 1 到 10：

/* example 1 */

for ($i = 1; $i <= 10; $i++) {
    print $i;
}

/* example 2 */

for ($i = 1;;$i++) {
    if ($i > 10) {
        break;
    }
    print $i;
}

/* example 3 */

$i = 1;
for (;;) {
    if ($i > 10) {
        break;
    }
    print $i;
    $i++;
}

/* example 4 */

for ($i = 1; $i <= 10; print $i, $i++);

当然，第一个例子看上去最正常（或者第四个），但你可能会发现在 for 循环中用空的表达式在很多场合下会很方便。

PHP 也支持用冒号的 for 循环的替代语法。

for (expr1; expr2; expr3): statement; ...; endfor;

其它语言具有 foreach 语句来遍历数组或散列表，PHP 也行（见 foreach）。在 PHP 3 中，可以结合 list() 和 each() 函数用 while 循环来达到同样效果。例子见这些函数的文档。

后退 | 起点 | 前进
do..while | 上一级 | foreach


foreach

PHP 4（不是 PHP 3）包括了 foreach 结构，和 Perl 以及其他语言很像。这只是一种遍历数组简便方法。foreach 仅能用于数组，当试图将其用于其它数据类型或者一个未初始化的变量时会产生错误。有两种语法，第二种比较次要但却是第一种的有用的扩展。

foreach(array_expression as $value) statement
foreach(array_expression as $key => $value) statement

第一种格式遍历给定的 array_expression 数组。每次循环中，当前单元的值被赋给 $value 并且数组内部的指针向前移一步（因此下一次循环中将会得到下一个单元）。

第二种格式做同样的事，只除了当前单元的键值也会在每次循环中被赋给变量 $key。

注: 当 foreach 开始执行时，数组内部的指针会自动指向第一个单元。这意味着不需要在 foreach 循环之前调用 reset()。

注: 此外注意 foreach 所操作的是指定数组的一个拷贝，而不是该数组本身。因此即使有 each() 的构造，原数组指针也没有变，数组单元的值也不受影响。

注: foreach 不支持用“@”来禁止错误信息的能力。

你可能注意到了以下的代码功能完全相同：

reset ($arr);
while (list(, $value) = each ($arr)) {
    echo "Value: $value<br>\n";
}

foreach ($arr as $value) {
    echo "Value: $value<br>\n";
}

以下代码功能也完全相同：

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";
}

示范用法的更多例子：

/* foreach example 1: value only */

$a = array (1, 2, 3, 17);

foreach ($a as $v) {
   print "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) {
    print "\$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) {
    print "\$a[$k] => $v.\n";
}

/* foreach example 4: multi-dimensional arrays */

$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";

foreach($a as $v1) {
    foreach ($v1 as $v2) {
        print "$v2\n";
    }
}

/* foreach example 5: dynamic arrays */

foreach(array(1, 2, 3, 4, 5) as $v) {
    print "$v\n";
}

后退 | 起点 | 前进
for | 上一级 | break


break

break 结束当前 for，foreach，while，do..while 或者 switch 结构的执行。

break 可以接受一个可选的数字参数来决定跳出几重循环。

$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;
    }
}

后退 | 起点 | 前进
foreach | 上一级 | continue


continue

continue 在循环结构用用来跳过本次循环中剩余的代码并开始执行下一次循环。

continue 接受一个可选的数字参数来决定跳过几重循环到循环结尾。

while (list ($key, $value) = each ($arr)) {
    if (!($key % 2)) { // skip odd members
        continue;
    }
    do_something_odd ($value);
}

$i = 0;
while ($i++ < 5) {
    echo "Outer<br>\n";
    while (1) {
        echo "&nbsp;&nbsp;Middle<br>\n";
        while (1) {
            echo "&nbsp;&nbsp;Inner<br>\n";
            continue 3;
        }
        echo "This never gets output.<br>\n";
    }
    echo "Neither does this.<br>\n";
}

后退 | 起点 | 前进
break | 上一级 | switch


switch

switch 语句和具有同样表达式的一系列的 IF 语句相似。很多场合下需要把同一个变量（或表达式）与很多不同的值比较，并根据它等于哪个值来执行不同的代码。这正是 switch 语句的用途。

下面两个例子使用两种不同方法实现同样的事，一个用一系列 if 语句，另一个用 switch 语句：

if ($i == 0) {
    print "i equals 0";
}
if ($i == 1) {
    print "i equals 1";
}
if ($i == 2) {
    print "i equals 2";
}

switch ($i) {
    case 0:
        print "i equals 0";
        break;
    case 1:
        print "i equals 1";
        break;
    case 2:
        print "i equals 2";
        break;
}

为避免错误，理解 switch 是怎样执行的非常重要。switch 语句一行接一行地执行（实际上是语句接语句）。开始时没有代码被执行。仅当一个 case 语句中的值和 switch 表达式的值匹配时 PHP 才开始执行语句，直到 switch 的程序段结束或者遇到第一个 break 语句为止。如果不在 case 的语句段最后写上 break 的话，PHP 将继续执行下一个 case 中的语句段。例如：

switch ($i) {
    case 0:
        print "i equals 0";
    case 1:
        print "i equals 1";
    case 2:
        print "i equals 2";
}

这里如果 $i 等于 0，PHP 将执行所有的 print 语句！如果 $i 等于 1，PHP 将执行后面两条 print 语句。只有当 $i 等于 2 时，你才得到“预期”的结果 － 只显示“i equals 2”。所以，别忘了 break 语句就很重要（即使在某些情况下你故意想避免提供它们时）。

在 switch 语句中条件只求值一次并用来和每个 case 语句比较。在 elseif 语句中条件会再次求值。如果条件比一个简单的比较要复杂得多或者在一个很多次的循环中，那么用 switch 语句可能会快一些。

在一个 case 中的语句也可以为空，这样只不过将控制转移到了下一个 case 中的语句。

switch ($i) {
    case 0:
    case 1:
    case 2:
        print "i is less than 3 but not negative";
        break;
    case 3:
        print "i is 3";
}

一个 case 的特例是 default。它匹配了任何和其它 case 都不匹配的情况，并且应该是最后一条 case 语句。例如：

switch ($i) {
    case 0:
        print "i equals 0";
        break;
    case 1:
        print "i equals 1";
        break;
    case 2:
        print "i equals 2";
        break;
    default:
        print "i is not equal to 0, 1 or 2";
}

case 表达式可以是任何求值为简单类型的表达式，即整型或浮点数以及字符串。不能用数组或对象，除非它们被解除了到简单类型的引用。

switch 支持替代语法的流程控制。更多信息见流程控制的替代语法一节。

switch ($i):
    case 0:
        print "i equals 0";
        break;
    case 1:
        print "i equals 1";
        break;
    case 2:
        print "i equals 2";
        break;
    default:
        print "i is not equal to 0, 1 or 2";
endswitch;

后退 | 起点 | 前进
continue | 上一级 | declare


declare

The declare 结构用来设定一段代码的执行指令。declare 的语法和其它流程控制结构相似：

declare (directive) statement

directive 部分允许设定 declare 代码段的行为。目前只认识一个指令：ticks（更多信息见下面 ticks 指令）。

declare 代码段中的 statement 部分将被执行 － 怎样执行以及执行中有什么副作用出现取决于 directive 中设定的指令。

Ticks

Tick 是一个在 declare 代码段中解释器每执行 N 条低级语句就会发生的事件。N 的值是在 declare 中的 directive 部分用 ticks=N 来指定的。

在每个 tick 中出现的事件是由 register_tick_function() 来指定的。更多细节见下面的例子。注意每个 tick 中可以出现多个事件。

例子 12-1. 评估一段 PHP 代码的执行时间

<?php
// A function that records the time when it is called
function profile ($dump = FALSE)
{
    static $profile;

    // Return the times stored in profile, then erase it
    if ($dump) {
        $temp = $profile;
        unset ($profile);
        return ($temp);
    }

    $profile[] = microtime ();
}

// Set up a tick handler
register_tick_function("profile");

// Initialize the function before the declare block
profile ();

// Run a block of code, throw a tick every 2nd statement
declare (ticks=2) {
    for ($x = 1; $x < 50; ++$x) {
        echo similar_text (md5($x), md5($x*$x)), "<br />;";
    }
}

// Display the data stored in the profiler
print_r (profile (TRUE));
?>
这个例子评估“declare”中的 PHP 代码，每执行两条低级语句就记录下时间。此信息可以用来找到一段特定代码中速度慢的部分。这个过程也可以用其它方法完成，但用 tick 更方便也更容易实现。

Ticks 很适合用来做调试，以及实现简单的多任务，后台 I/O 和很多其它任务。

参见 register_tick_function() 和 unregister_tick_function()。

后退 | 起点 | 前进
switch | 上一级 | return


return

如果在一个函数中调用，return() 语句立即结束此函数的执行并将它的参数作为函数的值返回。return() 也会终止 eval() 语句或者脚本文件的执行。

如果在全局范围中调用，则当前脚本文件中止运行。如果当前脚本文件是被 include() 的或者 require() 的，则控制交回调用文件。此外，如果当前脚本是被 include() 的，则 return() 的值会被当作 include() 调用的返回值。如果在主脚本文件中调用 return()，则脚本中止运行。如果当前脚本文件是在配置文件中的 auto_prepend_file 或者 auto_append_file 所指定的，则此脚本文件中止运行。

更多信息见返回值。

注: 注意既然 return() 是语言结构而不是函数，并不需要用括号将参数括起来。事实上不用括号比用括号更常见，尽管用哪一种并无所谓。

后退 | 起点 | 前进
declare | 上一级 | require()


require

PHP 手册
后退 章 12. 流程控制 前进

require()

require() 语句包括并运行指定文件。

require() 语句包括并运行指定文件。有关包括如何工作的详细信息见 include() 的文档。

require() 和 include() 除了怎样处理失败之外在各方面都完全一样。include() 产生一个警告而 require() 则导致一个致命错误。换句话说，如果你想在丢失文件时停止处理页面，那就别犹豫了，用 require() 吧。include() 就不是这样，脚本会继续运行。同时也要确认设置了合适的include_path。

例子 12-2. 基本的 require() 例子

<?php

require 'prepend.php';

require $somefile;

require ('somefile.txt');

?>

更多例子参见 include() 文档。

注: 在 PHP 4.0.2 之前适用以下规则：require() 总是会尝试读取目标文件，即使它所在的行根本就不会执行。条件语句不会影响 require()。不过如果 require() 所在的行没有执行，则目标文件中的代码也不会执行。同样，循环结构也不影响 require() 的行为。尽管目标文件中包含的代码仍然是循环的主体，但 require() 本身只会运行一次。

警告

Windows 版本的 PHP 目前还不支持该函数的远程文件访问，即使 allow_url_fopen 选项已被激活。

参见 include()，require_once()，include_once()，eval()，file()，readfile()，virtual() 和 include_path。

后退 | 起点 | 前进
return | 上一级 | include()


include

PHP 手册
后退 章 12. 流程控制 前进

include()

The include() 语句包括并运行指定文件。

以下文档也适用于 require()。这两种结构除了在如何处理失败之外完全一样。include() 产生一个警告而 require() 则导致一个致命错误。换句话说，如果你想在遇到丢失文件时停止处理页面就用 require()。include() 就不是这样，脚本会继续运行。同时也要确认设置了合适的 include_path。

当一个文件被包括时，其中所包含的代码继承了 include 所在行的变量范围。从该处开始，调用文件在该行处可用的任何变量在被调用的文件中也都可用。

例子 12-3. 基本的 include() 例子

vars.php
<?php

$color = 'green';
$fruit = 'apple';

?>

test.php
<?php

echo "A $color $fruit"; // A

include 'vars.php';

echo "A $color $fruit"; // A green apple

?>

如果 include 出现于调用文件中的一个函数里，则被调用的文件中所包含的所有代码将表现得如同它们是在该函数内部定义的一样。所以它将遵循该函数的变量范围。

例子 12-4. 函数中的包括

<?php

function foo()
{
global $color;

    include 'vars.php';

    echo "A $color $fruit";
}

/* vars.php is in the scope of foo() so     *
 * $fruit is NOT available outside of this  *
 * scope.  $color is because we declared it *
 * as global.                               */

foo();                    // A green apple
echo "A $color $fruit";   // A green

?>

当一个文件被包括时，语法解析器在目标文件的开头脱离 PHP 模式并进入 HTML 模式，到文件结尾处恢复。由于此原因，目标文件中应被当作 PHP 代码执行的任何代码都必须被包括在有效的 PHP 起始和结束标记之中。

如果“URL fopen wrappers”在 PHP 中被激活（默认配置），可以用 URL（通过 HTTP）而不是本地文件来指定要被包括的文件。如果目标服务器将目标文件作为 PHP 代码解释，则可以用适用于 HTTP GET 的 URL 请求字符串来向被包括的文件传递变量。严格的说这和包括一个文件并继承父文件的变量空间并不是一回事；该脚本文件实际上已经在远程服务器上运行了，而本地脚本则包括了其结果。

警告

Windows 版本的 PHP 目前还不支持该函数的远程文件访问，即使 allow_url_fopen 选项已被激活。

例子 12-5. 通过 HTTP 进行的 include()

<?php

/* This example assumes that www.example.com is configured to parse .php *
 * files and not .txt files. Also, 'Works' here means that the variables *
 * $foo and $bar are available within the included file.                 */

// Won't work; file.txt wasn't handled by www.example.com as PHP
include 'http://www.example.com/file.txt?foo=1&bar=2';

// Won't work; looks for a file named 'file.php?foo=1&bar=2' on the
// local filesystem.
include 'file.php?foo=1&bar=2';

// Works.
include 'http://www.example.com/file.php?foo=1&bar=2';

$foo = 1;
$bar = 2;
include 'file.txt';  // Works.
include 'file.php';  // Works.

?>
相关信息参见使用远程文件，fopen() 和 file()。

因为 include() 和 require() 是特殊的语言结构，在条件语句中使用必须将其放在语句组中（花括号中）。

例子 12-6. include() 与条件语句组

<?php

// This is WRONG and will not work as desired.
if ($condition)
    include $file;
else
    include $other;

// This is CORRECT.
if ($condition) {
    include $file;
} else {
    include $other;
}

?>

处理返回值：可以在被包括的文件中使用 return() 语句来终止该文件中程序的执行并返回调用它的脚本。同样也可以从被包括的文件中返回值。可以像普通函数一样获得 include 呼叫的返回值。

注: 在 PHP 3 中，除非是在函数中调用否则被包括的文件中不能出现 return。在此情况下 return() 作用于该函数而不是整个文件。

例子 12-7. include() 和 return() 语句

return.php
<?php

$var = 'PHP';

return $var;

?>

noreturn.php
<?php

$var = 'PHP';

?>

testreturns.php
<?php

$foo = include 'return.php';

echo $foo; // prints 'PHP'

$bar = include 'noreturn.php';

echo $bar; // prints 1

?>

$bar 的值为 1 是因为 include 成功运行了。注意以上例子中的区别。第一个在被包括的文件中用了 return() 而另一个没有。其它几种把文件“包括”到变量的方法是用 fopen()，file() 或者 include() 连同输出控制函数一起使用。

参见 require()，require_once()，include_once()，readfile()，virtual() 和 include_path。


require_once

PHP 手册
后退 章 12. 流程控制 前进

require_once()

require_once() 语句在脚本执行期间包括并运行指定文件。此行为和 require() 语句类似，唯一区别是如果该文件中的代码已经被包括了，则不会再次包括。有关此语句怎样工作参见 require() 的文档。

require_once() 应该用于在脚本执行期间同一个文件有可能被包括超过一次的情况下，你想确保它只被包括一次以避免函数重定义，变量重新赋值等问题。

使用 require_once() 和 include_once() 的例子见最新的 PHP 源程序发行包中的 PEAR 代码。

注: require_once() 是 PHP 4.0.1pl2 中新加入的。

注: 要注意 require_once() 和 include_once() 在大小写不敏感的操作系统中（例如 Windows）的行为可能不是你所期望的。

例子 12-8. require_once() 是大小写敏感的

require_once("a.php"); // this will include a.php
require_once("A.php"); // this will include a.php again on Windows!

警告

Windows 版本的 PHP 目前还不支持该函数的远程文件访问，即使 allow_url_fopen 选项已被激活。

参见: require()，include()，include_once()，get_required_files()，get_included_files()，readfile() 和 virtual()。


include_once

PHP 手册
后退 章 12. 流程控制 前进

include_once()

The include_once() 语句在脚本执行期间包括并运行指定文件。此行为和 include() 语句类似，唯一区别是如果该文件中的代码已经被包括了，则不会再次包括。如同此语句名字暗示的那样，只会包括一次。

include_once() 应该用于在脚本执行期间同一个文件有可能被包括超过一次的情况下，你想确保它只被包括一次以避免函数重定义，变量重新赋值等问题。

使用 require_once() 和 include_once() 的更多例子见最新的 PHP 源程序发行包中的 PEAR 代码。

注: include_once() 是 PHP 4.0.1pl2 中新加入的。

注: 要注意 include_once() 和 require_once() 在大小写不敏感的操作系统中（例如 Windows）的行为可能不是你所期望的。

例子 12-9. include_once() 是大小写敏感的

include_once("a.php"); // this will include a.php
include_once("A.php"); // this will include a.php again on Windows!

警告

Windows 版本的 PHP 目前还不支持该函数的远程文件访问，即使 allow_url_fopen 选项已被激活。

参见 include()，require()，require_once()，get_required_files()，get_included_files()，readfile() 和 virtual()。

后退 | 起点 | 前进
require_once() | 上一级 | 函数


函数

PHP 手册
后退 前进

章 13. 函数

目录
用户自定义函数
函数的参数
返回值
旧的函数
变量函数

用户自定义函数

一个函数可由以下的语法来定义：

function foo ($arg_1, $arg_2, ..., $arg_n)
{
    echo "Example function.\n";
    return $retval;
}

任何有效的 PHP 代码都有可能出现在函数内部，甚至包括其它函数和 类 定义。

在 PHP 3 中，函数必须在被调用之前定义。而 PHP 4 则不再有这样的 条件。

PHP 不支持函数重载，可能也不支持取消定义或者重定义已声明的函数。

PHP 3 虽然支持默认参数（更多的信息请参照� 默认参数的值） ，但是却不支持可变的参数个数。 PHP 4 支持: 见 可变长度的参数列表 和涉及到的相关函数 func_num_args()， func_get_arg()， 和 func_get_args() 以获取更多的信息。

后退 | 起点 | 前进
include_once() | 上一级 | 函数的参数


函数的参数

通过参数列表可以传递信息到函数，该列表是以逗号作为分隔符的函数 和/或常量列表。

PHP 支持按值传递参数（默认）, 通过引用传递, 和 默认参数值. 可变长度参数列表仅在 PHP 4 和后续版本中支持；更多信息请参照 可变长度参数列表 和涉及到的相关函数 func_num_args()， func_get_arg(), 和 func_get_args()。 PHP 3 中通过传递一个数组参数可以达到类似的效果：

function takes_array($input)
{
    echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}

通过引用传递参数

缺省情况下，函数参数通过值传递（因而即使在函数内部改变参数的值，它 并不会改变函数外部的值）。如果你希望允许函数修改它的参数值，你必须 通过引用传递参数。

如果想要函数的一个参数总是通过引用传递，你可以在函数定义中该参数的 前面预先加上符号（&）：

function add_some_extra(&$string)
{
    $string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str;    // outputs 'This is a string, and something extra.'

默认参数的值

函数可以定义 C++ 风格的标量参数默认值，如下：

function makecoffee ($type = "cappuccino")
{
    return "Making a cup of $type.\n";
}
echo makecoffee ();
echo makecoffee ("espresso");

上述片断的输出是：
Making a cup of cappuccino.
Making a cup of espresso.

默认值必须是标量，不是（比如）变量或者类成员。

请注意当使用默认参数时，任何默认参数必须放在任何非默认参数的右侧；否则， 可能函数将不会按照预期的情况工作。考虑下面的代码片断：

function makeyogurt ($type = "acidophilus", $flavour)
{
    return "Making a bowl of $type $flavour.\n";
}

echo makeyogurt ("raspberry");   // won't work as expected

上述例子的输出时：
Warning: Missing argument 2 in call to makeyogurt() in
/usr/local/etc/httpd/htdocs/php3test/functest.html on line 41
Making a bowl of raspberry .

现在，比较上面的例子和这个例子：

function makeyogurt ($flavour, $type = "acidophilus")
{
    return "Making a bowl of $type $flavour.\n";
}

echo makeyogurt ("raspberry");   // works as expected

这个例子的输出是：
Making a bowl of acidophilus raspberry.

可变长度参数列表

PHP 4 已经在用户自定义函数中支持可变长度参数列表。这个真的很简单， 使用 func_num_args()，func_get_arg()，和 func_get_args() 函数.

无需特别的语法，参数列表仍然能够被明确无误的传递给函数并且正常运转。

后退 | 起点 | 前进
函数 | 上一级 | 返回值


返回值

值通过使用可选的返回语句返回。任何类型都可以返回，其中包括列表和对象。 这导致函数立即结束它的运行，并且将控制权传递回它被调用的行。更多信息 请参照 return()。

function square ($num)
{
    return $num * $num;
}
echo square (4);   // outputs '16'.

函数不能返回多个值，但为了获得简单的结果，可以返回一个列表。

function small_numbers()
{
    return array (0, 1, 2);
}
list ($zero, $one, $two) = small_numbers();

从函数返回一个引用，你必须在函数申明和支派返回值给一个变量时都使用引用操作符 & ：

function &returns_reference()
{
    return $someref;
}

$newref =& returns_reference();

有关引用的更多信息, 请查看 引用的解释.

后退 | 起点 | 前进
函数的参数 | 上一级 | 旧的函数


旧的函数

old_function 语句允许你使用 PHP/FI2 的语法声明函数， （你必须把‘function’替换为‘old_function’） 旧的函数

这是一个不被赞成的特性，应该只用在 PHP/FI2->PHP 3 转换器中。

警告

以 old_function 声明的函数无法从 PHP 的内部代码调用。 除了别的事情以外, 这意味着你不能在诸如 usort()， array_walk()，和 register_shutdown_function() 等函数中使用它们。你可以通过写一个外壳函数（以正常的 PHP 3 形式）来 调用 old_function。

后退 | 起点 | 前进
返回值 | 上一级 | 变量函数


变量函数

PHP 支持变量函数的概念。这意味着如果一个变量名后有圆括号，PHP 将寻找 与变量的值相同的函数，并且将尝试执行它。除了别的事情以外，这个可以被 用于实现回调函数，函数表等等。

变量函数不能用于语言结构，例如 echo()，
unset()，isset()，
empty() 和 include()。
尽管如此，结构 print() 却是个例外，可以运行。
这是 PHP 函数和语言结构之间的主要不同之一。

例子 13-1. 变量函数示例

<?php
function foo()
{
    echo "In foo()<br>\n";
}

function bar($arg = '')
{
    echo "In bar(); argument was '$arg'.<br>\n";
}

$func = 'foo';
$func();
$func = 'bar';
$func('test');
?>

相关内容参考 变量的变量 和 function_exists().

后退 | 起点 | 前进
旧的函数 | 上一级 | 类与对象


类与对象

PHP 手册
后退 前进

章 14. 类与对象

目录
类
继承
构造函数
::
parent
序列化对象－会话中的对象
The magic functions __sleep and __wakeup
References inside the constructor

类

类是变量与作用于这些变量的函数的集合。使用下面的语法定义一个类：

<?php
class Cart
{
    var $items;  // Items in our shopping cart

    // Add $num articles of $artnr to the cart

    function add_item ($artnr, $num)
    {
        $this->items[$artnr] += $num;
    }

    // Take $num articles of $artnr out of the cart

    function remove_item ($artnr, $num)
    {
        if ($this->items[$artnr] > $num) {
            $this->items[$artnr] -= $num;
            return true;
        } else {
            return false;
        }
    }
}
?>

上面的例子定义了一个 Cart 类，这个类由购物车中的商品构成的数组和两个用于 从购物车中添加和删除商品的函数组成。

注意

下面的警告注解对 PHP4 有效。

名称 stdClass 已经被 Zend 使用并保留。您不能在您的 PHP 代码 中定义名为 stdClass 的类。

The function names __sleep and __wakeup 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. See below for more information.

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.

注: 在 PHP 4 中，var 变量的值只能初始化为常量。用非常量值初始化变量， 您需要一个初始化函数，该函数在对象被创建时自动被调用。这样一个函数被称之为构造函数 （见下面）。

<?php
/* None of these will work in PHP 4. */
class Cart
{
    var $todays_date = date("Y-m-d");
    var $name = $firstname;
    var $owner = 'Fred ' . 'Jones';
    var $items = array("VCR", "TV");
}

/* This is how it should be done. */
class Cart
{
    var $todays_date;
    var $name;
    var $owner;
    var $items;

    function Cart()
    {
        $this->todays_date = date("Y-m-d");
        $this->name = $GLOBALS['firstname'];
        /* etc. . . */
    }
}
?>

Classes are types, that is, they are blueprints for actual variables. You have to create a variable of the desired type with the new operator.

<?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 中一个变量 名只有一个单独的美元符号。

// correct, single $
$cart->items = array("10" => 1);

// invalid, because $cart->$items becomes $cart->""
$cart->$items = array("10" => 1);

// correct, but may or may not be what was intended:
// $cart->$myvar becomes $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 is called 'inheritance' despite the fact that nobody died） 的所有变量和函数，并包含所有你在派生类中定义的部分。类中的元素不可能减少，就是说， 不可以注销任何存在的函数或者变量。一个扩充类总是依赖一个单独的基类，也就是说， 多继承是不支持的。使用关键字‘extends’来扩展一个类。

class Named_Cart extends Cart
{
    var $owner;

    function set_owner ($name)
    {
        $this->owner = $name;
    }
}

上述示例定义了名为 Named_Cart 的类，该类拥有 Cart 类的所有变量和函数，加上 附加的变量 $owner 和一个附加函数 set_owner()。现在，你以正常的方式创建了一 个 named cart，并且可以设置并取得 carts 的所有者。而正常的 cart 类的函数依旧 可以在 named carts 中使用：

$ncart = new Named_Cart;    // Create a named cart
$ncart->set_owner("kris");  // Name that cart
print $ncart->owner;        // print the cart owners name
$ncart->add_item("10", 1);  // (inherited functionality from cart)

这个也可以叫做“父－子”关系。你创建一个类，父类，并使用 extends 来创建一个 基于 父类的新类：子类。你甚至可以使用这个新的子类来 创建另外一个基于这个子类的类。

注: 类只有在定义后才可以使用！如果你须要类 Named_Cart 继承类 Cart， 你必须首先定义 Cart 类。如果你须要创建另一个基于 Named_Cart 类 的 Yellow_named_cart 类，你必须首先定义 Named_Cart 类。 简捷的说：类定义的顺序是非常重要的。

后退 | 起点 | 前进
类与对象 | 上一级 | 构造函数


构造函数

注意

PHP 3 和 PHP4 的构造函数有所不同。PHP 4 的语义更可取。

构造函数是类中的一个特殊函数，当使用 new 操作符 创建一个类的实例时，构造函数将会自动调用。PHP 3 中，当函数于类同名时， 这个函数将成为构造函数。PHP 4 ，类中定义的函数与类同名时，这个函数将 成为一个构造函数－区别很微妙，但非常关键（见下文）。

// Works in PHP 3 and PHP 4.
class Auto_Cart extends Cart
{
    function Auto_Cart()
    {
        $this->add_item ("10", 1);
    }
}

上文定义了一个 Auto_Cart 类，即 Cart 类加上一个构造函数，当每次使用 "new" 创建 一个新的 Auto_Cart 类实例时，构造函数将自动调用并将一件商品的数目初始化为 “10”。 构造函数可以使用参数，而且这些参数可选的，它们可以使构造函数更加有用。为了依然可以 不带参数的使用类，所有构造函数的参数应该提供默认值，使其可选。

// Works in PHP 3 and PHP 4.
class Constructor_Cart extends Cart
{
    function Constructor_Cart($item = "10", $num = 1)
    {
        $this->add_item ($item, $num);
    }
}

// Shop the same old boring stuff.

$default_cart = new Constructor_Cart;

// Shop for real...

$different_cart = new Constructor_Cart("20", 17);

你也可以使用 @ 操作符来 消除 发生在构造函数中的错误。e.g. @new.

注意

PHP 3，派生类和构造函数有许多限制。仔细阅读下列范例以理解这些限制。

class A
{
    function A()
    {
      echo "I am the constructor of A.<br>\n";
    }
}

class B extends A
{
    function C()
    {
        echo "I am a regular function.<br>\n";
    }
}

// no constructor is being called in PHP 3.
$b = new B;

PHP 3，在上面的示例中将不会有构造函数被调用。PHP 3 的规则是：“构造函数是与类 同名的函数”。这里，类的名字是 B，但是类 B 中没有函数 B()。什么也不会发生。

PHP 4 修正了这个问题，并介绍了另外的新规则：如果一个类没有构造函数，如果父类有构造 函数的话，父类的构造函数将会被调用。PHP 4 中，上面的例子将会输出“I am the constructor of A.<br>”。

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";
    }
}

// This will call B() as a constructor.
$b = new B;

如果是 PHP 3，A 类中的函数 B() 将立即成为类 B 中的构造函数，虽然并不是有意如此。 PHP 3 中的规则是：“构造函数是与类同名的函数”。PHP 3 并不关心函数是不是在 B 类 中定义的，或者是否已经被继承。

PHP 4 修改了规则：“构造函数与定义其自身的类同名”。因而在 PHP 4 中，类 B 将 不会有属于自身的构造函数，并且父类的构造函数将会被调用，打印出 “I am the constructor of A.<br>”。 [译者注,by Verdana: 这里似乎有问题，实际输出的结果，并不象这里说的那样。实际输出的 内容是“I am a regular function named B in class A......”，输出的是 B() 的内容 也就是说，例子中的注释“This will call B() as a constructor”是正确的。如果从 A 类 中移除函数 B()，那么将输出 A() 的内容。]

注意

不管是 PHP 3 还是 PHP 4 都不能从派生类的构造函数中自动调用基类的构造函数。 It is your reponsibility to prapagater the call to constructors upstream where appropriate.

注: PHP 3 或者 PHP 4 中都没有析构函数。你可以使用 register_shutdown_function() 函数来模拟多数析构函数的效果。

当对象被销毁，使用 unset() 或者简单的脱离范围，析构函数都会自动调用。 但 PHP 中没有析构函数。

后退 | 起点 | 前进
继承 | 上一级 | ::


::

注意

下列内容仅在 PHP 4 中有效。

有时，在没有声明任何实例的情况下访问类中的函数或者基类中的函数和变量很有用处。 而 :: 操作符即用于此情况。

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();
    }
}

// there is no object of class A.
// this will print
//   I am the original function A::example().<br>
A::example();

// create an object of class B.
$b = new B;

// this will print
//   I am the redefined function B::example().<br>
//   I am the original function A::example().<br>
$b->example();

上面的例子调用了 A 类的函数 example()，但是这里并不存在 A 类的对象，
因此不能这样用 $a->example() 或者类似的方法调用 example()。反而我们
将 example() 作为一个类函数来调用，也就是说，作为一个类自身的函数来调用
，而不是这个类的任何对象。

这里有类函数，但没有类的变量。实际上，在调用函数时完全没有任何对象。因而 一个类的函数可以不使用任何对象（但可以使用局部或者全局变量），并且可以根本 不使用 $this 变量。

上面的例子中，类 B 重新定义了函数 example()。A 类中原始定义的函数 example() 将被屏蔽并且不再生效，除非你使用 :: 操作符来访问 A 类中的 example() 函数。 如： A::example() （实际上，你必须编写 parent::example()，下一章介绍该内容。）

就此而论，对于当前对象，它可能有对象变量。因而，你可以在对象函数的内部 使用 $this 和对象变量。

后退 | 起点 | 前进
构造函数 | 上一级 | parent


parent

当你发现自己正在写一些访问基类的变量和函数的代码时，这充分说明了 你的派生类非常的精练、专业。

Instead of using the literal name of the base class in your code, you should be using the special name parent, which refers to the name of your base class as given in the extends declaration of your class. By doing this, you avoid using the name of your base class in more than one place. Should your inheritance tree change during implementation, the change is easily made by simply changing the extends declaration of your class. 你应该在代码中使用专用名称 parent 替代基类的名称， 来访问

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;

// This will call B::example(), which will in turn call A::example().
$b->example();

后退 | 起点 | 前进
:: | 上一级 | 序列化对象－会话中的对象


序列化对象－会话中的对象

注: In PHP 3, objects will lose their class association throughout the process of serialization and unserialization. The resulting variable is of type object, but has no class and no methods, thus it is pretty useless (it has become just like an array with a funny syntax).

注意

The following information is valid for PHP 4 only.

serialize() returns a string containing a byte-stream representation of any value that can be stored in PHP. unserialize() can use this string to recreate the original variable values. Using serialize to save an object will save all variables in an object. The functions in an object will not be saved, only the name of the class.

In order to be able to unserialize() an object, the class of that object needs to be defined. That is, if you have an object $a of class A on page1.php and serialize this, you'll get a string that refers to class A and contains all values of variabled contained in $a. If you want to be able to unserialize this on page2.php, recreating $a of class A, the definition of class A must be present in page2.php. This can be done for example by storing the class defintion of class A in an include file and including this file in both page1.php and page2.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);
  // store $s somewhere where page2.php can find it.
  $fp = fopen("store", "w");
  fputs($fp, $s);
  fclose($fp);

page2.php:
  // this is needed for the unserialize to work properly.
  include("classa.inc");

  $s = implode("", @file("store"));
  $a = unserialize($s);

  // now use the function show_one() of the $a object.
  $a->show_one();

If you are using sessions and use session_register() to register objects, these objects are serialized automatically at the end of each PHP page, and are unserialized automatically on each of the following pages. This basically means that these objects can show up on any of your pages once they become part of your session.

It is strongly recommended that you include the class definitions of all such registered objects on all of your pages, even if you do not actually use these classes on all of your pages. If you don't and an object is being unserialized without its class definition being present, it will lose its class association and become an object of class stdClass without any functions available at all, that is, it will become quite useless.

So if in the example above $a became part of a session by running session_register("a"), you should include the file classa.inc on all of your pages, not only page1.php and page2.php.

后退 | 起点 | 前进
parent | 上一级 | The magic functions __sleep and __wakeup


The magic functions __sleep and __wakeup

serialize() checks if your class has a function with the magic name __sleep. If so, that function is being run 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 object may have, committing pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which need not 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 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.

后退 | 起点 | 前进
序列化对象－会话中的对象 | 上一级 | References inside the constructor


References inside the constructor

Creating references within the constructor can lead to confusing results. This tutorial-like section helps you to avoid problems.

class Foo
{
    function Foo($name)
    {
        // create a reference inside the global array $globalref
        global $globalref;
        $globalref[] = &$this;
        // set name to passed value
        $this->setName($name);
        // and put it out
        $this->echoName();
    }

    function echoName()
    {
        echo "<br>",$this->name;
    }

    function setName($name)
    {
        $this->name = $name;
    }
}

Let us check out if there is a difference between $bar1 which has been created using the copy = operator and $bar2 which has been created using the reference =& operator...

$bar1 = new Foo('set in constructor');
$bar1->echoName();
$globalref[0]->echoName();

/* output:
set in constructor
set in constructor
set in constructor */

$bar2 =& new Foo('set in constructor');
$bar2->echoName();
$globalref[1]->echoName();

/* output:
set in constructor
set in constructor
set in constructor */

Apparently there is no difference, but in fact there is a very significant one: $bar1 and $globalref[0] are _NOT_ referenced, they are NOT the same variable. This is because "new" does not return a reference by default, instead it returns a copy.

注: There is no performance loss (since PHP 4 and up use reference counting) returning copies instead of references. On the contrary it is most often better to simply work with copies instead of references, because creating references takes some time where creating copies virtually takes no time (unless none of them is a large array or object and one of them gets changed and the other(s) one(s) subsequently, then it would be wise to use references to change them all concurrently).

To prove what is written above let us watch the code below.

// now we will change the name. what do you expect?
// you could expect that both $bar1 and $globalref[0] change their names...
$bar1->setName('set from outside');

// as mentioned before this is not the case.
$bar1->echoName();
$globalref[0]->echoName();

/* output:
set from outside
set in constructor */

// let us see what is different with $bar2 and $globalref[1]
$bar2->setName('set from outside');

// luckily they are not only equal, they are the same variable
// thus $bar2->name and $globalref[1]->name are the same too
$bar2->echoName();
$globalref[1]->echoName();

/* output:
set from outside
set from outside */

Another final example, try to understand it.

class A
{
    function A($i)
    {
        $this->value = $i;
        // try to figure out why we do not need a reference here
        $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;
    }
}

// try to undestand why using a simple copy here would yield
// in an undesired result in the *-marked line
$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();

/*
output:
class A: 10
class B: 10
class B: 10
class A: 11
class B: 11
class B: 11
*/

后退 | 起点 | 前进
The magic functions __sleep and __wakeup | 上一级 | 引用的解释


引用的解释

PHP 手册
后退 前进

章 15. 引用的解释

目录
引用是什么
引用做什么
引用不是什么
引用传递
引用返回
取消引用
引用定位

引用是什么

在 PHP 中引用意味着用不同的名字访问同一个变量内容。这并不像 C 的指针，它们是符号表别名。注意在 PHP 中，变量名和变量内容是不一样的，因此同样的内容可以有不同的名字。最接近的比喻是 Unix 的文件名和文件本身 － 变量名是目录条目，而变量内容则是文件本身。引用可以被看作是 Unix 文件系统中的紧密连接。

后退 | 起点 | 前进
References inside the constructor | 上一级 | 引用做什么


引用做什么

PHP 的引用允许你用两个变量来指向同一个内容。意思是，当你这样做时：

$a =& $b

这意味着 $a 和 $b 指向了同一个变量。

注: $a 和 $b 在这里是完全相同的，这并不是 $a 指向了 $b 或者相反，而是 $a 和 $b 指向了同一个地方。

同样的语法可以用在函数中，它返回引用，以及用在 new 运算符中（PHP 4.0.4 以及以后版本）：

$bar =& new fooclass();
$foo =& find_var ($bar);

注: 不用 & 运算符导致对象生成了一个拷贝。如果你在类中用 $this，它将作用于该类当前的实例。没有用 & 的赋值将拷贝这个实例（例如对象）并且 $this 将作用于这个拷贝上，这并不总是想要的结果。由于性能和内存消耗的问题，通常你只想工作在一个实例上面。

尽管你可以用 @ 运算符来关闭构造函数中的任何错误信息，例如用 @new，但用 &new 语句时这不起效果。这是 Zend 引擎的一个限制并且会导致一个解析错误。

引用做的第二件事是用引用传递变量。这是通过在函数内建立一个本地变量并且该变量在呼叫范围内引用了同一个内容来实现的。例如：

function foo (&$var)
{
    $var++;
}

$a=5;
foo ($a);

将使 $a 变成 6。这是因为在 foo 函数中变量 $var 指向了和 $a 指向的同一个内容。更多详细解释见引用传递。

引用做的第三件事是引用返回。

后退 | 起点 | 前进
引用的解释 | 上一级 | 引用不是什么


引用不是什么

如前所述，引用不是指针。这意味着下面的结构不会产生你预期的效果：

function foo (&$var)
{
    $var =& $GLOBALS["baz"];
}
foo($bar);

这将使 foo 函数中的 $var 变量在函数调用时和 $bar 绑定在一起，但接着又被重新绑定到了 $GLOBALS["baz"] 上面。不可能通过引用机制将 $bar 在函数调用范围内绑定到别的变量上面，因为在函数 foo 中并没有变量 $bar（它被表示为 $var，但是 $var 只有变量内容而没有调用符号表中的名字到值的绑定）。

后退 | 起点 | 前进
引用做什么 | 上一级 | 引用传递


引用传递

你可以将一个变量通过引用传递给函数，这样该函数就可以修改其参数的值。语法如下：

function foo (&$var)
{
    $var++;
}

$a=5;
foo ($a);
// $a is 6 here

注意在函数调用时没有引用符号 － 只有函数定义中有。光是函数定义就足够使参数通过引用来正确传递了。

以下内容可以通过引用传递：

  • 变量，例如 foo($a)

  • New 语句，例如 foo(new foobar())

  • 从函数中返回的引用，例如：

    function &bar()
{
    $a = 5;
    return $a;
}
foo(bar());

    详细解释见引用返回。

任何其它表达式都不能通过引用传递，结果未定义。例如下面引用传递的例子是无效的：

function bar() // Note the missing &
{
    $a = 5;
    return $a;
}
foo(bar());

foo($a = 5) // Expression, not variable
foo(5) // Constant, not variable

这些条件是 PHP 4.0.4 以及以后版本有的。

后退 | 起点 | 前进
引用不是什么 | 上一级 | 引用返回


引用返回

引用返回用在当你想用函数找到引用应该被绑定在哪一个变量上面时。当返回引用时，使用此语法：

function &find_var ($param)
{
    ...code...
    return $found_var;
}

$foo =& find_var ($bar);
$foo->x = 2;

本例中 find_var 函数所返回的对象的属性将被设定（译者：指的是 $foo->x = 2; 语句），而不是拷贝，就和没有用引用语法一样。

注: 和参数传递不同，这里必须在两个地方都用 & 符号 － 来指出返回的是一个引用，而不是通常的一个拷贝，同样也指出 $foo 是作为引用的绑定，而不是通常的赋值。

后退 | 起点 | 前进
引用传递 | 上一级 | 取消引用


取消引用

当你 unset 一个引用，只是断开了变量名和变量内容之间的绑定。这并不意味着变量内容被销毁了。例如：

$a = 1;
$b =& $a;
unset ($a);

不会 unset $b，只是 $a。

再拿这个和 Unix 的 unlink 调用来类比一下可能有助于理解。

后退 | 起点 | 前进
引用返回 | 上一级 | 引用定位


引用定位

许多 PHP 的语法结构是通过引用机制实现的，所以上述有关引用绑定的一切也都适用于这些结构。一些结构，例如引用传递和返回，已经在上面提到了。其它使用引用的结构有：

global 引用

当用 global $var 声明一个变量时实际上建立了一个到全局变量的引用。也就是说和这样做是相同的：

$var =& $GLOBALS["var"];

这意味着，例如，unset $var 不会 unset 全局变量。

$this

在一个对象的方法中，$this 永远是调用它的对象的引用。

后退 | 起点 | 前进
取消引用 | 上一级 | 特点


特点

PHP 手册
后退 前进

III. 特点

目录
16. 错误处理
17. 图形的建立与操作
18. 用 PHP 进行 HTTP 认证
19. Cookies
20. 文件上传处理
21. 使用远程文件
22. 连接处理
23. 数据库永久连接
24. 安全模式
25. PHP 的命令行模式

后退 | 起点 | 前进
引用定位 |  | 错误处理


错误处理

PHP 手册
后退 前进

章 16. 错误处理

PHP 有如下几种错误和警告：

表格 16-1. PHP 错误类型

值 | 常量 | 描述 | 备注
1 | E_ERROR | 运行时致命错误 |
2 | E_WARNING | 运行时警告（非致命错误） |
4 | E_PARSE | 编译时解析错误 |
8 | E_NOTICE | 运行时提醒（比 Warning 的严重性更低） |
16 | E_CORE_ERROR | 在 PHP 初始化过程中发生的致命错误 | 仅 PHP 4 有效
32 | E_CORE_WARNING | 在 PHP 初始化过程中发生的警告（非指明错误） | 仅 PHP 4 有效
64 | E_COMPILE_ERROR | 编译时指明错误 | 仅 PHP 4 有效
128 | E_COMPILE_WARNING | 编译时警告（非指明错误） | 仅 PHP 4 有效
256 | E_USER_ERROR | 用户自定义错误信息 | 仅 PHP 4 有效
512 | E_USER_WARNING | 用户自定义警告信息 | 仅 PHP 4 有效
1024 | E_USER_NOTICE | 用户自定义提醒信息 | 仅 PHP 4 有效
 | E_ALL | 以上所有支持的项目 |

以上的值（不管是数字还是符号）被用来建立指定要报告的错误的位掩码（bitmask）。您可以使用位操作符来叠加或者掩去某一种类型的错误。请注意 php.ini 仅能识别“|”、“~”、“!”和“&”四种符号，而 php3.ini 无法识别任何位操作符。

在 PHP 4 中，error_reporting 默认的值为 E_ALL & ~E_NOTICE，表示显示除 E_NOTICE-level 以外所有错误的警告信息。在 PHP 3 中，其默认值为 (E_ERROR | E_WARNING | E_PARSE)，表示的内容和 PHP 4 相同。注意，由于 php3.ini 不支持常量，error_reporting 的设置应该用数字来表示，因此，其值应该为 7。

这项设置的初始设定可以通过更改 ini 文件中的 error_reporting 选项来改变，也可以在 Apache 系统中设置 httpd.conf 中的 php_error_reporting（PHP 3 为 php3_error_reporting）来改变。另外，脚本的运行过程中，也可以通过 error_reporting() 函数来更改该设置。

警告

在将服务端的代码从 PHP 3 升级到 PHP 4 时，您需要检查这些设置，或者调用 error_reporting()，否则您可能会屏蔽新类型的错误报告，尤其是 E_COMPILE_ERROR。这将有可能导致没有任何反馈信息的空文档，使得您不知道发生了什么，也不知道到哪里检查发生的问题。

所有的 PHP 表达式都可以使用“@”前缀，该前缀将屏蔽该表达式所有的错误信息。如果在该语句运行过程中出现了错误并且 track_errors 选项开启，则您可以在全局变量 $php_errormsg 中找到错误信息。

注: @ 错误信息控制符前缀不会屏蔽解析错误信息。

警告

目前 @ 错误信息控制符前缀有可能会屏蔽导致脚本停止运行的关键错误的信息。这也就是说，如果您在不可用的，或者未正确定义的函数前面使用 @ 符号来抑制错误，脚本程序会在该处停止运行，并且不会给出任何关于为什么停止的提示信息。

以下是在 PHP 中使用错误处理兼容的例子。我们定义了一个错误处理函数，该函数会将错误信息记录到一个文件中（用 XML 格式），并在脚本出现关键错误时将错误信息通过 Email 发送给开发者。

例子 16-1. 在脚本中使用错误处理

<?php
// we will do our own error handling
error_reporting(0);

// user defined error handling function
function userErrorHandler ($errno, $errmsg, $filename, $linenum, $vars) {
    // timestamp for the error entry
    $dt = date("Y-m-d H:i:s (T)");

    // define an assoc array of error string
    // in reality the only entries we should
    // consider are 2,8,256,512 and 1024
    $errortype = array (
                1   =>  "Error",
                2   =>  "Warning",
                4   =>  "Parsing Error",
                8   =>  "Notice",
                16  =>  "Core Error",
                32  =>  "Core Warning",
                64  =>  "Compile Error",
                128 =>  "Compile Warning",
                256 =>  "User Error",
                512 =>  "User Warning",
                1024=>  "User Notice"
                );
    // set of errors for which a var trace will be saved
    $user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE);

    $err = "<errorentry>\n";
    $err .= "\t<datetime>".$dt."</datetime>\n";
    $err .= "\t<errornum>".$errno."</errornum>\n";
    $err .= "\t<errortype>".$errortype[$errno]."</errortype>\n";
    $err .= "\t<errormsg>".$errmsg."</errormsg>\n";
    $err .= "\t<scriptname>".$filename."</scriptname>\n";
    $err .= "\t<scriptlinenum>".$linenum."</scriptlinenum>\n";

    if (in_array($errno, $user_errors))
        $err .= "\t<vartrace>".wddx_serialize_value($vars,"Variables")."</vartrace>\n";
    $err .= "</errorentry>\n\n";

    // for testing
    // echo $err;

    // save to the error log, and e-mail me if there is a critical user error
    error_log($err, 3, "/usr/local/php4/error.log");
    if ($errno == E_USER_ERROR)
        mail("phpdev@example.com","Critical User Error",$err);
}

function distance ($vect1, $vect2) {
    if (!is_array($vect1) || !is_array($vect2)) {
        trigger_error("Incorrect parameters, arrays expected", E_USER_ERROR);
        return NULL;
    }

    if (count($vect1) != count($vect2)) {
        trigger_error("Vectors need to be of the same size", E_USER_ERROR);
        return NULL;
    }

    for ($i=0; $i<count($vect1); $i++) {
        $c1 = $vect1[$i]; $c2 = $vect2[$i];
        $d = 0.0;
        if (!is_numeric($c1)) {
            trigger_error("Coordinate $i in vector 1 is not a number, using zero",
                            E_USER_WARNING);
            $c1 = 0.0;
        }
        if (!is_numeric($c2)) {
            trigger_error("Coordinate $i in vector 2 is not a number, using zero",
                            E_USER_WARNING);
            $c2 = 0.0;
        }
        $d += $c2*$c2 - $c1*$c1;
    }
    return sqrt($d);
}

$old_error_handler = set_error_handler("userErrorHandler");

// undefined constant, generates a warning
$t = I_AM_NOT_DEFINED;

// define some "vectors"
$a = array(2,3,"foo");
$b = array(5.5, 4.3, -1.6);
$c = array (1,-3);

// generate a user error
$t1 = distance($c,$b)."\n";

// generate another user error
$t2 = distance($b,"i am not an array")."\n";

// generate a warning
$t3 = distance($a,$b)."\n";

?>
这仅仅是关于错误处理和记录函数的一个简单的例子。

请参阅
error_reporting(),
error_log(),
set_error_handler(),
restore_error_handler(),
trigger_error(),
user_error()

后退 | 起点 | 前进
特点 | 上一级 | 图形的建立与操作


图形的建立与操作

PHP 手册
后退 前进

章 17. 图形的建立与操作

PHP 并不只局限于建立 HTML 的输出，它同样可以被用来建立和操作各种不同格式的图片文件，包括 GIF、PNG、JPG、WBMP 和 XPM。更方便的是，PHP 能够直接将图形以数据流方式输出浏览器。如果要使用该功能，您可能需要将 PHP 和 GD 图形函数库一同编译。根据您需要使用的图形格式的不同，GD 和 PHP 可能还需要其它的扩展库。另外，GD 在其 1.6 版本后就不再支持 GIF 格式了。

例子 17-1. 使用 PHP 建立 PNG 图像

<?php
    Header("Content-type: image/png");
    $string=implode($argv," ");
    $im = ImageCreateFromPng("images/button1.png");
    $orange = ImageColorAllocate($im, 220, 210, 60);
    $px = (imagesx($im)-7.5*strlen($string))/2;
    ImageString($im,3,$px,9,$string,$orange);
    ImagePng($im);
    ImageDestroy($im);
?>

该范例可以在页面中，以 <img src="button.php?text"> 的形式调用。上述的 button.php 脚本会将字符串“text”显示在以 "images/button1.png" 文件为基础的图像上，并输出最后得到的图像。使用这个方法，您就不用每次更改按钮上的文字都要制作新的按钮图形。使用这个方法，按钮图片可以动态的生成。

后退 | 起点 | 前进
错误处理 | 上一级 | 用 PHP 进行 HTTP 认证


用 PHP 进行 HTTP 认证

PHP 手册
后退 前进

章 18. 用 PHP 进行 HTTP 认证

PHP 的 HTTP 认证机制仅在 PHP 以 Apache 模块方式运行时才有效，因此该功能不适用于 CGI 版本。在 Apache 模块的 PHP 脚本中，可以用 header() 函数来向客户端浏览器发送“Authentication Required”信息，使其弹出一个用户名/密码输入窗口。当用户输入用户名和密码后，包含有 URL 的 PHP 脚本将会再次和预定义变量 PHP_AUTH_USER、PHP_AUTH_PW 和 PHP_AUTH_TYPE 一起被调用，这三个变量分别被设定为用户名，密码和认证类型。预定义变量保存在 $_SERVER 或者 $HTTP_SERVER_VARS 数组中。系统仅支持“基本的”认证。请参阅 header() 函数以获取更多信息。

PHP 版本问题: Autoglobals 全局变量，包括 $_SERVER等，在 PHP 4.1.0 以后版本有效， $HTTP_SERVER_VARS 从 PHP 3 开始有效。

以下是在页面上强迫客户端认证的脚本范例：

例子 18-1. HTTP 认证范例

<?php
  if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button\n';
    exit;
  } else {
    echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
    echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
  }
?>

兼容性问题: 在编写 HTTP 头信息代码时请格外小心。为了对所有的客户端保证兼容性，关键字“Basic”的第一个字母必须大写为“B”，分界字符串必须用双引号（不是单引号）引用；并且在头信息行 HTTP/1.0 401 中，在 401 前必须有且仅有一个空格。

在以上例程中，我们仅仅只打印出了 PHP_AUTH_USER 和 PHP_AUTH_PW 的值，但在实际运用中，您可能需要对用户名和密码的合法性进行检查。或许进行数据库的查询，或许从 dbm 文件中检索。

请注意由 Internet Explorer 浏览器本身的问题带来的错误。它对头信息的顺序显得似乎有点吹毛求疵。目前在 HTTP/1.0 401 头之前发送 WWW-Authenticate 头信息能解决该问题。

为了防止有人编写恶意代码来显示为以前通过传统外部机制认证的页面提供的密码，当某些页面的外部认证被激活时，PHP_AUTH 变量将不会被设置。在这种情况下，我们可以使用 REMOTE_USER 变量来辨别外部认证的用户，即 $_SERVER['REMOTE_USER']。

设置问题: PHP 用 AuthType 选项来判断外部认证机制是否有效。当您希望使用 PHP 认证的时候，请记得关闭该选项，否则任何认证的尝试操作都会失败。

注意，这仍然不能防止有人通过未认证的 URL 来从同一服务器上认证的 URL 上偷取密码。

Netscape Navigator 和 Internet Explorer 浏览器都会在收到 401 的服务端返回信息时清空所有的本地浏览器整个域的 Windows 认证缓存。这能够有效的注销一个用户，并迫使他们重新输入他们的用户名和密码。有些人用这种方法来使登录状态“过期”，或者作为“注销”按钮的响应行为。

例子 18-2. 强迫重新输入用户名和密码的 HTTP 认证的范例

<?php
  function authenticate() {
    header('WWW-Authenticate: Basic realm="Test Authentication System"');
    header('HTTP/1.0 401 Unauthorized');
    echo "You must enter a valid login ID and password to access this resource\n";
    exit;
  }

  if (!isset($_SERVER['PHP_AUTH_USER']) || ($_POST['SeenBefore'] == 1 && $_POST['OldAuth'] == $_SERVER['PHP_AUTH_USER'])) {
   authenticate();
  }
  else {
   echo "<p>Welcome: {$_SERVER['PHP_AUTH_USER']}<br>";
   echo "Old: {$_REQUEST['OldAuth']}";
   echo "<form action='{$_SERVER['PHP_SELF']}' METHOD='POST'>\n";
   echo "<input type='hidden' name='SeenBefore' value='1'>\n";
   echo "<input type='hidden' name='OldAuth' value='{$_SERVER['PHP_AUTH_USER']}'>\n";
   echo "<input type='submit' value='Re Authenticate'>\n";
   echo "</form></p>\n";
  }
?>

该行为对于 HTTP 基本认证标准来说并不是必须的，因此您不能依靠这种方法。对 Lynx 浏览器的测试表明 Lynx 在收到 401 的服务端返回信息时不会清空认证文件，因此只要对认证文件的检查要求没有变化，只要用户点击“后退”按钮，再点击“前进”按钮，其原有资源仍然能够被访问。不过，用户可以通过按“_”键来清空他们的认证信息。

同时请注意，由于微软的 IIS 服务器的一些限制，该功能对 IIS 和 PHP 的 CGI 版本不适用。

注: 如果安全模式被激活，脚本的 UID 会被加到 WWW-Authenticate 头信息的 realm 部分。

后退 | 起点 | 前进
图形的建立与操作 | 上一级 | Cookies


Cookies

PHP 手册
后退 前进

章 19. Cookies

PHP 完全地支持 HTTP Cookies。Cookie 是一种在远程浏览器端储存数据并以此来跟踪和识别用户的机制。您可以使用 setcookie() 函数来设置 Cookie。Cookie 是 HTTP 头的一部分，因此 setcookie() 函数必须在其它信息被输出到浏览器前调用，这和对 header() 函数的限制是类似的。您可以使用输出缓冲函数来延迟脚本的输出，直到按照您的需要设置好了所有的 cookies 或者其它 HTTP 头信息。

任何从客户端发送给您的 cookies 将会像 GET 和 POST 数据一样被自动的转换为 PHP 变量，该过程受 register_globals 和 variables_order 两个设置变量的影响。如果您希望对一个 cookie 变量设置多个值，则需在 cookie 的名称后加 [] 符号。

在 PHP 4.1.0 及更高版本，自动全局变量数组 $_COOKIE 将总是包含所有总客户端发来的 cookies 数据。在老版本的 PHP 中，当 track_vars 设置变量打开时，系统为 cookies 设置的数组变量是 $HTTP_COOKIE_VARS。

关于更多细节以及有关浏览器问题的注意事项，请参阅 setcookie() 函数。

后退 | 起点 | 前进
用 PHP 进行 HTTP 认证 | 上一级 | 文件上传处理


文件上传处理

PHP 手册
后退 前进

章 20. 文件上传处理

目录
POST 方法上传
关于错误信息的解释
一些注意事项
上传多个文件
对 PUT 方法的支持

POST 方法上传

PHP 能够接受任何来自符合 RFC-1867 标准的浏览器（包括 Netscape Navigator 3 及更高版本，Microsoft Internet Explorer 3 加微软补丁，或者更高版本）上传的文件。PHP 的这种特性使得我们既可以上传文本文件，也可以上传二进制文件。利用 PHP 的认证和文件操作函数，您就可以控制谁有上传的权限，以及在文件上传后进行哪些处理。

相关的设置: 请参阅 php.ini 的 file_uploads、 upload_max_filesize、upload_tmp_dir 以及 post_max_size 设置选项。

请注意 PHP 也支持 PUT 方法的文件上传，Netscape Composer 和 W3C 的 Amaya 客户端使用这种方法。请参阅 PUT 方法支持以获取更多信息。

您可以如下建立一个特殊的表单来支持文件上传：

例子 20-1. 文件上传表单

<form enctype="multipart/form-data" action="_URL_" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="1000">
Send this file: <input name="userfile" type="file">
<input type="submit" value="Send File">
</form>

该范例中的 _URL_ 应该指向一个 PHP 文件。 MAX_FILE_SIZE 隐藏字段必须在文件输入字段之前，且其值为接受文件的最大尺寸，单位为字节。

警告

MAX_FILE_SIZE 的值只是对浏览器的一个建议，实际上它可以被简单的绕过。因此不要把对浏览器的限制寄希望于该值。实际上，PHP 设置中的上传文件最大值，是不会失效的。

为上传文件定义的变量会根据 PHP 的版本及设置的不同而不同。自动全局变量 $_FILES 从 PHP 4.1.0 版本开始被支持。在这之前，从 4.0.0 版本开始，PHP 支持 $HTTP_POST_FILES 数组。这些数组将包含所有关于您上传的文件的信息，其中，我们推荐您使用 $_FILES。如果 PHP 的设置选项 register_globals 为 on，则相关的变量名将也会存在。从 PHP 4.2.0 版本开始，register_globals 的默认值被设为 off。

以上范例中 $_FILES 数组的内容如下所示。我们假设文件上传字段的名称如上例所示，为 userfile。

$_FILES['userfile']['name']

客户端机器文件的原名称。

$_FILES['userfile']['type']

文件的 MIME 类型，需要浏览器提供该信息的支持，例如“image/gif”。

$_FILES['userfile']['size']

已上传文件的大小，单位为字节。

$_FILES['userfile']['tmp_name']

文件被上传后在服务端储存的临时文件名。

$_FILES['userfile']['error']

和该文件上传相关的错误代码。['error'] 是在 PHP 4.2.0 版本中增加的。

注: 在 PHP 4.1.0 版本以前该数组的名称为 $HTTP_POST_FILES，它并不像 $_FILES 一样是自动全局变量。PHP 3 不支持 $HTTP_POST_FILES 数组。

当 php.ini 中的 register_globals 被设置为 on 时，您可以使用更多的变量。例如，$userfile_name 等价于 $_FILES['userfile']['name']，$userfile_type 等价于 $_FILES['userfile']['type'] 等。请记住从 PHP 4.2.0 开始，register_globals 的默认值为 off，因此我们建议您不要依赖于改设置项而使用刚刚提到的那些附加变量。

文件被上传后，默认地会被储存到服务端的默认临时目录中，除非您将 php.ini 中的 upload_tmp_dir 设置为了其它的路径。服务端的默认临时目录可以通过更改 PHP 运行环境的环境变量 TMPDIR 来重新设置，但是在 PHP 脚本内部通过运行 putenv() 函数来设置是不起作用的。该环境变量也可以用来确认其它的操作也是在上传的文件上进行的。

例子 20-2. 使文件上传生效

以下例程适用于 PHP 4.0.2 以上版本。请参阅函数 is_uploaded_file() 和 move_uploaded_file()。

<?php
// In PHP earlier then 4.1.0, $HTTP_POST_FILES  should be used instead of $_FILES.
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
    copy($_FILES['userfile']['tmp_name'], "/place/to/put/uploaded/file");
} else {
    echo "Possible file upload attack. Filename: " . $_FILES['userfile']['name'];
}
/* ...or... */
move_uploaded_file($_FILES['userfile']['tmp_name'], "/place/to/put/uploaded/file");
?>

接受上传文件的 PHP 脚本必须在文件上传后进行判断，来决定接下来要对该文件进行那些操作。例如，您可以通过 $_FILES['userfile']['size'] 变量来忽略尺寸太大或太小的文件，也可以通过 $_FILES['userfile']['type'] 变量来过滤文件类型和某种标准不相符合的文件。在 PHP 4.2.0 以上版本，您还可以通过 $_FILES['userfile']['error'] 变量来根据不同的错误代码来做相关的判断。不管做何种的判断，您必须将该文件从临时目录中删除，要么将其移动到其它的地方。

如果该文件没有被移动到其它地方也没有被改名，则该文件将在表单请求结束时被删除。

后退 | 起点 | 前进
Cookies | 上一级 | 关于错误信息的解释


关于错误信息的解释

从 PHP 4.2.0 开始，PHP 将随文件信息数组一起返回一个对应的错误代码。该代码可以在文件上传时生成的文件数组中的 ['error'] 字段中被找到，也就是 $_FILES['userfile']['error']。

UPLOAD_ERR_OK

值：0; 没有错误发生，文件上传成功。

UPLOAD_ERR_INI_SIZE

值：1; 上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值。

UPLOAD_ERR_FORM_SIZE

值：2; 上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。

UPLOAD_ERR_PARTIAL

值：3; 文件只有部分被上传。

UPLOAD_ERR_NO_FILE

值：4; 没有文件被上传。

注: 这些在 PHP 4.3.0 之后变成了 PHP 常量。

后退 | 起点 | 前进
文件上传处理 | 上一级 | 一些注意事项


一些注意事项

对 MAX_FILE_SIZE 设置的值，不能大于 ini 设置中 upload_max_filesize 选项设置的值。其默认值为 2M 字节。

如果内存限制设置被激活，您可能需要将 memory_limit 设置的更大些，请确认 memory_limit 的设置足够的大。

如果 max_execution_time 设置的值太小，脚本运行的时间可能会超过该设置。因此，也请保证 max_execution_time 足够的大。

如果 post_max_size 设置的值太小，则较大的文件会无法被上传。因此，请保证 post_max_size 的值足够的大。

不使您操作的文件有效化，可能意味着用户能够访问其它目录下的敏感信息。

请注意 CERN httpd 似乎会丢弃它从客户端获得的 content-type mime 头信息中第一个空格后所有的内容，基于这一点，CERN httpd 不支持文件上传特性。

鉴于文件路径的表示方法有很多种，我们无法确保用使用各种外语的文件名（尤其是包含空格的）能够被正确的处理。

后退 | 起点 | 前进
关于错误信息的解释 | 上一级 | 上传多个文件


上传多个文件

您可以对 input 域使用不同的 name 来上传多个文件。

PHP 支持同时上传多个文件并将它们的信息自动以数组的形式组织。要完成这项功能，您需要在 HTML 表单中对文件上传域使用类似于多下拉菜单和复选框的数组名称来提交。

注: 对多文件上传的支持是在 3.0.10 版本添加的。

例子 20-3. 上传多个文件

<form action="file-upload.php" method="post" enctype="multipart/form-data">
  Send these files:<br>
  <input name="userfile[]" type="file"><br>
  <input name="userfile[]" type="file"><br>
  <input type="submit" value="Send files">
</form>

当以上表单被提交后，数组 $_FILES['userfile']、$_FILES['userfile']['name'] 和 $_FILES['userfile']['size'] 将被初始化（在 PHP 4.1.0 以前版本是 $HTTP_POST_FILES。如果 register_globals 的设置为 on，则和文件上传相关的全局变量也将被初始化。）所有这些提交的信息都将被储存到以数字为索引的数组中。

例如，假设名为 /home/test/review.html 和 /home/test/xwp.out 的文件被提交，则 $_FILES['userfile']['name'][0] 将包含文件 review.html 的名称，而 $_FILES['userfile']['name'][1] 则将包含文件 xwp.out 的名称。类似的，$_FILES['userfile']['size'][0] 将包含文件 review.html 的大小，依此类推。

$_FILES['userfile']['name'][0]、$_FILES['userfile']['tmp_name'][0]、$_FILES['userfile']['size'][0] 以及 $_FILES['userfile']['type'][0] 都将被同时设置并有效。

后退 | 起点 | 前进
一些注意事项 | 上一级 | 对 PUT 方法的支持


对 PUT 方法的支持

PHP 提供对诸如 Netscape Composer 和 W3C Amaya 等客户端使用的 HTTP PUT 方法的支持。PUT 请求比文件上传要简单的多，它们一般的形式为：

PUT /path/filename.html HTTP/1.1

这通常意味着远程客户端会将其中的 /path/filename.html 存储到您的 WEB 目录树。让 Apache 或者 PHP 自动允许所有人覆盖您 WEB 目录数下的任何文件显然是很不明智的。因此，要处理类似的请求，您必须先告诉您的 WEB 服务器您需要用特定的 PHP 脚本来处理该请求。在 Apache 下，您可以用 Script 选项来设置。它可以被放置到 Apache 配置文件中几乎所有的位置。通常我们把它放置在 <Directory> 区域或者 <Virtualhost> 区域。您可以用如下一行来完成该设置：

Script PUT /put.php

这将告诉 Apache 将所有对 URIs 的 PUT 请求全部发送到 put.php 脚本，这些 URIs 必须和 PUT 命令中的内容相匹配。当然，这是建立在您的 PHP 支持 .php 扩展名，并且 PHP 已经在运行的假设之上。

在您的 put.php 文件中，您可以作如下操作：

<?php copy($PHP_UPLOADED_FILE_NAME,$DOCUMENT_ROOT.$REQUEST_URI); ?>

这将会把文件拷贝到远程客户端请求的位置。您可能希望在文件拷贝之前进行一些检查或者对用户认证之类的操作。这里唯一的问题是，当 PHP 接受到 PUT 方法的请求时，它将会把上传的文件储存到和其它用 POST 方法处理过的文件相同的临时目录。在请求结束时，临时文件将被删除。因此，您用来处理 PUT 的 PHP 脚本必须将该文件拷贝到其它的地方。该临时文件的文件名被储存在变量 $PHP_PUT_FILENAME 中，您也可以通过 $REQUEST_URI 变量获得建议的目标文件名（在非 Apache WEB 服务器上可能会有较大的变化）。该目标文件名是由远程客户端指定的。您也可以不听从改客户端的信息，而把所有上传的文件存储到一个特殊的上传目录下。

后退 | 起点 | 前进
上传多个文件 | 上一级 | 使用远程文件


使用远程文件

PHP 手册
后退 前进

章 21. 使用远程文件

由于 php.ini 文件支持 allow_url_fopen 选项，您可以在大多数需要用文件名作为参数的函数中使用 HTTP 和 FTP URL 来代替文件名。同时，您也可以在 include()、include_once()、require() 及 require_once() 语句中使用 URL。

注: 要在 PHP 4.0.3 及其以后版本中使用 URL，您需要用 --enable-url-fopen-wrapper 参数来配置 PHP。

注: Windows 版本的 PHP 当前不支持以下函数的远程访问：include()、include_once()、 require() 和 require_once()。

例如，您可以用以下范例来打开远程 WEB 服务器上的文件，解析您需要的输出数据，然后将这些数据用在数据库的检索中，或者简单地将其输出到您网站剩下内容的样式匹配中。

例子 21-1. 获取远程文件的标题

<?php
$file = fopen ("http://www.example.com/", "r");
if (!$file) {
    echo "<p>Unable to open remote file.\n";
    exit;
}
while (!feof ($file)) {
    $line = fgets ($file, 1024);
    /* This only works if the title and its tags are on one line */
    if (eregi ("<title>(.*)</title>", $line, $out)) {
        $title = $out[1];
        break;
    }
}
fclose($file);
?>

如果您用有合法的访问权限，以一个用户的身份和某 FTP 服务器建立了链接，您还可以向该 FTP 服务器端的文件进行写操作。您仅能用该方法来创建新的文件；如果您尝试覆盖已经存在的文件，fopen() 函数的操作将会失败。

要以“anonymous”以外的用户名连接服务器，您需要指明用户名（甚至密码），例如“ftp://user:password@ftp.example.com/path/to/file”。（如果通过 HTTP 协议访问远程文件时需要基本身份认证，您也可以用使用的语法。）

例子 21-2. 远程服务端的数据存储

<?php
$file = fopen ("ftp://ftp.example.com/incoming/outputfile", "w");
if (!$file) {
    echo "<p>Unable to open remote file for writing.\n";
    exit;
}
/* Write the data here. */
fputs ($file, $_SERVER['HTTP_USER_AGENT'] . "\n");
fclose ($file);
?>

注: 您或许可以从以上范例中得到启发，用该技术来存储远程日志文件。但是正如以上提到的，在用 fopen() 方式打开的 URL 中，您仅能对新文件进行写操作。如果远程文件已经存在 fopen() 函数的操作将会失败。要进行类似的分布式日志操作，您可以参考 syslog() 函数。

后退 | 起点 | 前进
对 PUT 方法的支持 | 上一级 | 连接处理


连接处理

PHP 手册
后退 前进

章 22. 连接处理

注: 以下内容对 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_timeout() 函数来检查超时是否导致关闭触发函数被调用。如果超时导致了关闭触发函数的调用，该函数将返回 TRUE。

需要注意的一点是 ABORTED 和 TIMEOUT 状态可以同时有效。这在你告诉 PHP 忽略用户的退出操作时是可能的。PHP 将仍然注意用户已经中断了连接但脚本仍然在运行的情况。如果到了运行的时间限制，脚本将被退出，设置过的关闭触发函数也将被执行。在这时您会发现函数 connection_timeout() 和 connection_aborted() 都返回 TRUE。您也可以通过执行 connection_status() 函数来同时检查这两种状态。该函数将返回被激活的状态的二进制位码。例如，如果这两种状态都被激活，则函数将返回 3。

后退 | 起点 | 前进
使用远程文件 | 上一级 | 数据库永久连接


数据库永久连接

PHP 手册
后退 前进

章 23. 数据库永久连接

永久的数据库连接是指在您的脚本结束运行时不关闭的 SQL 连接。当收到一个永久连接的请求时。PHP 将检查是否已经存在一个（前面已经开启的）相同的永久连接。如果存在，将直接使用这个连接；如果不存在，则建立一个新的连接。所谓“相同”的连接是指用相同的用户名和密码到相同主机的连接。

注: 另外，还有一些其它的扩展库也支持永久连接，例如 IMAP 扩展库。

对 WEB 服务器的工作和分布负载没有完全理解的读者可能会错误地理解永久连接的作用。特别的，永久连接不会在相同的 SQL 连接上为您提供建立“用户会话”的能力，也不提供有效建立事务的能力。实际上，从严格意义上来讲，永久连接不会给您提供任何非永久连接无法提供的特殊功能。

为什么？

这和 WEB 服务器工作的方式有关。您的 WEB 服务器可以用三种方法来利用 PHP 生成 WEB 页面。

第一种方法是将 PHP 用作一个“外壳”。以这种方法运行，PHP 会为向您的 WEB 服务器提出的每个 PHP 页面请求生成并结束一个 PHP 解释器线程。由于该线程会随每个请求的结束而结束，因此任何在这个线程中利用的任何资源（例如指向 SQL 数据库服务器的连接）都会随线程的结束而关闭。在这种情况下，您使用永久连接不会获得任何地改变——因为它们根本不是永久的。

第二，也是最常用的方法，是把 PHP 用作多过程 WEB 服务器的一个模块，这种方法目前只适用于 Apache。对于一个多过程的服务器，其典型特征是有一个父过程和一组子过程协调运行，其中实际生成 WEB 页面的是子过程。当客户端向父过程提出请求时，该请求会被传递给还没有被其它的客户端请求占用的子过程。这也就是说当相同的客户端第二次向服务端提出请求时，它将有可能被一个不同的子过程来处理。在这种情况下，永久连接使得每个子过程需要做的只是利用上一个页面请求时建立的连接。也就是说，当另一个页面向 SQL 数据库提出连接请求时，它可以使用处理该请求的子过程先前建立的连接。

最后一种方法是将 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 个线程试图连接，那么有一个线程将无法连接。如果这个时候，在您的脚本中出现了使得连接无法关闭的错误（例如无限循环），则该数据库的 32 个连接将迅速的受到影响。请查阅您使用的数据库的文档，以获取关于如何处理已放弃的及闲置的连接的方法。

警告

在使用永久连接时还有一些特别的问题需要注意。例如在永久连接中使用数据表锁时，如果脚本不管什么原因无法释放该数据表锁，其随后使用相同连接的脚本将会被永久的阻塞，使得您需要重新启动 httpd 服务或者数据库服务。另外，在使用事务处理时，如果脚本在事务阻塞产生前结束，则该阻塞也会影响到使用相同连接的下一个脚本。不管在什么情况下，您都可以通过使用 register_shutdown_function() 函数来注册一个简单的清理函数来打开数据表锁，或者滚回事务。或者更好的处理方法，是不在使用数据表锁或者事务处理的脚本中使用永久连接，这可以从根本上解决这个问题（当然您也可以在其它地方使用永久连接）。

以下是一点重要的总结。永久连接是为通常连接建立一对一的分布而设计的。这意味着您必须能够保证在将永久连接替换为非永久连接时，您脚本的行为不会改变。使用永久连接将（非常）有可能改变您脚本的效率，但不改变其行为！

请参阅 fbsql_pconnect(),
ibase_pconnect(), ifx_pconnect(),
imap_popen(), ingres_pconnect(),
msql_pconnect(), mssql_pconnect(),
mysql_pconnect(), OCIPLogon(),
odbc_pconnect(), Ora_pLogon(),
pfsockopen(), pg_pconnect() 及
sybase_pconnect().

后退 | 起点 | 前进
连接处理 | 上一级 | 安全模式


安全模式

PHP 手册
后退 前进

章 24. 安全模式

目录
被安全模式限制或屏蔽的函数

PHP 的安全模式是为了试图解决共享服务器（shared-server）安全问题而设立的。在结构上，试图在 PHP 层上解决这个问题是不合理的，但修改 WEB 服务器层和操作系统层显得非常不现实。因此许多人，特别是 ISP，目前使用安全模式。

表格 24-1. 控制安全模式的设置选项有：

设置选项 | 默认值
safe_mode | Off
safe_mode_gid | 0
safe_mode_include_dir | ""
safe_mode_exec_dir | 1
open_basedir | ""
safe_mode_allowed_env_vars | PHP_
safe_mode_protected_env_vars | LD_LIBRARY_PATH
disable_functions | ""

当 safe_mode 设置为 on，PHP 将检查当前脚本的拥有者是否和将被文件函数操作的文件的拥有者相匹配。例如：
-rw-rw-r--    1 rasmus   rasmus       33 Jul  1 19:20 script.php
-rw-r--r--    1 root     root       1116 May 26 18:01 /etc/passwd
运行 script.php
<?php
 readfile('/etc/passwd');
?>
如果安全模式被激活，则将会导致以下错误：
Warning: SAFE MODE Restriction in effect. The script whose uid is 500 is not
allowed to access /etc/passwd owned by uid 0 in /docroot/script.php on line 2

同时，或许会存在这样的环境，在该环境下，宽松的 GID 检查已经足够，但严格的 UID 检查反而是不适合的。您可以用 safe_mode_gid 选项来控制这种检查。如果设置为 On 则进行宽松的 GID 检查；设置为 Off（默认值）则进行 UID 检查。

除了 safe_mode 以外，如果您设置了 open_basedir 选项，则所有的文件操作将被限制在您指定的目录下。例如：
<Directory /docroot>
  php_admin_value open_basedir /docroot
</Directory>
如果您在设置了 open_basedir 选项后运行同样的 script.php，则其结果会是：
Warning: open_basedir restriction in effect. File is in wrong directory in
/docroot/script.php on line 2

您也可以单独地屏蔽某些函数。请注意 disable_functions 选项不能在 php.ini 文件外部使用，也就是说您无法在 httpd.conf 文件的按不同虚拟主机或不同目录的方式来屏蔽函数。 如果我们将如下内容加入到 php.ini 文件：
disable_functions readfile,system
则我们会得到如下的输出：
Warning: readfile() has been disabled for security reasons in
/docroot/script.php on line 2

被安全模式限制或屏蔽的函数

以下安全模式列表可能不完整或不正确。

表格 24-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 设置的目录下进行执行操作。基于某些原因，目前不能在可执行对象的路径中使用 ..。
system() | 您只能在 safe_mode_exec_dir 设置的目录下进行执行操作。基于某些原因，目前不能在可执行对象的路径中使用 ..。
passthru() | 您只能在 safe_mode_exec_dir 设置的目录下进行执行操作。基于某些原因，目前不能在可执行对象的路径中使用 ..。
popen() | 您只能在 safe_mode_exec_dir 设置的目录下进行执行操作。基于某些原因，目前不能在可执行对象的路径中使用 ..。
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）
getallheaders() | 在安全模式下，以“authorization”（区分大小写）开头的头信息将不会被返回。警告：getallheaders() 无法在 aol-server 下实现！
header() | 在安全模式下，如果您设置了 WWW-Authenticate，当前脚本的 uid 将被添加到该头信息的 realm 部分。
highlight_file(), show_source() | 将检查您将要操作的文件/目录与正在执行的脚本是否有相同的 UID。 将检查您将要操作的目录和正在执行的脚本是否有相同的 UID。 （注意，仅在 4.2.1 版本后有效）
parse_ini_file() | 将检查您将要操作的文件/目录与正在执行的脚本是否有相同的 UID。 将检查您将要操作的目录和正在执行的脚本是否有相同的 UID。 （注意，仅在 4.2.1 版本后有效）
任何使用 php4/main/fopen_wrappers.c 的函数 | ??

后退 | 起点 | 前进
数据库永久连接 | 上一级 | PHP 的命令行模式


PHP 的命令行模式

PHP 手册
后退 前进

章 25. PHP 的命令行模式

从版本 4.3 开始，PHP 提供了一种新类型的 SAPI（Server Application Programming Interface，服务端应用编程端口）支持，名为 CLI，意为 Command Line Interface，即命令行接口。顾名思义，该 SAPI 模块主要用作 PHP 的开发外壳应用。CLI SAPI 和其它 SAPI 模块相比有很多的不同之处，我们将在本章中详细阐述。

CLI SAPI 最先是随 PHP 4.2.0 版本发布的，但仍旧只是一个实验性的版本，并需要在运行 ./configure 时加上 --enable-cli 参数。从 PHP 4.3.0 版本开始，CLI SAPI 成为了正式模块，也因此将被永久地编译并安装为 PHP 二进制文件（即 Windows 下的 php.exe 文件）。

以下为 CLI SAPI 和其它 SAPI 模块相比的显著区别：

  • 与 CGI SAPI 不同，其输出没有任何头信息。

    尽管 CGI SAPI 提供了取消 HTTP 头信息的方法，但在 CLI SAPI 中并不存在类似的方法以开启 HTTP 头信息的输出。

    CLI 默认以安静模式开始，但为了保证兼容性， -q 参数使得您可以使用旧的 CGI 脚本。

    在运行时，不会把工作目录改为脚本的当前目录。（您可以使用 -C 参数来兼容 CGI 模式）。

    出错时输出纯文本的错误信息（非 HTML 格式）。

  • CLI SAPI 强制更改了 php.ini 中的某些设置，因为这些设置在外壳环境下是没有意义的。

    表格 25-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 | 在使用 CLI SAPI 时，PHP 的全局变量 $argc（传送给应用程序的参数的个数）及 $argv（实际参数的数组）将总是有效并被赋于对应的值。

    注: 这些设置无法在设置文件 php.ini 或任何指定的其它文件中被初始化为其它值。这些默认值被限制在所有其它的设置文件被解析后改变。不过，它们的值可以在程序运行的过程中被改变（尽管对于该运行过程来说，这些设置项是没有意义的）。

  • 为了减轻外壳环境下的工作，我们定义了如下常量：

    表格 25-2. CLI 专用常量

    常量名称 描 述
    STDIN 一个已打开的指向 stdin 的流。您可以用如下方法来调用：
    $stdin = fopen('php://stdin', 'r');
    STDOUT 一个已打开的指向 stdout 的流。您可以用如下方式来调用：
    $stdout = fopen('php://stdout', 'w');
    STDERR 一个已打开的指向 stdout 的流。您可以用如下方式来调用：
    $stderr = fopen('php://stderr', 'w');

    有了以上常量，您就无需自己建立指向诸如 stderr 的流，只需简单的使用这些常量来代替流指向：
    php -r 'fwrite(STDERR, "stderr\n");'
    您无需自己来关闭这些流，PHP 会自动完成这些操作。

  • CLI SAPI 不会将当前目录改为已运行的脚本所在的目录。

    以下范例显示了本模块与 CGI SAPI 模块之间的不同：
    <?php
    /* Our simple test application */
    echo getcwd(), "\n";
?>

    在使用 CGI 版本时，其输出为
    $ pwd
/tmp

$ php-cgi -f another_directory/test.php
/tmp/another_directory

    我们明显可以看到 PHP 将当前目录改成了刚刚运行过的脚本所在的目录。

    使用 CLI SAPI 模式，我们得到：
    $ pwd
/tmp

$ php -f another_directory/test.php
/tmp
    这使得我们在利用 PHP 编写外壳工具时获得了很大的便利。

    注: 您可以在命令行运行时给 CGI SAPI 加上 -C 参数，使其支持 CLI SAPI 的功能。

以下是 PHP 二进制文件（即 php.exe 程序）提供的命令行模式的选项参数，您随时可以通过 PHP -h 命令来查询这些参数。
Usage: php [options] [-f] <file> [args...]
       php [options] -r <code> [args...]
       php [options] [-- args...]
  -s               Display colour syntax highlighted source.
  -w               Display source with stripped comments and whitespace.
  -f <file>        Parse <file>.
  -v               Version number
  -c <path>|<file> Look for php.ini file in this directory
  -a               Run interactively
  -d foo[=bar]     Define INI entry foo with value 'bar'
  -e               Generate extended information for debugger/profiler
  -z <file>        Load Zend extension <file>.
  -l               Syntax check only (lint)
  -m               Show compiled in modules
  -i               PHP information
  -r <code>        Run PHP <code> without using script tags <?..?>
  -h               This help

  args...          Arguments passed to script. Use -- args when first argument
                   starts with - or script is read from stdin

CLI SAPI 模块有以下三种不同的方法来获取您要运行的 PHP 代码：

  1. 让 PHP 运行指定文件。

    php my_script.php

php -f my_script.php

    以上两种方法（使用或不使用 -f 参数）都能够运行给定的 my_script.php 文件。您可以选择任何文件来运行，您指定的 PHP 脚本并非必须要以 .php 为扩展名，它们可以有任意的文件名和扩展名。

  2. 在命令行直接运行 PHP 代码。

    php -r 'print_r(get_defined_constants());'

    在使用这种方法时，请您注意外壳变量的替代及引号的使用。

    注: 请仔细阅读以上范例，在运行代码时没有开始和结束的标记符！加上 -r 参数后，这些标记符是不需要的，加上它们会导致语法错误。

  3. 通过标准输入（stdin）提供需要运行的 PHP 代码。

    以上用法给我们提供了非常强大的功能，使得我们可以如下范例所示，动态地生成 PHP 代码并通过命令行运行这些代码：
    $ some_application | some_filter | php | sort -u >final_output.txt

以上三种运行代码的方法不能同时使用。

和所有的外壳应用程序一样，PHP 的二进制文件（php.exe 文件）及其运行的 PHP 脚本能够接受一系列的参数。PHP 没有限制传送给脚本程序的参数的个数（外壳程序对命令行的字符数有限制，但您通常都不会超过该限制）。传递给您脚本的参数可在全局变量 $argv 中获取。该数组中下标为零的成员为脚本的名称（当 PHP 代码来自标准输入获直接用 -r 参数以命令行方式运行时，该名称为“-”）。另外，全局变量 $argc 存有 $argv 数组中成员变量的个数（而非传送给脚本程序的参数的个数）。

只要您传送给您脚本的参数不是以 - 符号开头，您就无需过多的注意什么。向您的脚本传送以 - 开头的参数会导致错误，因为 PHP 会认为应该由它自身来处理这些参数。您可以用参数列表分隔符 -- 来解决这个问题。在 PHP 解析完参数后，该符号后所有的参数将会被原样传送给您的脚本程序。

# 以下命令将不会运行 PHP 代码，而只显示 PHP 命令行模式的使用说明：
$ php -r 'var_dump($argv);' -h
Usage: php [options] [-f] <file> [args...]
[...]

# 以下命令将会把“-h”参数传送给脚本程序，PHP 不会显示命令行模式的使用说明：
$ php -r 'var_dump($argv);' -- -h
array(2) {
  [0]=>
  string(1) "-"
  [1]=>
  string(2) "-h"
}

除此之外，我们还有另一个方法将 PHP 用于外壳脚本。您可以在写一个脚本，并在第一行以 #!/usr/bin/php 开头，在其后加上以 PHP 开始和结尾标记符包含的正常的 PHP 代码，然后为该文件设置正确的运行属性。该方法可以使得该文件能够像外壳脚本或 PERL 脚本一样被直接执行。
#!/usr/bin/php
<?php
    var_dump($argv);
?>

假设改文件名为 test 并被放置在当前目录下，我们可以做如下操作：
$ chmod 755 test
$ ./test -h -- foo
array(4) {
  [0]=>
  string(6) "./test"
  [1]=>
  string(2) "-h"
  [2]=>
  string(2) "--"
  [3]=>
  string(3) "foo"
}

正如您所看到的，在您向该脚本传送以 - 开头的参数时，脚本仍然能够正常运行。

表格 25-3. 命令行选项

选项名称 | 描 述
-s

显示有语法高亮色彩的源文件。

该参数使用内建机制来解析文件并为其生成一个 HTML 高亮版本并将结果写到标准输出。请注意该过程所做的只是生成了一个 <code> [...] </code> 的 HTML 标记符块，并不包含任何的 HTML 头。

注: 该选项不能和 -r 参数同时使用。

-w

显示除去了注释和空格的源代码。

注: 该选项不能和 -r 参数同时使用。

-f

解析并运行给定的文件名。该参数为可选参数且可以不加，仅指明需要运行的文件名即可。

-v

将 PHP、PHP SAPI 及 Zend 的版本信息写入的标准输出。例如：
$ php -v
PHP 4.3.0-dev (cli), Copyright (c) 1997-2002 The PHP Group
Zend Engine v1.2.1, Copyright (c) 1998-2002 Zend Technologies

-c

用该参数，您可以指定一个放置 php.ini 文件的目录，或者直接指定一个自定义的 INI 文件，其文件名可以不是 php.ini。例如：
$ php -c /custom/directory/ my_script.php

$ php -c /custom/directory/custom-file.ini my_script.php

-a

交互地运行 PHP。

-d

用该参数可以自行设置 php.ini 文件中设置变量的值，其语法为：
-d configuration_directive[=value]

范例：
# Ommiting the value part will set the given configuration directive to "1"
$ php -d max_execution_time -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(1) "1"

# Passing an empty value part will set the configuration directive to ""
php -d max_execution_time= -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(0) ""

# The configuration directive will be set to anything passed after the '=' character
$  php -d max_execution_time=20 -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(2) "20"
$  php -d max_execution_time=doesntmakesense -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(15) "doesntmakesense"

-e

为调试器等生成扩展信息。

-z

加载 Zend 扩展库。如果仅给定一个文件名，PHP 将试图从您系统扩展库的默认路径（在 Linux 系统下，该路径通常由 /etc/ld.so.conf 指定）加载该扩展库。如果您用一个绝对路径指定文件名，则系统的扩展库默认路径将不会被使用。如果用相对路径指定的文件名，PHP 则仅试图加载相对于当前目录的扩展库。

-l

该参数提供了对指定 PHP 代码进行语法检查的方便的方法。如果成功，则向标准输出写入 No syntax errors detected in <filename> 字符串，并且外壳返回值为 0。如果失败，则 Errors parsing <filename> 以及内部解析器错误信息会一起被写入到标准输出，同时外壳返回值将别设置为 255。

该参数将无法检查致命错误（如未定义函数），如果您希望检测之名错误，请使用 -f 参数。

注: 该参数不能和 -r 一同使用。

-m

使用该参数，PHP 将打印出内置以及已加载的 PHP 及 Zend 模块：
$ php -m
[PHP Modules]
xml
tokenizer
standard
session
posix
pcre
overload
mysql
mbstring
ctype

[Zend Modules]

-i | 该命令行参数会调用 phpinfo() 函数，并打印出结果。如果 PHP 没有正常工作，我们建议您执行 php -i 命令来查看在信息表格之前或者对应的地方是否有任何错误信息输出。请注意输出的内容为 HTML 格式，因此输出的信息篇幅较大。
-r

使用该参数可以在命令行运行 PHP 代码。您无需加上 PHP 的起始和结束标识符（<?php 和 ?>），否则将会导致语法解析错误。

注: 使用这种形式的 PHP 时，应个别注意避免和外壳环境进行的命令行参数替换相冲突。

显示语法解析错误的范例
$ php -r "$foo = get_defined_constants();"
Command line code(1) : Parse error - parse error, unexpected '='

这里的问题在于即时使用了双引号 "，sh/bash 仍然实行了参数替换。由于 $foo 没有被定义，被替换后它所在的位置变成了空字符，因此在运行时，实际被 PHP 读取的代码为：
$ php -r " = get_defined_constants();"

正确的方法是使用单引号 '。在用单引号引用的字符串中，变量不会被 sh/bash 还原成其原值。
$ php -r '$foo = get_defined_constants(); var_dump($foo);'
array(370) {
  ["E_ERROR"]=>
  int(1)
  ["E_WARNING"]=>
  int(2)
  ["E_PARSE"]=>
  int(4)
  ["E_NOTICE"]=>
  int(8)
  ["E_CORE_ERROR"]=>
  [...]

如果您使用的外壳不是 sh/bash，您可能会碰到其它的问题。请报告您碰到的 bug，或者发邮件到 phpdoc@lists.php.net。

当您试图将外壳的环境变量引入到马或者用反斜线来转义字符时也可能碰到各种各样的问题，请您在使用时注意！

-h | 使用该参数，您可以得到完整的命令行参数的列表及这些参数作用的简单描述。

PHP 的命令行模式能使得 PHP 脚本能完全独立于 WEB 服务器单独运行。如果您使用 Unix 系统，您需要在您的 PHP 脚本的最前面加上一行特殊的代码，使得它能够被执行，这样系统就能知道用什么样的程序要运行该脚本。在 Windows 平台下您可以将 php.exe 和 .php 文件的双击属性相关联，您也可以编写一个批处理文件来用 PHP 执行脚本。为 Unix 系统增加的第一行代码不会影响该脚本在 Windows 下的运行，因此您也可以用该方法编写跨平台的脚本程序。以下是一个简单的PHP 命令行程序的范例。

例子 25-1. 试图以命令行方式运行的 PHP 脚本（script.php）

#!/usr/bin/php
<?php

if ($argc != 2 || in_array($argv[1], array('--help', '-help', '-h', '-?'))) {
?>

This is a command line PHP script with one option.

  Usage:
  <?php echo $argv[0]; ?> <option>

  <option> can be some word you would like
  to print out. With the --help, -help, -h,
  or -? options, you can get this help.

<?php
} else {
    echo $argv[1];
}
?>

在以上脚本中，我们用第一行特殊的代码来指明该文件应该由 PHP 来执行。我们在这里使用 CLI 的版本，因此不会有 HTTP 头信息输出。在您用 PHP 编写命令行应用程序时，您可以使用两个参数：$argc 和 $argv。前面一个的值是比参数个数大 1 的整数（运行的脚本本身的名称也被当作一个参数）。第二个时包含有参数的数组，其第一个元素为脚本的名称，下标为数字 0（$argv[0]）。

在以上程序中我们检查了参数的个数是大于 1 个还是小于 1 个。即时参数是 --help、-help、-h 或 -?，我们仍然打印出帮助信息，并同时动态输出脚本的名称。如果还收到了其它参数，我们也把它们显示出来。

如果您希望在 Unix 下运行以上脚本，您需要使得它成为可执行脚本，然后简单的运行 script.php echothis 或 script.php -h。在 Windows 下，您可以为此编写一个批处理文件：

例子 25-2. 运行 PHP 命令行脚本的批处理文件（script.bat）

@c:\php\php.exe script.php %1 %2 %3 %4

假设您将上述程序命名为 script.php，且您的 php.exe 文件放置在 c:\php\php.exe，该批处理文件会帮助您将附加的参数传给脚本程序： script.bat echothis 或 script.bat -h。

请参阅 Readline 扩展模块的有关文档，以获取更多的函数的信息。这些函数可以帮助您完善您的 PHP 命令行应用程序。

后退 | 起点 | 前进
安全模式 | 上一级 | 函数参考


函数参考

PHP 手册
后退 前进

IV. 函数参考

目录
I. Apache 专用函数
II. 数组函数库
III. Aspell functions [deprecated]
IV. BCMath Arbitrary Precision Mathematics Functions
V. Bzip2 Compression Functions
VI. Calendar functions
VII. CCVS API Functions
VIII. COM support functions for Windows
IX. Class/Object Functions
X. ClibPDF functions
XI. Crack functions
XII. CURL, Client URL Library Functions
XIII. Cybercash payment functions
XIV. Crédit Mutuel CyberMUT functions
XV. Cyrus IMAP administration functions
XVI. Character type functions
XVII. Database (dbm-style) abstraction layer functions
XVIII. 时间日期函数库
XIX. dBase functions
XX. DBM Functions
XXI. dbx functions
XXII. DB++ Functions
XXIII. Direct IO functions
XXIV. Directory functions
XXV. DOM XML functions
XXVI. .NET functions
XXVII. Error Handling and Logging Functions
XXVIII. FrontBase Functions
XXIX. filePro functions
XXX. Filesystem functions
XXXI. Forms Data Format functions
XXXII. FriBiDi functions
XXXIII. FTP functions
XXXIV. Function Handling functions
XXXV. Gettext
XXXVI. GMP functions
XXXVII. HTTP functions
XXXVIII. Hyperwave functions
XXXIX. Hyperwave API functions
XL. iconv functions
XLI. Image functions
XLII. IMAP, POP3 and NNTP functions
XLIII. Informix functions
XLIV. InterBase functions
XLV. Ingres II functions
XLVI. IRC Gateway Functions
XLVII. PHP / Java Integration
XLVIII. LDAP functions
XLIX. Mail functions
L. mailparse functions
LI. Mathematical Functions
LII. Multi-Byte String Functions
LIII. MCAL functions
LIV. Mcrypt Encryption Functions
LV. Mhash Functions
LVI. Mimetype Functions
LVII. Microsoft SQL Server functions
LVIII. Ming functions for Flash
LIX. Miscellaneous functions
LX. mnoGoSearch Functions
LXI. mSQL functions
LXII. MySQL 函数库
LXIII. Mohawk Software session handler functions
LXIV. muscat functions
LXV. Network Functions
LXVI. Ncurses terminal screen control functions
LXVII. Lotus Notes functions
LXVIII. Unified ODBC functions
LXIX. Object Aggregation/Composition Functions
LXX. Oracle 8 functions
LXXI. OpenSSL functions
LXXII. Oracle functions
LXXIII. Ovrimos SQL functions
LXXIV. Output Control Functions
LXXV. Object property and method call overloading
LXXVI. PDF functions
LXXVII. Verisign Payflow Pro functions
LXXVIII. PHP Options&Information
LXXIX. POSIX functions
LXXX. PostgreSQL 数据库函数库
LXXXI. Process Control Functions
LXXXII. Program Execution functions
LXXXIII. Printer functions
LXXXIV. Pspell Functions
LXXXV. GNU Readline
LXXXVI. GNU Recode functions
LXXXVII. Regular Expression Functions (Perl-Compatible)
LXXXVIII. qtdom functions
LXXXIX. Regular Expression Functions (POSIX Extended)
XC. Semaphore, Shared Memory and IPC Functions
XCI. SESAM database functions
XCII. Session handling functions
XCIII. Shared Memory Functions
XCIV. Shockwave Flash functions
XCV. SNMP functions
XCVI. Socket functions
XCVII. String functions
XCVIII. Sybase functions
XCIX. Tokenizer functions
C. URL Functions
CI. Variable Functions
CII. vpopmail functions
CIII. W32api functions
CIV. WDDX Functions
CV. XML 语法解析函数
CVI. XML-RPC functions
CVII. XSLT functions
CVIII. YAZ functions
CIX. YP/NIS Functions
CX. Zip File Functions (Read Only Access)
CXI. Zlib Compression Functions

后退 | 起点 | 前进
PHP 的命令行模式 |  | Apache 专用函数


Apache 专用函数

PHP 手册
后退 前进

I. Apache 专用函数

介绍

这些函数仅在 PHP 作为 Apache 1.x 的模块运行时可用。

安装

PHP 在 Apache 1.x 下的安装见安装一章中的 Apache 服务器一节。

运行时配置

Apache 的 PHP 模块的行为受 php.ini 的设置影响。在 php.ini 中的设置可以被服务器配置文件或本地的 .htaccess 文件所覆盖。

例子 1. 用 .htaccess 禁用一个目录的 PHP 解析

php_flag engine off

表格 1. Apache 配置选项

名称 | 默认值 | 作用范围 | 功能
engine | On | PHP_INI_ALL | 启用或禁用 PHP 解析
child_terminate | Off | PHP_INI_ALL | 指定 PHP 脚本是否可以要求子进程在请求结束时终止，参见 apache_child_terminate()
last_modified | Off | PHP_INI_ALL | 在此请求中将 PHP 脚本的最后修改时间以头信息 Last-Modified: 的形式发送
xbit_hack | Off | PHP_INI_ALL | 让 PHP 不管文件是否结束而将文件作为可执行的比特集来解析

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

目录
apache_child_terminate — Terminate apache process after this request
apache_lookup_uri — 为指定的URI执行部分请求并且返回信息有关URI的
apache_note — Get and set apache request notes
apache_request_headers — Fetch all HTTP request headers
apache_response_headers — Fetch all HTTP response headers
apache_setenv — Set an Apache subprocess_env variable
ascii2ebcdic — Translate string from ASCII to EBCDIC
ebcdic2ascii — Translate string from EBCDIC to ASCII
getallheaders — Fetch all HTTP request headers
virtual — Perform an Apache sub-request

后退 | 起点 | 前进
函数参考 | 上一级 | apache_child_terminate


apache_child_terminate

(PHP 4 >= 4.0.5)

apache_child_terminate -- Terminate apache process after this request

Description

bool apache_child_terminate ( void)

apache_child_terminate() will register the Apache process executing the current PHP request for termination once execution of PHP code it is completed. It may be used to terminate a process after a script with high memory consumption has been run as memory will usually only be freed internally but not given back to the operating system.

注: The availability of this feature is controlled by the php.ini directive apache.child_terminate, which is set to off by default.

This feature is also not available on multithreaded versions of apache like the win32 version.

See also exit().

后退 | 起点 | 前进
Apache 专用函数 | 上一级 | apache_lookup_uri


apache_lookup_uri

(PHP 3>= 3.0.4, PHP 4 )

apache_lookup_uri -- 为指定的URI执行部分请求并且返回信息有关URI的

描述

object apache_lookup_uri ( string filename)

这是URI返回的部分请求. 这里能获得足够的重要的信息关于资源的类别并且返回信息。返回的属性class是:

状态（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

注: apache_lookup_uri() 只工作在PHP的apache的模块下

后退 | 起点 | 前进
apache_child_terminate | 上一级 | apache_note


apache_note

(PHP 3>= 3.0.2, PHP 4 )

apache_note -- Get and set apache request notes

Description

string apache_note ( string note_name [, string note_value])

apache_note() is an Apache-specific function which gets and sets values in a request's notes table. If called with one argument, it returns the current value of note note_name. If called with two arguments, it sets the value of note note_name to note_value and returns the previous value of note note_name.

后退 | 起点 | 前进
apache_lookup_uri | 上一级 | apache_request_headers


apache_request_headers

(PHP 4 CVS only)

apache_request_headers -- Fetch all HTTP request headers

Description

array apache_request_headers ( void)

apache_request_headers() returns an associative array of all the HTTP headers in the current request. This is only supported when PHP runs as an Apache module.

注:
      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().

例子 1. apache_request_headers() Example

<?php
$headers = apache_request_headers();

foreach ($headers as $header => $value) {
    echo "$header: $value <br />\n";
}
?>

注: 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.

后退 | 起点 | 前进
apache_note | 上一级 | apache_response_headers


apache_response_headers

(PHP 4 CVS only)

apache_response_headers -- Fetch all HTTP response headers

Description

array apache_response_headers ( void)

Returns an array of all Apache response headers. This functionality is only available in PHP version 4.3.0 and greater.

See also getallheaders() and headers_sent().

后退 | 起点 | 前进
apache_request_headers | 上一级 | apache_setenv


apache_setenv

(PHP 4 >= 4.2.0)

apache_setenv -- Set an Apache subprocess_env variable

Description

int apache_setenv ( string variable, string value [, bool walk_to_top])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
apache_response_headers | 上一级 | ascii2ebcdic


ascii2ebcdic

(PHP 3>= 3.0.17)

ascii2ebcdic -- Translate string from ASCII to EBCDIC

Description

int ascii2ebcdic ( string ascii_str)

ascii2ebcdic() is an Apache-specific function which is available only on EBCDIC based operating systems (OS/390, BS2000). It translates the ASCII encoded string ascii_str to its equivalent EBCDIC representation (binary safe), and returns the result.

See also the reverse function ebcdic2ascii()

后退 | 起点 | 前进
apache_setenv | 上一级 | ebcdic2ascii


ebcdic2ascii

(PHP 3>= 3.0.17)

ebcdic2ascii -- Translate string from EBCDIC to ASCII

Description

int ebcdic2ascii ( string ebcdic_str)

ebcdic2ascii() is an Apache-specific function which is available only on EBCDIC based operating systems (OS/390, BS2000). It translates the EBCDIC encoded string ebcdic_str to its equivalent ASCII representation (binary safe), and returns the result.

See also the reverse function ascii2ebcdic()

后退 | 起点 | 前进
ascii2ebcdic | 上一级 | getallheaders


getallheaders

(PHP 3, PHP 4 )

getallheaders -- Fetch all HTTP request headers

Description

array getallheaders ( void)

getallheaders() is an alias for apache_request_headers(). It will return an associative array of all the HTTP headers in the current request. Please read the apache_request_headers() documentation for more information on how this function works.

注: In PHP 4.3.0, getallheaders() became an alias for apache_request_headers(). Essentially, it was renamed. This is because this function only works when PHP is compiled as an Apache Module.

See also apache_request_headers().

后退 | 起点 | 前进
ebcdic2ascii | 上一级 | virtual


virtual

(PHP 3, PHP 4 )

virtual -- Perform an Apache sub-request

Description

int virtual ( string filename)

virtual() is an Apache-specific function which is equivalent to <!--#include virtual...--> in mod_include. It performs an Apache sub-request. It is useful for including CGI scripts or .shtml files, or anything else that you would parse through Apache. Note that for a CGI script, the script must generate valid CGI headers. At the minimum that means it must generate a Content-type header. For PHP files, you need to use include() or require(); virtual() cannot be used to include a document which is itself a PHP file.

To run the sub-request, all buffers are terminated and flushed to the browser, pending headers are sent too.

后退 | 起点 | 前进
getallheaders | 上一级 | 数组函数库


数组函数库

PHP 手册
后退 前进

II. 数组函数库

介绍

这些函数允许你用多种方法来操作数组和与之交互。数组的本质是储存，管理和操作一组变量。

PHP 支持一维和多维数组，不论是用户创建或由另一个函数创建。有一些特定的数据库处理函数可以从数据库查询中生成数组，还有一些函数返回数组。

参见手册中的数组一节关于 PHP 是怎样实现和使用数组的详细解释。

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

这些函数作为 PHP 核心的一部分，无需被安装即可使用。

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

这里列出的所有常量将作为 PHP 核心的一部分一直有效。

CASE_LOWER (integer)

CASE_LOWER 用在 array_change_key_case() 中将数组的键名转换成小写字母。这也是 array_change_key_case() 的默认值。

CASE_UPPER (integer)

CASE_UPPER 用在 array_change_key_case() 中将数组的键名转换成大写字母。

相关参考

参见 is_array()，explode()，implode()，split()，preg_split() 和 join()。

【译者注】本节中出现的“结合数组”指的是键名为字符串的数组，“索引”和“键名”指的是同一样东西。

目录
array_change_key_case — 返回字符串键名全为小写或大写的数组
array_chunk — 将一个数组分割成多个
array_count_values — 统计数组中所有的值出现的次数
array_diff — 计算数组的差集
array_fill — 用给定的值填充数组
array_filter — 用回调函数过滤数组中的单元
array_flip — 反转数组中的键和值
array_intersect — 计算数组的交集
array_key_exists — 检查给定的键名或索引是否存在于数组中
array_keys — 返回数组中所有的键名
array_map — 将回调函数作用到给定数组的单元上
array_merge_recursive — 递归地合并两个或多个数组
array_merge — 合并两个或多个数组
array_multisort — 对多个数组或多维数组进行排序
array_pad — 用值将数组填补到指定长度
array_pop — 将数组最后一个单元弹出（出栈）
array_push — 将一个或多个单元压入数组的末尾（入栈）
array_rand — 从数组中随机取出一个或多个单元
array_reduce — 用回调函数迭代地将数组简化为单一的值
array_reverse — 返回一个单元顺序相反的数组
array_search — 在数组中搜索给定的值，如果成功则返回相应的键名
array_shift — 将数组开头的单元移出数组
array_slice — 从数组中取出一段
array_splice — 把数组中的一部分去掉并用其它值取代
array_sum — 计算数组中所有值的和
array_unique — 移除数组中重复的值
array_unshift — 在数组开头插入一个或多个单元
array_values — 返回数组中所有的值
array_walk — 对数组中的每个成员应用用户函数
array — 新建一个数组
arsort — 对数组进行逆向排序并保持索引关系
asort — 对数组进行排序并保持索引关系
compact — 建立一个数组，包括变量名和它们的值
count — 统计变量中的单元数目
current — 返回数组中的当前单元
each — 返回数组中当前的键／值对并将数组指针向前移动一步
end — 将数组的内部指针指向最后一个单元
extract — 从数组中将变量导入到当前的符号表
in_array — 如果数组中存在该值则返回 TRUE
key — 从结合数组中取得键名
krsort — 对数组按照键名逆向排序
ksort — 对数组按照键名排序
list — 把数组中的值赋给一些变量
natcasesort — 用“自然排序”算法对数组进行不区分大小写字母的排序
natsort — 用“自然排序”算法对数组排序
next — 将数组中的内部指针向前移动一位
pos — 得到数组当前的单元
prev — 将数组的内部指针倒回一位
range — 建立一个包含指定范围单元的数组
reset — 将数组的内部指针指向第一个单元
rsort — 对数组逆向排序
shuffle — 将数组打乱
sizeof — 统计变量中的单元数目
sort — 对数组排序
uasort — 使用用户自定义的比较函数对数组中的值进行排序并保持索引关联
uksort — 使用用户自定义的比较函数对数组中的键名进行排序
usort — 使用用户自定义的比较函数对数组中的值进行排序

后退 | 起点 | 前进
virtual | 上一级 | array_change_key_case


array_change_key_case

(PHP 4 >= 4.2.0)

array_change_key_case -- 返回字符串键名全为小写或大写的数组

说明

array array_change_key_case ( array input [, int case])

array_change_key_case() 将 input 数组中的所有键名改为全小写或大写。改变是根据后一个选项 case 参数来进行的。可以在这里用两个常量，CASE_UPPER 和 CASE_LOWER。默认值是 CASE_LOWER。本函数不改变数字索引。

例子 1. array_change_key_case() 例子

$input_array = array("FirSt" => 1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));

以上程序显示结果为：
Array
(
    [FIRST] => 1
    [SECOND] => 2
)

后退 | 起点 | 前进
数组函数库 | 上一级 | array_chunk


array_chunk

(PHP 4 >= 4.2.0)

array_chunk -- 将一个数组分割成多个

说明

array array_chunk ( array input, int size [, bool preserve_keys])

array_chunk() 将一个数组分割成多个数组，其中每个数组的单元数目由 size 决定。最后一个数组的单元数目可能会少几个。得到的数组是一个多维数组中的单元，其索引从零开始。

将可选参数 preserve_keys 设为 TRUE，可以使 PHP 保留输入数组中原来的键名。如果你指定了 FALSE，那每个结果数组将用从零开始的新数字索引。默认值是 FALSE。

例子 1. array_chunk() 例子

$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, TRUE));

以上程序输出为：
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [2] => c
            [3] => d
        )

    [2] => Array
        (
            [4] => e
        )

)

后退 | 起点 | 前进
array_change_key_case | 上一级 | array_count_values


array_count_values

(PHP 4 )

array_count_values -- 统计数组中所有的值出现的次数

说明

array array_count_values ( array input)

array_count_values() 返回一个数组，该数组用 input 数组中的值作为键名，该值在 input 数组中出现的次数作为值。

例子 1. array_count_values() 例子

$array = array (1, "hello", 1, "world", "hello");
print_r(array_count_values ($array));

以上程序输出为：
Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

后退 | 起点 | 前进
array_chunk | 上一级 | array_diff


array_diff

(PHP 4 >= 4.0.1)

array_diff -- 计算数组的差集

说明

array array_diff ( array array1, array array2 [, array ...])

array_diff() 返回一个数组，该数组包括了所有在 array1 中但是不在任何其它参数数组中的值。注意键名保留不变。

例子 1. array_diff() 例子

$array1 = array ("a" => "green", "red", "blue", "red");
$array2 = array ("b" => "green", "yellow", "red");
$result = array_diff ($array1, $array2);

这使得 $result 成为 array (1 => "blue");。在 $array1 中多次出现的值同样对待。

注: 两个单元仅在 (string) $elem1 === (string) $elem2 时被认为是相同的。也就是说，当字符串的表达是一样的时候。

注: 注意此函数仅检查多维数组中的一维。当然你可以用 array_diff($array1[0], $array2[0]); 检查更深的维度。

警告

本函数在 PHP 4.0.4 中是坏的！

参见 array_intersect()。

后退 | 起点 | 前进
array_count_values | 上一级 | array_fill


array_fill

(PHP 4 >= 4.2.0)

array_fill -- 用给定的值填充数组

说明

array array_fill ( int start_index, int num, mixed value)

array_fill() 用 value 参数的值将一个数组填充 num 个条目，键名由 start_index 参数指定的开始。

例子 1. array_fill() 例子

$a = array_fill(5, 6, 'banana');

用 print_r() 查看 $a 显示如下：
Array
(
    [5]  => banana
    [6]  => banana
    [7]  => banana
    [8]  => banana
    [9]  => banana
    [10] => banana
)

后退 | 起点 | 前进
array_diff | 上一级 | array_filter


array_filter

(PHP 4 >= 4.0.6)

array_filter -- 用回调函数过滤数组中的单元

说明

array array_filter ( array input [, mixed callback])

array_filter() 返回一个数组，该数组包含了 input 数组经过回调函数过滤后的所有单元。如果 input 是一个结合数组，则键名保留。

例子 1. array_filter() 例子

function odd($var) {
    return ($var % 2 == 1);
}

function even($var) {
    return ($var % 2 == 0);
}

$array1 = array ("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array (6, 7, 8, 9, 10, 11, 12);

echo "Odd :\n";
print_r(array_filter($array1, "odd"));
echo "Even:\n";
print_r(array_filter($array2, "even"));

以上程序的输出为：
Odd :
Array
(
    [a] => 1
    [c] => 3
    [e] => 5
)
Even:
Array
(
    [0] => 6
    [2] => 8
    [4] => 10
    [6] => 12
)

注: 第二个参数函数名可以替换为一个数组，该数组由一个对象名和该对象名的一个方法名两个元素组成。

用户不应在回调函数中修改数组本身。例如增加／删除单元或者对 array_filter() 正在作用的数组进行 unset。如果数组改变了，此函数的行为没有定义。

参见 array_map() 和 array_reduce()。

后退 | 起点 | 前进
array_fill | 上一级 | array_flip


array_flip

(PHP 4 )

array_flip -- 反转数组中的键和值

说明

array array_flip ( array trans)

array_flip() 返回一个反转后的 array，例如 trans 中的键名变成了值，而 trans 中的值成了键名。

注意 trans 中的值需要能够作为合法的键名，例如需要是 integer 或者 string。如果值的类型不对将发出一个警告，并且有问题的键／值对将不会反转。

如果同一个值出现了多次，则最后一个键名将作为它的值，所有其它的都丢失了。

array_flip() 如果失败返回 FALSE。

例子 1. array_flip() 例子

$trans = array_flip ($trans);
$original = strtr ($str, $trans);

例子 2. array_flip() 例子：冲突

$trans = array ("a" => 1, "b" => 1, "c" => 2);
$trans = array_flip ($trans);
print_r($trans);

现在 $trans 变成了：
Array
(
    [1] => b
    [2] => c
)

后退 | 起点 | 前进
array_filter | 上一级 | array_intersect


array_intersect

(PHP 4 >= 4.0.1)

array_intersect -- 计算数组的交集

说明

array array_intersect ( array array1, array array2 [, array ...])

array_intersect() 返回一个数组，该数组包含了所有在 array1 中也同时出现在所有其它参数数组中的值。注意键名保留不变。

例子 1. array_intersect() 例子

$array1 = array ("a" => "green", "red", "blue");
$array2 = array ("b" => "green", "yellow", "red");
$result = array_intersect ($array1, $array2);

这使得 $result 成为：
Array
(
    [a] => green
    [0] => red
)

注: 两个单元仅在 (string) $elem1 === (string) $elem2 时被认为是相同的。也就是说，当字符串的表达是一样的时候。

警告

本函数在 PHP 4.0.4 中是坏的！

参见 array_diff()。

后退 | 起点 | 前进
array_flip | 上一级 | array_key_exists


array_key_exists

(PHP 4 >= 4.1.0)

array_key_exists -- 检查给定的键名或索引是否存在于数组中

说明

bool array_key_exists ( mixed key, array search)

array_key_exists() 在给定的 key 存在于数组中时返回 TRUE。key 可以是任何能作为数组索引的值。

例子 1. array_key_exists() 例子

$search_array = array("first" => 1, "second" => 4);
if (array_key_exists("first", $search_array)) {
    echo "The 'first' element is in the array";
}

注: 在 PHP 4.0.6 中本函数名为 key_exists()。

参见 isset()。

后退 | 起点 | 前进
array_intersect | 上一级 | array_keys


array_keys

(PHP 4 )

array_keys -- 返回数组中所有的键名

说明

array array_keys ( array input [, mixed search_value])

array_keys() 返回 input 数组中的数字或者字符串的键名。

如果指定了可选参数 search_value，则只返回该值的键名。否则 input 数组中的所有键名都会被返回。

例子 1. array_keys() 例子

$array = array (0 => 100, "color" => "red");
print_r(array_keys ($array));

$array = array ("blue", "red", "green", "blue", "blue");
print_r(array_keys ($array, "blue"));

$array = array ("color" => array("blue", "red", "green"),
                "size" => array("small", "medium", "large"));
print_r(array_keys ($array));

以上程序输出为：
Array
(
    [0] => 0
    [1] => color
)
Array
(
    [0] => 0
    [1] => 3
    [2] => 4
)
Array
(
    [0] => color
    [1] => size
)

注: 本函数是 PHP 4 新增的，下面是仍在使用 PHP 3 的用户的实现方法：

例子 2. array_keys() 在 PHP 3 中的实现

function array_keys ($arr, $term="") {
    $t = array();
    while (list($k,$v) = each($arr)) {
        if ($term && $v != $term) {
            continue;
        }
        $t[] = $k;
    }
    return $t;
}

参见 array_values()。

后退 | 起点 | 前进
array_key_exists | 上一级 | array_map


array_map

(PHP 4 >= 4.0.6)

array_map -- 将回调函数作用到给定数组的单元上

说明

array array_map ( mixed callback, array arr1 [, array arr2...])

array_map() 返回一个数组，该数组包含了 arr1 中的所有单元经过回调函数作用过之后的单元。回调函数接受的参数数目应该和传递给 array_map() 函数的数组数目一致。

例子 1. array_map() 例子

function cube($n) {
    return $n*$n*$n;
}

$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);

这使得 $b 成为：
Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
)

例子 2. array_map() - 使用更多的数组

function show_Spanish($n, $m) {
    return "The number $n is called $m in Spanish";
}

function map_Spanish($n, $m) {
    return array ($n => $m);
}

$a = array(1, 2, 3, 4, 5);
$b = array("uno", "dos", "tres", "cuatro", "cinco");

$c = array_map("show_Spanish", $a, $b);
print_r($c);

$d = array_map("map_Spanish", $a , $b);
print_r($d);

结果为：
// printout of $c
Array
(
    [0] => The number 1 is called uno in Spanish
    [1] => The number 2 is called dos in Spanish
    [2] => The number 3 is called tres in Spanish
    [3] => The number 4 is called cuatro in Spanish
    [4] => The number 5 is called cinco in Spanish
)

// printout of $d
Array
(
    [0] => Array
        (
            [1] => uno
        )

    [1] => Array
        (
            [2] => dos
        )

    [2] => Array
        (
            [3] => tres
        )

    [3] => Array
        (
            [4] => cuatro
        )

    [4] => Array
        (
            [5] => cinco
        )

)

通常使用了两个或更多数组时，它们的长度应该相同，因为回调函数是平行作用于相应的单元上的。如果数组的长度不同，则最短的一个将被用空的单元扩充。

本函数一个有趣的用法是构造一个数组的数组，这可以很容易的通过用 NULL 作为回调函数名来实现。

例子 3. 建立一个数组的数组

$a = array(1, 2, 3, 4, 5);
$b = array("one", "two", "three", "four", "five");
$c = array("uno", "dos", "tres", "cuatro", "cinco");

$d = array_map(null, $a, $b, $c);
print_r($d);

以上程序输出为：
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => one
            [2] => uno
        )

    [1] => Array
        (
            [0] => 2
            [1] => two
            [2] => dos
        )

    [2] => Array
        (
            [0] => 3
            [1] => three
            [2] => tres
        )

    [3] => Array
        (
            [0] => 4
            [1] => four
            [2] => cuatro
        )

    [4] => Array
        (
            [0] => 5
            [1] => five
            [2] => cinco
        )

)

参见 array_filter() 和 array_reduce()。

后退 | 起点 | 前进
array_keys | 上一级 | array_merge_recursive


array_merge_recursive

(PHP 4 >= 4.0.1)

array_merge_recursive -- 递归地合并两个或多个数组

说明

array array_merge_recursive ( array array1, array array2 [, array ...])

array_merge_recursive() 将两个或多个数组的单元合并起来，一个数组中的值附加在前一个数组的后面。返回作为结果的数组。

如果输入的数组中有相同的字符串键名，则这些值会被合并到一个数组中去，这将递归下去，因此如果一个值本身是一个数组，本函数将按照相应的条目把它合并为另一个数组。然而，如果数组具有相同的数组键名，后一个值将不会覆盖原来的值，而是附加到后面。

例子 1. array_merge_recursive() 例子

$ar1 = array ("color" => array ("favorite" => "red"), 5);
$ar2 = array (10, "color" => array ("favorite" => "green", "blue"));
$result = array_merge_recursive ($ar1, $ar2);

$result 成为：
Array
(
    [color] => Array
        (
            [favorite] => Array
                (
                    [0] => red
                    [1] => green
                )

            [0] => blue
        )

    [0] => 5
    [1] => 10
)

参见 array_merge()。

后退 | 起点 | 前进
array_map | 上一级 | array_merge


array_merge

(PHP 4 )

array_merge -- 合并两个或多个数组

说明

array array_merge ( array array1, array array2 [, array ...])

array_merge() 将两个或多个数组的单元合并起来，一个数组中的值附加在前一个数组的后面。返回作为结果的数组。

如果输入的数组中有相同的字符串键名，则该键名后面的值将覆盖前一个值。然而，如果数组包含数字键名，后面的值将不会覆盖原来的值，而是附加到后面。

例子 1. array_merge() 例子

$array1 = array ("color" => "red", 2, 4);
$array2 = array ("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge ($array1, $array2);

$result 成为：
Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)

例子 2. 简单的 array_merge() 例子

$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);

别忘了数字键名将会被重新编号！
Array
(
    [0] => data
)

如果你想完全保留原有数组并只想新的数组附加到后面，用 + 运算符：
$array1 = array();
$array2 = array(1 => "data");
$result = $array1 + $array2;
数字键名将被保留从而原来的关联保持不变。
Array
(
    [1] => data
)

注: 共有的键名将根据先来先服务的原则被覆盖掉。

参见 array_merge_recursive()。

后退 | 起点 | 前进
array_merge_recursive | 上一级 | array_multisort


array_multisort

(PHP 4 )

array_multisort -- 对多个数组或多维数组进行排序

说明

bool array_multisort ( array ar1 [, mixed arg [, mixed ... [, array ...]]])

array_multisort() 可以用来一次对多个数组进行排序或者根据某一维对多维数组进行排序。排序时保留原有的键名关联。

输入数组被当成一个表的列并以行来排序 － 这类似于 SQL 的 ORDER BY 子句的功能。第一个数组是要排序的主要数组。数组中的行（值）比较为相同的话就按照下一个输入数组中相应值的大小来排序，依此类推。

本函数的参数结构有些不同寻常，但是非常灵活。第一个参数必须是一个数组。接下来的每个参数可以是数组或者是下面列出的排序标志。

排序顺序标志：

  • SORT_ASC - 按照上升顺序排序

  • SORT_DESC - 按照下降顺序排序

排序类型标志：

  • SORT_REGULAR - 将项目按照通常方法比较

  • SORT_NUMERIC - 将项目按照数值比较

  • SORT_STRING - 将项目按照字符串比较

每个数组之后不能指定两个同类的排序标志。每个数组后指定的排序标志仅对该数组有效，默认值为 SORT_ASC 和 SORT_REGULAR。

如果成功则返回 TRUE，失败则返回 FALSE。

例子 1. 对多个数组排序

$ar1 = array ("10", 100, 100, "a");
$ar2 = array (1, 3, "2", 1);
array_multisort ($ar1, $ar2);

本例中经过排序后，第一个数组将包含 10，"a"，100，100。第二个数组将包含 1，1，"2"，3。第二个数组中的项目顺序完全和第一个数组中相应的项目（100 和 100）顺序一致。

例子 2. 对多维数组排序

$ar = array (array ("10", 100, 100, "a"), array (1, 3, "2", 1));
array_multisort ($ar[0], SORT_ASC, SORT_STRING,
                 $ar[1], SORT_NUMERIC, SORT_DESC);

本例中经过排序后，第一个数组将包含 10，100，100，"a"（作为字符串上升排序），第二个数组将包含 1，3，"2"，1（作为数值下降排序）。

【译者注】本函数相当有用，为有助于理解，请看下面这个例子：

例子 3. 名次排列

$grade = array("score" => array(70, 95, 70.0, 60, "70"),
               "name" => array("Zhang San", "Li Si", "Wang Wu",
                               "Zhao Liu", "Liu Qi"));
array_multisort($grade["score"], SORT_NUMERIC, SORT_DESC,
                // 将分数作为数值，由高到低排序
                $grade["name"], SORT_STRING, SORT_ASC);
                // 将名字作为字符串，由小到大排序
var_dump($grade);

上例输出结果如下：
array(2) {
  ["score"]=>
  array(5) {
    [0]=>
    int(95)
    [1]=>
    string(2) "70"
    [2]=>
    float(70)
    [3]=>
    int(70)
    [4]=>
    int(60)
  }
  ["name"]=>
  array(5) {
    [0]=>
    string(5) "Li Si"
    [1]=>
    string(6) "Liu Qi"
    [2]=>
    string(7) "Wang Wu"
    [3]=>
    string(9) "Zhang San"
    [4]=>
    string(8) "Zhao Liu"
  }
}
本例中对包含成绩的数组 $grade 按照分数（score）由高到低进行排序，分数相同的人则按照名字（name）由小到大排序。排序后李四 95 分为第一名，赵六 60 分为第五名没有异议。张三、王五和刘七都是 70 分，他们的名次则由其姓名的字母顺序排列，Liu 在前，Wang 在后而 Zhang 在最后。为了区别，三个 70 分分别用了整数，浮点数和字符串来表示，可以在程序输出中清楚地看到它们排序的结果。

后退 | 起点 | 前进
array_merge | 上一级 | array_pad


array_pad

(PHP 4 )

array_pad -- 用值将数组填补到指定长度

说明

array array_pad ( array input, int pad_size, mixed pad_value)

array_pad() 返回 input 的一个拷贝，并用 pad_value 将其填补到 pad_size 指定的长度。如果 pad_size 为正，则数组被填补到右侧，如果为负则从左侧开始填补。如果 pad_size 的绝对值小于或等于 input 数组的长度则没有任何填补。

例子 1. array_pad() 例子

$input = array (12, 10, 9);

$result = array_pad ($input, 5, 0);
// result is array (12, 10, 9, 0, 0)

$result = array_pad ($input, -7, -1);
// result is array (-1, -1, -1, -1, 12, 10, 9)

$result = array_pad ($input, 2, "noop");
// not padded

后退 | 起点 | 前进
array_multisort | 上一级 | array_pop


array_pop

(PHP 4 )

array_pop -- 将数组最后一个单元弹出（出栈）

说明

mixed array_pop ( array array)

array_pop() 弹出并返回 array 数组的最后一个单元，并将数组 array 的长度减一。如果 array 为空（或者不是数组）将返回 NULL。

例子 1. array_pop() 例子

$stack = array ("orange", "banana", "apple", "raspberry");
$fruit = array_pop ($stack);

经过此操作后，$stack 将只有 3 个单元：
Array
(
    [0] => orange
    [1] => banana
    [2] => apple
)
并且 rasberry 将被赋给 $fruit。

警告

这个函数可能返回 Boolean FALSE，也可能返回一个与 FALSE 相等地非 Boolean 值，比如 0 或者 "" 。请参阅 Booleans 的有关章节以获取更多信息。请使用 === 操作符 来测试该函数的返回值。

参见 array_push()，array_shift() 和 array_unshift()。

后退 | 起点 | 前进
array_pad | 上一级 | array_push


array_push

(PHP 4 )

array_push -- 将一个或多个单元压入数组的末尾（入栈）

说明

int array_push ( array array, mixed var [, mixed ...])

array_push() 将 array 当成一个栈，并将传入的变量压入 array 的末尾。 array 的长度将增加入栈变量的数目。和如下效果相同：
$array[] = $var;
并对每个 var 重复以上动作。

返回数组新的单元总数。

例子 1. array_push() 例子

$stack = array ("orange", "banana");
array_push ($stack, "apple", "raspberry");

本例将使 $stack 具有如下单元：
Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)

参见 array_pop()，array_shift() 和 array_unshift()。

后退 | 起点 | 前进
array_pop | 上一级 | array_rand


array_rand

(PHP 4 )

array_rand -- 从数组中随机取出一个或多个单元

说明

mixed array_rand ( array input [, int num_req])

array_rand() 在你想从数组中取出一个或多个随机的单元时相当有用。它接受 input 作为输入数组和一个可选的参数 num_req，指明了你想取出多少个单元 － 如果没有指定，默认为 1。

如果你只取出一个，array_rand() 返回一个随机单元的键名，否则就返回一个包含随机键名的数组。这样你就可以随机从数组中取出键名和值。

不要忘记调用 srand() 来撒下随机数发生器的种子。

例子 1. array_rand() 例子

srand ((float) microtime() * 10000000);
$input = array ("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand ($input, 2);
print $input[$rand_keys[0]]."\n";
print $input[$rand_keys[1]]."\n";

后退 | 起点 | 前进
array_push | 上一级 | array_reduce


array_reduce

(PHP 4 >= 4.0.5)

array_reduce -- 用回调函数迭代地将数组简化为单一的值

说明

mixed array_reduce ( array input, mixed callback [, int initial])

array_reduce() 将回调函数 callback 迭代地作用到 input 数组中的每一个单元中，从而将数组简化为单一的值。如果指定了可选参数 initial，该参数将被当成是数组中的第一个值来处理，或者如果数组为空的话就作为最终返回值。

例子 1. array_reduce() 例子

function rsum($v, $w) {
    $v += $w;
    return $v;
}

function rmul($v, $w) {
    $v *= $w;
    return $v;
}

$a = array(1, 2, 3, 4, 5);
$x = array();
$b = array_reduce($a, "rsum");
$c = array_reduce($a, "rmul", 10);
$d = array_reduce($x, "rsum", 1);

这将使 $b 的值为 15，$c 的值为 1200（= 1*2*3*4*5*10），以及 $d 的值为 1。

参见 array_filter() 和 array_map()。

后退 | 起点 | 前进
array_rand | 上一级 | array_reverse


array_reverse

(PHP 4 )

array_reverse -- 返回一个单元顺序相反的数组

说明

array array_reverse ( array array [, bool preserve_keys])

array_reverse() 接受数组 array 作为输入并返回一个单元为相反顺序的新数组，如果 preserve_keys 为 TRUE 则保留原来的键名。

例子 1. array_reverse() 例子

$input  = array ("php", 4.0, array ("green", "red"));
$result = array_reverse ($input);
$result_keyed = array_reverse ($input, TRUE);

这将使 $result 和 $result_keyed 具有相同的单元，但是注意键名的区别。$result 和 $result_keyed 的打印输出显示分别为：
Array
(
    [0] => Array
        (
            [0] => green
            [1] => red
        )

    [1] => 4
    [2] => php
)
Array
(
    [2] => Array
        (
            [0] => green
            [1] => red
        )

    [1] => 4
    [0] => php
)

注: 第二个参数是 PHP 4.0.3 中新加的。

后退 | 起点 | 前进
array_reduce | 上一级 | array_search


array_search

(PHP 4 >= 4.0.5)

array_search -- 在数组中搜索给定的值，如果成功则返回相应的键名

说明

mixed array_search ( mixed needle, array haystack [, bool strict])

在 haystack 中搜索 needle 参数并在找到的情况下返回键名，否则返回 FALSE。

注: 在 PHP 4.2.0 之前，array_search() 在失败时返回 NULL 而不是 FALSE。

如果可选的第三个参数 strict 为 TRUE，则 array_search() 还将在 haystack 中检查 needle 的类型。

警告

这个函数可能返回 Boolean FALSE，也可能返回一个与 FALSE 相等地非 Boolean 值，比如 0 或者 "" 。请参阅 Booleans 的有关章节以获取更多信息。请使用 === 操作符 来测试该函数的返回值。

参见 array_keys() 和 in_array()。

后退 | 起点 | 前进
array_reverse | 上一级 | array_shift


array_shift

(PHP 4 )

array_shift -- 将数组开头的单元移出数组

说明

mixed array_shift ( array array)

array_shift() 将 array 的第一个单元移出并作为结果返回，将 array 的长度减一并将所有其它单元向前移动一位。所有的数字键名将改为从零开始计数，文字键名将不变。如果 array 为空（或者不是数组），则返回 NULL。

例子 1. array_shift() 例子

$stack = array ("orange", "banana", "apple", "raspberry");
$fruit = array_shift ($stack);

这将使 $stack 剩下 3 个单元：
Array
(
    [0] => banana
    [1] => apple
    [2] => raspberry
)
并且 orange 被赋给了 $fruit。

参见 array_unshift()，array_push() 和 array_pop()。

后退 | 起点 | 前进
array_search | 上一级 | array_slice


array_slice

(PHP 4 )

array_slice -- 从数组中取出一段

说明

array array_slice ( array array, int offset [, int length])

array_slice() 返回根据 offset 和 length 参数所指定的 array 数组中的一段序列。

如果 offset 为正，则序列将从 array 中的此偏移量开始。如果 offset 为负，则序列将从 array 中距离末端这么远的地方开始。

如果给出了 length 并且为正，则序列中将具有这么多的单元。如果给出了 length 并且为负，则序列将终止在距离数组末端这么远的地方。如果省略，则序列将从 offset 开始一直到 array 的末端。

注意 array_slice() 将忽略键名，并且是根据单元在数组中的实际位置来计算偏移量和长度的。

例子 1. array_slice() 例子

$input = array ("a", "b", "c", "d", "e");

$output = array_slice ($input, 2);      // returns "c", "d", and "e"
$output = array_slice ($input, 2, -1);  // returns "c", "d"
$output = array_slice ($input, -2, 1);  // returns "d"
$output = array_slice ($input, 0, 3);   // returns "a", "b", and "c"

参见 array_splice()。

后退 | 起点 | 前进
array_shift | 上一级 | array_splice


array_splice

(PHP 4 )

array_splice -- 把数组中的一部分去掉并用其它值取代

说明

array array_splice ( array input, int offset [, int length [, array replacement]])

array_splice() 把 input 数组中由 offset 和 length 指定的单元去掉，如果提供了 replacement 参数，则用 replacement 数组中的单元取代。返回一个包含有被移除单元的数组。

如果 offset 为正，则从 input 数组中该值指定的偏移量开始移除。如果 offset 为负，则从 input 末尾倒数该值指定的偏移量开始移除。

如果省略 length，则移除数组中从 offset 到结尾的所有部分。如果指定了 length 并且为正值，则移除这么多单元。如果指定了 length 并且为负值，则移除从 offset 到数组末尾倒数 length 为止中间所有的单元。小窍门：当给出了 replacement 时要移除从 offset 到数组末尾所有单元时，用 count($input) 作为 length。

如果给出了 replacement 数组，则被移除的单元被此数组中的单元替代。如果 offset 和 length 的组合结果是不会移除任何值，则 replacement 数组中的单元将被插入到 offset 指定的位置。小窍门：如果用来替换的值只是一个单元，那么不需要给它加上 array()，除非该单元本身就是一个数组。

以下的表达式具有同样效果：
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() 例子

$input = array ("red", "green", "blue", "yellow");
array_splice ($input, 2);
// $input is now array ("red", "green")

$input = array ("red", "green", "blue", "yellow");
array_splice ($input, 1, -1);
// $input is now array ("red", "yellow")

$input = array ("red", "green", "blue", "yellow");
array_splice ($input, 1, count($input), "orange");
// $input is now array ("red", "orange")

$input = array ("red", "green", "blue", "yellow");
array_splice ($input, -1, 1, array("black", "maroon"));
// $input is now array ("red", "green",
//          "blue", "black", "maroon")

参见 array_slice()。

后退 | 起点 | 前进
array_slice | 上一级 | array_sum


array_sum

(PHP 4 >= 4.0.4)

array_sum -- 计算数组中所有值的和

说明

mixed array_sum ( array array)

array_sum() 将数组中的所有值的和以整数或浮点数的结果返回。

例子 1. array_sum() 例子

$a = array(2, 4, 6, 8);
echo "sum(a) = ".array_sum($a)."\n";

$b = array("a"=>1.2,"b"=>2.3,"c"=>3.4);
echo "sum(b) = ".array_sum($b)."\n";

以上程序输出为：
sum(a) = 20
sum(b) = 6.9

注: PHP 4.0.6 之前的版本修改了传入的数组本身，将其中的字符串值转换成数值（大多数情况下都转换成了零，根据具体值而定）。

后退 | 起点 | 前进
array_splice | 上一级 | array_unique


array_unique

(PHP 4 >= 4.0.1)

array_unique -- 移除数组中重复的值

说明

array array_unique ( array array)

array_unique() 接受 array 作为输入并返回没有重复值的新数组。

注意键名保留不变。array_unique() 先将值作为字符串排序，然后对每个值只保留第一个遇到的键名，接着忽略所有后面的键名。这并不意味着在未排序的 array 中同一个值的第一个出现的键名会被保留。

注: 当且仅当 (string) $elem1 === (string) $elem2 时两个单元被认为相同。就是说，当字符串的表达一样时。

第一个单元将被保留。

警告

本函数在 PHP 4.0.4 中是坏的！

例子 1. array_unique() 例子

$input = array ("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique ($input);
print_r($result);

上例将输出：
Array
(
    [b] => green
    [1] => blue
    [2] => red
)

例子 2. array_unique() 和类型

$input = array (4,"4","3",4,3,"3");
$result = array_unique ($input);
var_dump($result);

以上程序输出结果为（PHP 4.0.6）：
array(2) {

  [0]=>

  int(4)

  [2]=>

  string(1) "3"

}

后退 | 起点 | 前进
array_sum | 上一级 | array_unshift


array_unshift

(PHP 4 )

array_unshift -- 在数组开头插入一个或多个单元

说明

int array_unshift ( array array, mixed var [, mixed ...])

array_unshift() 将传入的单元插入到 array 数组的开头。注意单元是作为整体被插入的，因此传入单元将保持同样的顺序。所有的数值键名将修改为从零开始重新计数，所有的文字键名保持不变。

返回 array 数组新的单元数目。

例子 1. array_unshift() 例子

$queue = array ("orange", "banana");
array_unshift ($queue, "apple", "raspberry");

这将使 $queue 包含如下单元：
Array
(
    [0] => apple
    [1] => raspberry
    [2] => orange
    [3] => banana
)

参见 array_shift()，array_push() 和 array_pop()。

后退 | 起点 | 前进
array_unique | 上一级 | array_values


array_values

(PHP 4 )

array_values -- 返回数组中所有的值

说明

array array_values ( array input)

array_values() 返回 input 数组中所有的值。

例子 1. array_values() 例子

$array = array ("size" => "XL", "color" => "gold");
print_r(array_values ($array));

上例将输出：
Array
(
    [0] => XL
    [1] => gold
)

注: 本函数是 PHP 4 新加的，以下是 PHP 3 的实现：

例子 2. array_values() 对PHP 3 用户的实现

function array_values ($arr) {
    $t = array();
    while (list($k, $v) = each ($arr)) {
        $t[] = $v;
    }
    return $t;
}

参见 array_keys()。

后退 | 起点 | 前进
array_unshift | 上一级 | array_walk


array_walk

(PHP 3>= 3.0.3, PHP 4 )

array_walk -- 对数组中的每个成员应用用户函数

说明

int array_walk ( array array, string func [, mixed userdata])

对 array 数组的每个单元应用用户自定义函数 func。数组中的值作为第一个参数，键名作为第二个参数传入 func 函数。如果提供了 userdata，将会被作为第三个参数传入用户函数。func 必须是一个用户自定义函数，而不能是 PHP 本来有的函数。因此不能在 array_walk() 中直接使用 str2lower()，必须先建立一个用户自定义函数，再把这个函数名当作参数传递进去。

注: 第二个参数函数名可以替换为一个数组，该数组由一个对象名和该对象名的一个方法名两个元素组成。

如果 func 需要超过两个或三个参数（根据 userdata），每次 array_walk() 调用 func 都会产生一个警告。这些警告可以通过在 array_walk() 调用的前面加上“@”符号来抑制住，或者通过 error_reporting()。

注: 如果 func 需要直接作用于数组中的值，则 func 定义中的第一个参数应该用引用传递。这样任何对这些单元的改变也将会改变数组本身。

在 func 中修改数组可能会产生不可预知的行为。

注: 将键名和 userdata 传递到 func 中是 PHP 4.0 新增加的。

在 PHP 4 中需要调用 reset()，因为 array_walk() 默认不会重置数组。

用户最好不要在回调函数中修改数组本身。例如添加／删除单元，unset array_walk() 正在作用的数组。如果数组改变了，本函数的行为没有定义。

例子 1. array_walk() 例子

$fruits = array ("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");

function test_alter (&$item1, $key, $prefix) {
    $item1 = "$prefix: $item1";
}

function test_print ($item2, $key) {
    echo "$key. $item2<br>\n";
}
echo "Before ...:\n";
array_walk ($fruits, 'test_print');
reset ($fruits);
array_walk ($fruits, 'test_alter', 'fruit');
echo "... and after:\n";
reset ($fruits);
array_walk ($fruits, 'test_print');

以上程序输出为：
Before ...:
d. lemon
a. orange
b. banana
c. apple
... and after:
d. fruit: lemon
a. fruit: orange
b. fruit: banana
c. fruit: apple

参见 each() 和 list()。

后退 | 起点 | 前进
array_values | 上一级 | array


array

(no version information, might be only in CVS)

array -- 新建一个数组

说明

array array ( [mixed ...])

返回根据参数建立的数组。参数可以用 => 运算符给出索引。

注: array() 是一个语言结构，用于字面上表示数组，不是常规的函数。

语法“index => values”，用逗号分开，定义了索引和值。索引可以是字符串或数字。如果省略了索引，会自动产生从 0 开始的整数索引。如果索引是整数，则下一个产生的索引将是目前最大的整数索引 + 1。注意如果定义了两个完全一样的索引，则后面一个会覆盖前一个。

下面的例子演示了怎样建立一个二维数组，怎样给相应的数组指定键名，以及怎样在普通数组中略过和继续数字索引。

例子 1. array() 例子

$fruits = array (
    "fruits"  => array ("a"=>"orange", "b"=>"banana", "c"=>"apple"),
    "numbers" => array (1, 2, 3, 4, 5, 6),
    "holes"   => array ("first", 5 => "second", "third")
);

例子 2. array() 的自动索引

$array = array( 1, 1, 1, 1,  1, 8=>1,  4=>1, 19, 3=>13);
print_r($array);

将显示：
Array
(
    [0] => 1
    [1] => 1
    [2] => 1
    [3] => 13
    [4] => 1
    [8] => 1
    [9] => 19
)

注意索引 3 被定义了两次，保留了最后的值 13。索引 4 在 索引 8 之后定义，下一个自动生成的索引（值为 19 那个）为 9，因为最大的索引是 8。

本例建立了从 1 开始的数组。

例子 3. 从 1 开始索引的 array()

$firstquarter  = array(1 => 'January', 'February', 'March');
print_r($firstquarter);

将显示：
Array
(
    [1] => 'January'
    [2] => 'February'
    [3] => 'March'
)

参见 array_pad()，list() 和 range()。

后退 | 起点 | 前进
array_walk | 上一级 | arsort


arsort

(PHP 3, PHP 4 )

arsort -- 对数组进行逆向排序并保持索引关系

说明

void arsort ( array array [, int sort_flags])

本函数对数组进行排序，数组的索引保持和单元的关联。主要用于对那些单元顺序很重要的结合数组进行排序。

例子 1. arsort() 例子

$fruits = array ("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
arsort ($fruits);
reset ($fruits);
while (list ($key, $val) = each ($fruits)) {
    echo "$key = $val\n";
}

本例输出如下：
a = orange
d = lemon
b = banana
c = apple

fruits 被按照字母顺序逆向排序，并且单元的索引关系不变。

可以用可选的参数 sort_flags 改变排序的行为，详情见 sort()。

参见 asort()，rsort()，ksort() 和 sort()。

后退 | 起点 | 前进
array | 上一级 | asort


asort

(PHP 3, PHP 4 )

asort -- 对数组进行排序并保持索引关系

说明

void asort ( array array [, int sort_flags])

本函数对数组进行排序，数组的索引保持和单元的关联。主要用于对那些单元顺序很重要的结合数组进行排序。

例子 1. asort() 例子

$fruits = array ("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
asort ($fruits);
reset ($fruits);
while (list ($key, $val) = each ($fruits)) {
    echo "$key = $val\n";
}

本例显示为：
c = apple
b = banana
d = lemon
a = orange

fruits 被按照字母顺序排序，并且单元的索引关系不变。

可以用可选的参数 sort_flags 改变排序的行为，详情见 sort()。

参见 arsort()，rsort()，ksort() 和 sort()。

后退 | 起点 | 前进
arsort | 上一级 | compact


compact

(PHP 4 )

compact -- 建立一个数组，包括变量名和它们的值

说明

array compact ( mixed varname [, mixed ...])

compact() 接受可变的参数数目。每个参数可以是一个包括变量名的字符串或者是一个包含变量名的数组，该数组中还可以包含其它单元内容为变量名的数组， compact() 可以递归处理。

对每个参数，compact() 在当前的符号表中查找该变量名并将它添加到输出的数组中，变量名成为键名而变量的内容成为该键的值。简单说，它做的事和 extract() 正好相反。返回将所有变量添加进去后的数组。

任何没有设定为变量名的字符串都被跳过。

例子 1. compact() 例子

$city = "San Francisco";
$state = "CA";
$event = "SIGGRAPH";

$location_vars = array ("city", "state");

$result = compact ("event", "nothing_here", $location_vars);

经过处理后，$result 为：
Array
(
    [event] => SIGGRAPH
    [city] => San Francisco
    [state] => CA
)

参见 extract()。

后退 | 起点 | 前进
asort | 上一级 | count


count

(PHP 3, PHP 4 )

count -- 统计变量中的单元数目

说明

int count ( mixed var)

返回 var 中的单元数目，通常是一个 array（任何其它类型都只有一个单元）。

如果 var 不是数组类型，将返回 1（例外：count(NULL) 的结果是 0）。

警告

count() 对没有初始化的变量返回 0，但对于空的数组也会返回 0。用 isset() 来测试变量是否已经初始化。

请参考手册中数组一节中关于怎样在 PHP 中实现和使用数组的详细解释。

例子 1. count() 例子

$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count ($a);
// $result == 3

$b[0] = 7;
$b[5] = 9;
$b[10] = 11;
$result = count ($b);
// $result == 3;

注: sizeof() 函数是 count() 的别名。

参见 is_array()，isset() 和 strlen()。

后退 | 起点 | 前进
compact | 上一级 | current


current

(PHP 3, PHP 4 )

current -- 返回数组中的当前单元

说明

mixed current ( array array)

每个数组中都有一个内部的指针指向它“当前的”单元，初始指向插入到数组中的第一个单元。

current() 函数返回当前被内部指针指向的数组单元的值，并不移动指针。如果内部指针指向超出了单元列表的末端，current() 返回 FALSE。

警告

如果数组包含有空的单元（0 或者 ""，空字符串）则本函数在碰到这个单元时也返回 FALSE。这使得用 current() 不可能判断是否到了此数组列表的末端。要正确遍历可能含有空单元的数组，用 each() 函数。

参见 end()，next()，prev() 和 reset()。

后退 | 起点 | 前进
count | 上一级 | each


each

(PHP 3, PHP 4 )

each -- 返回数组中当前的键／值对并将数组指针向前移动一步

说明

array each ( array array)

返回 array 数组中当前指针位置的键／值对并向前移动数组指针。键值对被返回为四个单元的数组，键名为 0，1，key 和 value。单元 0 和 key 包含有数组单元的键名，1 和 value 包含有数据。

如果内部指针越过了数组的末端，则 each() 返回 FALSE。

例子 1. each() 例子

$foo = array ("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bar = each ($foo);

$bar 现在包含有如下的键／值对：

  • 0 => 0
  • 1 => 'bob'
  • key => 0
  • value => 'bob'
$foo = array ("Robert" => "Bob", "Seppo" => "Sepi");
$bar = each ($foo);

$bar 现在包含有如下的键／值对：

  • 0 => 'Robert'
  • 1 => 'Bob'
  • key => 'Robert'
  • value => 'Bob'

each() 经常和 list() 结合使用来遍历数组，例如 $_POST：

例子 2. 用 each() 遍历 $_POST：

echo "Values submitted via POST method:<br />\n";
reset ($_POST);
while (list ($key, $val) = each ($_POST)) {
    echo "$key => $val<br />\n";
}

在执行 each() 之后，数组指针将停留在数组中的下一个单元或者当碰到数组结尾时停留在最后一个单元。如果要再用 each 遍历数组，必须使用 reset()。

参见 key()，list()，current()，reset()，next()，prev() 和 foreach()。

后退 | 起点 | 前进
current | 上一级 | end


end

(PHP 3, PHP 4 )

end -- 将数组的内部指针指向最后一个单元

说明

mixed end ( array array)

end() 将 array 的内部指针移动到最后一个单元，并返回该单元。

例子 1. 简单的 end() 例子

<?php

  $fruits = array('apple','banana','cranberry');

  print end($fruits); // cranberry

?>

参见 current()，each()，next() 和 reset()。

后退 | 起点 | 前进
each | 上一级 | extract


extract

(PHP 3>= 3.0.7, PHP 4 )

extract -- 从数组中将变量导入到当前的符号表

说明

int extract ( array var_array [, int extract_type [, string prefix]])

本函数用来将变量从数组中导入到当前的符号表中。接受结合数组 var_array 作为参数并将键名当作变量名，值作为变量的值。对每个键／值对都会在当前的符号表中建立变量，并受到 extract_type 和 prefix 参数的影响。

注: 自版本 4.0.5 起本函数返回被提取的变量数目。

注: EXTR_IF_EXISTS 和 EXTR_PREFIX_IF_EXISTS 是版本 4.2.0 中引进的。

extract() 检查每个键名看是否可以作为一个合法的变量名，同时也检查和符号表中已有的变量名的冲突。对待非法／数字和冲突的键名的方法将根据 extract_type 参数决定。可以是以下值之一：

EXTR_OVERWRITE

如果有冲突，覆盖已有的变量。

EXTR_SKIP

如果有冲突，不覆盖已有的变量。

EXTR_PREFIX_SAME

如果有冲突，在变量名前加上前缀 prefix。

EXTR_PREFIX_ALL

给所有变量名加上前缀 prefix。自 PHP 4.0.5 起这也包括了对数字索引的处理。

EXTR_PREFIX_INVALID

仅在非法／数字的变量名前加上前缀 prefix。本标记是 PHP 4.0.5 新加的。

EXTR_IF_EXISTS

仅在当前符号表中已有同名变量时，覆盖它们的值。其它的都不处理。可以用在已经定义了一组合法的变量，然后要从一个数组例如 $_REQUEST 中提取值覆盖这些变量的场合。本标记是 PHP 4.2.0 新加的。

EXTR_PREFIX_IF_EXISTS

仅在当前符号表中已有同名变量时，建立附加了前缀的变量名，其它的都不处理。本标记是 PHP 4.2.0 新加的。

如果没有指定 extract_type，则被假定为 EXTR_OVERWRITE。

注意 prefix 仅在 extract_type 的值是 EXTR_PREFIX_SAME，EXTR_PREFIX_ALL，EXTR_PREFIX_INVALID 或 EXTR_PREFIX_IF_EXISTS 时需要。如果附加了前缀后的结果不是合法的变量名，将不会导入到符号表中。

extract() 返回成功导入到符号表中的变量数目。

一种可能的用法是将 wddx_deserialize() 返回的结合数组中的内容导入到符号表变量中去。

例子 1. extract() 例子

<?php

/* 假定 $var_array 是 wddx_deserialize 返回的数组*/

$size = "large";
$var_array = array ("color" => "blue",
                    "size"  => "medium",
                    "shape" => "sphere");
extract ($var_array, EXTR_PREFIX_SAME, "wddx");

print "$color, $size, $shape, $wddx_size\n";

?>

以上例子将产生：
blue, large, sphere, medium

$size 没有被覆盖，因为指定了 EXTR_PREFIX_SAME，这使得 $wddx_size 被建立。如果指定了 EXTR_SKIP，则 $wddx_size 也不会被建立。EXTR_OVERWRITE 将使 $size 的值为“medium”，EXTR_PREFIX_ALL 将建立新变量 $wddx_color，$wddx_size 和 $wddx_shape。

必须使用结合数组，数字索引的数组将不会产生结果，除非用了 EXTR_PREFIX_ALL 或者 EXTR_PREFIX_INVALID。

参见 compact()。

后退 | 起点 | 前进
end | 上一级 | in_array


in_array

(PHP 4 )

in_array -- 如果数组中存在该值则返回 TRUE

说明

bool in_array ( mixed needle, array haystack [, bool strict])

在 haystack 中搜索 needle，如果找到则返回 TRUE，否则返回 FALSE。

如果第三个参数 strict 的值为 TRUE 则 in_array() 函数还会检查 needle 的类型是否和 haystack 中的相同。

注: 如果 needle 是字符串，则比较是区分大小写的。

注: 在 PHP 版本 4.2.0 之前，needle 不允许是一个数组。

例子 1. in_array() 例子

$os = array ("Mac", "NT", "Irix", "Linux");
if (in_array ("Irix", $os)) {
    print "Got Irix";
}
if (in_array ("mac", $os)) {
    print "Got mac";
}

第二个条件失败，因为 in_array() 是区分大小写的，所以以上程序显示为：
Got Irix

例子 2. in_array() 严格类型检查例子

<?php
$a = array('1.10', 12.4, 1.13);

if (in_array('12.4', $a, TRUE))
    echo "'12.4' found with strict check\n";
if (in_array(1.13, $a, TRUE))
    echo "1.13 found with strict check\n";
?>

将显示：
1.13 found with strict check

例子 3. in_array() 中用数组作为 needle

<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');

if (in_array(array ('p', 'h'), $a))
    echo "'ph' was found\n";
if (in_array(array ('f', 'i'), $a))
    echo "'fi' was found\n";
if (in_array('o', $a))
    echo "'o' was found\n";
?>

// This will output:

'ph' was found
'o' was found

参见 array_search()。

后退 | 起点 | 前进
extract | 上一级 | key


key

(PHP 3, PHP 4 )

key -- 从结合数组中取得键名

说明

mixed key ( array array)

key() 返回数组中当前单元的键名。

参见 current() 和 next()。

后退 | 起点 | 前进
in_array | 上一级 | krsort


krsort

(PHP 3>= 3.0.13, PHP 4 )

krsort -- 对数组按照键名逆向排序

说明

int krsort ( array array [, int sort_flags])

对数组按照键名逆向排序，保留键名到数据的关联。主要用于结合数组。

例子 1. krsort() 例子

$fruits = array ("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
krsort ($fruits);
reset ($fruits);
while (list ($key, $val) = each ($fruits)) {
    echo "$key = $val\n";
}

本例将显示：

d = lemon
c = apple
b = banana
a = orange

可以用可选参数 sort_flags 改变排序的行为，详情见 sort()。

参见 asort()，arsort()，ksort()，sort()，natsort() 和 rsort()。

后退 | 起点 | 前进
key | 上一级 | ksort


ksort

(PHP 3, PHP 4 )

ksort -- 对数组按照键名排序

说明

int ksort ( array array [, int sort_flags])

对数组按照键名排序，保留键名到数据的关联。本函数主要用于结合数组。

例子 1. ksort() 例子

$fruits = array ("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort ($fruits);
reset ($fruits);
while (list ($key, $val) = each ($fruits)) {
    echo "$key = $val\n";
}

本例将显示：

a = orange
b = banana
c = apple
d = lemon

可以用可选参数 sort_flags 改变排序的行为，详情见 sort()。

参见 asort()，arsort()，krsort()，uksort()，sort()，natsort() 和 rsort()。

注: 第二个参数是 PHP 4 新加的。

后退 | 起点 | 前进
krsort | 上一级 | list


list

(no version information, might be only in CVS)

list -- 把数组中的值赋给一些变量

说明

void list ( mixed ...)

像 array() 一样，这不是真正的函数，而是语言结构。list() 用一步操作给一组变量进行赋值。

注: list() 仅能用于数字索引的数组并假定数字索引从 0 开始。

例子 1. list() 例子

<?php

$info = array('coffee', 'brown', 'caffeine');

// Listing all the variables
list($drink, $color, $power) = $info;
print "$drink is $color and $power makes it special.\n";

// Listing some of them
list($drink, , $power) = $info;
print "$drink has $power.\n";

// Or let's skip to only the third one
list( , , $power) = $info;
print "I need $power!\n";

?>

例子 2. 使用 list() 的例子

<table>
 <tr>
  <th>Employee name</th>
  <th>Salary</th>
 </tr>

<?php

$result = mysql_query ("SELECT id, name, salary FROM employees",$conn);
while (list ($id, $name, $salary) = mysql_fetch_row ($result)) {
    print (" <tr>\n".
           "  <td><a href=\"info.php?id=$id\">$name</a></td>\n".
           "  <td>$salary</td>\n".
           " </tr>\n");
}

?>

</table>

警告

list() 从最右边一个参数开始赋值。如果你用单纯的变量，不用担心这一点。但是如果你用了具有索引的数组，通常你期望得到的结果和在 list() 中写的一样是从左到右的，但实际上不是。是以相反顺序赋值的。

例子 3. 在 list() 中使用数组索引

<?php

$info = array('coffee', 'brown', 'caffeine');

list($a[0], $a[1], $a[2]) = $info;

var_dump($a);
产生如下输出（注意单元顺序和 list() 语法中所写的顺序的比较）：
array(3) {
  [2]=>
  string(8) "caffeine"
  [1]=>
  string(5) "brown"
  [0]=>
  string(6) "coffee"
}

参见 each()，array() 和 extract()。

后退 | 起点 | 前进
ksort | 上一级 | natcasesort


natcasesort

(PHP 4 )

natcasesort -- 用“自然排序”算法对数组进行不区分大小写字母的排序

说明

void natcasesort ( array array)

本函数实现了一个和人们通常对字母数字字符串进行排序的方法一样的排序算法，这被称为“自然排序”。

natcasesort() 是 natsort() 函数的不区分大小写字母的版本。见 natsort() 中说明本算法和通常的计算机字符串排序算法的区别的例子。

更多信息见 Martin Pool 的 Natural Order String Comparison 页面。

参见 sort()，natsort()，strnatcmp() 和 strnatcasecmp()。

后退 | 起点 | 前进
list | 上一级 | natsort


natsort

(PHP 4 )

natsort -- 用“自然排序”算法对数组排序

说明

void natsort ( array array)

本函数实现了一个和人们通常对字母数字字符串进行排序的方法一样的排序算法，这被称为“自然排序”。本算法和通常的计算机字符串排序算法（用于 sort()）的区别示例如下：

例子 1. natsort() 例子

<?php
$array1 = $array2 = array ("img12.png", "img10.png", "img2.png", "img1.png");

sort($array1);
echo "Standard sorting\n";
print_r($array1);

natsort($array2);
echo "\nNatural order sorting\n";
print_r($array2);
?>

以上代码显示结果为：

Standard sorting
Array
(
    [0] => img1.png
    [1] => img10.png
    [2] => img12.png
    [3] => img2.png
)

Natural order sorting
Array
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)
更多信息见 Martin Pool 的 Natural Order String Comparison 页面。

注: 如果你想保持索引／值的关联，考虑使用 usort($arr, 'strnatcmp')。

参见 natcasesort()，strnatcmp() 和 strnatcasecmp()。

后退 | 起点 | 前进
natcasesort | 上一级 | next


next

(PHP 3, PHP 4 )

next -- 将数组中的内部指针向前移动一位

说明

mixed next ( array array)

返回数组内部指针指向的下一个单元，或当没有更多单元时返回 FALSE。

next() 和 current() 的行为类似，只有一点区别，在返回值之前将内部指针向前移动一位。这意味着它返回的是下一个数组单元并将数组指针向前移动了一位。如果移动指针的结果是超出了数组单元的末端，则 next() 返回 FALSE。

警告

如果数组包含空的单元，或者单元的值是 0 则本函数碰到这些单元也返回 FALSE。要正确遍历可能含有空单元或者单元值为 0 的数组，参见 each() 函数。

参见 current()，end()，prev() 和 reset()。

后退 | 起点 | 前进
natsort | 上一级 | pos


pos

(PHP 3, PHP 4 )

pos -- 得到数组当前的单元

说明

mixed pos ( array array)

本函数是 current() 的别名。

参见 end()，next()，prev() 和 reset()。

后退 | 起点 | 前进
next | 上一级 | prev


prev

(PHP 3, PHP 4 )

prev -- 将数组的内部指针倒回一位

说明

mixed prev ( array array)

返回数组内部指针指向的前一个单元，或当没有更多单元时返回 FALSE。

警告

如果数组包含空的单元，或者单元的值是 0 则本函数碰到这些单元也返回 FALSE。要正确遍历可能含有空单元或者单元值为 0 的数组，参见 each() 函数。

prev() 和 next() 的行为类似，只除了它将内部指针倒回一位而不是前移一位。

参见 current()，end()，next() 和 reset()。

后退 | 起点 | 前进
pos | 上一级 | range


range

(PHP 3>= 3.0.8, PHP 4 )

range -- 建立一个包含指定范围单元的数组

说明

array range ( mixed low, mixed high)

range() 返回数组中从 low 到 high 的单元，包括它们本身。如果 low > high，则序列将从 high 到 low。

例子 1. range() 例子

foreach(range(0, 9) as $number) {
    echo $number;
}
foreach(range('a', 'z') as $letter) {
    echo $letter;
}
foreach(range('z', 'a') as $letter) {
    echo $letter;
}

注: 在版本 4.1.0 之前 range() 函数只产生递增的整数数组。对于字符序列和递减数组的支持是 4.1.0 加入的。

例子 2. 模拟递减序列和字符序列

# array_reverse 可以用来调换 range 的顺序
foreach(array_reverse(range(0,9)) as $number) {
    echo $number;
}

# array_map() 可以用 chr() 将整数转换成字符
foreach(array_map('chr', range(ord('a'),ord('z'))) as $character) {
    echo $character;
}

另一个使用的例子参见 shuffle()。

后退 | 起点 | 前进
prev | 上一级 | reset


reset

(PHP 3, PHP 4 )

reset -- 将数组的内部指针指向第一个单元

说明

mixed reset ( array array)

reset() 将 array 的内部指针倒回到第一个单元。

reset() 返回第一个数组单元的值。

参见 current()，each()，next() 和 prev()。

后退 | 起点 | 前进
range | 上一级 | rsort


rsort

(PHP 3, PHP 4 )

rsort -- 对数组逆向排序

说明

void rsort ( array array [, int sort_flags])

本函数对数组进行逆向排序（最高到最低）。

例子 1. rsort() 例子

$fruits = array ("lemon", "orange", "banana", "apple");
rsort ($fruits);
reset ($fruits);
while (list ($key, $val) = each ($fruits)) {
    echo "$key = $val\n";
}

本例将显示：

0 = orange
1 = lemon
2 = banana
3 = apple

fruits 被按照字母顺序逆向排序。

可以用可选参数 sort_flags 改变排序的行为，详情见 sort()。

参见 arsort()，asort()，ksort()，sort() 和 usort()。

后退 | 起点 | 前进
reset | 上一级 | shuffle


shuffle

(PHP 3>= 3.0.8, PHP 4 )

shuffle -- 将数组打乱

说明

void shuffle ( array array)

本函数打乱（随机排列单元的顺序）一个数组。必须用 srand() 播下本函数的随机数发生器种子。

例子 1. shuffle() 例子

$numbers = range (1,20);
srand ((float)microtime()*1000000);
shuffle ($numbers);
while (list (, $number) = each ($numbers)) {
    echo "$number ";
}

参见 arsort()，asort()，ksort()，rsort()，sort() 和 usort()。

后退 | 起点 | 前进
rsort | 上一级 | sizeof


sizeof

(PHP 3, PHP 4 )

sizeof -- 统计变量中的单元数目

说明

int sizeof ( mixed var)

sizeof() 函数是 count() 的别名。。

参见 count()。

后退 | 起点 | 前进
shuffle | 上一级 | sort


sort

(PHP 3, PHP 4 )

sort -- 对数组排序

说明

void sort ( array array [, int sort_flags])

本函数对数组进行排序。当本函数结束时数组单元将被从最低到最高重新安排。

例子 1. sort() 例子

<?php

$fruits = array ("lemon", "orange", "banana", "apple");
sort ($fruits);
reset ($fruits);
while (list ($key, $val) = each ($fruits)) {
    echo "fruits[".$key."] = ".$val."\n";
}

?>

本例将显示：

fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange

fruits 被按照字母顺序排序。

可选的第二个参数 sort_flags 可以用以下值改变排序的行为：

排序类型标记：

  • SORT_REGULAR - 正常比较单元

  • SORT_NUMERIC - 单元被作为数字来比较

  • SORT_STRING - 单元被作为字符串来比较

参见 arsort()，asort()，ksort()，natsort()，natcasesort()，rsort()，usort()，array_multisort() 和 uksort()。

注: 第二个参数是 PHP 4 新加的。

后退 | 起点 | 前进
sizeof | 上一级 | uasort


uasort

(PHP 3>= 3.0.4, PHP 4 )

uasort -- 使用用户自定义的比较函数对数组中的值进行排序并保持索引关联

说明

void uasort ( array array, function cmp_function)

本函数对数组排序并保持索引和单元之间的关联。主要用于对那些单元顺序很重要的结合数组进行排序。比较函数是用户自定义的。

注: 用户自定义比较函数的例子请参考 usort() 和 uksort()。

注: 第二个参数函数名可以替换为一个数组，该数组由一个对象名和该对象名的一个方法名两个元素组成。

参见 usort()，uksort()，sort()，asort()，arsort()，ksort() 和 rsort()。

后退 | 起点 | 前进
sort | 上一级 | uksort


uksort

(PHP 3>= 3.0.4, PHP 4 )

uksort -- 使用用户自定义的比较函数对数组中的键名进行排序

说明

void uksort ( array array, function cmp_function)

本函数将使用用户提供的比较函数对数组中的键名进行排序。如果要排序的数组需要用一种不寻常的标准进行排序，那么应该使用此函数。

例子 1. uksort() 例子

function cmp ($a, $b) {
    if ($a == $b) return 0;
    return ($a > $b) ? -1 : 1;
}

$a = array (4 => "four", 3 => "three", 20 => "twenty", 10 => "ten");

uksort ($a, "cmp");

while (list ($key, $value) = each ($a)) {
    echo "$key: $value\n";
}

本例将显示：

20: twenty
10: ten
4: four
3: three

注: 第二个参数函数名可以替换为一个数组，该数组由一个对象名和该对象名的一个方法名两个元素组成。

参见 usort()，uasort()，sort()，asort()，arsort()，ksort()，natsort() 和 rsort()。

后退 | 起点 | 前进
uasort | 上一级 | usort


usort

(PHP 3>= 3.0.3, PHP 4 )

usort -- 使用用户自定义的比较函数对数组中的值进行排序

说明

void usort ( array array, string cmp_function)

本函数将用用户自定义的比较函数对一个数组中的值进行排序。如果要排序的数组需要用一种不寻常的标准进行排序，那么应该使用此函数。

比较函数必须在第一个参数被认为小于，等于或大于第二个参数时分别返回一个小于，等于或大于零的整数。

注: 如果两个成员比较结果相同，则它们在排序后的数组中的顺序未经定义。直到 PHP 4.0.6 为止，用户自定义函数将保留这些单元的原有顺序。但是由于在 4.1.0 中引进了新的排序算法，结果将不是这样了，对此也没有一个有效的解决方案。

例子 1. usort() 例子

function cmp ($a, $b) {
    if ($a == $b) return 0;
    return ($a > $b) ? -1 : 1;
}

$a = array (3, 2, 5, 6, 1);

usort ($a, "cmp");

while (list ($key, $value) = each ($a)) {
    echo "$key: $value\n";
}

本例将显示：

0: 6
1: 5
2: 3
3: 2
4: 1

注: 很明显在这个小例子中用 rsort() 函数更合适。

例子 2. 使用多维数组的 usort() 例子

function cmp ($a, $b) {
    return strcmp($a["fruit"], $b["fruit"]);
}

$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";

usort($fruits, "cmp");

while (list ($key, $value) = each ($fruits)) {
    echo "\$fruits[$key]: " . $value["fruit"] . "\n";
}

当排序多维数组时，$a 和 $b 包含到数组第一个索引的引用。

本例将显示：

$fruits[0]: apples
$fruits[1]: grapes
$fruits[2]: lemons

注: 第二个参数函数名可以替换为一个数组，该数组由一个对象名和该对象名的一个方法名两个元素组成。

例子 3. 使用对象的成员函数的 usort() 例子

class TestObj {
    var $name;

    function TestObj($name)
    {
        $this->name = $name;
    }

    /* This is the static comparing function: */
    function cmp_obj($a, $b)
    {
        $al = strtolower($a->name);
        $bl = strtolower($b->name);
        if ($al == $bl) return 0;
        return ($al > $bl) ? +1 : -1;
    }
}

$a[] = new TestObj("c");
$a[] = new TestObj("b");
$a[] = new TestObj("d");

uasort($a, array ("TestObj", "cmp_obj"));

foreach ($a as $item) {
    print $item->name."\n";
}

本例将显示：

b
c
d

警告

如果比较函数没有返回相容的值的话，在某些 C 的库中（例如 Solaris 系统）的基本的快速排序函数可能会导致 PHP 崩溃。

参见 uasort()，uksort()，sort()，asort()，arsort()，ksort()，natsort() 和 rsort()。

后退 | 起点 | 前进
uksort | 上一级 | Aspell functions [deprecated]


Aspell functions [deprecated]

PHP 手册
后退 前进

III. Aspell functions [deprecated]

介绍

The aspell() functions allows you to check the spelling on a word and offer suggestions.

需求

aspell works only with very old (up to .27.* or so) versions of aspell library. Neither this module, nor those versions of aspell library are supported any longer. If you want to use spell-checking capabilities in PHP, use pspell instead. It uses pspell library and works with newer versions of aspell.

安装

You need the aspell library, available from: http://aspell.sourceforge.net/.

相关参考

See also pspell.

目录
aspell_check_raw — Check a word without changing its case or trying to trim it [deprecated]
aspell_check — Check a word [deprecated]
aspell_new — Load a new dictionary [deprecated]
aspell_suggest — Suggest spellings of a word [deprecated]

后退 | 起点 | 前进
usort | 上一级 | aspell_check_raw


aspell_check_raw

(PHP 3>= 3.0.7, PHP 4 )

aspell_check_raw -- Check a word without changing its case or trying to trim it [deprecated]

Description

bool aspell_check_raw ( int dictionary_link, string word)

aspell_check_raw() checks the spelling of a word, without changing its case or trying to trim it in any way and returns TRUE if the spelling is correct, FALSE if not.

例子 1. aspell_check_raw()

$aspell_link = aspell_new("english");

if (aspell_check_raw($aspell_link, "test")) {
    echo "This is a valid spelling";
} else {
    echo "Sorry, wrong spelling";
}

后退 | 起点 | 前进
Aspell functions [deprecated] | 上一级 | aspell_check


aspell_check

(PHP 3>= 3.0.7, PHP 4 )

aspell_check -- Check a word [deprecated]

Description

bool aspell_check ( int dictionary_link, string word)

aspell_check() checks the spelling of a word and returns TRUE if the spelling is correct, FALSE if not.

例子 1. aspell_check()

$aspell_link = aspell_new("english");

if (aspell_check($aspell_link, "testt")) {
    echo "This is a valid spelling";
} else {
    echo "Sorry, wrong spelling";
}

后退 | 起点 | 前进
aspell_check_raw | 上一级 | aspell_new


aspell_new

(PHP 3>= 3.0.7, PHP 4 )

aspell_new -- Load a new dictionary [deprecated]

Description

int aspell_new ( string master [, string personal])

aspell_new() opens up a new dictionary and returns the dictionary link identifier for use in other aspell functions. Returns FALSE on error.

例子 1. aspell_new()

$aspell_link = aspell_new("english");

后退 | 起点 | 前进
aspell_check | 上一级 | aspell_suggest


aspell_suggest

(PHP 3>= 3.0.7, PHP 4 )

aspell_suggest -- Suggest spellings of a word [deprecated]

Description

array aspell_suggest ( int dictionary_link, string word)

aspell_suggest() returns an array of possible spellings for the given word.

例子 1. aspell_suggest()

$aspell_link = aspell_new("english");

if (!aspell_check($aspell_link, "test")) {
    $suggestions = aspell_suggest($aspell_link, "test");

    foreach ($suggestions as $suggestion) {
        echo "Possible spelling: $suggestion<br>\n";
    }
}

后退 | 起点 | 前进
aspell_new | 上一级 | BCMath Arbitrary Precision Mathematics Functions


BCMath Arbitrary Precision Mathematics Functions

PHP 手册
后退 前进

IV. BCMath Arbitrary Precision Mathematics Functions

介绍

For arbitrary precision mathematics PHP offers the Binary Calculator which supports numbers of any size and precision, represented as strings.

需求

Since PHP 4.0.4, libbcmath is bundled with PHP. You don't need any external libraries for this extension.

安装

In PHP 4, these functions are only available if PHP was configured with --enable-bcmath. In PHP 3, these functions are only available if PHP was not configured with --disable-bcmath.

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. BC math configuration options

Name | Default | Changeable
bcmath.scale | 0 | PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

Here is a short explanation of the configuration directives.

bcmath.scale integer

Number of decimal digits for all bcmath functions.

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

目录
bcadd — Add two arbitrary precision numbers
bccomp — Compare two arbitrary precision numbers
bcdiv — Divide two arbitrary precision numbers
bcmod — Get modulus of an arbitrary precision number
bcmul — Multiply two arbitrary precision number
bcpow — Raise an arbitrary precision number to another
bcscale — Set default scale parameter for all bc math functions
bcsqrt — Get the square root of an arbitrary precision number
bcsub — Subtract one arbitrary precision number from another

后退 | 起点 | 前进
aspell_suggest | 上一级 | bcadd


bcadd

(PHP 3, PHP 4 )

bcadd -- Add two arbitrary precision numbers

Description

string bcadd ( string left_operand, string right_operand [, int scale])

Adds the left_operand to the right_operand and returns the sum in a string. The optional scale parameter is used to set the number of digits after the decimal place in the result.

See also bcsub().

后退 | 起点 | 前进
BCMath Arbitrary Precision Mathematics Functions | 上一级 | bccomp


bccomp

(PHP 3, PHP 4 )

bccomp -- Compare two arbitrary precision numbers

Description

int bccomp ( string left_operand, string right_operand [, int scale])

Compares the left_operand to the right_operand and returns the result as an integer. The optional scale parameter is used to set the number of digits after the decimal place which will be used in the comparison. The return value is 0 if the two operands are equal. If the left_operand is larger than the right_operand the return value is +1 and if the left_operand is less than the right_operand the return value is -1.

后退 | 起点 | 前进
bcadd | 上一级 | bcdiv


bcdiv

(PHP 3, PHP 4 )

bcdiv -- Divide two arbitrary precision numbers

Description

string bcdiv ( string left_operand, string right_operand [, int scale])

Divides the left_operand by the right_operand and returns the result. The optional scale sets the number of digits after the decimal place in the result.

See also bcmul().

后退 | 起点 | 前进
bccomp | 上一级 | bcmod


bcmod

(PHP 3, PHP 4 )

bcmod -- Get modulus of an arbitrary precision number

Description

string bcmod ( string left_operand, string modulus)

Get the modulus of the left_operand using modulus.

See also bcdiv().

后退 | 起点 | 前进
bcdiv | 上一级 | bcmul


bcmul

(PHP 3, PHP 4 )

bcmul -- Multiply two arbitrary precision number

Description

string bcmul ( string left_operand, string right_operand [, int scale])

Multiply the left_operand by the right_operand and returns the result. The optional scale sets the number of digits after the decimal place in the result.

See also bcdiv().

后退 | 起点 | 前进
bcmod | 上一级 | bcpow


bcpow

(PHP 3, PHP 4 )

bcpow -- Raise an arbitrary precision number to another

Description

string bcpow ( string x, string y [, int scale])

Raise x to the power y. The optional scale can be used to set the number of digits after the decimal place in the result.

See also bcsqrt().

后退 | 起点 | 前进
bcmul | 上一级 | bcscale


bcscale

(PHP 3, PHP 4 )

bcscale -- Set default scale parameter for all bc math functions

Description

string bcscale ( int scale)

This function sets the default scale parameter for all subsequent bc math functions that do not explicitly specify a scale parameter.

后退 | 起点 | 前进
bcpow | 上一级 | bcsqrt


bcsqrt

(PHP 3, PHP 4 )

bcsqrt -- Get the square root of an arbitrary precision number

Description

string bcsqrt ( string operand [, int scale])

Return the square root of the operand. The optional scale parameter sets the number of digits after the decimal place in the result.

See also bcpow().

后退 | 起点 | 前进
bcscale | 上一级 | bcsub


bcsub

(PHP 3, PHP 4 )

bcsub -- Subtract one arbitrary precision number from another

Description

string bcsub ( string left_operand, string right_operand [, int scale])

Subtracts the right_operand from the left_operand and returns the result in a string. The optional scale parameter is used to set the number of digits after the decimal place in the result.

See also bcadd().

后退 | 起点 | 前进
bcsqrt | 上一级 | Bzip2 Compression Functions


Bzip2 Compression Functions

PHP 手册
后退 前进

V. Bzip2 Compression Functions

介绍

The bzip2 functions are used to transparently read and write bzip2 (.bz2) compressed files.

需求

This module uses the functions of the bzip2 library by Julian Seward

安装

Bzip2 support in PHP is not enabled by default. You will need to use the --with-bz2 configuration option when compiling PHP to enable bzip2 support. This module requires bzip2/libbzip2 version >= 1.0.x.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

This extension defines one resource type: a file pointer identifying the bz2-file to work on.

预定义常量

该扩展模块未定义任何常量。

范例

This example opens a temporary file and writes a test string to it, then prints out the contents of the file.

例子 1. Small bzip2 Example

<?php

$filename = "/tmp/testfile.bz2";
$str = "This is a test string.\n";

// open file for writing
$bz = bzopen($filename, "w");

// write string to file
bzwrite($bz, $str);

// close file
bzclose($bz);

// open file for reading
$bz = bzopen($filename, "r");

// read 10 characters
print bzread($bz, 10);

// output until end of the file (or the next 1024 char) and close it.
print bzread($bz);

bzclose($bz);

?>
目录
bzclose — Close a bzip2 file pointer
bzcompress — Compress a string into bzip2 encoded data
bzdecompress — Decompresses bzip2 encoded data
bzerrno — Returns a bzip2 error number
bzerror — Returns the bzip2 error number and error string in an array
bzerrstr — Returns a bzip2 error string
bzflush — Force a write of all buffered data
bzopen — Open a bzip2 compressed file
bzread — Binary safe bzip2 file read
bzwrite — Binary safe bzip2 file write

后退 | 起点 | 前进
bcsub | 上一级 | bzclose


bzclose

(PHP 4 >= 4.0.4)

bzclose -- Close a bzip2 file pointer

Description

int bzclose ( resource bz)

Closes the bzip2 file referenced by the pointer bz.

如果成功则返回 TRUE，失败则返回 FALSE。

The file pointer must be valid, and must point to a file successfully opened by bzopen().

See also bzopen().

后退 | 起点 | 前进
Bzip2 Compression Functions | 上一级 | bzcompress


bzcompress

(PHP 4 >= 4.0.4)

bzcompress -- Compress a string into bzip2 encoded data

Description

string bzcompress ( string source [, int blocksize [, int workfactor]])

bzcompress() compresses the source string and returns it as bzip2 encoded data.

The optional parameter blocksize specifies the blocksize used during compression and should be a number from 1 to 9 with 9 giving the best compression, but using more resources to do so. blocksize defaults to 4.

The optional parameter workfactor controls how the compression phase behaves when presented with worst case, highly repetitive, input data. The value can be between 0 and 250 with 0 being a special case and 30 being the default value. Regardless of the workfactor, the generated output is the same.

例子 1. bzcompress() Example

<?php
$str = "sample data";
$bzstr = bzcompress($str, 9);
print( $bzstr );
?>

See also bzdecompress().

后退 | 起点 | 前进
bzclose | 上一级 | bzdecompress


bzdecompress

(PHP 4 >= 4.0.4)

bzdecompress -- Decompresses bzip2 encoded data

Description

string bzdecompress ( string source [, int small])

bzdecompress() decompresses the source string containing bzip2 encoded data and returns it. If the optional parameter small is 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.

例子 1. bzdecompress()

<?php
$start_str = "This is not an honest face?";
$bzstr = bzcompress($start_str);

print( "Compressed String: " );
print( $bzstr );
print( "\n<br>\n" );

$str = bzdecompress($bzstr);
print( "Decompressed String: " );
print( $str );
print( "\n<br>\n" );
?>

See also bzcompress().

后退 | 起点 | 前进
bzcompress | 上一级 | bzerrno


bzerrno

(PHP 4 >= 4.0.4)

bzerrno -- Returns a bzip2 error number

Description

int bzerrno ( resource bz)

Returns the error number of any bzip2 error returned by the file pointer bz.

See also bzerror() and bzerrstr().

后退 | 起点 | 前进
bzdecompress | 上一级 | bzerror


bzerror

(PHP 4 >= 4.0.4)

bzerror -- Returns the bzip2 error number and error string in an array

Description

array bzerror ( resource bz)

Returns the error number and error string, in an associative array, of any bzip2 error returned by the file pointer bz.

例子 1. bzerror() Example

<?php
$error = bzerror($bz);

echo $error["errno"];
echo $error["errstr"];
?>

See also bzerrno() and bzerrstr().

后退 | 起点 | 前进
bzerrno | 上一级 | bzerrstr


bzerrstr

(PHP 4 >= 4.0.4)

bzerrstr -- Returns a bzip2 error string

Description

string bzerrstr ( resource bz)

Returns the error string of any bzip2 error returned by the file pointer bz.

See also bzerrno() and bzerror().

后退 | 起点 | 前进
bzerror | 上一级 | bzflush


bzflush

(PHP 4 >= 4.0.4)

bzflush -- Force a write of all buffered data

Description

int bzflush ( resource bz)

Forces a write of all buffered bzip2 data for the file pointer bz.

如果成功则返回 TRUE，失败则返回 FALSE。

See also bzread() and bzwrite().

后退 | 起点 | 前进
bzerrstr | 上一级 | bzopen


bzopen

(PHP 4 >= 4.0.4)

bzopen -- Open a bzip2 compressed file

Description

resource bzopen ( string filename, string mode)

Opens a bzip2 (.bz2) file for reading or writing. filename is the name of the file to open. mode is similar to the fopen() function (`r' for read, `w' for write, etc.).

If the open fails, the function returns FALSE, otherwise it returns a pointer to the newly opened file.

例子 1. bzopen() Example

<?php
$bz = bzopen("/tmp/foo.bz2", "r");
$decompressed_file = bzread($bz, filesize("/tmp/foo.bz2"));
bzclose($bz);

print( "The contents of /tmp/foo.bz2 are: " );
print( "\n<br>\n" );
print( $decompressed_file );
?>

See also bzclose().

后退 | 起点 | 前进
bzflush | 上一级 | bzread


bzread

(PHP 4 >= 4.0.4)

bzread -- Binary safe bzip2 file read

Description

string bzread ( resource bz [, int length])

bzread() reads up to length bytes from the bzip2 file pointer referenced by bz. Reading stops when length (uncompressed) bytes have been read or EOF is reached, whichever comes first. If the optional parameter length is not specified, bzread() will read 1024 (uncompressed) bytes at a time.

例子 1. bzread() Example

<?php
$bz = bzopen("/tmp/foo.bz2", "r");
$str = bzread($bz, 2048);
print( $str );
?>

See also bzwrite() and bzopen().

后退 | 起点 | 前进
bzopen | 上一级 | bzwrite


bzwrite

(PHP 4 >= 4.0.4)

bzwrite -- Binary safe bzip2 file write

Description

int bzwrite ( resource bz, string data [, int length])

bzwrite() writes the contents of the string data to the bzip2 file stream pointed to by bz. If the optional length argument is given, writing will stop after length (uncompressed) bytes have been written or the end of string is reached, whichever comes first.

例子 1. bzwrite() Example

<?php
$str = "uncompressed data";
$bz = bzopen("/tmp/foo.bz2", "w");
bzwrite($bz, $str, strlen($str));
bzclose($bz);
?>

See also bzread() and bzopen().

后退 | 起点 | 前进
bzread | 上一级 | Calendar functions


Calendar functions

PHP 手册
后退 前进

VI. Calendar functions

介绍

The calendar extension presents a series of functions to simplify converting between different calendar formats. The intermediary or standard it is based on is the Julian Day Count. The Julian Day Count is a count of days starting from January 1st, 4713 B.C. To convert between calendar systems, you must first convert to Julian Day Count, then to the calendar system of your choice. Julian Day Count is very different from the Julian Calendar! For more information on Julian Day Count, visit http://serendipity.magnet.ch/hermetic/cal_stud/jdn.htm. For more information on calendar systems visit http://genealogy.org/~scottlee/cal-overview.html. Excerpts from this page are included in these instructions, and are in quotes.

安装

To get these functions to work, you have to compile PHP with --enable-calendar.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

CAL_GREGORIAN (integer)

CAL_JULIAN (integer)

CAL_JEWISH (integer)

CAL_FRENCH (integer)

CAL_NUM_CALS (integer)

CAL_DOW_DAYNO (integer)

CAL_DOW_SHORT (integer)

CAL_DOW_LONG (integer)

CAL_MONTH_GREGORIAN_SHORT (integer)

CAL_MONTH_GREGORIAN_LONG (integer)

CAL_MONTH_JULIAN_SHORT (integer)

CAL_MONTH_JULIAN_LONG (integer)

CAL_MONTH_JEWISH (integer)

CAL_MONTH_FRENCH (integer)

The following constants are available since PHP 4.3.0 :

CAL_EASTER_DEFAULT (integer)

CAL_EASTER_ROMAN (integer)

CAL_EASTER_ALWAYS_GREGORIAN (integer)

CAL_EASTER_ALWAYS_JULIAN (integer)

目录
cal_days_in_month — Return the number of days in a month for a given year and calendar
cal_from_jd — Converts from Julian Day Count to a supported calendar and return extended information
cal_info — Returns information about a particular calendar
cal_to_jd — Converts from a supported calendar to Julian Day Count
easter_date — Get UNIX timestamp for midnight on Easter of a given year
easter_days — Get number of days after March 21 on which Easter falls for a given year
FrenchToJD — Converts a date from the French Republican Calendar to a Julian Day Count
GregorianToJD — Converts a Gregorian date to Julian Day Count
JDDayOfWeek — Returns the day of the week
JDMonthName — Returns a month name
JDToFrench — Converts a Julian Day Count to the French Republican Calendar
JDToGregorian — Converts Julian Day Count to Gregorian date
JDToJewish — Converts a Julian Day Count to the Jewish Calendar
JDToJulian — Converts a Julian Day Count to a Julian Calendar Date
jdtounix — Convert Julian Day to UNIX timestamp
JewishToJD — Converts a date in the Jewish Calendar to Julian Day Count
JulianToJD — Converts a Julian Calendar date to Julian Day Count
unixtojd — Convert UNIX timestamp to Julian Day

后退 | 起点 | 前进
bzwrite | 上一级 | cal_days_in_month


cal_days_in_month

(PHP 4 >= 4.1.0)

cal_days_in_month -- Return the number of days in a month for a given year and calendar

Description

int cal_days_in_month ( int calendar, int month, int year)

This function will return the number of days in the month of year for the specified calendar.

See also jdtounix().

后退 | 起点 | 前进
Calendar functions | 上一级 | cal_from_jd


cal_from_jd

(PHP 4 >= 4.1.0)

cal_from_jd -- Converts from Julian Day Count to a supported calendar and return extended information

Description

array cal_from_jd ( int jd, int calendar)

后退 | 起点 | 前进
cal_days_in_month | 上一级 | cal_info


cal_info

(PHP 4 >= 4.1.0)

cal_info -- Returns information about a particular calendar

Description

array cal_info ( int calendar)

后退 | 起点 | 前进
cal_from_jd | 上一级 | cal_to_jd


cal_to_jd

(PHP 4 >= 4.1.0)

cal_to_jd -- Converts from a supported calendar to Julian Day Count

Description

int cal_to_jd ( int calendar, int month, int day, int year)

后退 | 起点 | 前进
cal_info | 上一级 | easter_date


easter_date

(PHP 3>= 3.0.9, PHP 4 )

easter_date -- Get UNIX timestamp for midnight on Easter of a given year

Description

int easter_date ( [int year])

Returns the UNIX timestamp corresponding to midnight on Easter of the given year.

Since PHP 4.3.0, the year parameter is optional and defaults to the current year according to the localtime if ommited.

Warning: This function will generate a warning if the year is outside of the range for UNIX timestamps (i.e. before 1970 or after 2037).

例子 1. easter_date() example

echo date ("M-d-Y", easter_date(1999));        /* "Apr-04-1999" */
echo date ("M-d-Y", easter_date(2000));        /* "Apr-23-2000" */
echo date ("M-d-Y", easter_date(2001));        /* "Apr-15-2001" */

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@ely.anglican.org>)

See easter_days() for calculating Easter before 1970 or after 2037.

后退 | 起点 | 前进
cal_to_jd | 上一级 | easter_days


easter_days

(PHP 3>= 3.0.9, PHP 4 )

easter_days -- Get number of days after March 21 on which Easter falls for a given year

Description

int easter_days ( [int year [, int method]])

Returns the number of days after March 21 on which Easter falls for a given year. If no year is specified, the current year is assumed.

Since PHP 4.3.0, the year parameter is optional and defaults to the current year according to the localtime if ommited.

The method parameter was also introduced in PHP 4.3.0 and allows to calculate easter dates based on the Gregorian calendar during the years 1582 - 1752 when set to CAL_EASTER_ROMAN. See the calendar constants for more valid constants.

This function can be used instead of easter_date() to calculate Easter for years which fall outside the range of UNIX timestamps (i.e. before 1970 or after 2037).

例子 1. easter_days() example

echo easter_days (1999);        /* 14, i.e. April 4   */
echo easter_days (1492);        /* 32, i.e. April 22  */
echo easter_days (1913);        /*  2, i.e. March 23  */

The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.

(The code is based on a C program by Simon Kershaw, <webmaster@ely.anglican.org>)

See also easter_date().

后退 | 起点 | 前进
easter_date | 上一级 | FrenchToJD


FrenchToJD

(PHP 3, PHP 4 )

FrenchToJD -- Converts a date from the French Republican Calendar to a Julian Day Count

Description

int frenchtojd ( int month, int day, int year)

Converts a date from the French Republican Calendar to a Julian Day Count.

These routines only convert dates in years 1 through 14 (Gregorian dates 22 September 1792 through 22 September 1806). This more than covers the period when the calendar was in use.

后退 | 起点 | 前进
easter_days | 上一级 | GregorianToJD


GregorianToJD

(PHP 3, PHP 4 )

GregorianToJD -- Converts a Gregorian date to Julian Day Count

Description

int gregoriantojd ( int month, int day, int year)

Valid Range for Gregorian Calendar 4714 B.C. to 9999 A.D.

Although this function can handle dates all the way back to 4714 B.C., such use may not be meaningful. The Gregorian calendar was not instituted until October 15, 1582 (or October 5, 1582 in the Julian calendar). Some countries did not accept it until much later. For example, Britain converted in 1752, The USSR in 1918 and Greece in 1923. Most European countries used the Julian calendar prior to the Gregorian.

例子 1. Calendar functions

<?php
$jd = GregorianToJD (10,11,1970);
echo "$jd\n";
$gregorian = JDToGregorian ($jd);
echo "$gregorian\n";
?>

后退 | 起点 | 前进
FrenchToJD | 上一级 | JDDayOfWeek


JDDayOfWeek

(PHP 3, PHP 4 )

JDDayOfWeek -- Returns the day of the week

Description

mixed jddayofweek ( int julianday, int mode)

Returns the day of the week. Can return a string or an integer depending on the mode.

表格 1. Calendar week modes

Mode | Meaning
0 | Returns the day number as an int (0=sunday, 1=monday, etc)
1 | Returns string containing the day of week (english-gregorian)
2 | Returns a string containing the abbreviated day of week (english-gregorian)

后退 | 起点 | 前进
GregorianToJD | 上一级 | JDMonthName


JDMonthName

(PHP 3, PHP 4 )

JDMonthName -- Returns a month name

Description

string jdmonthname ( int julianday, int mode)

Returns a string containing a month name. mode tells this function which calendar to convert the Julian Day Count to, and what type of month names are to be returned.

表格 1. Calendar modes

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

后退 | 起点 | 前进
JDDayOfWeek | 上一级 | JDToFrench


JDToFrench

(PHP 3, PHP 4 )

JDToFrench -- Converts a Julian Day Count to the French Republican Calendar

Description

string jdtofrench ( int juliandaycount)

Converts a Julian Day Count to the French Republican Calendar.

后退 | 起点 | 前进
JDMonthName | 上一级 | JDToGregorian


JDToGregorian

(PHP 3, PHP 4 )

JDToGregorian -- Converts Julian Day Count to Gregorian date

Description

string jdtogregorian ( int julianday)

Converts Julian Day Count to a string containing the Gregorian date in the format of "month/day/year".

后退 | 起点 | 前进
JDToFrench | 上一级 | JDToJewish


JDToJewish

(PHP 3, PHP 4 )

JDToJewish -- Converts a Julian Day Count to the Jewish Calendar

Description

string jdtojewish ( int julianday)

Converts a Julian Day Count the the Jewish Calendar.

后退 | 起点 | 前进
JDToGregorian | 上一级 | JDToJulian


JDToJulian

(PHP 3, PHP 4 )

JDToJulian -- Converts a Julian Day Count to a Julian Calendar Date

Description

string jdtojulian ( int julianday)

Converts Julian Day Count to a string containing the Julian Calendar Date in the format of "month/day/year".

后退 | 起点 | 前进
JDToJewish | 上一级 | jdtounix


jdtounix

(PHP 4 )

jdtounix -- Convert Julian Day to UNIX timestamp

Description

int jdtounix ( int jday)

This function will return a UNIX timestamp corresponding to the Julian Day given in jday or FALSE if jday is not inside the UNIX epoch (Gregorian years between 1970 and 2037 or 2440588 <= jday <= 2465342 ). The time returned is localtime (and not GMT).

See also unixtojd().

后退 | 起点 | 前进
JDToJulian | 上一级 | JewishToJD


JewishToJD

(PHP 3, PHP 4 )

JewishToJD -- Converts a date in the Jewish Calendar to Julian Day Count

Description

int jewishtojd ( int month, int day, int year)

Although this function can handle dates all the way back to the year 1 (3761 B.C.), such use may not be meaningful. The Jewish calendar has been in use for several thousand years, but in the early days there was no formula to determine the start of a month. A new month was started when the new moon was first observed.

后退 | 起点 | 前进
jdtounix | 上一级 | JulianToJD


JulianToJD

(PHP 3, PHP 4 )

JulianToJD -- Converts a Julian Calendar date to Julian Day Count

Description

int juliantojd ( int month, int day, int year)

Valid Range for Julian Calendar 4713 B.C. to 9999 A.D.

Although this function can handle dates all the way back to 4713 B.C., such use may not be meaningful. The calendar was created in 46 B.C., but the details did not stabilize until at least 8 A.D., and perhaps as late at the 4th century. Also, the beginning of a year varied from one culture to another - not all accepted January as the first month.

注意

Remember, the current calendar system being used worldwide is the Gregorian calendar. gregoriantojd() can be used to convert such dates to their Julian Day count.

后退 | 起点 | 前进
JewishToJD | 上一级 | unixtojd


unixtojd

(PHP 4 )

unixtojd -- Convert UNIX timestamp to Julian Day

Description

int unixtojd ( [int timestamp])

Return the Julian Day for a UNIX timestamp (seconds since 1.1.1970), or for the current day if no timestamp is given.

See also jdtounix().

后退 | 起点 | 前进
JulianToJD | 上一级 | CCVS API Functions


CCVS API Functions

PHP 手册
后退 前进

VII. CCVS API Functions

介绍

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!

安装

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=$ccvs_path, where $ccvs_path is the path to your CCVS installation. Please note that CCVS support requires that $ccvs_path/lib and $ccvs_path/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.)

相关参考

Additional information about CCVS can be found at http://www.redhat.com/products/ccvs. RedHat maintains slightly outdated but still useful documentation at http://www.redhat.com/products/ccvs/support/CCVS3.3docs/ProgPHP.html.

目录
ccvs_add — Add data to a transaction
ccvs_auth — Perform credit authorization test on a transaction
ccvs_command — Performs a command which is peculiar to a single protocol, and thus is not available in the general CCVS API
ccvs_count — Find out how many transactions of a given type are stored in the system
ccvs_delete — Delete a transaction
ccvs_done — Terminate CCVS engine and do cleanup work
ccvs_init — Initialize CCVS for use
ccvs_lookup — Look up an item of a particular type in the database #
ccvs_new — Create a new, blank transaction
ccvs_report — Return the status of the background communication process
ccvs_return — Transfer funds from the merchant to the credit card holder
ccvs_reverse — Perform a full reversal on an already-processed authorization
ccvs_sale — Transfer funds from the credit card holder to the merchant
ccvs_status — Check the status of an invoice
ccvs_textvalue — Get text return value for previous function call
ccvs_void — Perform a full reversal on a completed transaction

后退 | 起点 | 前进
unixtojd | 上一级 | ccvs_add


ccvs_add

(PHP 4 >= 4.0.2)

ccvs_add -- Add data to a transaction

Description

string ccvs_add ( string session, string invoice, string argtype, string argval)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
CCVS API Functions | 上一级 | ccvs_auth


ccvs_auth

(PHP 4 >= 4.0.2)

ccvs_auth -- Perform credit authorization test on a transaction

Description

string ccvs_auth ( string session, string invoice)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ccvs_add | 上一级 | ccvs_command


ccvs_command

(PHP 4 >= 4.0.2)

ccvs_command -- Performs a command which is peculiar to a single protocol, and thus is not available in the general CCVS API

Description

string ccvs_command ( string session, string type, string argval)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ccvs_auth | 上一级 | ccvs_count


ccvs_count

(PHP 4 >= 4.0.2)

ccvs_count -- Find out how many transactions of a given type are stored in the system

Description

int ccvs_count ( string session, string type)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ccvs_command | 上一级 | ccvs_delete


ccvs_delete

(PHP 4 >= 4.0.2)

ccvs_delete -- Delete a transaction

Description

string ccvs_delete ( string session, string invoice)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ccvs_count | 上一级 | ccvs_done


ccvs_done

(PHP 4 >= 4.0.2)

ccvs_done -- Terminate CCVS engine and do cleanup work

Description

string ccvs_done ( string sess)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ccvs_delete | 上一级 | ccvs_init


ccvs_init

(PHP 4 >= 4.0.2)

ccvs_init -- Initialize CCVS for use

Description

string ccvs_init ( string name)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ccvs_done | 上一级 | ccvs_lookup


ccvs_lookup

(PHP 4 >= 4.0.2)

ccvs_lookup -- Look up an item of a particular type in the database #

Description

string ccvs_lookup ( string session, string invoice, int inum)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ccvs_init | 上一级 | ccvs_new


ccvs_new

(PHP 4 >= 4.0.2)

ccvs_new -- Create a new, blank transaction

Description

string ccvs_new ( string session, string invoice)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ccvs_lookup | 上一级 | ccvs_report


ccvs_report

(PHP 4 >= 4.0.2)

ccvs_report -- Return the status of the background communication process

Description

string ccvs_report ( string session, string type)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ccvs_new | 上一级 | ccvs_return


ccvs_return

(PHP 4 >= 4.0.2)

ccvs_return -- Transfer funds from the merchant to the credit card holder

Description

string ccvs_return ( string session, string invoice)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ccvs_report | 上一级 | ccvs_reverse


ccvs_reverse

(PHP 4 >= 4.0.2)

ccvs_reverse -- Perform a full reversal on an already-processed authorization

Description

string ccvs_reverse ( string session, string invoice)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ccvs_return | 上一级 | ccvs_sale


ccvs_sale

(PHP 4 >= 4.0.2)

ccvs_sale -- Transfer funds from the credit card holder to the merchant

Description

string ccvs_sale ( string session, string invoice)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ccvs_reverse | 上一级 | ccvs_status


ccvs_status

(PHP 4 >= 4.0.2)

ccvs_status -- Check the status of an invoice

Description

string ccvs_status ( string session, string invoice)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ccvs_sale | 上一级 | ccvs_textvalue


ccvs_textvalue

(PHP 4 >= 4.0.2)

ccvs_textvalue -- Get text return value for previous function call

Description

string ccvs_textvalue ( string session)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ccvs_status | 上一级 | ccvs_void


ccvs_void

(PHP 4 >= 4.0.2)

ccvs_void -- Perform a full reversal on a completed transaction

Description

string ccvs_void ( string session, string invoice)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ccvs_textvalue | 上一级 | COM support functions for Windows


COM support functions for Windows

PHP 手册
后退 前进

VIII. COM support functions for Windows

介绍

COM is a technology which allows the reuse of code written in any language (by any language) using a standard calling convention and hiding behind APIs the implementation details such as what machine the Component is stored on and the executable which houses it. It can be thought of as a super Remote Procedure Call (RPC) mechanism with some basic object roots. It separates implementation from interface.

COM encourages versioning, separation of implementation from interface and hiding the implementation details such as executable location and the language it was written in.

需求

COM functions are only available on the Windows version of PHP.

安装

这些函数作为 PHP 核心的一部分，无需被安装即可使用。

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. Com configuration options

Name | Default | Changeable
com.allow_dcom | "0" | PHP_INI_SYSTEM
com.autoregister_typelib | "0" | PHP_INI_SYSTEM
com.autoregister_verbose | "0" | PHP_INI_SYSTEM
com.autoregister_casesensitive | "1" | PHP_INI_SYSTEM
com.typelib_file | "" | PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

CLSCTX_INPROC_SERVER (integer)

CLSCTX_INPROC_HANDLER (integer)

CLSCTX_LOCAL_SERVER (integer)

CLSCTX_REMOTE_SERVER (integer)

CLSCTX_SERVER (integer)

CLSCTX_ALL (integer)

VT_NULL (integer)

VT_EMPTY (integer)

VT_UI1 (integer)

VT_I2 (integer)

VT_I4 (integer)

VT_R4 (integer)

VT_R8 (integer)

VT_BOOL (integer)

VT_ERROR (integer)

VT_CY (integer)

VT_DATE (integer)

VT_BSTR (integer)

VT_DECIMAL (integer)

VT_UNKNOWN (integer)

VT_DISPATCH (integer)

VT_VARIANT (integer)

VT_I1 (integer)

VT_UI2 (integer)

VT_UI4 (integer)

VT_INT (integer)

VT_UINT (integer)

VT_ARRAY (integer)

VT_BYREF (integer)

CP_ACP (integer)

CP_MACCP (integer)

CP_OEMCP (integer)

CP_UTF7 (integer)

CP_UTF8 (integer)

CP_SYMBOL (integer)

CP_THREAD_ACP (integer)

相关参考

For further information on COM read the COM specification or perhaps take a look at Don Box's Yet Another COM Library (YACL)

目录
COM — COM class
VARIANT — VARIANT class
com_addref — Increases the components reference counter.
com_get — Gets the value of a COM Component's property
com_invoke — Calls a COM component's method.
com_isenum — Grabs an IEnumVariant
com_load_typelib — Loads a Typelib
com_load — Creates a new reference to a COM component
com_propget — Gets the value of a COM Component's property
com_propput — Assigns a value to a COM component's property
com_propset — Assigns a value to a COM component's property
com_release — Decreases the components reference counter.
com_set — Assigns a value to a COM component's property

后退 | 起点 | 前进
ccvs_void | 上一级 | COM


COM

(no version information, might be only in CVS)

COM -- COM class

大纲

$obj = new COM("server.object")

Description

The COM class provides a framework to integrate (D)COM components into your php scripts.

Methods

string COM::COM ( string module_name [, string server_name [, int codepage]])

COM class constructor. Parameters:

module_name

name or class-id of the requested component.

server_name

name of the DCOM server from which the component should be fetched. If NULL, localhost is assumed. To allow DCOM com.allow_dcom has to be set to TRUE in php.ini.

codepage

specifies the codepage that is used to convert php-strings to unicode-strings and vice versa. Possible values are CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 and CP_UTF8.

例子 1. COM example (1)

// starting word
$word = new COM("word.application") or die("Unable to instanciate Word");
print "Loaded Word, version {$word->Version}\n";

//bring it to front
$word->Visible = 1;

//open an empty document
$word->Documents->Add();

//do some weird stuff
$word->Selection->TypeText("This is a test...");
$word->Documents[1]->SaveAs("Useless test.doc");

//closing word
$word->Quit();

//free the object
$word->Release();
$word = null;

例子 2. COM example (2)

$conn = new COM("ADODB.Connection") or die("Cannot start ADO");
$conn->Open("Provider=SQLOLEDB; Data Source=localhost;
Initial Catalog=database; User ID=user; Password=password");

$rs = $conn->Execute("SELECT * FROM sometable");    // Recordset

$num_columns = $rs->Fields->Count();
echo $num_columns . "\n";

for ($i=0; $i < $num_columns; $i++)
{
    $fld[$i] = $rs->Fields($i);
}

$rowcount = 0;
while (!$rs->EOF)
{
    for ($i=0; $i < $num_columns; $i++)
    {
        echo $fld[$i]->value . "\t";
    }
    echo "\n";
    $rowcount++;            // increments rowcount
    $rs->MoveNext();
}

$rs->Close();
$conn->Close();

$rs->Release();
$conn->Release();

$rs = null;
$conn = null;

后退 | 起点 | 前进
COM support functions for Windows | 上一级 | VARIANT


VARIANT

(no version information, might be only in CVS)

VARIANT -- VARIANT class

大纲

$vVar = new VARIANT($var)

Description

A simple container to wrap variables into VARIANT structures.

Methods

string VARIANT::VARIANT ( [mixed value [, int type [, int codepage]]])

VARIANT class constructor. Parameters:

value

initial value. if omitted an VT_EMPTY object is created.

type

specifies the content type of the VARIANT object. Possible values are 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 and VT_VARIANT. These values are mutual exclusive, but they can be combined with VT_BYREF to specify being a value. If omitted, the type of value is used. Consult the msdn library for additional information.

codepage

specifies the codepage that is used to convert php-strings to unicode-strings and vice versa. Possible values are CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 and CP_UTF8.

后退 | 起点 | 前进
COM | 上一级 | com_addref


com_addref

(PHP 4 >= 4.1.0)

com_addref -- Increases the components reference counter.

Description

void com_addref ( void)

Increases the components reference counter.

后退 | 起点 | 前进
VARIANT | 上一级 | com_get


com_get

(PHP 3>= 3.0.3, PHP 4 >= 4.0.5)

com_get -- Gets the value of a COM Component's property

Description

mixed com_get ( resource com_object, string property)

Returns the value of the property of the COM component referenced by com_object. Returns FALSE on error.

后退 | 起点 | 前进
com_addref | 上一级 | com_invoke


com_invoke

(PHP 3>= 3.0.3)

com_invoke -- Calls a COM component's method.

Description

mixed com_invoke ( resource com_object, string function_name [, mixed function parameters, ...])

com_invoke() invokes a method of the COM component referenced by com_object. Returns FALSE on error, returns the function_name's return value on success.

后退 | 起点 | 前进
com_get | 上一级 | com_isenum


com_isenum

(PHP 4 >= 4.1.0)

com_isenum -- Grabs an IEnumVariant

Description

void com_isenum ( object com_module)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
com_invoke | 上一级 | com_load_typelib


com_load_typelib

(PHP 4 >= 4.1.0)

com_load_typelib -- Loads a Typelib

Description

void com_load_typelib ( string typelib_name [, int case_insensitive])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
com_isenum | 上一级 | com_load


com_load

(PHP 3>= 3.0.3)

com_load -- Creates a new reference to a COM component

Description

string com_load ( string module name [, string server name [, int codepage]])

com_load() creates a new COM component and returns a reference to it. Returns FALSE on failure. Possible values for codepage are CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 and CP_UTF8.

后退 | 起点 | 前进
com_load_typelib | 上一级 | com_propget


com_propget

(PHP 3>= 3.0.3, PHP 4 >= 4.0.5)

com_propget -- Gets the value of a COM Component's property

Description

mixed com_propget ( resource com_object, string property)

This function is an alias for com_get().

后退 | 起点 | 前进
com_load | 上一级 | com_propput


com_propput

(PHP 3>= 3.0.3, PHP 4 >= 4.0.5)

com_propput -- Assigns a value to a COM component's property

Description

void com_propput ( resource com_object, string property, mixed value)

This function is an alias for com_set().

后退 | 起点 | 前进
com_propget | 上一级 | com_propset


com_propset

(PHP 3>= 3.0.3, PHP 4 >= 4.0.5)

com_propset -- Assigns a value to a COM component's property

Description

void com_propset ( resource com_object, string property, mixed value)

This function is an alias for com_set().

后退 | 起点 | 前进
com_propput | 上一级 | com_release


com_release

(PHP 4 >= 4.1.0)

com_release -- Decreases the components reference counter.

Description

void com_release ( void)

Decreases the components reference counter.

后退 | 起点 | 前进
com_propset | 上一级 | com_set


com_set

(PHP 3>= 3.0.3, PHP 4 >= 4.0.5)

com_set -- Assigns a value to a COM component's property

Description

void com_set ( resource com_object, string property, mixed value)

Sets the value of the property of the COM component referenced by com_object. Returns the newly set value if succeeded, FALSE on error.

后退 | 起点 | 前进
com_release | 上一级 | Class/Object Functions


Class/Object Functions

PHP 手册
后退 前进

IX. Class/Object Functions

介绍

These functions allow you to obtain information about classes and instance objects. You can obtain the name of the class to which a object belongs, as well as its member properties and methods. Using these functions, you can find out not only the class membership of an object, but also its parentage (i.e. what class is the object class extending).

范例

In this example, we first define a base class and an extension of the class. The base class describes a general vegetable, whether it is edible or not and what is its color. The subclass Spinach adds a method to cook it and another to find out if it is cooked.

例子 1. classes.inc

<?php

// base class with member properties and methods
class Vegetable {

    var $edible;
    var $color;

    function Vegetable( $edible, $color="green" ) {
        $this->edible = $edible;
        $this->color = $color;
    }

    function is_edible() {
        return $this->edible;
    }

    function what_color() {
        return $this->color;
    }

} // end of class Vegetable

// extends the base class
class Spinach extends Vegetable {

    var $cooked = false;

    function Spinach() {
        $this->Vegetable( true, "green" );
    }

    function cook_it() {
        $this->cooked = true;
    }

    function is_cooked() {
        return $this->cooked;
    }

} // end of class Spinach

?>

We then instantiate 2 objects from these classes and print out information about them, including their class parentage. We also define some utility functions, mainly to have a nice printout of the variables.

例子 2. test_script.php

<pre>
<?php

include "classes.inc";

// utility functions

function print_vars($obj) {
    $arr = get_object_vars($obj);
    while (list($prop, $val) = each($arr))
        echo "\t$prop = $val\n";
}

function print_methods($obj) {
    $arr = get_class_methods(get_class($obj));
    foreach ($arr as $method)
        echo "\tfunction $method()\n";
}

function class_parentage($obj, $class) {
    global $$obj;
    if (is_subclass_of($$obj, $class)) {
        echo "Object $obj belongs to class ".get_class($$obj);
        echo " a subclass of $class\n";
    } else {
        echo "Object $obj does not belong to a subclass of $class\n";
    }
}

// instantiate 2 objects

$veggie = new Vegetable(true,"blue");
$leafy = new Spinach();

// print out information about objects
echo "veggie: CLASS ".get_class($veggie)."\n";
echo "leafy: CLASS ".get_class($leafy);
echo ", PARENT ".get_parent_class($leafy)."\n";

// show veggie properties
echo "\nveggie: Properties\n";
print_vars($veggie);

// and leafy methods
echo "\nleafy: Methods\n";
print_methods($leafy);

echo "\nParentage:\n";
class_parentage("leafy", "Spinach");
class_parentage("leafy", "Vegetable");
?>
</pre>

One important thing to note in the example above is that the object $leafy is an instance of the class Spinach which is a subclass of Vegetable, therefore the last part of the script above will output:

[...]
Parentage:
Object leafy does not belong to a subclass of Spinach
Object leafy belongs to class spinach a subclass of Vegetable

目录
call_user_method_array — Call a user method given with an array of parameters [deprecated]
call_user_method — Call a user method on an specific object [deprecated]
class_exists — Checks if the class has been defined
get_class_methods — Returns an array of class methods' names
get_class_vars — Returns an array of default properties of the class
get_class — Returns the name of the class of an object
get_declared_classes — Returns an array with the name of the defined classes
get_object_vars — Returns an associative array of object properties
get_parent_class — Retrieves the parent class name for object or class
is_a — Returns TRUE if the object is of this class or has this class as one of its parents
is_subclass_of — Returns TRUE if the object has this class as one of its parents
method_exists — Checks if the class method exists

后退 | 起点 | 前进
com_set | 上一级 | call_user_method_array


call_user_method_array

(PHP 4 >= 4.0.5)

call_user_method_array -- Call a user method given with an array of parameters [deprecated]

Description

mixed call_user_method_array ( string method_name, object obj [, array paramarr])

警告

The call_user_method_array() function is deprecated as of PHP 4.1.0, use the call_user_func_array() variety with the array(&$obj, "method_name") syntax instead.

Calls the method referred by method_name from the user defined obj object, using the parameters in paramarr.

See also:
call_user_func_array(),
call_user_func(),
call_user_method().

注: This function was added to the CVS code after release of PHP 4.0.4pl1

后退 | 起点 | 前进
Class/Object Functions | 上一级 | call_user_method


call_user_method

(PHP 3>= 3.0.3, PHP 4 )

call_user_method -- Call a user method on an specific object [deprecated]

Description

mixed call_user_method ( string method_name, object obj [, mixed parameter [, mixed ...]])

警告

The call_user_method() function is deprecated as of PHP 4.1.0, use the call_user_func() variety with the array(&$obj, "method_name") syntax instead.

Calls the method referred by method_name from the user defined obj object. An example of usage is below, where we define a class, instantiate an object and use call_user_method() to call indirectly its print_info method.

<?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");
?>

See also call_user_func_array(),
call_user_func(), and
call_user_method_array().

后退 | 起点 | 前进
call_user_method_array | 上一级 | class_exists


class_exists

(PHP 4 )

class_exists -- Checks if the class has been defined

Description

bool class_exists ( string class_name)

This function returns TRUE if the class given by class_name has been defined, FALSE otherwise.

后退 | 起点 | 前进
call_user_method | 上一级 | get_class_methods


get_class_methods

(PHP 4 )

get_class_methods -- Returns an array of class methods' names

Description

array get_class_methods ( mixed class_name)

This function returns an array of method names defined for the class specified by class_name.

注: As of PHP 4.0.6, you can specify the object itself instead of class_name. For example:

$class_methods = get_class_methods($my_class); // see below the full example

例子 1. get_class_methods() example

<?php

class myclass {
    // constructor
    function myclass() {
        return(TRUE);
    }

    // method 1
    function myfunc1() {
        return(TRUE);
    }

    // method 2
    function myfunc2() {
        return(TRUE);
    }
}

$my_object = new myclass();

$class_methods = get_class_methods(get_class($my_object));

foreach ($class_methods as $method_name) {
    echo "$method_name\n";
}

?>

Will produce:

myclass
myfunc1
myfunc2

See also get_class_vars() and get_object_vars().

后退 | 起点 | 前进
class_exists | 上一级 | get_class_vars


get_class_vars

(PHP 4 )

get_class_vars -- Returns an array of default properties of the class

Description

array get_class_vars ( string class_name)

This function will return an associative array of default properties of the class. The resulting array elements are in the form of varname => value.

注: Uninitialized class variables will not be reported by get_class_vars().

例子 1. get_class_vars() example

<?php

class myclass {

    var $var1; // this has no default value...
    var $var2 = "xyz";
    var $var3 = 100;

    // constructor
    function myclass() {
        return(TRUE);
    }

}

$my_class = new myclass();

$class_vars = get_class_vars(get_class($my_class));

foreach ($class_vars as $name => $value) {
    echo "$name : $value\n";
}

?>

Will produce:

var2 : xyz
var3 : 100

See also get_class_methods(), get_object_vars()

后退 | 起点 | 前进
get_class_methods | 上一级 | get_class


get_class

(PHP 4 )

get_class -- Returns the name of the class of an object

Description

string get_class ( object obj)

This function returns the name of the class of which the object obj is an instance. Returns FALSE if obj is not an object.

注: get_class() returns a user defined class name in lowercase. A class defined in a PHP extension is returned in its original notation.

See also get_parent_class(),
gettype(), and
is_subclass_of().

后退 | 起点 | 前进
get_class_vars | 上一级 | get_declared_classes


get_declared_classes

(PHP 4 )

get_declared_classes -- Returns an array with the name of the defined classes

Description

array get_declared_classes ( void)

This function returns an array of the names of the declared classes in the current script.

注: In PHP 4.0.1pl2, three extra classes are returned at the beginning of the array: stdClass (defined in Zend/zend.c), OverloadedTestClass (defined in ext/standard/basic_functions.c) and Directory (defined in ext/standard/dir.c).

Also note that depending on what libraries you have compiled into PHP, additional classes could be present. This means that you will not be able to define your own classes using these names. There is a list of predefined classes in the Predefined Classes section of the appendices.

后退 | 起点 | 前进
get_class | 上一级 | get_object_vars


get_object_vars

(PHP 4 )

get_object_vars -- Returns an associative array of object properties

Description

array get_object_vars ( object obj)

This function returns an associative array of defined object properties for the specified object obj. If variables declared in the class of which the obj is an instance, have not been assigned a value, those will not be returned in the array.

例子 1. Use of get_object_vars()

<?php
class Point2D {
    var $x, $y;
    var $label;

    function Point2D($x, $y) {
        $this->x = $x;
        $this->y = $y;
    }

    function setLabel($label) {
        $this->label = $label;
    }

    function getPoint() {
        return array("x" => $this->x,
                     "y" => $this->y,
                     "label" => $this->label);
    }
}

// "$label" is declared but not defined
$p1 = new Point2D(1.233, 3.445);
print_r(get_object_vars($p1));

$p1->setLabel("point #1");
print_r(get_object_vars($p1));

?>
The printout of the above program will be:
Array
 (
     [x] => 1.233
     [y] => 3.445
 )

 Array
 (
     [x] => 1.233
     [y] => 3.445
     [label] => point #1
 )

See also get_class_methods() and get_class_vars()!

后退 | 起点 | 前进
get_declared_classes | 上一级 | get_parent_class


get_parent_class

(PHP 4 )

get_parent_class -- Retrieves the parent class name for object or class

Description

string get_parent_class ( mixed obj)

If obj is an object, returns the name of the parent class of the class of which obj is an instance.

If obj is a string, returns the name of the parent class of the class with that name. This functionality was added in PHP 4.0.5.

See also get_class() and is_subclass_of()

后退 | 起点 | 前进
get_object_vars | 上一级 | is_a


is_a

(PHP 4 >= 4.2.0)

is_a -- Returns TRUE if the object is of this class or has this class as one of its parents

Description

bool is_a ( object object, string class_name)

This function returns TRUE if the object is of this class or has this class as one of its parents, FALSE otherwise.

See also get_class(),
get_parent_class(), and
is_subclass_of().

后退 | 起点 | 前进
get_parent_class | 上一级 | is_subclass_of


is_subclass_of

(PHP 4 )

is_subclass_of -- Returns TRUE if the object has this class as one of its parents

Description

bool is_subclass_of ( object object, string class_name)

This function returns TRUE if the object object, belongs to a class which is a subclass of class_name, FALSE otherwise.

See also get_class(),
get_parent_class() and
is_a().

后退 | 起点 | 前进
is_a | 上一级 | method_exists


method_exists

(PHP 4 )

method_exists -- Checks if the class method exists

Description

bool method_exists ( object object, string method_name)

This function returns TRUE if the method given by method_name has been defined for the given object, FALSE otherwise.

后退 | 起点 | 前进
is_subclass_of | 上一级 | ClibPDF functions


ClibPDF functions

PHP 手册
后退 前进

X. ClibPDF functions

介绍

ClibPDF lets you create PDF documents with PHP. It is available for download from FastIO, but requires that you purchase a license for commercial use. 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.

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

CPDF_PM_NONE (integer)

CPDF_PM_OUTLINES (integer)

CPDF_PM_THUMBS (integer)

CPDF_PM_FULLSCREEN (integer)

CPDF_PL_SINGLE (integer)

CPDF_PL_1COLUMN (integer)

CPDF_PL_2LCOLUMN (integer)

CPDF_PL_2RCOLUMN (integer)

范例

例子 1. Simple ClibPDF Example

<?php
$cpdf = cpdf_open(0);
cpdf_page_init($cpdf, 1, 0, 595, 842, 1.0);
cpdf_add_outline($cpdf, 0, 0, 0, 1, "Page 1");
cpdf_begin_text($cpdf);
cpdf_set_font($cpdf, "Times-Roman", 30, "WinAnsiEncoding");
cpdf_set_text_rendering($cpdf, 1);
cpdf_text($cpdf, "Times Roman outlined", 50, 750);
cpdf_end_text($cpdf);
cpdf_moveto($cpdf, 50, 740);
cpdf_lineto($cpdf, 330, 740);
cpdf_stroke($cpdf);
cpdf_finalize($cpdf);
Header("Content-type: application/pdf");
cpdf_output_buffer($cpdf);
cpdf_close($cpdf);
?>

The pdflib distribution contains a more complex example which creates a series of pages with an analog clock. Here is that example converted into PHP using the ClibPDF extension:

例子 2. pdfclock example from pdflib 2.0 distribution

<?php
$radius = 200;
$margin = 20;
$pagecount = 40;

$pdf = cpdf_open(0);
cpdf_set_creator($pdf, "pdf_clock.php3");
cpdf_set_title($pdf, "Analog Clock");

while($pagecount-- > 0) {
  cpdf_page_init($pdf, $pagecount+1, 0, 2 * ($radius + $margin), 2 * ($radius + $margin), 1.0);

  cpdf_set_page_animation($pdf, 4, 0.5, 0, 0, 0);  /* wipe */

  cpdf_translate($pdf, $radius + $margin, $radius + $margin);
  cpdf_save($pdf);
  cpdf_setrgbcolor($pdf, 0.0, 0.0, 1.0);

  /* minute strokes */
  cpdf_setlinewidth($pdf, 2.0);
  for ($alpha = 0; $alpha < 360; $alpha += 6)
    {
    cpdf_rotate($pdf, 6.0);
    cpdf_moveto($pdf, $radius, 0.0);
    cpdf_lineto($pdf, $radius-$margin/3, 0.0);
    cpdf_stroke($pdf);
    }

  cpdf_restore($pdf);
  cpdf_save($pdf);

  /* 5 minute strokes */
  cpdf_setlinewidth($pdf, 3.0);
  for ($alpha = 0; $alpha < 360; $alpha += 30)
  {
    cpdf_rotate($pdf, 30.0);
    cpdf_moveto($pdf, $radius, 0.0);
    cpdf_lineto($pdf, $radius-$margin, 0.0);
    cpdf_stroke($pdf);
  }

  $ltime = getdate();

  /* draw hour hand */
  cpdf_save($pdf);
  cpdf_rotate($pdf, -(($ltime['minutes']/60.0) + $ltime['hours'] - 3.0) * 30.0);
  cpdf_moveto($pdf, -$radius/10, -$radius/20);
  cpdf_lineto($pdf, $radius/2, 0.0);
  cpdf_lineto($pdf, -$radius/10, $radius/20);
  cpdf_closepath($pdf);
  cpdf_fill($pdf);
  cpdf_restore($pdf);

  /* draw minute hand */
  cpdf_save($pdf);
  cpdf_rotate($pdf, -(($ltime['seconds']/60.0) + $ltime['minutes'] - 15.0) * 6.0);
  cpdf_moveto($pdf, -$radius/10, -$radius/20);
  cpdf_lineto($pdf, $radius * 0.8, 0.0);
  cpdf_lineto($pdf, -$radius/10, $radius/20);
  cpdf_closepath($pdf);
  cpdf_fill($pdf);
  cpdf_restore($pdf);

  /* draw second hand */
  cpdf_setrgbcolor($pdf, 1.0, 0.0, 0.0);
  cpdf_setlinewidth($pdf, 2);
  cpdf_save($pdf);
  cpdf_rotate($pdf, -(($ltime['seconds'] - 15.0) * 6.0));
  cpdf_moveto($pdf, -$radius/5, 0.0);
  cpdf_lineto($pdf, $radius, 0.0);
  cpdf_stroke($pdf);
  cpdf_restore($pdf);

  /* draw little circle at center */
  cpdf_circle($pdf, 0, 0, $radius/30);
  cpdf_fill($pdf);

  cpdf_restore($pdf);

  cpdf_finalize_page($pdf, $pagecount+1);
}

cpdf_finalize($pdf);
Header("Content-type: application/pdf");
cpdf_output_buffer($pdf);
cpdf_close($pdf);
?>

相关参考

See also the PDFlib extension documentation.

目录
cpdf_add_annotation — Adds annotation
cpdf_add_outline — Adds bookmark for current page
cpdf_arc — Draws an arc
cpdf_begin_text — Starts text section
cpdf_circle — Draw a circle
cpdf_clip — Clips to current path
cpdf_close — Closes the pdf document
cpdf_closepath_fill_stroke — Close, fill and stroke current path
cpdf_closepath_stroke — Close path and draw line along path
cpdf_closepath — Close path
cpdf_continue_text — Output text in next line
cpdf_curveto — Draws a curve
cpdf_end_text — Ends text section
cpdf_fill_stroke — Fill and stroke current path
cpdf_fill — Fill current path
cpdf_finalize_page — Ends page
cpdf_finalize — Ends document
cpdf_global_set_document_limits — Sets document limits for any pdf document
cpdf_import_jpeg — Opens a JPEG image
cpdf_lineto — Draws a line
cpdf_moveto — Sets current point
cpdf_newpath — Starts a new path
cpdf_open — Opens a new pdf document
cpdf_output_buffer — Outputs the pdf document in memory buffer
cpdf_page_init — Starts new page
cpdf_place_inline_image — Places an image on the page
cpdf_rect — Draw a rectangle
cpdf_restore — Restores formerly saved environment
cpdf_rlineto — Draws a line
cpdf_rmoveto — Sets current point
cpdf_rotate_text — Sets text rotation angle
cpdf_rotate — Sets rotation
cpdf_save_to_file — Writes the pdf document into a file
cpdf_save — Saves current environment
cpdf_scale — Sets scaling
cpdf_set_action_url — Sets hyperlink
cpdf_set_char_spacing — Sets character spacing
cpdf_set_creator — Sets the creator field in the pdf document
cpdf_set_current_page — Sets current page
cpdf_set_font_directories — Sets directories to search when using external fonts
cpdf_set_font_map_file — Sets fontname to filename translation map when using external fonts
cpdf_set_font — Select the current font face and size
cpdf_set_horiz_scaling — Sets horizontal scaling of text
cpdf_set_keywords — Sets the keywords field of the pdf document
cpdf_set_leading — Sets distance between text lines
cpdf_set_page_animation — Sets duration between pages
cpdf_set_subject — Sets the subject field of the pdf document
cpdf_set_text_matrix — Sets the text matrix
cpdf_set_text_pos — Sets text position
cpdf_set_text_rendering — Determines how text is rendered
cpdf_set_text_rise — Sets the text rise
cpdf_set_title — Sets the title field of the pdf document
cpdf_set_viewer_preferences — How to show the document in the viewer
cpdf_set_word_spacing — Sets spacing between words
cpdf_setdash — Sets dash pattern
cpdf_setflat — Sets flatness
cpdf_setgray_fill — Sets filling color to gray value
cpdf_setgray_stroke — Sets drawing color to gray value
cpdf_setgray — Sets drawing and filling color to gray value
cpdf_setlinecap — Sets linecap parameter
cpdf_setlinejoin — Sets linejoin parameter
cpdf_setlinewidth — Sets line width
cpdf_setmiterlimit — Sets miter limit
cpdf_setrgbcolor_fill — Sets filling color to rgb color value
cpdf_setrgbcolor_stroke — Sets drawing color to rgb color value
cpdf_setrgbcolor — Sets drawing and filling color to rgb color value
cpdf_show_xy — Output text at position
cpdf_show — Output text at current position
cpdf_stringwidth — Returns width of text in current font
cpdf_stroke — Draw line along path
cpdf_text — Output text with parameters
cpdf_translate — Sets origin of coordinate system

后退 | 起点 | 前进
method_exists | 上一级 | cpdf_add_annotation


cpdf_add_annotation

(PHP 3>= 3.0.12, PHP 4 )

cpdf_add_annotation -- Adds annotation

Description

void cpdf_add_annotation ( int pdf document, float llx, float lly, float urx, float ury, string title, string content [, int mode])

The cpdf_add_annotation() adds a note with the lower left corner at (llx, lly) and the upper right corner at (urx, ury).

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

后退 | 起点 | 前进
ClibPDF functions | 上一级 | cpdf_add_outline


cpdf_add_outline

(PHP 3>= 3.0.9, PHP 4 )

cpdf_add_outline -- Adds bookmark for current page

Description

void cpdf_add_outline ( int pdf document, string text)

The cpdf_add_outline() function adds a bookmark with text text that points to the current page.

例子 1. Adding a page outline

<?php
$cpdf = cpdf_open(0);
cpdf_page_init($cpdf, 1, 0, 595, 842);
cpdf_add_outline($cpdf, 0, 0, 0, 1, "Page 1");
// ...
// some drawing
// ...
cpdf_finalize($cpdf);
Header("Content-type: application/pdf");
cpdf_output_buffer($cpdf);
cpdf_close($cpdf);
?>

后退 | 起点 | 前进
cpdf_add_annotation | 上一级 | cpdf_arc


cpdf_arc

(PHP 3>= 3.0.8, PHP 4 )

cpdf_arc -- Draws an arc

Description

void cpdf_arc ( int pdf document, float x-coor, float y-coor, float radius, float start, float end [, int mode])

The cpdf_arc() function draws an arc with center at point (x-coor, y-coor) and radius radius, starting at angle start and ending at angle end.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_circle().

后退 | 起点 | 前进
cpdf_add_outline | 上一级 | cpdf_begin_text


cpdf_begin_text

(PHP 3>= 3.0.8, PHP 4 )

cpdf_begin_text -- Starts text section

Description

void cpdf_begin_text ( int pdf document)

The cpdf_begin_text() function starts a text section. It must be ended with cpdf_end_text().

例子 1. Text output

<?php
cpdf_begin_text($pdf);
cpdf_set_font($pdf, 16, "Helvetica", "WinAnsiEncoding");
cpdf_text($pdf, 100, 100, "Some text");
cpdf_end_text($pdf)
?>

See also cpdf_end_text().

后退 | 起点 | 前进
cpdf_arc | 上一级 | cpdf_circle


cpdf_circle

(PHP 3>= 3.0.8, PHP 4 )

cpdf_circle -- Draw a circle

Description

void cpdf_circle ( int pdf document, float x-coor, float y-coor, float radius [, int mode])

The cpdf_circle() function draws a circle with center at point (x-coor, y-coor) and radius radius.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_arc().

后退 | 起点 | 前进
cpdf_begin_text | 上一级 | cpdf_clip


cpdf_clip

(PHP 3>= 3.0.8, PHP 4 )

cpdf_clip -- Clips to current path

Description

void cpdf_clip ( int pdf document)

The cpdf_clip() function clips all drawing to the current path.

后退 | 起点 | 前进
cpdf_circle | 上一级 | cpdf_close


cpdf_close

(PHP 3>= 3.0.8, PHP 4 )

cpdf_close -- Closes the pdf document

Description

void cpdf_close ( int pdf document)

The cpdf_close() function closes the pdf document. This should be the last function even after cpdf_finalize(), cpdf_output_buffer() and cpdf_save_to_file().

See also cpdf_open().

后退 | 起点 | 前进
cpdf_clip | 上一级 | cpdf_closepath_fill_stroke


cpdf_closepath_fill_stroke

(PHP 3>= 3.0.8, PHP 4 )

cpdf_closepath_fill_stroke -- Close, fill and stroke current path

Description

void cpdf_closepath_fill_stroke ( int pdf document)

The cpdf_closepath_fill_stroke() function closes, fills the interior of the current path with the current fill color and draws current path.

See also cpdf_closepath(),
         cpdf_stroke(),
         cpdf_fill(),
         cpdf_setgray_fill(),
         cpdf_setgray(),
         cpdf_setrgbcolor_fill(),
         cpdf_setrgbcolor().

后退 | 起点 | 前进
cpdf_close | 上一级 | cpdf_closepath_stroke


cpdf_closepath_stroke

(PHP 3>= 3.0.8, PHP 4 )

cpdf_closepath_stroke -- Close path and draw line along path

Description

void cpdf_closepath_stroke ( int pdf document)

The cpdf_closepath_stroke() function is a
combination of cpdf_closepath() and
cpdf_stroke(). Then clears the path.

See also cpdf_closepath(), cpdf_stroke().

后退 | 起点 | 前进
cpdf_closepath_fill_stroke | 上一级 | cpdf_closepath


cpdf_closepath

(PHP 3>= 3.0.8, PHP 4 )

cpdf_closepath -- Close path

Description

void cpdf_closepath ( int pdf document)

The cpdf_closepath() function closes the current path.

后退 | 起点 | 前进
cpdf_closepath_stroke | 上一级 | cpdf_continue_text


cpdf_continue_text

(PHP 3>= 3.0.8, PHP 4 )

cpdf_continue_text -- Output text in next line

Description

void cpdf_continue_text ( int pdf document, string text)

The cpdf_continue_text() function outputs the string in text in the next line.

See also cpdf_show_xy(),
         cpdf_text(),
         cpdf_set_leading(),
         cpdf_set_text_pos().

后退 | 起点 | 前进
cpdf_closepath | 上一级 | cpdf_curveto


cpdf_curveto

(PHP 3>= 3.0.8, PHP 4 )

cpdf_curveto -- Draws a curve

Description

void cpdf_curveto ( int pdf document, float x1, float y1, float x2, float y2, float x3, float y3 [, int mode])

The cpdf_curveto() function draws a Bezier curve from the current point to the point (x3, y3) using (x1, y1) and (x2, y2) as control points.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_moveto(),
         cpdf_rmoveto(),
         cpdf_rlineto(),
         cpdf_lineto().

后退 | 起点 | 前进
cpdf_continue_text | 上一级 | cpdf_end_text


cpdf_end_text

(PHP 3>= 3.0.8, PHP 4 )

cpdf_end_text -- Ends text section

Description

void cpdf_end_text ( int pdf document)

The cpdf_end_text() function ends a text section which was started with cpdf_begin_text().

例子 1. Text output

<?php
cpdf_begin_text($pdf);
cpdf_set_font($pdf, 16, "Helvetica", "WinAnsiEncoding");
cpdf_text($pdf, 100, 100, "Some text");
cpdf_end_text($pdf)
?>

See also cpdf_begin_text().

后退 | 起点 | 前进
cpdf_curveto | 上一级 | cpdf_fill_stroke


cpdf_fill_stroke

(PHP 3>= 3.0.8, PHP 4 )

cpdf_fill_stroke -- Fill and stroke current path

Description

void cpdf_fill_stroke ( int pdf document)

The cpdf_fill_stroke() function fills the interior of the current path with the current fill color and draws current path.

See also cpdf_closepath(),
         cpdf_stroke(),
         cpdf_fill(),
         cpdf_setgray_fill(),
         cpdf_setgray(),
         cpdf_setrgbcolor_fill(),
         cpdf_setrgbcolor().

后退 | 起点 | 前进
cpdf_end_text | 上一级 | cpdf_fill


cpdf_fill

(PHP 3>= 3.0.8, PHP 4 )

cpdf_fill -- Fill current path

Description

void cpdf_fill ( int pdf document)

The cpdf_fill() function fills the interior of the current path with the current fill color.

See also cpdf_closepath(),
         cpdf_stroke(),
         cpdf_setgray_fill(),
         cpdf_setgray(),
         cpdf_setrgbcolor_fill(),
         cpdf_setrgbcolor().

后退 | 起点 | 前进
cpdf_fill_stroke | 上一级 | cpdf_finalize_page


cpdf_finalize_page

(PHP 3>= 3.0.10, PHP 4 )

cpdf_finalize_page -- Ends page

Description

void cpdf_finalize_page ( int pdf document, int page number)

The cpdf_finalize_page() function ends the page with page number page number.

This function is only for saving memory. A finalized page takes less memory but cannot be modified anymore.

See also cpdf_page_init().

后退 | 起点 | 前进
cpdf_fill | 上一级 | cpdf_finalize


cpdf_finalize

(PHP 3>= 3.0.8, PHP 4 )

cpdf_finalize -- Ends document

Description

void cpdf_finalize ( int pdf document)

The cpdf_finalize() function ends the document. You still have to call cpdf_close()

See also cpdf_close().

后退 | 起点 | 前进
cpdf_finalize_page | 上一级 | cpdf_global_set_document_limits


cpdf_global_set_document_limits

(PHP 4 )

cpdf_global_set_document_limits -- Sets document limits for any pdf document

Description

void cpdf_global_set_document_limits ( int maxpages, int maxfonts, int maximages, int maxannotations, int maxobjects)

The cpdf_global_set_document_limits() function sets several document limits. This function has to be called before cpdf_open() to take effect. It sets the limits for any document open afterwards.

See also cpdf_open().

后退 | 起点 | 前进
cpdf_finalize | 上一级 | cpdf_import_jpeg


cpdf_import_jpeg

(PHP 3>= 3.0.9, PHP 4 )

cpdf_import_jpeg -- Opens a JPEG image

Description

int cpdf_import_jpeg ( int pdf document, string file name, float x-coor, float y-coor, float angle, float width, float height, float x-scale, float y-scale [, int mode])

The cpdf_import_jpeg() function opens an image stored in the file with the name file name. The format of the image has to be jpeg. The image is placed on the current page at position (x-coor, y-coor). The image is rotated by angle degrees.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_place_inline_image().

后退 | 起点 | 前进
cpdf_global_set_document_limits | 上一级 | cpdf_lineto


cpdf_lineto

(PHP 3>= 3.0.8, PHP 4 )

cpdf_lineto -- Draws a line

Description

void cpdf_lineto ( int pdf document, float x-coor, float y-coor [, int mode])

The cpdf_lineto() function draws a line from the current point to the point with coordinates (x-coor, y-coor).

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_moveto(),
         cpdf_rmoveto(),
         cpdf_curveto().

后退 | 起点 | 前进
cpdf_import_jpeg | 上一级 | cpdf_moveto


cpdf_moveto

(PHP 3>= 3.0.8, PHP 4 )

cpdf_moveto -- Sets current point

Description

void cpdf_moveto ( int pdf document, float x-coor, float y-coor [, int mode])

The cpdf_moveto() function set the current point to the coordinates x-coor and y-coor.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

后退 | 起点 | 前进
cpdf_lineto | 上一级 | cpdf_newpath


cpdf_newpath

(PHP 3>= 3.0.9, PHP 4 )

cpdf_newpath -- Starts a new path

Description

void cpdf_newpath ( int pdf document)

The cpdf_newpath() starts a new path on the document given by the pdf document parameter.

后退 | 起点 | 前进
cpdf_moveto | 上一级 | cpdf_open


cpdf_open

(PHP 3>= 3.0.8, PHP 4 )

cpdf_open -- Opens a new pdf document

Description

int cpdf_open ( int compression [, string filename])

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(), cpdf_output_buffer().

后退 | 起点 | 前进
cpdf_newpath | 上一级 | cpdf_output_buffer


cpdf_output_buffer

(PHP 3>= 3.0.9, PHP 4 )

cpdf_output_buffer -- Outputs the pdf document in memory buffer

Description

void cpdf_output_buffer ( int pdf document)

The cpdf_output_buffer() function outputs the pdf document to stdout. The document has to be created in memory which is the case if cpdf_open() has been called with no filename parameter.

See also cpdf_open().

后退 | 起点 | 前进
cpdf_open | 上一级 | cpdf_page_init


cpdf_page_init

(PHP 3>= 3.0.8, PHP 4 )

cpdf_page_init -- Starts new page

Description

void cpdf_page_init ( int pdf document, int page number, int orientation, float height, float width [, float unit])

The cpdf_page_init() function starts a new page with height height and width width. The page has number page number and orientation orientation. orientation can be 0 for portrait and 1 for landscape. The last optional parameter unit sets the unit for the coordinate system. The value should be the number of postscript points per unit. Since one inch is equal to 72 points, a value of 72 would set the unit to one inch. The default is also 72.

See also cpdf_set_current_page().

后退 | 起点 | 前进
cpdf_output_buffer | 上一级 | cpdf_place_inline_image


cpdf_place_inline_image

(PHP 3>= 3.0.9, PHP 4 )

cpdf_place_inline_image -- Places an image on the page

Description

void cpdf_place_inline_image ( int pdf document, int image, float x-coor, float y-coor, float angle, float width, float height [, int mode])

The cpdf_place_inline_image() function places an image created with the php image functions on the page at position (x-coor, y-coor). The image can be scaled at the same time.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_import_jpeg().

后退 | 起点 | 前进
cpdf_page_init | 上一级 | cpdf_rect


cpdf_rect

(PHP 3>= 3.0.8, PHP 4 )

cpdf_rect -- Draw a rectangle

Description

void cpdf_rect ( int pdf document, float x-coor, float y-coor, float width, float height [, int mode])

The cpdf_rect() function draws a rectangle with its lower left corner at point (x-coor, y-coor). This width is set to width. This height is set to height.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

后退 | 起点 | 前进
cpdf_place_inline_image | 上一级 | cpdf_restore


cpdf_restore

(PHP 3>= 3.0.8, PHP 4 )

cpdf_restore -- Restores formerly saved environment

Description

void cpdf_restore ( int pdf document)

The cpdf_restore() function restores the environment saved with cpdf_save(). It works like the postscript command grestore. Very useful if you want to translate or rotate an object without effecting other objects.

例子 1. Save/Restore

<?php
cpdf_save($pdf);
// do all kinds of rotations, transformations, ...
cpdf_restore($pdf)
?>

See also cpdf_save().

后退 | 起点 | 前进
cpdf_rect | 上一级 | cpdf_rlineto


cpdf_rlineto

(PHP 3>= 3.0.9, PHP 4 )

cpdf_rlineto -- Draws a line

Description

void cpdf_rlineto ( int pdf document, float x-coor, float y-coor [, int mode])

The cpdf_rlineto() function draws a line from the current point to the relative point with coordinates (x-coor, y-coor).

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_moveto(),
         cpdf_rmoveto(),
         cpdf_curveto().

后退 | 起点 | 前进
cpdf_restore | 上一级 | cpdf_rmoveto


cpdf_rmoveto

(PHP 3>= 3.0.9, PHP 4 )

cpdf_rmoveto -- Sets current point

Description

void cpdf_rmoveto ( int pdf document, float x-coor, float y-coor [, int mode])

The cpdf_rmoveto() function set the current point relative to the coordinates x-coor and y-coor.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_moveto().

后退 | 起点 | 前进
cpdf_rlineto | 上一级 | cpdf_rotate_text


cpdf_rotate_text

(PHP 3>= 3.0.9, PHP 4 )

cpdf_rotate_text -- Sets text rotation angle

Description

void cpdf_rotate_text ( int pdfdoc, float angle)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
cpdf_rmoveto | 上一级 | cpdf_rotate


cpdf_rotate

(PHP 3>= 3.0.8, PHP 4 )

cpdf_rotate -- Sets rotation

Description

void cpdf_rotate ( int pdf document, float angle)

The cpdf_rotate() function set the rotation in degrees to angle.

后退 | 起点 | 前进
cpdf_rotate_text | 上一级 | cpdf_save_to_file


cpdf_save_to_file

(PHP 3>= 3.0.8, PHP 4 )

cpdf_save_to_file -- Writes the pdf document into a file

Description

void cpdf_save_to_file ( int pdf document, string filename)

The cpdf_save_to_file() function outputs the pdf document into a file if it has been created in memory.

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(), cpdf_open().

后退 | 起点 | 前进
cpdf_rotate | 上一级 | cpdf_save


cpdf_save

(PHP 3>= 3.0.8, PHP 4 )

cpdf_save -- Saves current environment

Description

void cpdf_save ( int pdf document)

The cpdf_save() function saves the current environment. It works like the postscript command gsave. Very useful if you want to translate or rotate an object without effecting other objects.

See also cpdf_restore().

后退 | 起点 | 前进
cpdf_save_to_file | 上一级 | cpdf_scale


cpdf_scale

(PHP 3>= 3.0.8, PHP 4 )

cpdf_scale -- Sets scaling

Description

void cpdf_scale ( int pdf document, float x-scale, float y-scale)

The cpdf_scale() function set the scaling factor in both directions.

后退 | 起点 | 前进
cpdf_save | 上一级 | cpdf_set_action_url


cpdf_set_action_url

(PHP 3>= 3.0.9, PHP 4 )

cpdf_set_action_url -- Sets hyperlink

Description

void cpdf_set_action_url ( int pdfdoc, float xll, float yll, float xur, float xur, string url [, int mode])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
cpdf_scale | 上一级 | cpdf_set_char_spacing


cpdf_set_char_spacing

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_char_spacing -- Sets character spacing

Description

void cpdf_set_char_spacing ( int pdf document, float space)

The cpdf_set_char_spacing() function sets the spacing between characters.

See also cpdf_set_word_spacing(), cpdf_set_leading().

后退 | 起点 | 前进
cpdf_set_action_url | 上一级 | cpdf_set_creator


cpdf_set_creator

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_creator -- Sets the creator field in the pdf document

Description

void cpdf_set_creator ( string creator)

The cpdf_set_creator() function sets the creator of a pdf document.

See also cpdf_set_subject(),
         cpdf_set_title(),
         cpdf_set_keywords().

后退 | 起点 | 前进
cpdf_set_char_spacing | 上一级 | cpdf_set_current_page


cpdf_set_current_page

(PHP 3>= 3.0.9, PHP 4 )

cpdf_set_current_page -- Sets current page

Description

void cpdf_set_current_page ( int pdf document, int page number)

The cpdf_set_current_page() function set the page on which all operations are performed. One can switch between pages until a page is finished with cpdf_finalize_page().

See also cpdf_finalize_page().

后退 | 起点 | 前进
cpdf_set_creator | 上一级 | cpdf_set_font_directories


cpdf_set_font_directories

(PHP 4 >= 4.0.6)

cpdf_set_font_directories -- Sets directories to search when using external fonts

Description

void cpdf_set_font_directories ( int pdfdoc, string pfmdir, string pfbdir)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
cpdf_set_current_page | 上一级 | cpdf_set_font_map_file


cpdf_set_font_map_file

(PHP 4 >= 4.0.6)

cpdf_set_font_map_file -- Sets fontname to filename translation map when using external fonts

Description

void cpdf_set_font_map_file ( int pdfdoc, string filename)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
cpdf_set_font_directories | 上一级 | cpdf_set_font


cpdf_set_font

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_font -- Select the current font face and size

Description

void cpdf_set_font ( int pdf document, string font name, float size, string encoding)

The cpdf_set_font() function sets the current font face, font size and encoding. Currently only the standard postscript fonts are supported.

The last parameter encoding can take the following values: "MacRomanEncoding", "MacExpertEncoding", "WinAnsiEncoding", and "NULL". "NULL" stands for the font's built-in encoding.

See the ClibPDF Manual for more information, especially how to support asian fonts.

后退 | 起点 | 前进
cpdf_set_font_map_file | 上一级 | cpdf_set_horiz_scaling


cpdf_set_horiz_scaling

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_horiz_scaling -- Sets horizontal scaling of text

Description

void cpdf_set_horiz_scaling ( int pdf document, float scale)

The cpdf_set_horiz_scaling() function sets the horizontal scaling to scale percent.

后退 | 起点 | 前进
cpdf_set_font | 上一级 | cpdf_set_keywords


cpdf_set_keywords

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_keywords -- Sets the keywords field of the pdf document

Description

void cpdf_set_keywords ( string keywords)

The cpdf_set_keywords() function sets the keywords of a pdf document.

See also cpdf_set_title(),
         cpdf_set_creator(),
         cpdf_set_subject().

后退 | 起点 | 前进
cpdf_set_horiz_scaling | 上一级 | cpdf_set_leading


cpdf_set_leading

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_leading -- Sets distance between text lines

Description

void cpdf_set_leading ( int pdf document, float distance)

The cpdf_set_leading() function sets the distance between text lines. This will be used if text is output by cpdf_continue_text().

See also cpdf_continue_text().

后退 | 起点 | 前进
cpdf_set_keywords | 上一级 | cpdf_set_page_animation


cpdf_set_page_animation

(PHP 3>= 3.0.9, PHP 4 )

cpdf_set_page_animation -- Sets duration between pages

Description

void cpdf_set_page_animation ( int pdf document, int transition, float duration)

The cpdf_set_page_animation() function set the transition between following pages.

The value of transition can be

0 for none,
1 for two lines sweeping across the screen reveal the page,
2 for multiple lines sweeping across the screen reveal the page,
3 for a box reveals the page,
4 for a single line sweeping across the screen reveals the page,
5 for the old page dissolves to reveal the page,
6 for the dissolve effect moves from one screen edge to another,
7 for the old page is simply replaced by the new page (default)

The value of duration is the number of seconds between page flipping.

后退 | 起点 | 前进
cpdf_set_leading | 上一级 | cpdf_set_subject


cpdf_set_subject

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_subject -- Sets the subject field of the pdf document

Description

void cpdf_set_subject ( string subject)

The cpdf_set_subject() function sets the subject of a pdf document.

See also cpdf_set_title(),
         cpdf_set_creator(),
         cpdf_set_keywords().

后退 | 起点 | 前进
cpdf_set_page_animation | 上一级 | cpdf_set_text_matrix


cpdf_set_text_matrix

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_text_matrix -- Sets the text matrix

Description

void cpdf_set_text_matrix ( int pdf document, array matrix)

The cpdf_set_text_matrix() function sets a matrix which describes a transformation applied on the current text font.

后退 | 起点 | 前进
cpdf_set_subject | 上一级 | cpdf_set_text_pos


cpdf_set_text_pos

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_text_pos -- Sets text position

Description

void cpdf_set_text_pos ( int pdf document, float x-coor, float y-coor [, int mode])

The cpdf_set_text_pos() function sets the position of text for the next cpdf_show() function call.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_show(), cpdf_text().

后退 | 起点 | 前进
cpdf_set_text_matrix | 上一级 | cpdf_set_text_rendering


cpdf_set_text_rendering

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_text_rendering -- Determines how text is rendered

Description

void cpdf_set_text_rendering ( int pdf document, int mode)

The cpdf_set_text_rendering() function determines how text is rendered.

The possible values for mode are 0=fill text, 1=stroke text, 2=fill and stroke text, 3=invisible, 4=fill text and add it to clipping path, 5=stroke text and add it to clipping path, 6=fill and stroke text and add it to clipping path, 7=add it to clipping path.

后退 | 起点 | 前进
cpdf_set_text_pos | 上一级 | cpdf_set_text_rise


cpdf_set_text_rise

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_text_rise -- Sets the text rise

Description

void cpdf_set_text_rise ( int pdf document, float value)

The cpdf_set_text_rise() function sets the text rising to value units.

后退 | 起点 | 前进
cpdf_set_text_rendering | 上一级 | cpdf_set_title


cpdf_set_title

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_title -- Sets the title field of the pdf document

Description

void cpdf_set_title ( string title)

The cpdf_set_title() function sets the title of a pdf document.

See also cpdf_set_subject(),
         cpdf_set_creator(),
         cpdf_set_keywords().

后退 | 起点 | 前进
cpdf_set_text_rise | 上一级 | cpdf_set_viewer_preferences


cpdf_set_viewer_preferences

(PHP 3>= 3.0.9, PHP 4 )

cpdf_set_viewer_preferences -- How to show the document in the viewer

Description

void cpdf_set_viewer_preferences ( int pdfdoc, array preferences)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
cpdf_set_title | 上一级 | cpdf_set_word_spacing


cpdf_set_word_spacing

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_word_spacing -- Sets spacing between words

Description

void cpdf_set_word_spacing ( int pdf document, float space)

The cpdf_set_word_spacing() function sets the spacing between words.

See also cpdf_set_char_spacing(), cpdf_set_leading().

后退 | 起点 | 前进
cpdf_set_viewer_preferences | 上一级 | cpdf_setdash


cpdf_setdash

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setdash -- Sets dash pattern

Description

void cpdf_setdash ( int pdf document, float white, float black)

The cpdf_setdash() function set the dash pattern white white units and black black units. If both are 0 a solid line is set.

后退 | 起点 | 前进
cpdf_set_word_spacing | 上一级 | cpdf_setflat


cpdf_setflat

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setflat -- Sets flatness

Description

void cpdf_setflat ( int pdf document, float value)

The cpdf_setflat() function set the flatness to a value between 0 and 100.

后退 | 起点 | 前进
cpdf_setdash | 上一级 | cpdf_setgray_fill


cpdf_setgray_fill

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setgray_fill -- Sets filling color to gray value

Description

void cpdf_setgray_fill ( int pdf document, float value)

The cpdf_setgray_fill() function sets the current gray value to fill a path.

See also cpdf_setrgbcolor_fill().

后退 | 起点 | 前进
cpdf_setflat | 上一级 | cpdf_setgray_stroke


cpdf_setgray_stroke

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setgray_stroke -- Sets drawing color to gray value

Description

void cpdf_setgray_stroke ( int pdf document, float gray value)

The cpdf_setgray_stroke() function sets the current drawing color to the given gray value.

See also cpdf_setrgbcolor_stroke().

后退 | 起点 | 前进
cpdf_setgray_fill | 上一级 | cpdf_setgray


cpdf_setgray

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setgray -- Sets drawing and filling color to gray value

Description

void cpdf_setgray ( int pdf document, float gray value)

The cpdf_setgray() function sets the current drawing and filling color to the given gray value.

See also cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor_fill().

后退 | 起点 | 前进
cpdf_setgray_stroke | 上一级 | cpdf_setlinecap


cpdf_setlinecap

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setlinecap -- Sets linecap parameter

Description

void cpdf_setlinecap ( int pdf document, int value)

The cpdf_setlinecap() function set the linecap parameter between a value of 0 and 2. 0 = butt end, 1 = round, 2 = projecting square.

后退 | 起点 | 前进
cpdf_setgray | 上一级 | cpdf_setlinejoin


cpdf_setlinejoin

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setlinejoin -- Sets linejoin parameter

Description

void cpdf_setlinejoin ( int pdf document, long value)

The cpdf_setlinejoin() function set the linejoin parameter between a value of 0 and 2. 0 = miter, 1 = round, 2 = bevel.

后退 | 起点 | 前进
cpdf_setlinecap | 上一级 | cpdf_setlinewidth


cpdf_setlinewidth

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setlinewidth -- Sets line width

Description

void cpdf_setlinewidth ( int pdf document, float width)

The cpdf_setlinewidth() function set the line width to width.

后退 | 起点 | 前进
cpdf_setlinejoin | 上一级 | cpdf_setmiterlimit


cpdf_setmiterlimit

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setmiterlimit -- Sets miter limit

Description

void cpdf_setmiterlimit ( int pdf document, float value)

The cpdf_setmiterlimit() function set the miter limit to a value greater or equal than 1.

后退 | 起点 | 前进
cpdf_setlinewidth | 上一级 | cpdf_setrgbcolor_fill


cpdf_setrgbcolor_fill

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setrgbcolor_fill -- Sets filling color to rgb color value

Description

void cpdf_setrgbcolor_fill ( int pdf document, float red value, float green value, float blue value)

The cpdf_setrgbcolor_fill() function sets the current rgb color value to fill a path.

See also cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor().

后退 | 起点 | 前进
cpdf_setmiterlimit | 上一级 | cpdf_setrgbcolor_stroke


cpdf_setrgbcolor_stroke

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setrgbcolor_stroke -- Sets drawing color to rgb color value

Description

void cpdf_setrgbcolor_stroke ( int pdf document, float red value, float green value, float blue value)

The cpdf_setrgbcolor_stroke() function sets the current drawing color to the given rgb color value.

See also cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().

后退 | 起点 | 前进
cpdf_setrgbcolor_fill | 上一级 | cpdf_setrgbcolor


cpdf_setrgbcolor

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setrgbcolor -- Sets drawing and filling color to rgb color value

Description

void cpdf_setrgbcolor ( int pdf document, float red value, float green value, float blue value)

The cpdf_setrgbcolor() function sets the current drawing and filling color to the given rgb color value.

See also cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor_fill().

后退 | 起点 | 前进
cpdf_setrgbcolor_stroke | 上一级 | cpdf_show_xy


cpdf_show_xy

(PHP 3>= 3.0.8, PHP 4 )

cpdf_show_xy -- Output text at position

Description

void cpdf_show_xy ( int pdf document, string text, float x-coor, float y-coor [, int mode])

The cpdf_show_xy() function outputs the string text at position with coordinates (x-coor, y-coor).

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

注: The function cpdf_show_xy() is identical to cpdf_text() without the optional parameters.

See also cpdf_text().

后退 | 起点 | 前进
cpdf_setrgbcolor | 上一级 | cpdf_show


cpdf_show

(PHP 3>= 3.0.8, PHP 4 )

cpdf_show -- Output text at current position

Description

void cpdf_show ( int pdf document, string text)

The cpdf_show() function outputs the string in text at the current position.

See also cpdf_text(),
         cpdf_begin_text(),
         cpdf_end_text().

后退 | 起点 | 前进
cpdf_show_xy | 上一级 | cpdf_stringwidth


cpdf_stringwidth

(PHP 3>= 3.0.8, PHP 4 )

cpdf_stringwidth -- Returns width of text in current font

Description

float cpdf_stringwidth ( int pdf document, string text)

The cpdf_stringwidth() function returns the width of the string in text. It requires a font to be set before.

See also cpdf_set_font().

后退 | 起点 | 前进
cpdf_show | 上一级 | cpdf_stroke


cpdf_stroke

(PHP 3>= 3.0.8, PHP 4 )

cpdf_stroke -- Draw line along path

Description

void cpdf_stroke ( int pdf document)

The cpdf_stroke() function draws a line along current path.

See also cpdf_closepath(), cpdf_closepath_stroke().

后退 | 起点 | 前进
cpdf_stringwidth | 上一级 | cpdf_text


cpdf_text

(PHP 3>= 3.0.8, PHP 4 )

cpdf_text -- Output text with parameters

Description

void cpdf_text ( int pdf document, string text, float x-coor, float y-coor [, int mode [, float orientation [, int alignmode]]])

The cpdf_text() function outputs the string text at position with coordinates (x-coor, y-coor).

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit. The optional parameter orientation is the rotation of the text in degree. The optional parameter alignmode determines how the text is aligned.

See the ClibPDF documentation for possible values.

See also cpdf_show_xy().

后退 | 起点 | 前进
cpdf_stroke | 上一级 | cpdf_translate


cpdf_translate

(PHP 3>= 3.0.8, PHP 4 )

cpdf_translate -- Sets origin of coordinate system

Description

void cpdf_translate ( int pdf document, float x-coor, float y-coor [, int mode])

The cpdf_translate() function set the origin of coordinate system to the point (x-coor, y-coor).

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

后退 | 起点 | 前进
cpdf_text | 上一级 | Crack functions


Crack functions

PHP 手册
后退 前进

XI. Crack functions

介绍

These functions allow you to use the CrackLib library to test the 'strength' of a password. The 'strength' of a password is tested by that checks length, use of upper and lower case and checked against the specified CrackLib dictionary. CrackLib will also give helpful diagnostic messages that will help 'strengthen' the password.

需求

More information regarding CrackLib along with the library can be found at http://www.users.dircon.co.uk/~crypto/.

安装

In order to use these functions, you must compile PHP with Crack support by using the --with-crack[=DIR] option.

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. Crack configuration options

Name | Default | Changeable
crack.default_dictionary | NULL | PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

范例

This example shows how to open a CrackLib dictionary, test a given password, retrieve any diagnostic messages, and close the dictionary.

例子 1. CrackLib example

<?php
// Open CrackLib Dictionary
$dictionary = crack_opendict('/usr/local/lib/pw_dict')
     or die('Unable to open CrackLib dictionary');

// Perform password check
$check = crack_check($dictionary, 'gx9A2s0x');

// Retrieve messages
$diag = crack_getlastmessage();
echo $diag; // 'strong password'

// Close dictionary
crack_closedict($dictionary);
?>

注: If crack_check() returns TRUE, crack_getlastmessage() will return 'strong password'.

目录
crack_check — Performs an obscure check with the given password
crack_closedict — Closes an open CrackLib dictionary
crack_getlastmessage — Returns the message from the last obscure check
crack_opendict — Opens a new CrackLib dictionary

后退 | 起点 | 前进
cpdf_translate | 上一级 | crack_check


crack_check

(PHP 4 >= 4.0.5)

crack_check -- Performs an obscure check with the given password

Description

bool crack_check ( [resource dictionary, string password])

Returns TRUE if password is strong, or FALSE otherwise.

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

crack_check() performs an obscure check with the given password on the specified dictionary . If dictionary is not specified, the last opened dictionary is used.

后退 | 起点 | 前进
Crack functions | 上一级 | crack_closedict


crack_closedict

(PHP 4 >= 4.0.5)

crack_closedict -- Closes an open CrackLib dictionary

Description

bool crack_closedict ( [resource dictionary])

如果成功则返回 TRUE，失败则返回 FALSE。

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

crack_closedict() closes the specified dictionary identifier. If dictionary is not specified, the current dictionary is closed.

后退 | 起点 | 前进
crack_check | 上一级 | crack_getlastmessage


crack_getlastmessage

(PHP 4 >= 4.0.5)

crack_getlastmessage -- Returns the message from the last obscure check

Description

string crack_getlastmessage ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

crack_getlastmessage() returns the message from the last obscure check.

后退 | 起点 | 前进
crack_closedict | 上一级 | crack_opendict


crack_opendict

(PHP 4 >= 4.0.5)

crack_opendict -- Opens a new CrackLib dictionary

Description

resource crack_opendict ( string dictionary)

Returns a dictionary resource identifier on success, or FALSE on failure.

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

crack_opendict() opens the specified CrackLib dictionary for use with crack_check().

注: Only one dictionary may be open at a time.

See also: crack_check(), and crack_closedict().

后退 | 起点 | 前进
crack_getlastmessage | 上一级 | CURL, Client URL Library Functions


CURL, Client URL Library Functions

PHP 手册
后退 前进

XII. CURL, Client URL Library Functions

介绍

PHP supports libcurl, a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.

These functions have been added in PHP 4.0.2.

需求

In order to use the CURL functions you need to install the CURL package. PHP requires that you use CURL 7.0.2-beta or higher. PHP will not work with any version of CURL below version 7.0.2-beta.

安装

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.

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

CURLOPT_PORT (integer)

CURLOPT_FILE (integer)

CURLOPT_INFILE (integer)

CURLOPT_INFILESIZE (integer)

CURLOPT_URL (integer)

CURLOPT_PROXY (integer)

CURLOPT_VERBOSE (integer)

CURLOPT_HEADER (integer)

CURLOPT_HTTPHEADER (integer)

CURLOPT_NOPROGRESS (integer)

CURLOPT_NOBODY (integer)

CURLOPT_FAILONERROR (integer)

CURLOPT_UPLOAD (integer)

CURLOPT_POST (integer)

CURLOPT_FTPLISTONLY (integer)

CURLOPT_FTPAPPEND (integer)

CURLOPT_NETRC (integer)

CURLOPT_FOLLOWLOCATION (integer)

CURLOPT_FTPASCII (integer)

CURLOPT_PUT (integer)

CURLOPT_MUTE (integer)

CURLOPT_USERPWD (integer)

CURLOPT_PROXYUSERPWD (integer)

CURLOPT_RANGE (integer)

CURLOPT_TIMEOUT (integer)

CURLOPT_POSTFIELDS (integer)

CURLOPT_REFERER (integer)

CURLOPT_USERAGENT (integer)

CURLOPT_FTPPORT (integer)

CURLOPT_LOW_SPEED_LIMIT (integer)

CURLOPT_LOW_SPEED_TIME (integer)

CURLOPT_RESUME_FROM (integer)

CURLOPT_COOKIE (integer)

CURLOPT_SSLCERT (integer)

CURLOPT_SSLCERTPASSWD (integer)

CURLOPT_WRITEHEADER (integer)

CURLOPT_SSL_VERIFYHOST (integer)

CURLOPT_COOKIEFILE (integer)

CURLOPT_SSLVERSION (integer)

CURLOPT_TIMECONDITION (integer)

CURLOPT_TIMEVALUE (integer)

CURLOPT_CUSTOMREQUEST (integer)

CURLOPT_STDERR (integer)

CURLOPT_TRANSFERTEXT (integer)

CURLOPT_RETURNTRANSFER (integer)

CURLOPT_QUOTE (integer)

CURLOPT_POSTQUOTE (integer)

CURLOPT_INTERFACE (integer)

CURLOPT_KRB4LEVEL (integer)

CURLOPT_HTTPPROXYTUNNEL (integer)

CURLOPT_FILETIME (integer)

CURLOPT_WRITEFUNCTION (integer)

CURLOPT_READFUNCTION (integer)

CURLOPT_PASSWDFUNCTION (integer)

CURLOPT_HEADERFUNCTION (integer)

CURLOPT_MAXREDIRS (integer)

CURLOPT_MAXCONNECTS (integer)

CURLOPT_CLOSEPOLICY (integer)

CURLOPT_FRESH_CONNECT (integer)

CURLOPT_FORBID_REUSE (integer)

CURLOPT_RANDOM_FILE (integer)

CURLOPT_EGDSOCKET (integer)

CURLOPT_CONNECTTIMEOUT (integer)

CURLOPT_SSL_VERIFYPEER (integer)

CURLOPT_CAINFO (integer)

CURLOPT_COOKIEJAR (integer)

CURLOPT_SSL_CIPHER_LIST (integer)

CURLOPT_BINARYTRANSFER (integer)

CURLCLOSEPOLICY_LEAST_RECENTLY_USED (integer)

CURLCLOSEPOLICY_LEAST_TRAFFIC (integer)

CURLCLOSEPOLICY_SLOWEST (integer)

CURLCLOSEPOLICY_CALLBACK (integer)

CURLCLOSEPOLICY_OLDEST (integer)

CURLINFO_EFFECTIVE_URL (integer)

CURLINFO_HTTP_CODE (integer)

CURLINFO_HEADER_SIZE (integer)

CURLINFO_REQUEST_SIZE (integer)

CURLINFO_TOTAL_TIME (integer)

CURLINFO_NAMELOOKUP_TIME (integer)

CURLINFO_CONNECT_TIME (integer)

CURLINFO_PRETRANSFER_TIME (integer)

CURLINFO_SIZE_UPLOAD (integer)

CURLINFO_SIZE_DOWNLOAD (integer)

CURLINFO_SPEED_DOWNLOAD (integer)

CURLINFO_SPEED_UPLOAD (integer)

CURLINFO_FILETIME (integer)

CURLINFO_SSL_VERIFYRESULT (integer)

CURLINFO_CONTENT_LENGTH_DOWNLOAD (integer)

CURLINFO_CONTENT_LENGTH_UPLOAD (integer)

CURLE_OK (integer)

CURLE_UNSUPPORTED_PROTOCOL (integer)

CURLE_FAILED_INIT (integer)

CURLE_URL_MALFORMAT (integer)

CURLE_URL_MALFORMAT_USER (integer)

CURLE_COULDNT_RESOLVE_PROXY (integer)

CURLE_COULDNT_RESOLVE_HOST (integer)

CURLE_COULDNT_CONNECT (integer)

CURLE_FTP_WEIRD_SERVER_REPLY (integer)

CURLE_FTP_ACCESS_DENIED (integer)

CURLE_FTP_USER_PASSWORD_INCORRECT (integer)

CURLE_FTP_WEIRD_PASS_REPLY (integer)

CURLE_FTP_WEIRD_USER_REPLY (integer)

CURLE_FTP_WEIRD_PASV_REPLY (integer)

CURLE_FTP_WEIRD_227_FORMAT (integer)

CURLE_FTP_CANT_GET_HOST (integer)

CURLE_FTP_CANT_RECONNECT (integer)

CURLE_FTP_COULDNT_SET_BINARY (integer)

CURLE_PARTIAL_FILE (integer)

CURLE_FTP_COULDNT_RETR_FILE (integer)

CURLE_FTP_WRITE_ERROR (integer)

CURLE_FTP_QUOTE_ERROR (integer)

CURLE_HTTP_NOT_FOUND (integer)

CURLE_WRITE_ERROR (integer)

CURLE_MALFORMAT_USER (integer)

CURLE_FTP_COULDNT_STOR_FILE (integer)

CURLE_READ_ERROR (integer)

CURLE_OUT_OF_MEMORY (integer)

CURLE_OPERATION_TIMEOUTED (integer)

CURLE_FTP_COULDNT_SET_ASCII (integer)

CURLE_FTP_PORT_FAILED (integer)

CURLE_FTP_COULDNT_USE_REST (integer)

CURLE_FTP_COULDNT_GET_SIZE (integer)

CURLE_HTTP_RANGE_ERROR (integer)

CURLE_HTTP_POST_ERROR (integer)

CURLE_SSL_CONNECT_ERROR (integer)

CURLE_FTP_BAD_DOWNLOAD_RESUME (integer)

CURLE_FILE_COULDNT_READ_FILE (integer)

CURLE_LDAP_CANNOT_BIND (integer)

CURLE_LDAP_SEARCH_FAILED (integer)

CURLE_LIBRARY_NOT_FOUND (integer)

CURLE_FUNCTION_NOT_FOUND (integer)

CURLE_ABORTED_BY_CALLBACK (integer)

CURLE_BAD_FUNCTION_ARGUMENT (integer)

CURLE_BAD_CALLING_ORDER (integer)

CURLE_HTTP_PORT_FAILED (integer)

CURLE_BAD_PASSWORD_ENTERED (integer)

CURLE_TOO_MANY_REDIRECTS (integer)

CURLE_UNKNOWN_TELNET_OPTION (integer)

CURLE_TELNET_OPTION_SYNTAX (integer)

CURLE_OBSOLETE (integer)

CURLE_SSL_PEER_CERTIFICATE (integer)

范例

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_exec() and then you finish off your session using the curl_close(). Here is an example that uses the CURL functions to fetch the example.com homepage into a file:

例子 1. Using PHP's CURL module to fetch the example.com homepage

<?php

$ch = curl_init ("http://www.example.com/");
$fp = fopen ("example_homepage.txt", "w");

curl_setopt ($ch, CURLOPT_FILE, $fp);
curl_setopt ($ch, CURLOPT_HEADER, 0);

curl_exec ($ch);
curl_close ($ch);
fclose ($fp);
?>

目录
curl_close — Close a CURL session
curl_errno — Return an integer containing the last error number
curl_error — Return a string containing the last error for the current session
curl_exec — Perform a CURL session
curl_getinfo — Get information regarding a specific transfer
curl_init — Initialize a CURL session
curl_setopt — Set an option for a CURL transfer
curl_version — Return the current CURL version

后退 | 起点 | 前进
crack_opendict | 上一级 | curl_close


curl_close

(PHP 4 >= 4.0.2)

curl_close -- Close a CURL session

Description

void curl_close ( resource ch)

This function closes a CURL session and frees all resources. The CURL handle, ch, is also deleted.

后退 | 起点 | 前进
CURL, Client URL Library Functions | 上一级 | curl_errno


curl_errno

(PHP 4 >= 4.0.3)

curl_errno -- Return an integer containing the last error number

Description

int curl_errno ( resource ch)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
curl_close | 上一级 | curl_error


curl_error

(PHP 4 >= 4.0.3)

curl_error -- Return a string containing the last error for the current session

Description

string curl_error ( resource ch)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
curl_errno | 上一级 | curl_exec


curl_exec

(PHP 4 >= 4.0.2)

curl_exec -- Perform a CURL session

Description

bool curl_exec ( resource ch)

This function should be called after you initialize a CURL session and all the options for the session are set. Its purpose is simply to execute the predefined CURL session (given by the ch).

提示: 为了防止程序直接将结果输出到浏览器，您可以使用输出控制函数（output-control functions）来捕获函数的输出，并把它们保存到一个 string 型的变量中。

后退 | 起点 | 前进
curl_error | 上一级 | curl_getinfo


curl_getinfo

(PHP 4 >= 4.0.4)

curl_getinfo -- Get information regarding a specific transfer

Description

string curl_getinfo ( resource ch, int opt)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
curl_exec | 上一级 | curl_init


curl_init

(PHP 4 >= 4.0.2)

curl_init -- Initialize a CURL session

Description

resource curl_init ( [string url])

The curl_init() will initialize a new session and return a CURL handle for use with the curl_setopt(), curl_exec(), and curl_close() functions. If the optional url parameter is supplied then the CURLOPT_URL option will be set to the value of the parameter. You can manually set this using the curl_setopt() function.

例子 1. Initializing a new CURL session and fetching a webpage

<?php
$ch = curl_init();

curl_setopt ($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt ($ch, CURLOPT_HEADER, 0);

curl_exec ($ch);

curl_close ($ch);
?>

See also: curl_close(), curl_setopt()

后退 | 起点 | 前进
curl_getinfo | 上一级 | curl_setopt


curl_setopt

(PHP 4 >= 4.0.2)

curl_setopt -- Set an option for a CURL transfer

Description

bool curl_setopt ( resource ch, string option, mixed value)

The curl_setopt() function will set options for a CURL session identified by the ch parameter. The option parameter is the option you want to set, and the value is the value of the option given by the option.

The value should be a long for the following options (specified in the option parameter):

  • CURLOPT_INFILESIZE: When you are uploading a file to a remote site, this option should be used to tell PHP what the expected size of the infile will be.

  • CURLOPT_VERBOSE: Set this option to a non-zero value if you want CURL to report everything that is happening.

  • CURLOPT_HEADER: Set this option to a non-zero value if you want the header to be included in the output.

  • CURLOPT_NOPROGRESS: Set this option to a non-zero value if you don't want PHP to display a progress meter for CURL transfers.

    注: PHP automatically sets this option to a non-zero parameter, this should only be changed for debugging purposes.

  • CURLOPT_NOBODY: Set this option to a non-zero value if you don't want the body included with the output.

  • CURLOPT_FAILONERROR: Set this option to a non-zero value if you want PHP 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_UPLOAD: Set this option to a non-zero value if you want PHP to prepare for an upload.

  • CURLOPT_POST: Set this option to a non-zero value if you want PHP to do a regular HTTP POST. This POST is a normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.

  • CURLOPT_FTPLISTONLY: Set this option to a non-zero value and PHP will just list the names of an FTP directory.

  • CURLOPT_FTPAPPEND: Set this option to a non-zero value and PHP will append to the remote file instead of overwriting it.

  • CURLOPT_NETRC: Set this option to a non-zero value and PHP will scan your ~./netrc file to find your username and password for the remote site that you're establishing a connection with.

  • CURLOPT_FOLLOWLOCATION: Set this option to a non-zero value to follow any "Location: " header that the server sends as a part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent.)

  • CURLOPT_PUT: Set this option to a non-zero value to HTTP PUT a file. The file to PUT must be set with the CURLOPT_INFILE and CURLOPT_INFILESIZE.

  • CURLOPT_MUTE: Set this option to a non-zero value and PHP will be completely silent with regards to the CURL functions.

  • CURLOPT_TIMEOUT: Pass a long as a parameter that contains the maximum time, in seconds, that you'll allow the CURL functions to take.

  • CURLOPT_LOW_SPEED_LIMIT: Pass a long as a parameter that contains the transfer speed in bytes per second that the transfer should be below during CURLOPT_LOW_SPEED_TIME seconds for PHP to consider it too slow and abort.

  • CURLOPT_LOW_SPEED_TIME: Pass a long as a parameter that contains the time in seconds that the transfer should be below the CURLOPT_LOW_SPEED_LIMIT for PHP to consider it too slow and abort.

  • CURLOPT_RESUME_FROM: Pass a long as a parameter that contains the offset, in bytes, that you want the transfer to start from.

  • CURLOPT_SSLVERSION: Pass a long as a parameter that contains the SSL version (2 or 3) to use. By default PHP will try and determine this by itself, although, in some cases you must set this manually.

  • CURLOPT_SSL_VERIFYHOST: Pass a long if CURL should verify the Common name of the peer certificate in the SSL handshake. A value of 1 denotes that we should check for the existence of the common name, a value of 2 denotes that we should make sure it matches the provided hostname.

  • CURLOPT_TIMECONDITION: Pass a long as a parameter that defines how the CURLOPT_TIMEVALUE is treated. You can set this parameter to TIMECOND_IFMODSINCE or TIMECOND_ISUNMODSINCE. This is a HTTP-only feature.

  • CURLOPT_TIMEVALUE: Pass a long as a parameter that is the time in seconds since January 1st, 1970. The time will be used as specified by the CURLOPT_TIMEVALUE option, or by default the TIMECOND_IFMODSINCE will be used.

  • CURLOPT_RETURNTRANSFER: Pass a non-zero value if you want CURL to directly return the transfer instead of printing it out directly.

The value parameter should be a string for the following values of the option parameter:

  • CURLOPT_URL: This is the URL that you want PHP to fetch. You can also set this option when initializing a session with the curl_init() function.

  • CURLOPT_USERPWD: Pass a string formatted in the [username]:[password] manner, for PHP to use for the connection.

  • CURLOPT_PROXYUSERPWD: Pass a string formatted in the [username]:[password] format for connection to the HTTP proxy.

  • CURLOPT_RANGE: Pass the specified range you want. It should be in the "X-Y" format, where X or Y may be left out. The HTTP transfers also support several intervals, separated with commas as in X-Y,N-M.

  • CURLOPT_POSTFIELDS: Pass a string containing the full data to post in an HTTP "POST" operation.

  • CURLOPT_REFERER: Pass a string containing the "referer" header to be used in an HTTP request.

  • CURLOPT_USERAGENT: Pass a string containing the "user-agent" header to be used in an HTTP request.

  • CURLOPT_FTPPORT: Pass a string containing 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_COOKIE: Pass a string containing the content of the cookie to be set in the HTTP header.

  • CURLOPT_SSLCERT: Pass a string containing the filename of PEM formatted certificate.

  • CURLOPT_SSLCERTPASSWD: Pass a string containing the password required to use the CURLOPT_SSLCERT certificate.

  • CURLOPT_COOKIEFILE: Pass a string containing 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_CUSTOMREQUEST: Pass a string to be used instead of GET or HEAD when doing an HTTP request. This is useful for doing DELETE or other, more obscure, HTTP requests. Valid values are things like GET, POST, and so on; i.e. do not enter a whole HTTP request line here. For instance, entering 'GET /index.html HTTP/1.0\r\n\r\n' would be incorrect.

    注: Don't do this without making sure your server supports the command first.

  • CURLOPT_PROXY: Give the name of the HTTP proxy to tunnel requests through.

  • CURLOPT_INTERFACE: Pass the name of the outgoing network interface to use. This can be an interface name, an IP address or a host name.

  • CURLOPT_KRB4LEVEL: Pass the KRB4 (Kerberos 4) security level. Anyone of the following strings (in order from least powerful, to most powerful): 'clear', 'safe', 'confidential', 'private'. If the string does not match one of these, then 'private' is used. If you set this to NULL, this disables KRB4 security. KRB4 security only works with FTP transactions currently.

  • CURLOPT_HTTPHEADER: Pass an array of HTTP header fields to set.

  • CURLOPT_QUOTE: Pass an array of FTP commands to perform on the server prior to the FTP request.

  • CURLOPT_POSTQUOTE: Pass an array of FTP commands to execute on the server, after the FTP request has been performed.

The following options expect a file descriptor that is obtained by using the fopen() function:

  • CURLOPT_FILE: The file where the output of your transfer should be placed, the default is STDOUT.

  • CURLOPT_INFILE: The file where the input of your transfer comes from.

  • CURLOPT_WRITEHEADER: The file to write the header part of the output into.

  • CURLOPT_STDERR: The file to write errors to instead of stderr.

后退 | 起点 | 前进
curl_init | 上一级 | curl_version


curl_version

(PHP 4 >= 4.0.2)

curl_version -- Return the current CURL version

Description

string curl_version ( void)

The curl_version() function returns a string containing the current CURL version.

后退 | 起点 | 前进
curl_setopt | 上一级 | Cybercash payment functions


Cybercash payment functions

PHP 手册
后退 前进

XIII. Cybercash payment functions

安装

These functions are only available if the interpreter has been compiled with the --with-cybercash=[DIR].

目录
cybercash_base64_decode — base64 decode data for Cybercash
cybercash_base64_encode — base64 encode data for Cybercash
cybercash_decr — Cybercash decrypt
cybercash_encr — Cybercash encrypt

后退 | 起点 | 前进
curl_version | 上一级 | cybercash_base64_decode


cybercash_base64_decode

(PHP 4 )

cybercash_base64_decode -- base64 decode data for Cybercash

Description

string cybercash_base64_decode ( string inbuff)

后退 | 起点 | 前进
Cybercash payment functions | 上一级 | cybercash_base64_encode


cybercash_base64_encode

(PHP 4 )

cybercash_base64_encode -- base64 encode data for Cybercash

Description

string cybercash_base64_encode ( string inbuff)

后退 | 起点 | 前进
cybercash_base64_decode | 上一级 | cybercash_decr


cybercash_decr

(PHP 4 )

cybercash_decr -- Cybercash decrypt

Description

array cybercash_decr ( string wmk, string sk, string inbuff)

The function returns an associative array with the elements "errcode" and, if "errcode" is FALSE, "outbuff" (string), "outLth" (long) and "macbuff" (string).

后退 | 起点 | 前进
cybercash_base64_encode | 上一级 | cybercash_encr


cybercash_encr

(PHP 4 )

cybercash_encr -- Cybercash encrypt

Description

array cybercash_encr ( string wmk, string sk, string inbuff)

The function returns an associative array with the elements "errcode" and, if "errcode" is FALSE, "outbuff" (string), "outLth" (long) and "macbuff" (string).

后退 | 起点 | 前进
cybercash_decr | 上一级 | Crédit Mutuel CyberMUT functions


Crédit Mutuel CyberMUT functions

PHP 手册
后退 前进

XIV. Crédit Mutuel CyberMUT functions

介绍

This extension allows you to process credit cards transactions using Crédit Mutuel CyberMUT system (http://www.creditmutuel.fr/centre_commercial/vendez_sur_internet.html).

CyberMUT is a popular Web Payment Service in France, provided by the Crédit 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 SDK functions, except for the parameters of return for cybermut_creerformulairecm() and cybermut_creerreponsecm(), which are returned directly by functions PHP, whereas they had passed in reference in the original functions.

These functions have been added in PHP 4.0.6.

注: These functions only provide a link to CyberMUT SDK. Be sure to read the CyberMUT Developers Guide for full details of the required parameters.

安装

These functions are only available if PHP has been compiled with the --with-cybermut[=DIR] option, where DIR is the location of libcm-mac.a and cm-mac.h. 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 Crédit Mutuel).

目录
cybermut_creerformulairecm — Generate HTML form of request for payment
cybermut_creerreponsecm — Generate the acknowledgement of delivery of the confirmation of payment
cybermut_testmac — Make sure that there no was data diddling contained in the received message of confirmation

后退 | 起点 | 前进
cybercash_encr | 上一级 | cybermut_creerformulairecm


cybermut_creerformulairecm

(PHP 4 >= 4.0.5)

cybermut_creerformulairecm -- Generate HTML form of request for payment

Description

string cybermut_creerformulairecm ( string url_CM, string version, string TPE, string montant, string ref_commande, string texte_libre, string url_retour, string url_retour_ok, string url_retour_err, string langue, string code_societe, string texte_bouton)

cybermut_creerformulairecm() is used to generate the HTML form of request for payment.

例子 1. First step of payment (equiv cgi1.c)

<?php
// Directory where the keys are located
putenv("CMKEYDIR=/var/creditmut/cles");

// Version number
$VERSION="1.2";

  $retour =  cybermut_creerformulairecm(
  "https://www.creditmutuel.fr/test/telepaiement/paiement.cgi",
  $VERSION,
  "1234567890",
  "300FRF",
  $REFERENCE,
  $TEXTE_LIBRE,
  $URL_RETOUR,
  $URL_RETOUR_OK,
  $URL_RETOUR_ERR,
  "francais",
  "company",
  "Paiement par carte bancaire");

  echo $retour;
?>

See also cybermut_testmac() and cybermut_creerreponsecm().

后退 | 起点 | 前进
Crédit Mutuel CyberMUT functions | 上一级 | cybermut_creerreponsecm


cybermut_creerreponsecm

(PHP 4 >= 4.0.5)

cybermut_creerreponsecm -- Generate the acknowledgement of delivery of the confirmation of payment

Description

string cybermut_creerreponsecm ( string phrase)

cybermut_creerreponsecm() returns a string containing delivery acknowledgement message.

The parameter is "OK" if the message of confirmation of the payment was correctly identified by cybermut_testmac(). Any other chain is regarded as an error message.

See also cybermut_creerformulairecm() and cybermut_testmac().

后退 | 起点 | 前进
cybermut_creerformulairecm | 上一级 | cybermut_testmac


cybermut_testmac

(PHP 4 >= 4.0.5)

cybermut_testmac -- Make sure that there no was data diddling contained in the received message of confirmation

Description

bool cybermut_testmac ( string code_MAC, string version, string TPE, string cdate, string montant, string ref_commande, string texte_libre, string code-retour)

cybermut_testmac() is used to make sure that there was not data diddling contained in the received message of confirmation. Pay attention to parameters code-retour and texte-libre, which cannot be evaluated as is, because of the dash. You must retrieve them by using:
<?php
  $code_retour = $_GET["code-retour"];
  $texte_libre = $_GET["texte-libre"];
?>

例子 1. Last step of payment (equiv cgi2.c)

<?php
// Make sure that Enable Track Vars is ON.
// Directory where are located the keys
putenv("CMKEYDIR=/var/creditmut/cles");

// Version number
$VERSION="1.2";

$texte_libre = $_GET["texte-libre"];
$code_retour = $_GET["code-retour"];

$mac_ok = cybermut_testmac($MAC,$VERSION,$TPE,$date,$montant,$reference,$texte_libre,$code_retour);

if ($mac_ok) {

  //
  // insert data processing here
  //
  //

  $result=cybermut_creerreponsecm("OK");
} else {
  $result=cybermut_creerreponsecm("Document Falsifie");
}

?>

See also cybermut_creerformulairecm() and cybermut_creerreponsecm().

后退 | 起点 | 前进
cybermut_creerreponsecm | 上一级 | Cyrus IMAP administration functions


Cyrus IMAP administration functions

PHP 手册
后退 前进

XV. Cyrus IMAP administration functions

介绍

警告

该文档目前尚无参考文档；仅参数列表可用。

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

CYRUS_CONN_NONSYNCLITERAL (integer)

CYRUS_CONN_INITIALRESPONSE (integer)

CYRUS_CALLBACK_NUMBERED (integer)

CYRUS_CALLBACK_NOLITERAL (integer)

目录
cyrus_authenticate — Authenticate against a Cyrus IMAP server
cyrus_bind — Bind callbacks to a Cyrus IMAP connection
cyrus_close — Close connection to a Cyrus IMAP server
cyrus_connect — Connect to a Cyrus IMAP server
cyrus_query — Send a query to a Cyrus IMAP server
cyrus_unbind — Unbind ...

后退 | 起点 | 前进
cybermut_testmac | 上一级 | cyrus_authenticate


cyrus_authenticate

(PHP 4 >= 4.1.0)

cyrus_authenticate -- Authenticate against a Cyrus IMAP server

Description

bool cyrus_authenticate ( resource connection [, string mechlist [, string service [, string user [, int minssf [, int maxssf]]]]])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
Cyrus IMAP administration functions | 上一级 | cyrus_bind


cyrus_bind

(PHP 4 >= 4.1.0)

cyrus_bind -- Bind callbacks to a Cyrus IMAP connection

Description

bool cyrus_bind ( resource connection, array callbacks)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
cyrus_authenticate | 上一级 | cyrus_close


cyrus_close

(PHP 4 >= 4.1.0)

cyrus_close -- Close connection to a Cyrus IMAP server

Description

bool cyrus_close ( resource connection)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
cyrus_bind | 上一级 | cyrus_connect


cyrus_connect

(PHP 4 >= 4.1.0)

cyrus_connect -- Connect to a Cyrus IMAP server

Description

resource cyrus_connect ( [string host [, string port [, int flags]]])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
cyrus_close | 上一级 | cyrus_query


cyrus_query

(PHP 4 >= 4.1.0)

cyrus_query -- Send a query to a Cyrus IMAP server

Description

bool cyrus_query ( resource connection, string query)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
cyrus_connect | 上一级 | cyrus_unbind


cyrus_unbind

(PHP 4 >= 4.1.0)

cyrus_unbind -- Unbind ...

Description

bool cyrus_unbind ( resource connection, string trigger_name)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
cyrus_query | 上一级 | Character type functions


Character type functions

PHP 手册
后退 前进

XVI. Character type functions

介绍

The functions provided by this extension check whether a character or string falls into a certain character class according to the current locale (see also setlocale()).

When called with an integer argument these functions behave exactly like their C counterparts from "ctype.h".

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.

需求

None besides functions from the standard C library which are always available.

安装

Beginning with PHP 4.2.0 these functions are enabled by default. For older versions you have to configure and compile PHP with --enable-ctype.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

目录
ctype_alnum — Check for alphanumeric character(s)
ctype_alpha — Check for alphabetic character(s)
ctype_cntrl — Check for control character(s)
ctype_digit — Check for numeric character(s)
ctype_graph — Check for any printable character(s) except space
ctype_lower — Check for lowercase character(s)
ctype_print — Check for printable character(s)
ctype_punct — Check for any printable character which is not whitespace or an alphanumeric character
ctype_space — Check for whitespace character(s)
ctype_upper — Check for uppercase character(s)
ctype_xdigit — Check for character(s) representing a hexadecimal digit

后退 | 起点 | 前进
cyrus_unbind | 上一级 | ctype_alnum


ctype_alnum

(PHP 4 >= 4.0.4)

ctype_alnum -- Check for alphanumeric character(s)

Description

bool ctype_alnum ( string text)

Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise. In the standard C locale letters are just [A-Za-z]. The function is equivalent to (ctype_alpha($text) || ctype_digit($text)).

See also ctype_alpha(), ctype_digit(), and setlocale().

后退 | 起点 | 前进
Character type functions | 上一级 | ctype_alpha


ctype_alpha

(PHP 4 >= 4.0.4)

ctype_alpha -- Check for alphabetic character(s)

Description

bool ctype_alpha ( string text)

Returns TRUE if every character in text is a letter from the current locale, FALSE otherwise. In the standard C locale letters are just [A-Za-z] and ctype_alpha() is equivalent to (ctype_upper($text) || ctype_lower($text)), but other languages have letters that are considered neither upper nor lower case.

See also ctype_upper(),
ctype_lower(), and
setlocale().

后退 | 起点 | 前进
ctype_alnum | 上一级 | ctype_cntrl


ctype_cntrl

(PHP 4 >= 4.0.4)

ctype_cntrl -- Check for control character(s)

Description

bool ctype_cntrl ( string text)

Returns TRUE if every character in text has a special control function, FALSE otherwise. Control characters are e.g. line feed, tab, esc.

后退 | 起点 | 前进
ctype_alpha | 上一级 | ctype_digit


ctype_digit

(PHP 4 >= 4.0.4)

ctype_digit -- Check for numeric character(s)

Description

bool ctype_digit ( string text)

Returns TRUE if every character in text is a decimal digit, FALSE otherwise.

See also ctype_alnum() and ctype_xdigit().

后退 | 起点 | 前进
ctype_cntrl | 上一级 | ctype_graph


ctype_graph

(PHP 4 >= 4.0.4)

ctype_graph -- Check for any printable character(s) except space

Description

bool ctype_graph ( string text)

Returns TRUE if every character in text is printable and actually creates visible output (no white space), FALSE otherwise.

See also ctype_alnum(), ctype_print(), and ctype_punct().

后退 | 起点 | 前进
ctype_digit | 上一级 | ctype_lower


ctype_lower

(PHP 4 >= 4.0.4)

ctype_lower -- Check for lowercase character(s)

Description

bool ctype_lower ( string text)

Returns TRUE if every character in text is a lowercase letter in the current locale.

See also ctype_alpha() and ctype_upper().

后退 | 起点 | 前进
ctype_graph | 上一级 | ctype_print


ctype_print

(PHP 4 >= 4.0.4)

ctype_print -- Check for printable character(s)

Description

bool ctype_print ( string text)

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.

See also ctype_cntrl(), ctype_graph(), and ctype_punct().

后退 | 起点 | 前进
ctype_lower | 上一级 | ctype_punct


ctype_punct

(PHP 4 >= 4.0.4)

ctype_punct -- Check for any printable character which is not whitespace or an alphanumeric character

Description

bool ctype_punct ( string text)

Returns TRUE if every character in text is printable, but neither letter, digit or blank, FALSE otherwise.

See also ctype_cntrl(), ctype_graph(), and ctype_punct().

后退 | 起点 | 前进
ctype_print | 上一级 | ctype_space


ctype_space

(PHP 4 >= 4.0.4)

ctype_space -- Check for whitespace character(s)

Description

bool ctype_space ( string text)

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.

后退 | 起点 | 前进
ctype_punct | 上一级 | ctype_upper


ctype_upper

(PHP 4 >= 4.0.4)

ctype_upper -- Check for uppercase character(s)

Description

bool ctype_upper ( string text)

Returns TRUE if every character in text is a uppercase letter in the current locale.

See also ctype_alpha() and ctype_lower().

后退 | 起点 | 前进
ctype_space | 上一级 | ctype_xdigit


ctype_xdigit

(PHP 4 >= 4.0.4)

ctype_xdigit -- Check for character(s) representing a hexadecimal digit

Description

bool ctype_xdigit ( string text)

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.

See also ctype_digit().

后退 | 起点 | 前进
ctype_upper | 上一级 | Database (dbm-style) abstraction layer functions


Database (dbm-style) abstraction layer functions

PHP 手册
后退 前进

XVII. Database (dbm-style) abstraction layer functions

介绍

These functions build the foundation for accessing Berkeley DB style databases.

This is a general abstraction layer for several file-based databases. As such, functionality is limited to a common subset of features supported by modern databases such as Sleepycat Software's DB2. (This is not to be confused with IBM's DB2 software, which is supported through the ODBC functions.)

需求

The behaviour of various aspects depends on the implementation of the underlying database. Functions such as dba_optimize() and dba_sync() will do what they promise for one database and will do nothing for others. You have to download and install supported dba-Handlers.

表格 1. List of DBA handlers

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.
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 here. Since it is constant, we support only reading operations.

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().

安装

By using the --enable-dba=shared configuration option you can build a dynamic loadable modul 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.

表格 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].
cdb | To enable support for cdb add --with-cdb[=DIR].

运行时配置

该扩展模块未定义任何设置指令。

资源类型

The functions dba_open() and dba_popen() return a handle to the specified database file to access which is used by all other dba-function calls.

预定义常量

该扩展模块未定义任何常量。

范例

例子 1. DBA example

<?php

$id = dba_open ("/tmp/test.db", "n", "db2");

if (!$id) {
    echo "dba_open failed\n";
    exit;
}

dba_replace ("key", "This is an example!", $id);

if (dba_exists ("key", $id)) {
    echo dba_fetch ("key", $id);
    dba_delete ("key", $id);
}

dba_close ($id);
?>

DBA is binary safe and does not have any arbitrary limits. However, it inherits all limits set by the underlying database implementation.

All file-based databases must provide a way of setting the file mode of a new created database, if that is possible at all. The file mode is commonly passed as the fourth argument to dba_open() or dba_popen().

You can access all entries of a database in a linear way by using the dba_firstkey() and dba_nextkey() functions. You may not change the database while traversing it.

例子 2. Traversing a database

<?php

// ...open database...

$key = dba_firstkey ($id);

while ($key != false) {
    if (...) {          // remember the key to perform some action later
        $handle_later[] = $key;
    }
    $key = dba_nextkey ($id);
}

for ($i = 0; $i < count($handle_later); $i++)
    dba_delete ($handle_later[$i], $id);

?>

目录
dba_close — Close database
dba_delete — Delete entry specified by key
dba_exists — Check whether key exists
dba_fetch — Fetch data specified by key
dba_firstkey — Fetch first key
dba_insert — Insert entry
dba_nextkey — Fetch next key
dba_open — Open database
dba_optimize — Optimize database
dba_popen — Open database persistently
dba_replace — Replace or insert entry
dba_sync — Synchronize database

后退 | 起点 | 前进
ctype_xdigit | 上一级 | dba_close


dba_close

(PHP 3>= 3.0.8, PHP 4 )

dba_close -- Close database

Description

void dba_close ( resource handle)

dba_close() closes the established database and frees all resources specified by handle.

handle is a database handle returned by dba_open().

dba_close() does not return any value.

See also: dba_open() and dba_popen()

后退 | 起点 | 前进
Database (dbm-style) abstraction layer functions | 上一级 | dba_delete


dba_delete

(PHP 3>= 3.0.8, PHP 4 )

dba_delete -- Delete entry specified by key

Description

bool dba_delete ( string key, resource handle)

dba_delete() deletes the entry specified by key from the database specified with handle.

key is the key of the entry which is deleted.

handle is a database handle returned by dba_open().

dba_delete() returns TRUE or FALSE, if the entry is deleted or not deleted, respectively.

See also: dba_exists(),
dba_fetch(), dba_insert(),
and dba_replace().

后退 | 起点 | 前进
dba_close | 上一级 | dba_exists


dba_exists

(PHP 3>= 3.0.8, PHP 4 )

dba_exists -- Check whether key exists

Description

bool dba_exists ( string key, resource handle)

dba_exists() checks whether the specified key exists in the database specified by handle.

Key is the key the check is performed for.

Handle is a database handle returned by dba_open().

dba_exists() returns TRUE or FALSE, if the key is found or not found, respectively.

See also: dba_fetch(),
dba_delete(), dba_insert(),
and dba_replace().

后退 | 起点 | 前进
dba_delete | 上一级 | dba_fetch


dba_fetch

(PHP 3>= 3.0.8, PHP 4 )

dba_fetch -- Fetch data specified by key

Description

string dba_fetch ( string key, resource handle)

dba_fetch() fetches the data specified by key from the database specified with handle.

Key is the key the data is specified by.

Handle is a database handle returned by dba_open().

dba_fetch() returns the associated string or FALSE, if the key/data pair is found or not found, respectively.

See also: dba_exists(),
dba_delete(), dba_insert(),
and dba_replace().

后退 | 起点 | 前进
dba_exists | 上一级 | dba_firstkey


dba_firstkey

(PHP 3>= 3.0.8, PHP 4 )

dba_firstkey -- Fetch first key

Description

string dba_firstkey ( resource handle)

dba_firstkey() returns the first key of the database specified by handle and resets the internal key pointer. This permits a linear search through the whole database.

Handle is a database handle returned by dba_open().

dba_firstkey() returns the key or FALSE depending on whether it succeeds or fails, respectively.

See also: dba_nextkey() and example 2 in the DBA examples

后退 | 起点 | 前进
dba_fetch | 上一级 | dba_insert


dba_insert

(PHP 3>= 3.0.8, PHP 4 )

dba_insert -- Insert entry

Description

bool dba_insert ( string key, string value, resource handle)

dba_insert() inserts the entry described with key and value into the database specified by handle. It fails, if an entry with the same key already exists.

key is the key of the entry to be inserted.

value is the value to be inserted.

handle is a database handle returned by dba_open().

dba_insert() returns TRUE or FALSE, depending on whether it succeeds of fails, respectively.

See also:
dba_exists()
dba_delete()
dba_fetch()
dba_replace()

后退 | 起点 | 前进
dba_firstkey | 上一级 | dba_nextkey


dba_nextkey

(PHP 3>= 3.0.8, PHP 4 )

dba_nextkey -- Fetch next key

Description

string dba_nextkey ( resource handle)

dba_nextkey() returns the next key of the database specified by handle and advances the internal key pointer.

handle is a database handle returned by dba_open().

dba_nextkey() returns the key or FALSE depending on whether it succeeds or fails, respectively.

See also: dba_firstkey() and example 2 in the DBA examples

后退 | 起点 | 前进
dba_insert | 上一级 | dba_open


dba_open

(PHP 3>= 3.0.8, PHP 4 )

dba_open -- Open database

Description

resource dba_open ( string path, string mode, string handler [, ...])

dba_open() establishes a database instance for path with mode using handler.

path is commonly a regular path in your filesystem.

mode is "r" for read access, "w" for read/write access to an already existing database, "c" for read/write access and database creation if it doesn't currently exist, and "n" for create, truncate and read/write access.

handler is 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.

dba_open() returns a positive handle or FALSE, in the case the open is successful or fails, respectively.

See also: dba_popen() dba_close()

后退 | 起点 | 前进
dba_nextkey | 上一级 | dba_optimize


dba_optimize

(PHP 3>= 3.0.8, PHP 4 )

dba_optimize -- Optimize database

Description

bool dba_optimize ( resource handle)

dba_optimize() optimizes the underlying database specified by handle.

handle is a database handle returned by dba_open().

dba_optimize() returns TRUE or FALSE, if the optimization succeeds or fails, respectively.

See also: dba_sync()

后退 | 起点 | 前进
dba_open | 上一级 | dba_popen


dba_popen

(PHP 3>= 3.0.8, PHP 4 )

dba_popen -- Open database persistently

Description

resource dba_popen ( string path, string mode, string handler [, ...])

dba_popen() establishes a persistent database instance for path with mode using handler.

path is commonly a regular path in your filesystem.

mode is "r" for read access, "w" for read/write access to an already existing database, "c" for read/write access and database creation if it doesn't currently exist, and "n" for create, truncate and read/write access.

handler is 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_popen() returns a positive handle or FALSE, in the case the open is successful or fails, respectively.

See also: dba_open() dba_close()

后退 | 起点 | 前进
dba_optimize | 上一级 | dba_replace


dba_replace

(PHP 3>= 3.0.8, PHP 4 )

dba_replace -- Replace or insert entry

Description

bool dba_replace ( string key, string value, resource handle)

dba_replace() replaces or inserts the entry described with key and value into the database specified by handle.

key is the key of the entry to be inserted.

value is the value to be inserted.

handle is a database handle returned by dba_open().

dba_replace() returns TRUE or FALSE, depending on whether it succeeds of fails, respectively.

See also: dba_exists(),
dba_delete(), dba_fetch(),
and dba_insert().

后退 | 起点 | 前进
dba_popen | 上一级 | dba_sync


dba_sync

(PHP 3>= 3.0.8, PHP 4 )

dba_sync -- Synchronize database

Description

bool dba_sync ( resource handle)

dba_sync() synchronizes the database specified by handle. This will probably trigger a physical write to disk, if supported.

handle is a database handle returned by dba_open().

dba_sync() returns TRUE or FALSE, if the synchronization succeeds or fails, respectively.

See also: dba_optimize()

后退 | 起点 | 前进
dba_replace | 上一级 | 时间日期函数库


时间日期函数库

PHP 手册
后退 前进

XVIII. 时间日期函数库

介绍

可以用这些函数得到 PHP 所运行的服务器的日期和时间。可以用这些函数将日期和时间以很多不同方式格式化输出。

注: 请留意这些函数依赖于服务器的地区设置。确认在使用这些函数时考虑到了夏令时的设置和闰年。

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

这些函数作为 PHP 核心的一部分，无需被安装即可使用。

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

目录
checkdate — 验证一个格里高里日期
date — 格式化一个本地时间／日期
getdate — 取得日期／时间信息
gettimeofday — 取得当前时间
gmdate — 格式化一个 GMT/CUT 日期／时间
gmmktime — 取得 GMT 日期的 UNIX 时间戳
gmstrftime — 根据区域设置格式化 GMT/CUT 时间／日期
localtime — Get the local time
microtime — 返回当前 UNIX 时间戳和微秒数
mktime — 取得一个日期的 UNIX 时间戳
strftime — 根据区域设置格式化本地时间／日期
strtotime — 将任何英文文本的日期时间描述解析为 UNIX 时间戳
time — 返回当前的 UNIX 时间戳

后退 | 起点 | 前进
dba_sync | 上一级 | checkdate


checkdate

(PHP 3, PHP 4 )

checkdate -- 验证一个格里高里日期

说明

bool checkdate ( int month, int day, int year)

如果给出的日期有效则返回 TRUE，否则返回 FALSE。检查由参数构成的日期的合法性。日期在以下情况下被认为有效：

  • year 的值是从 1 到 32767

  • month 的值是从 1 到 12

  • Day 的值在给定的 month 所应该具有的天数范围之内，闰年已经考虑进去了。

参见 mktime() 和 strtotime()。

后退 | 起点 | 前进
时间日期函数库 | 上一级 | date


date

(PHP 3, PHP 4 )

date -- 格式化一个本地时间／日期

说明

string date ( string format [, int timestamp])

返回将整数 timestamp 按照给定的格式字串而产生的字符串。如果没有给出时间戳则使用本地当前时间。

注: 有效的时间戳典型范围是格林威治时间 1901 年 12 月 13 日 20:45:54 到 2038 年 1 月 19 日 03:14:07。（此范围符合 32 位有符号整数的最小值和最大值）。在 Windows 系统中此范围限制为从 1970 年 1 月 1 日到 2038 年 1 月 19 日。

要将字符串表达的时间转换成时间戳，应该使用 strtotime()。此外一些数据库有一些函数将其时间格式转换成时间戳（例如 MySQL 的 UNIX_TIMESTAMP 函数）。

格式字串可以识别以下字符：

  • a - "am" 或 "pm"

  • A - "AM" 或 "PM"

  • B - Swatch Internet Time（【译者注】参见 http://swatch.com/alu_beat/fs_itime.html）

  • d - 月份中的第几天，有前导零的 2 位数字，例如 "01" to "31"

  • D - 星期中的第几天，文本表示，3 个字母，例如 "Fri"

  • F - 月份，完整的文本格式，例如 "January"

  • g - 小时，12 小时格式，没有前导零，例如 "1" 到 "12"

  • G - 小时，24 小时格式，没有前导零，例如 "0" 到 "23"

  • h - 小时，12 小时格式，例如 "01" 到 "12"

  • H - 小时，24 小时格式，例如 "00" 到 "23"

  • i - 分钟，例如 "00" 到 "59"

  • I（“i”的大写的字母）- 如果是夏令时则为 "1"，否则为 "0"

  • j - 月份中的第几天，没有前导零，例如 "1" 到 "31"

  • l（“L”的小写字母）- 星期中的第几天，完整的文本格式，例如 "Friday"

  • L - 布尔值表示是否为闰年，例如 "0" 或者 "1"

  • m - 月份，例如 "01" to "12"

  • M - 月份，文本表示，3 个字母，例如 "Jan"

  • n - 月份，没有前导零，例如 "1" 到 "12"

  • O - 与格林威治时间相差的小时数，例如 "+0200"

  • r - RFC 822 格式的日期，例如 "Thu, 21 Dec 2000 16:01:07 +0200"（PHP 4.0.4新增）

  • s - 秒数，例如 "00" 到 "59"

  • S - 每月天数后面的英文后缀，2 个字符，例如 "st"，"nd"，"rd" 或者 "th"

  • t - 给定月份所应有的天数，例如 "28" 到 "31"

  • T - 本机所在的时区，例如 "EST" 或 "MDT"（【译者注】在 Windows 下为完整文本格式，例如“Eastern Standard Time”，中文版会显示“中国标准时间”。）

  • U - 从 Unix 纪元（January 1 1970 00:00:00 GMT）开始至今的秒数

  • w - 星期中的第几天，数字表示，例如 "0"（星期天）到 "6" (Saturday)

  • W - ISO-8601 格式年份中的第几周，每周从星期一开始（PHP 4.1.0 新加的）

  • Y - 年份，4 位数字，例如 "1999"

  • y - 年费，2 位数字，例如 "99"

  • z - 年份中的第几天，例如 "0" 到 "365"

  • Z - 时差偏移量的秒数（例如 "-43200" 到 "43200"）。UTC 西边的时区偏移量总是负的，UTC 东边的时区偏移量总是正的。

格式字串中不能被识别的字符将原样显示。“Z”格式在使用 gmdate() 时总是返回“0”。

例子 1. date() 例子

echo date ("l dS of F Y h:i:s A");
echo "July 1, 2000 is on a " . date ("l", mktime(0,0,0,7,1,2000));

在格式字串中的字符前加上反斜线来转义可以避免它被按照上表解释。如果加上反斜线后的字符本身就是一个特殊序列，那还要转义反斜线。

例子 2. 在 date() 中转义字符

echo date("l \\t\h\e jS"); // 显示类似于：Saturday the 8th

可以把 date() 和 mktime() 结合使用来得到未来或过去的日期。

例子 3. date() 和 mktime() 例子

$tomorrow  = mktime (0,0,0,date("m")  ,date("d")+1,date("Y"));
$lastmonth = mktime (0,0,0,date("m")-1,date("d"),  date("Y"));
$nextyear  = mktime (0,0,0,date("m"),  date("d"),  date("Y")+1);

注: 由于夏令时的缘故，这种方法比简单地在时间戳上加减一天或者一个月的秒数更可靠。

一些使用 date() 格式化日期的例子。注意要转义所有其它的字符，因为目前有特殊含义的字符会产生不需要的结果，而其余字符在 PHP 将来的版本中可能会被用上。当转义时，注意用单引号以避免类似 \n 的字符变成了换行符。

例子 4. date() Formatting

/* Today is March 10th, 2001, 5:16:18 pm */
$today = date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
$today = date("m.d.y");                         // 03.10.01
$today = date("j, n, Y");                       // 10, 3, 2001
$today = date("Ymd");                           // 20010310
$today = date('h-i-s, j-m-y, it is w Day z ');  // 05-16-17, 10-03-01, 1631 1618 6 Fripm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.');   // It is the 10th day.
$today = date("D M j G:i:s T Y");               // Sat Mar 10 15:16:08 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:17 m is month
$today = date("H:i:s");                         // 17:16:17

要格式化其它语种的日期，应该用 setlocale() 和 strftime() 函数。

参见 getlastmod()，gmdate()，mktime()，strftime() 和 time()。

后退 | 起点 | 前进
checkdate | 上一级 | getdate


getdate

(PHP 3, PHP 4 )

getdate -- 取得日期／时间信息

说明

array getdate ( [int timestamp])

返回一个根据 timestamp 得出的包含有日期信息的结合数组。如果没有给出时间戳则认为是当前本地时间。数组中的单元如下：

  • "seconds" - 秒数

  • "minutes" - 分钟数

  • "hours" - 小时数

  • "mday" - 月份中的第几日

  • "wday" - 星期中的第几日，数字格式，从 0 表示星期天到 6 表示星期六

  • "mon" - 月份，数字

  • "year" - 年份，数字

  • "yday" - 年份中的第几日，数字，例如 "299"

  • "weekday" - 星期中的第几日，完整的文本格式，例如 "Friday"

  • "month" - 月份，完整的文本格式，例如 "January"

例子 1. getdate() 例子

$today = getdate();
$month = $today['month'];
$mday = $today['mday'];
$year = $today['year'];
echo "$month $mday, $year";

后退 | 起点 | 前进
date | 上一级 | gettimeofday


gettimeofday

(PHP 3>= 3.0.7, PHP 4 )

gettimeofday -- 取得当前时间

说明

array gettimeofday ( void)

本函数是 gettimeofday(2) 的接口。返回一个结合数组，包含有系统调用返回的数据。

  • "sec" - 秒数

  • "usec" - 微秒数

  • "minuteswest" - 格林威治向西的分钟数

  • "dsttime" - 夏令时修正的类型

后退 | 起点 | 前进
getdate | 上一级 | gmdate


gmdate

(PHP 3, PHP 4 )

gmdate -- 格式化一个 GMT/CUT 日期／时间

说明

string gmdate ( string format [, int timestamp])

同 date() 函数完全一样，只除了返回的时间是格林威治标准时（GMT）。例如当在中国（GMT +0800）运行以下程序时，第一行显示“Jan 01 2000 00:00:00”而第二行显示“Dec 31 1999 16:00:00”。

例子 1. gmdate() 例子

echo date ("M d Y H:i:s", mktime (0,0,0,1,1,2000));
echo gmdate ("M d Y H:i:s", mktime (0,0,0,1,1,2000));

参见 date()，mktime()，gmmktime() 和 strftime()。

后退 | 起点 | 前进
gettimeofday | 上一级 | gmmktime


gmmktime

(PHP 3, PHP 4 )

gmmktime -- 取得 GMT 日期的 UNIX 时间戳

说明

int gmmktime ( int hour, int minute, int second, int month, int day, int year [, int is_dst])

和 mktime() 完全一样，只除了返回值是格林威治标准时的时间戳。

后退 | 起点 | 前进
gmdate | 上一级 | gmstrftime


gmstrftime

(PHP 3>= 3.0.12, PHP 4 )

gmstrftime -- 根据区域设置格式化 GMT/CUT 时间／日期

说明

string gmstrftime ( string format [, int timestamp])

和 strftime() 的行为相同，只除了返回时间是格林威治标准时（GMT）。例如，当在东部标准时（EST，GMT -500）运行时，下面第一行显示“Dec 31 1998 20:00:00”，而第二行显示“Jan 01 1999 01:00:00”。

例子 1. gmstrftime() 例子

setlocale (LC_TIME, 'en_US');
echo strftime ("%b %d %Y %H:%M:%S", mktime (20,0,0,12,31,98))."\n";
echo gmstrftime ("%b %d %Y %H:%M:%S", mktime (20,0,0,12,31,98))."\n";

参见 strftime()。

后退 | 起点 | 前进
gmmktime | 上一级 | localtime


localtime

(PHP 4 )

localtime -- Get the local time

Description

array localtime ( [int timestamp [, bool is_associative]])

The localtime() function returns an array identical to that of the structure returned by the C function call. The first argument to localtime() is the timestamp, if this is not given the current time is used. The second argument to the localtime() is the is_associative, if this is set to 0 or not supplied than the array is returned as a regular, numerically indexed array. If the argument is set to 1 then localtime() is an associative array containing all the different elements of the structure returned by the C function call to localtime. The names of the different keys of the associative array are as follows:

  • "tm_sec" - seconds

  • "tm_min" - minutes

  • "tm_hour" - hour

  • "tm_mday" - day of the month

  • "tm_mon" - month of the year, starting with 0 for January

  • "tm_year" - Years since 1900

  • "tm_wday" - Day of the week

  • "tm_yday" - Day of the year

  • "tm_isdst" - Is daylight savings time in effect

后退 | 起点 | 前进
gmstrftime | 上一级 | microtime


microtime

(PHP 3, PHP 4 )

microtime -- 返回当前 UNIX 时间戳和微秒数

说明

string microtime ( void)

返回格式为“msec sec”的字符串，其中 sec 是当前的 Unix 时间戳，msec 是微秒部分。本函数仅在支持 gettimeofday() 系统调用的操作系统下可用。

字符串的两部分都是以秒为单位返回的。

例子 1. microtime() 例子

function getmicrotime(){
    list($usec, $sec) = explode(" ",microtime());
    return ((float)$usec + (float)$sec);
    }

$time_start = getmicrotime();

for ($i=0; $i < 1000; $i++){
    //do nothing, 1000 times
    }

$time_end = getmicrotime();
$time = $time_end - $time_start;

echo "Did nothing in $time seconds";

参见 time()。

后退 | 起点 | 前进
localtime | 上一级 | mktime


mktime

(PHP 3, PHP 4 )

mktime -- 取得一个日期的 UNIX 时间戳

说明

int mktime ( int hour, int minute, int second, int month, int day, int year [, int is_dst])

警告：注意参数的奇怪顺序，这和标准的 UNIX mktime() 调用中的参数顺序不同。在脚本经常会混淆这些值而出错。

根据给出的参数返回 Unix 时间戳。时间戳是一个长整数，包含了从 Unix 新纪元（1970 年 1 月 1 日）到给定时间的秒数。

参数可以从右向左省略，任何省略的参数会被设置成本地日期和时间的当前值。

is_dst 在夏令时可以被设为 1，如果不是则设为 0，或者不知道是否为夏令时的话设为 -1（默认值）。如果不知道，PHP 会尝试自己判断。这可能会产生未预期（但不是错误）的结果。

注: is_dst 是 3.0.10 版新加的。

mktime() 可以用来做日期计算和验证，对于超出范围的输入它可以自动计算出正确的值来。例如，下面的每一行都会输出字符串“Jan-01-1998”。

例子 1. mktime() 例子

echo date ("M-d-Y", mktime (0,0,0,12,32,1997));
echo date ("M-d-Y", mktime (0,0,0,13,1,1997));
echo date ("M-d-Y", mktime (0,0,0,1,1,1998));
echo date ("M-d-Y", mktime (0,0,0,1,1,98));
Year 可以是两位或四位数字，取值从 0-69 表示 2000-2069 以及 70-99 表示 1970-1999（在如今很常见的 time_t 是 32 位有符号整数的系统中，year 的有效范围是 1902 到 2037）。

给定月份的最后一天可以表达为下个月的第 "0" 天，而不是 -1 天。下面两个例子都将产生字符串“The last day in Feb 2000 is: 29”。

例子 2. 每个月的最后一天

$lastday = mktime (0,0,0,3,0,2000);
echo strftime ("Last day in Feb 2000 is: %d", $lastday);

$lastday = mktime (0,0,0,4,-31,2000);
echo strftime ("Last day in Feb 2000 is: %d", $lastday);

年，月，日都等于零的日期被认为是非法的（否则会被当作 30.11.1999，这是很怪的行为）。

参见 date() 和 time()。

后退 | 起点 | 前进
microtime | 上一级 | strftime


strftime

(PHP 3, PHP 4 )

strftime -- 根据区域设置格式化本地时间／日期

说明

string strftime ( string format [, int timestamp])

返回用给定的格式字串对给出的 timestamp 进行格式输出后的字符串。如果没有给出时间戳则用当前的本地时间。月份和星期几以及其它和语言有关的字符串写法和用 setlocale() 设定的当前的区域有关。

格式字串能识别下列转换标记：

  • %a - 当前区域星期几的简写

  • %A - 当前区域星期几的全称

  • %b - 当前区域月份的简写

  • %B - 当前区域月份的全称

  • %c - 当前区域首选的日期时间表达

  • %C - 世纪值（年份除以 100 后取整，范围从 00 到 99）

  • %d - 月份中的第几天，十进制数字（范围从 01 到 31）

  • %D - 和 %m/%d/%y 一样

  • %e - 月份中的第几天，十进制数字，一位的数字前会加上一个空格（范围从 ' 1' 到 '31'）

  • %g - 和 %G 一样，但是没有世纪

  • %G - 4 位数的年份，符合 ISO 星期数（参见 %V）。和 %V 的格式和值一样，只除了如果 ISO 星期数属于前一年或者后一年，则使用那一年。

  • %h - 和 %b 一样

  • %H - 24 小时制的十进制小时数（范围从 00 到 23）

  • %I - 12 小时制的十进制小时数（范围从 00 到 12）

  • %j - 年份中的第几天，十进制数（范围从 001 到 366）

  • %m - 十进制月份（范围从 01 到 12）

  • %M - 十进制分钟数

  • %n - 换行符

  • %p - 根据给定的时间值为 `am' 或 `pm'，或者当前区域设置中的相应字符串

  • %r - 用 a.m. 和 p.m. 符号的时间

  • %R - 24 小时符号的时间

  • %S - 十进制秒数

  • %t - 制表符

  • %T - 当前时间，和 %H:%M:%S 一样

  • %u - 星期几的十进制数表达 [1,7]，1 表示星期一

    警告

    尽管 ISO 9889:1999（当前的 C 标准）明确指出一周从星期一开始，但是 Sun Solaris 的一周似乎从星期天开始并作为 1。

  • %U - 本年的第几周，从第一周的第一个星期天作为第一天开始

  • %V - 本年第几周的 ISO 8601:1988 格式，范围从 01 到 53，第 1 周是本年第一个至少还有 4 天的星期，星期一作为每周的第一天。（用 %G 或者 %g 作为指定时间戳相应周数的年份组成。）

  • %W - 本年的第几周数，从第一周的第一个星期一作为第一天开始

  • %w - 星期中的第几天，星期天为 0

  • %x - 当前区域首选的时间表示法，不包括时间

  • %X - 当前区域首选的时间表示法，不包括日期

  • %y - 没有世纪数的十进制年份（范围从 00 到 99）

  • %Y - 包括世纪数的十进制年份

  • %Z - 时区名或缩写

  • %% - 文字上的 `%' 字符

注: 可能不是所有的转换标记都被 C 库文件支持，这种情况下 PHP 的 strftime() 也不支持。这意味着例如 %e, %T 和 %D（可能更多）在 Windows 下不起作用。

例子 1. strftime() 例子

setlocale (LC_TIME, "C");
print (strftime ("%A in Finnish is "));
setlocale (LC_TIME, "fi_FI");
print (strftime ("%A, in French "));
setlocale (LC_TIME, "fr_FR");
print (strftime ("%A and in German "));
setlocale (LC_TIME, "de_DE");
print (strftime ("%A.\n"));
本例在你的系统中安装有各自的区域设置后才能工作。

参见 setlocale() 和 mktime() 以及 Open Group specification of strftime()。

后退 | 起点 | 前进
mktime | 上一级 | strtotime


strtotime

(PHP 3>= 3.0.12, PHP 4 )

strtotime -- 将任何英文文本的日期时间描述解析为 UNIX 时间戳

说明

int strtotime ( string time [, int now])

本函数预期接受一个包含英文日期格式的字符串并尝试将其解析为 UNIX 时间戳。如果 time 的格式是绝对时间则 now 参数不起作用。如果 time 的格式是相对时间则其所相对的时间由 now 提供，或者如果未提供 now 参数时用当前时间。失败时返回 -1。

因为 strtotime() 的行为是依照 GNU 日期语法的，因此请看看 GNU 手册中的 Date Input Formats。这里记述了 time 参数的合法语法。

例子 1. strtotime() 例子

echo strtotime ("now"), "\n";
echo strtotime ("10 September 2000"), "\n";
echo strtotime ("+1 day"), "\n";
echo strtotime ("+1 week"), "\n";
echo strtotime ("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime ("next Thursday"), "\n";
echo strtotime ("last Monday"), "\n";

例子 2. 检查失败

$str = 'Not Good';
if (($timestamp = strtotime($str)) === -1) {
    echo "The string ($str) is bogus";
} else {
    echo "$str == ". date('l dS of F Y h:i:s A',$timestamp);
}

注: 有效的时间戳典型范围是从格林威治时间 1901 年 12 月 13 日 星期五 20:45:54 到 2038年 1 月 19 日 星期二 03:14:07。（该日期根据 32 位有符号整数的最小值和最大值而来。）

后退 | 起点 | 前进
strftime | 上一级 | time


time

(PHP 3, PHP 4 )

time -- 返回当前的 UNIX 时间戳

说明

int time ( void)

返回自从 Unix 新纪元（格林威治时间 1970 年 1 月 1 日 00:00:00）到当前时间的秒数。

参见 date()。

后退 | 起点 | 前进
strtotime | 上一级 | dBase functions


dBase functions

PHP 手册
后退 前进

XIX. dBase functions

介绍

These functions allow you to access records stored in dBase-format (dbf) databases.

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.

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().

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 use these functions, you must compile PHP with the --enable-dbase option.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

目录
dbase_add_record — Add a record to a dBase database
dbase_close — Close a dBase database
dbase_create — Creates a dBase database
dbase_delete_record — Deletes a record from a dBase database
dbase_get_record_with_names — Gets a record from a dBase database as an associative array
dbase_get_record — Gets a record from a dBase database
dbase_numfields — Find out how many fields are in a dBase database
dbase_numrecords — Find out how many records are in a dBase database
dbase_open — Opens a dBase database
dbase_pack — Packs a dBase database
dbase_replace_record — Replace a record in a dBase database

后退 | 起点 | 前进
time | 上一级 | dbase_add_record


dbase_add_record

(PHP 3, PHP 4 )

dbase_add_record -- Add a record to a dBase database

Description

bool dbase_add_record ( int dbase_identifier, array record)

Adds the data in the record to the database. If the number of items in the supplied record isn't equal to the number of fields in the database, the operation will fail and FALSE will be returned.

后退 | 起点 | 前进
dBase functions | 上一级 | dbase_close


dbase_close

(PHP 3, PHP 4 )

dbase_close -- Close a dBase database

Description

bool dbase_close ( int dbase_identifier)

Closes the database associated with dbase_identifier.

后退 | 起点 | 前进
dbase_add_record | 上一级 | dbase_create


dbase_create

(PHP 3, PHP 4 )

dbase_create -- Creates a dBase database

Description

int dbase_create ( string filename, array fields)

The fields parameter is an array of arrays, each array describing the format of one field in the database. Each field consists of a name, a character indicating the field type, a length, and a precision.

The types of fields available are:

L

Boolean. These do not have a length or precision.

M

Memo. (Note that these aren't supported by PHP.) These do not have a length or precision.

D

Date (stored as YYYYMMDD). These do not have a length or precision.

N

Number. These have both a length and a precision (the number of digits after the decimal point).

C

String.

If the database is successfully created, a dbase_identifier is returned, otherwise FALSE is returned.

例子 1. Creating a dBase database file

// "database" name
$dbname = "/tmp/test.dbf";

// database "definition"
$def =
    array(
        array("date",     "D"),
        array("name",     "C",  50),
        array("age",      "N",   3, 0),
        array("email",    "C", 128),
        array("ismember", "L")
    );

// creation
if (!dbase_create($dbname, $def))
    print "<strong>Error!</strong>";

后退 | 起点 | 前进
dbase_close | 上一级 | dbase_delete_record


dbase_delete_record

(PHP 3, PHP 4 )

dbase_delete_record -- Deletes a record from a dBase database

Description

bool dbase_delete_record ( int dbase_identifier, int record)

Marks record to be deleted from the database. To actually remove the record from the database, you must also call dbase_pack().

后退 | 起点 | 前进
dbase_create | 上一级 | dbase_get_record_with_names


dbase_get_record_with_names

(PHP 3>= 3.0.4, PHP 4 )

dbase_get_record_with_names -- Gets a record from a dBase database as an associative array

Description

array dbase_get_record_with_names ( int dbase_identifier, int record)

Returns the data from record in an associative array. The array also includes an associative member 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

后退 | 起点 | 前进
dbase_delete_record | 上一级 | dbase_get_record


dbase_get_record

(PHP 3, PHP 4 )

dbase_get_record -- Gets a record from a dBase database

Description

array dbase_get_record ( int dbase_identifier, int record)

Returns the data from record in an array. The array is indexed starting at 0, and includes an associative member 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

后退 | 起点 | 前进
dbase_get_record_with_names | 上一级 | dbase_numfields


dbase_numfields

(PHP 3, PHP 4 )

dbase_numfields -- Find out how many fields are in a dBase database

Description

int dbase_numfields ( int dbase_identifier)

Returns 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).

例子 1. Using dbase_numfields()

$rec = dbase_get_record($db, $recno);
$nf  = dbase_numfields($db);
for ($i=0; $i < $nf; $i++) {
    print $rec[$i]."<br>\n";
}

后退 | 起点 | 前进
dbase_get_record | 上一级 | dbase_numrecords


dbase_numrecords

(PHP 3, PHP 4 )

dbase_numrecords -- Find out how many records are in a dBase database

Description

int dbase_numrecords ( int dbase_identifier)

Returns 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_numfields | 上一级 | dbase_open


dbase_open

(PHP 3, PHP 4 )

dbase_open -- Opens a dBase database

Description

int dbase_open ( string filename, int flags)

The flags correspond to those for the open() system call. (Typically 0 means read-only, 1 means write-only, and 2 means read and write.)

Returns a dbase_identifier for the opened database, or FALSE if the database couldn't be opened.

注: 当 安全模式（safe mode） 被激活，PHP 将检查您将要操作的文件或者目录与正在执行的脚本是否有相同的 UID。

后退 | 起点 | 前进
dbase_numrecords | 上一级 | dbase_pack


dbase_pack

(PHP 3, PHP 4 )

dbase_pack -- Packs a dBase database

Description

bool dbase_pack ( int dbase_identifier)

Packs the specified database (permanently deleting all records marked for deletion using dbase_delete_record()).

后退 | 起点 | 前进
dbase_open | 上一级 | dbase_replace_record


dbase_replace_record

(PHP 3>= 3.0.11, PHP 4 )

dbase_replace_record -- Replace a record in a dBase database

Description

bool dbase_replace_record ( int dbase_identifier, array record, int dbase_record_number)

Replaces the data associated with the record record_number with the data in the record in the database. If the number of items in the supplied record is not equal to the number of fields in the database, the operation will fail and FALSE will be returned.

dbase_record_number is an integer which spans from 1 to the number of records in the database (as returned by dbase_numrecords()).

后退 | 起点 | 前进
dbase_pack | 上一级 | DBM Functions


DBM Functions

PHP 手册
后退 前进

XX. DBM Functions

介绍

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 encourged 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 addtion you must ensure support for an underlying database or you can use some sytem libraries.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

The function dbmopen() returns an database identifier which is used by the other dbm-functions.

预定义常量

该扩展模块未定义任何常量。

范例

例子 1. DBM example

$dbm = dbmopen ("lastseen", "w");
if (dbmexists ($dbm, $userid)) {
    $last_seen = dbmfetch ($dbm, $userid);
} else {
    dbminsert ($dbm, $userid, time());
}
do_stuff();
dbmreplace ($dbm, $userid, time());
dbmclose ($dbm);

目录
dblist — Describes the DBM-compatible library being used
dbmclose — Closes a dbm database
dbmdelete — Deletes the value for a key from a DBM database
dbmexists — Tells if a value exists for a key in a DBM database
dbmfetch — Fetches a value for a key from a DBM database
dbmfirstkey — Retrieves the first key from a DBM database
dbminsert — Inserts a value for a key in a DBM database
dbmnextkey — Retrieves the next key from a DBM database
dbmopen — Opens a DBM database
dbmreplace — Replaces the value for a key in a DBM database

后退 | 起点 | 前进
dbase_replace_record | 上一级 | dblist


dblist

(PHP 3, PHP 4 )

dblist -- Describes the DBM-compatible library being used

Description

string dblist ( void)

后退 | 起点 | 前进
DBM Functions | 上一级 | dbmclose


dbmclose

(PHP 3, PHP 4 )

dbmclose -- Closes a dbm database

Description

bool dbmclose ( resource dbm_identifier)

Unlocks and closes the specified database.

后退 | 起点 | 前进
dblist | 上一级 | dbmdelete


dbmdelete

(PHP 3, PHP 4 )

dbmdelete -- Deletes the value for a key from a DBM database

Description

bool dbmdelete ( resource dbm_identifier, string key)

Deletes the value for key in the database.

Returns FALSE if the key didn't exist in the database.

后退 | 起点 | 前进
dbmclose | 上一级 | dbmexists


dbmexists

(PHP 3, PHP 4 )

dbmexists -- Tells if a value exists for a key in a DBM database

Description

bool dbmexists ( resource dbm_identifier, string key)

Returns TRUE if there is a value associated with the key.

后退 | 起点 | 前进
dbmdelete | 上一级 | dbmfetch


dbmfetch

(PHP 3, PHP 4 )

dbmfetch -- Fetches a value for a key from a DBM database

Description

string dbmfetch ( resource dbm_identifier, string key)

Returns the value associated with key.

后退 | 起点 | 前进
dbmexists | 上一级 | dbmfirstkey


dbmfirstkey

(PHP 3, PHP 4 )

dbmfirstkey -- Retrieves the first key from a DBM database

Description

string dbmfirstkey ( resource dbm_identifier)

Returns the first key in the database. Note that no particular order is guaranteed since the database may be built using a hash-table, which doesn't guarantee any ordering.

后退 | 起点 | 前进
dbmfetch | 上一级 | dbminsert


dbminsert

(PHP 3, PHP 4 )

dbminsert -- Inserts a value for a key in a DBM database

Description

int dbminsert ( resource dbm_identifier, string key, string value)

Adds the value to the database with the specified key.

Returns -1 if the database was opened read-only, 0 if the insert was successful, and 1 if the specified key already exists. (To replace the value, use dbmreplace().)

后退 | 起点 | 前进
dbmfirstkey | 上一级 | dbmnextkey


dbmnextkey

(PHP 3, PHP 4 )

dbmnextkey -- Retrieves the next key from a DBM database

Description

string dbmnextkey ( resource dbm_identifier, string key)

Returns the next key after key. By calling dbmfirstkey() followed by successive calls to dbmnextkey() it is possible to visit every key/value pair in the dbm database. For example:

例子 1. Visiting every key/value pair in a DBM database

$key = dbmfirstkey ($dbm_id);
while ($key) {
    echo "$key = " . dbmfetch ($dbm_id, $key) . "\n";
    $key = dbmnextkey ($dbm_id, $key);
}

后退 | 起点 | 前进
dbminsert | 上一级 | dbmopen


dbmopen

(PHP 3, PHP 4 )

dbmopen -- Opens a DBM database

Description

resource dbmopen ( string filename, string flags)

The first argument is the full-path filename of the DBM file to be opened and the second is the file open mode which is one of "r", "n", "c" or "w" for read-only, new (implies read-write, and most likely will truncate an already-existing database of the same name), create (implies read-write, and will not truncate an already-existing database of the same name) and read-write respectively.

Returns an identifier to be passed to the other DBM functions on success, or FALSE on failure.

If NDBM support is used, NDBM will actually create filename.dir and filename.pag files. GDBM only uses one file, as does the internal flat-file support, and Berkeley DB creates a filename.db file. Note that PHP does its own file locking in addition to any file locking that may be done by the DBM library itself. PHP does not delete the .lck files it creates. It uses these files simply as fixed inodes on which to do the file locking. For more information on DBM files, see your Unix man pages, or obtain GNU's GDBM.

注: 当 安全模式（safe mode） 被激活，PHP 将检查您将要操作的文件或者目录与正在执行的脚本是否有相同的 UID。

后退 | 起点 | 前进
dbmnextkey | 上一级 | dbmreplace


dbmreplace

(PHP 3, PHP 4 )

dbmreplace -- Replaces the value for a key in a DBM database

Description

int dbmreplace ( resource dbm_identifier, string key, string value)

Replaces the value for the specified key in the database.

This will also add the key to the database if it didn't already exist.

后退 | 起点 | 前进
dbmopen | 上一级 | dbx functions


dbx functions

PHP 手册
后退 前进

XXI. dbx functions

介绍

The dbx module is a database abstraction layer (db 'X', where 'X' is a supported database). The dbx functions allow you to access all supported databases using a single calling convention. The dbx-functions themselves do not interface directly to the databases, but interface to the modules that are used to support these databases.

需求

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, following databases are supported, but others will follow (soon, I hope :-):

  • FrontBase (available from PHP 4.1.0).

  • Microsoft SQL Server

  • MySQL

  • ODBC

  • PostgreSQL

  • Sybase-CT (available from PHP 4.2.0).

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.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

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 helds the result of a query.

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

DBX_MYSQL (integer)

DBX_ODBC (integer)

DBX_PGSQL (integer)

DBX_MSSQL (integer)

DBX_FBSQL (integer)

DBX_OCI8 (integer)

DBX_SYBASECT (integer)

DBX_PERSISTENT (integer)

DBX_RESULT_INFO (integer)

DBX_RESULT_INDEX (integer)

DBX_RESULT_ASSOC (integer)

DBX_CMP_NATIVE (integer)

DBX_CMP_TEXT (integer)

DBX_CMP_NUMBER (integer)

DBX_CMP_ASC (integer)

DBX_CMP_DESC (integer)

目录
dbx_close — Close an open connection/database
dbx_compare — Compare two rows for sorting purposes
dbx_connect — Open a connection/database
dbx_error — Report the error message of the latest function call in the module (not just in the connection)
dbx_query — Send a query and fetch all results (if any)
dbx_sort — Sort a result from a dbx_query by a custom sort function

后退 | 起点 | 前进
dbmreplace | 上一级 | dbx_close


dbx_close

(PHP 4 >= 4.0.6)

dbx_close -- Close an open connection/database

Description

bool dbx_close ( object link_identifier)

如果成功则返回 TRUE，失败则返回 FALSE。

例子 1. dbx_close() example

<?php
$link = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die ("Could not connect");

print("Connected successfully");
dbx_close($link);
?>

注: Always refer to the module-specific documentation as well.

See also: dbx_connect().

后退 | 起点 | 前进
dbx functions | 上一级 | dbx_compare


dbx_compare

(PHP 4 >= 4.1.0)

dbx_compare -- Compare two rows for sorting purposes

Description

int dbx_compare ( array row_a, array row_b, string column_key [, int flags])

dbx_compare() returns 0 if the row_a[$column_key] is equal to row_b[$column_key], and 1 or -1 if the former is greater or is smaller than the latter one, respectively, or vice versa if the flag is set to DBX_CMP_DESC. dbx_compare() is a helper function for dbx_sort() to ease the make and use of the custom sorting function.

The flags can be set to specify comparison direction:

  • DBX_CMP_ASC - ascending order

  • DBX_CMP_DESC - descending order

and the preferred comparison type:

  • DBX_CMP_NATIVE - no type conversion

  • DBX_CMP_TEXT - compare items as strings

  • DBX_CMP_NUMBER - compare items numerically

One of the direction and one of the type constant can be combined with bitwise OR operator (|). The default value for the flags parameter is DBX_CMP_ASC | DBX_CMP_NATIVE.

例子 1. dbx_compare() example

<?php
function user_re_order ($a, $b) {
    $rv = dbx_compare ($a, $b, "parentid", DBX_CMP_DESC);
    if ( !$rv ) {
        $rv = dbx_compare ($a, $b, "id", DBX_CMP_NUMBER);
    }
    return $rv;
}

$link   = dbx_connect (DBX_ODBC, "", "db", "username", "password")
    or die ("Could not connect");

$result = dbx_query ($link, "SELECT id, parentid, description FROM table ORDER BY id");
    // data in $result is now ordered by id

dbx_sort ($result, "user_re_order");
    // date in $result is now ordered by parentid (descending), then by id

dbx_close ($link);
?>

See also dbx_sort().

后退 | 起点 | 前进
dbx_close | 上一级 | dbx_connect


dbx_connect

(PHP 4 >= 4.0.6)

dbx_connect -- Open a connection/database

Description

object dbx_connect ( mixed module, string host, string database, string username, string password [, int persistent])

dbx_connect() returns an object on success, FALSE on error. If a connection has been made but the database could not be selected, the connection is closed and FALSE is returned. The persistent parameter can be set to DBX_PERSISTENT, if so, a persistent connection will be created.

The module parameter can be either a string or a constant, though the latter form is preferred. The possible values are given below, but keep in mind that they only work if the module is actually loaded.

  • DBX_MYSQL or "mysql"

  • DBX_ODBC or "odbc"

  • DBX_PGSQL or "pgsql"

  • DBX_MSSQL or "mssql"

  • DBX_FBSQL or "fbsql" (available from PHP 4.1.0)

  • DBX_SYBASECT or "sybase_ct" (available from PHP 4.2.0)

The host, database, username and password parameters are expected, but not always used depending on the connect functions for the abstracted module.

The returned object has three properties:

database

It is the name of the currently selected database.

handle

It is a valid handle for the connected database, and as such it can be used in module-specific functions (if required).

$link = dbx_connect (DBX_MYSQL, "localhost", "db", "username", "password");
mysql_close ($link->handle); // dbx_close($link) would be better here

module

It is used internally by dbx only, and is actually the module number mentioned above.

例子 1. dbx_connect() example

<?php
$link = dbx_connect (DBX_ODBC, "", "db", "username", "password", DBX_PERSISTENT)
    or die ("Could not connect");

print ("Connected successfully");
dbx_close ($link);
?>

注: Always refer to the module-specific documentation as well.

See also: dbx_close().

后退 | 起点 | 前进
dbx_compare | 上一级 | dbx_error


dbx_error

(PHP 4 >= 4.0.6)

dbx_error -- Report the error message of the latest function call in the module (not just in the connection)

Description

string dbx_error ( object link_identifier)

dbx_error() returns a string containing the error message from the last function call of the abstracted module (e.g. mysql module). If there are multiple connections in the same module, just the last error is given. If there are connections on different modules, the latest error is returned for the module specified by the link_identifier parameter.

例子 1. dbx_error() example

<?php
$link   = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die ("Could not connect");

$result = dbx_query($link, "select id from non_existing_table");
if ( $result == 0 ) {
    echo dbx_error ($link);
}
dbx_close ($link);
?>

注: Always refer to the module-specific documentation as well.

The error message for Microsoft SQL Server is actually the result of the mssql_get_last_message() function.

后退 | 起点 | 前进
dbx_connect | 上一级 | dbx_query


dbx_query

(PHP 4 >= 4.0.6)

dbx_query -- Send a query and fetch all results (if any)

Description

object dbx_query ( object link_identifier, string sql_statement [, long flags])

dbx_query() returns an object or 1 on success, and 0 on failure. The result object is returned only if the query given in sql_statement produces a result set.

例子 1. How to handle the returned value

<?php
$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, 'SELECT id, parentid, description FROM table');

if ( is_object($result) ) {
    // ... do some stuff here, see detailed examples below ...
    // first, print out field names and types
    // then, draw a table filled with the returned field values
}
else if ( $result == 1 ) {
    echo("Query executed successfully, but no result set returned");
}
else {
    exit("Query failed");
}

dbx_close($link);
?>

The flags parameter is used to control the amount of information that is returned. It may be any combination of the following constants with the bitwise OR operator (|):

DBX_RESULT_INDEX

It is always set, that is, the returned object has a data property which is a 2 dimensional array indexed numerically. For example, in the expression data[2][3] 2 stands for the row (or record) number and 3 stands for the column (or field) number. The first row and column are indexed at 0.

If DBX_RESULT_ASSOC is also specified, the returning object contains the information related to DBX_RESULT_INFO too, even if it was not specified.

DBX_RESULT_INFO

It provides info about columns, such as field names and field types.

DBX_RESULT_ASSOC

It effects that the field values can be accessed with the respective column names used as keys to the returned object's data property.

Associated results are actually references to the numerically indexed data, so modifying data[0][0] causes that data[0]['field_name_for_first_column'] is modified as well.

Note that DBX_RESULT_INDEX is always used, regardless of the actual value of flags parameter. This means that the following combinations is effective only:

  • 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 returing object has four or five properties depending on flags:

handle

It is a valid handle for the connected database, and as such it can be used in module specific functions (if required).

$result = dbx_query ($link, "SELECT id FROM table");
mysql_field_len ($result->handle, 0);

cols and rows

These contain the number of columns (or fields) and rows (or records) respectively.

$result = dbx_query ($link, 'SELECT id FROM table');
echo $result->rows; // number of records
echo $result->cols; // number of fields

info (optional)

It is returned only if either DBX_RESULT_INFO or DBX_RESULT_ASSOC is specified in the flags parameter. It is a 2 dimensional array, that has two named rows (name and type) to retrieve column information.

例子 2. lists each field's name and type

$result = dbx_query ($link, 'SELECT id FROM table',
                     DBX_RESULT_INDEX | DBX_RESULT_INFO);

for ($i = 0; $i < $result->cols; $i++ ) {
    echo $result->info['name'][$i] . "\n";
    echo $result->info['type'][$i] . "\n";
}
data

This property contains the actual resulting data, possibly associated with column names as well depending on flags. If DBX_RESULT_ASSOC is set, it is possible to use $result->data[2]["field_name"].

例子 3. outputs the content of data property into HTML table

$result = dbx_query ($link, 'SELECT id, parentid, description FROM table');

echo "<table>\n";
foreach ( $result->data as $row ) {
    echo "<tr>\n";
    foreach ( $row as $field ) {
        echo "<td>$field</td>";
    }
    echo "</tr>\n";
}
echo "</table>\n";

注: Always refer to the module-specific documentation as well.

See also: dbx_connect().

后退 | 起点 | 前进
dbx_error | 上一级 | dbx_sort


dbx_sort

(PHP 4 >= 4.0.6)

dbx_sort -- Sort a result from a dbx_query by a custom sort function

Description

bool dbx_sort ( object result, string user_compare_function)

如果成功则返回 TRUE，失败则返回 FALSE。

注: It is always better to use ORDER BY SQL clause instead of dbx_sort(), if possible.

例子 1. dbx_sort() example

<?php
function user_re_order ($a, $b) {
    $rv = dbx_compare ($a, $b, "parentid", DBX_CMP_DESC);
    if ( !$rv ) {
        $rv = dbx_compare ($a, $b, "id", DBX_CMP_NUMBER);
    }
    return $rv;
}

$link   = dbx_connect (DBX_ODBC, "", "db", "username", "password")
    or die ("Could not connect");

$result = dbx_query ($link, "SELECT id, parentid, description FROM tbl ORDER BY id");
    // data in $result is now ordered by id

dbx_sort ($result, "user_re_order");
    // data in $result is now ordered by parentid (descending), then by id

dbx_close ($link);
?>

See also dbx_compare().

后退 | 起点 | 前进
dbx_query | 上一级 | DB++ Functions


DB++ Functions

PHP 手册
后退 前进

XXII. DB++ Functions

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

介绍

db++, made by the German company Concept asa, is a relational database system with high performance and low memory and disk usage in mind. While providing SQL as an additional language interface, it is not really a SQL database in the first place but provides its own AQL query language which is much more influenced by the relational algebra then SQL is.

Concept asa always had an interest in supporting open source languages, db++ has had Perl and Tcl call interfaces for years now and uses Tcl as its internal stored procedure language.

需求

This extension relies on external client libraries so you have to have a db++ client installed on the system you want to use this extension on.

Concept asa provides db++ Demo versions and documentation for Linux, some other UNIX versions. There is also a Windows version of db++, but this extension doesn't support it (yet).

安装

In order to build this extension yourself you need the db++ client libraries and header files to be installed on your system (these are included in the db++ installation archives by default). You have to run configure with option --with-dbplus to build this extension.

configure looks for the client libraries and header files under the default paths /usr/dbplus, /usr/local/dbplus and /opt/dblus. If you have installed db++ in a different place you have add the installation path to the configure option like this: --with-dbplus=/your/installation/path.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

dbplus_relation

Most db++ functions operate on or return dbplus_relation resources. A dbplus_relation is a handle to a stored relation or a relation generated as the result of a query.

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

db++ error codes

表格 1. DB++ Error Codes

PHP 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 |

目录
dbplus_add — Add a tuple to a relation
dbplus_aql — Perform AQL query
dbplus_chdir — Get/Set database virtual current directory
dbplus_close — Close a relation
dbplus_curr — Get current tuple from relation
dbplus_errcode — Get error string for given errorcode or last error
dbplus_errno — Get error code for last operation
dbplus_find — Set a constraint on a relation
dbplus_first — Get first tuple from relation
dbplus_flush — Flush all changes made on a relation
dbplus_freealllocks — Free all locks held by this client
dbplus_freelock — Release write lock on tuple
dbplus_freerlocks — Free all tuple locks on given relation
dbplus_getlock — Get a write lock on a tuple
dbplus_getunique — Get a id number unique to a relation
dbplus_info — ???
dbplus_last — Get last tuple from relation
dbplus_lockrel — Request write lock on relation
dbplus_next — Get next tuple from relation
dbplus_open — Open relation file
dbplus_prev — Get previous tuple from relation
dbplus_rchperm — Change relation permissions
dbplus_rcreate — Creates a new DB++ relation
dbplus_rcrtexact — Creates an exact but empty copy of a relation including indices
dbplus_rcrtlike — Creates an empty copy of a relation with default indices
dbplus_resolve — Resolve host information for relation
dbplus_restorepos — ???
dbplus_rkeys — Specify new primary key for a relation
dbplus_ropen — Open relation file local
dbplus_rquery — Perform local (raw) AQL query
dbplus_rrename — Rename a relation
dbplus_rsecindex — Create a new secondary index for a relation
dbplus_runlink — Remove relation from filesystem
dbplus_rzap — Remove all tuples from relation
dbplus_savepos — ???
dbplus_setindex — ???
dbplus_setindexbynumber — ???
dbplus_sql — Perform SQL query
dbplus_tcl — Execute TCL code on server side
dbplus_tremove — Remove tuple and return new current tuple
dbplus_undo — ???
dbplus_undoprepare — ???
dbplus_unlockrel — Give up write lock on relation
dbplus_unselect — Remove a constraint from relation
dbplus_update — Update specified tuple in relation
dbplus_xlockrel — Request exclusive lock on relation
dbplus_xunlockrel — Free exclusive lock on relation

后退 | 起点 | 前进
dbx_sort | 上一级 | dbplus_add


dbplus_add

(4.1.0 - 4.2.3 only)

dbplus_add -- Add a tuple to a relation

Description

int dbplus_add ( resource relation, array tuple)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

This function will add a tuple to a relation. The tuple data is an array of attribute/value pairs to be inserted into the given relation. After successful execution the tuple array will contain the complete data of the newly created tuple, including all implicitly set domain fields like sequences.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

后退 | 起点 | 前进
DB++ Functions | 上一级 | dbplus_aql


dbplus_aql

(4.1.0 - 4.2.3 only)

dbplus_aql -- Perform AQL query

Description

resource dbplus_aql ( string query [, string server [, string dbpath]])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_aql() will execute an AQL query on the given server and dbpath.

On success it will return a relation handle. The result data may be fetched from this relation by calling dbplus_next() and dbplus_current(). Other relation access functions will not work on a result relation.

Further information on the AQL A... Query Language is provided in the original db++ manual.

后退 | 起点 | 前进
dbplus_add | 上一级 | dbplus_chdir


dbplus_chdir

(4.1.0 - 4.2.3 only)

dbplus_chdir -- Get/Set database virtual current directory

Description

string dbplus_chdir ( [string newdir])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_chdir() will change the virtual current directory where relation files will be looked for by dbplus_open(). dbplus_chdir() will return the absolute path of the current directory. Calling dbplus_chdir() without giving any newdir may be used to query the current working directory.

后退 | 起点 | 前进
dbplus_aql | 上一级 | dbplus_close


dbplus_close

(4.1.0 - 4.2.3 only)

dbplus_close -- Close a relation

Description

int dbplus_close ( resource relation)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Calling dbplus_close() will close a relation previously opened by dbplus_open().

后退 | 起点 | 前进
dbplus_chdir | 上一级 | dbplus_curr


dbplus_curr

(4.1.0 - 4.2.3 only)

dbplus_curr -- Get current tuple from relation

Description

int dbplus_curr ( resource relation, array tuple)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_curr() will read the data for the current tuple for the given relation and will pass it back as an associative array in tuple.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_first(),
dbplus_prev(),
dbplus_next(), and
dbplus_last().

后退 | 起点 | 前进
dbplus_close | 上一级 | dbplus_errcode


dbplus_errcode

(4.1.0 - 4.2.3 only)

dbplus_errcode -- Get error string for given errorcode or last error

Description

string dbplus_errcode ( int errno)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_errcode() returns a cleartext error string for the error code passed as errno of for the result code of the last db++ operation if no parameter is given.

后退 | 起点 | 前进
dbplus_curr | 上一级 | dbplus_errno


dbplus_errno

(4.1.0 - 4.2.3 only)

dbplus_errno -- Get error code for last operation

Description

int dbplus_errno ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_errno() will return the error code returned by the last db++ operation.

See also dbplus_errcode().

后退 | 起点 | 前进
dbplus_errcode | 上一级 | dbplus_find


dbplus_find

(4.1.0 - 4.2.3 only)

dbplus_find -- Set a constraint on a relation

Description

int dbplus_find ( resource relation, array constraints, mixed tuple)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_find() will place a constraint on the given relation. Further calls to functions like dbplus_curr() or dbplus_next() will only return tuples matching the given constraints.

Constraints are triplets of strings containing of a domain name, a comparison operator and a comparison value. The constraints parameter array may consist of a collection of string arrays, each of which contains a domain, an operator and a value, or of a single string array containing a multiple of three elements.

The comparison operator may be one of the following strings: '==', '>', '>=', '<', '<=', '!=', '~' for a regular expression match and 'BAND' or 'BOR' for bitwise operations.

See also dbplus_unselect().

后退 | 起点 | 前进
dbplus_errno | 上一级 | dbplus_first


dbplus_first

(4.1.0 - 4.2.3 only)

dbplus_first -- Get first tuple from relation

Description

int dbplus_first ( resource relation, array tuple)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_curr() will read the data for the first tuple for the given relation, make it the current tuple and pass it back as an associative array in tuple.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_curr(),
dbplus_prev(),
dbplus_next(), and
dbplus_last().

后退 | 起点 | 前进
dbplus_find | 上一级 | dbplus_flush


dbplus_flush

(4.1.0 - 4.2.3 only)

dbplus_flush -- Flush all changes made on a relation

Description

int dbplus_flush ( resource relation)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_flush() will write all changes applied to relation since the last flush to disk.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

后退 | 起点 | 前进
dbplus_first | 上一级 | dbplus_freealllocks


dbplus_freealllocks

(4.1.0 - 4.2.3 only)

dbplus_freealllocks -- Free all locks held by this client

Description

int dbplus_freealllocks ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_freeaalllocks() will free all tuple locks held by this client.

See also dbplus_getlock(),
dbplus_freelock(), and
dbplus_freerlocks().

后退 | 起点 | 前进
dbplus_flush | 上一级 | dbplus_freelock


dbplus_freelock

(4.1.0 - 4.2.3 only)

dbplus_freelock -- Release write lock on tuple

Description

int dbplus_freelock ( resource relation, string tname)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_freelock() will release a write lock on the given tuple previously obtained by dbplus_getlock().

See also dbplus_getlock(),
dbplus_freerlocks(), and
dbplus_freealllocks().

后退 | 起点 | 前进
dbplus_freealllocks | 上一级 | dbplus_freerlocks


dbplus_freerlocks

(4.1.0 - 4.2.3 only)

dbplus_freerlocks -- Free all tuple locks on given relation

Description

int dbplus_freerlocks ( resource relation)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_freerlocks() will free all tuple locks held on the given relation.

See also dbplus_getlock(),
dbplus_freelock(), and
dbplus_freealllocks().

后退 | 起点 | 前进
dbplus_freelock | 上一级 | dbplus_getlock


dbplus_getlock

(4.1.0 - 4.2.3 only)

dbplus_getlock -- Get a write lock on a tuple

Description

int dbplus_getlock ( resource relation, string tname)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_getlock() will request a write lock on the specified tuple. It will return zero on success or a non-zero error code, especially DBPLUS_ERR_WLOCKED, on failure.

See also dbplus_freelock(),
dbplus_freerlocks(), and
dbplus_freealllocks().

后退 | 起点 | 前进
dbplus_freerlocks | 上一级 | dbplus_getunique


dbplus_getunique

(4.1.0 - 4.2.3 only)

dbplus_getunique -- Get a id number unique to a relation

Description

int dbplus_getunique ( resource relation, int uniqueid)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_getunique() will obtain a number guaranteed to be unique for the given relation and will pass it back in the variable given as uniqueid.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

后退 | 起点 | 前进
dbplus_getlock | 上一级 | dbplus_info


dbplus_info

(4.1.0 - 4.2.3 only)

dbplus_info -- ???

Description

int dbplus_info ( resource relation, string key, array )

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Not implemented yet.

后退 | 起点 | 前进
dbplus_getunique | 上一级 | dbplus_last


dbplus_last

(4.1.0 - 4.2.3 only)

dbplus_last -- Get last tuple from relation

Description

int dbplus_last ( resource relation, array tuple)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_curr() will read the data for the last tuple for the given relation, make it the current tuple and pass it back as an associative array in tuple.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_first(),
dbplus_curr(),
dbplus_prev(), and
dbplus_next().

后退 | 起点 | 前进
dbplus_info | 上一级 | dbplus_lockrel


dbplus_lockrel

(no version information, might be only in CVS)

dbplus_lockrel -- Request write lock on relation

Description

int dbplus_lockrel ( resource relation)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_lockrel() will request a write lock on the given relation. Other clients may still query the relation, but can't alter it while it is locked.

后退 | 起点 | 前进
dbplus_last | 上一级 | dbplus_next


dbplus_next

(4.1.0 - 4.2.3 only)

dbplus_next -- Get next tuple from relation

Description

int dbplus_next ( resource relation, array )

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_curr() will read the data for the next tuple for the given relation, will make it the current tuple and will pass it back as an associative array in tuple.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_first(),
dbplus_curr(),
dbplus_prev(), and
dbplus_last().

后退 | 起点 | 前进
dbplus_lockrel | 上一级 | dbplus_open


dbplus_open

(4.1.0 - 4.2.3 only)

dbplus_open -- Open relation file

Description

resource dbplus_open ( string name)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

The relation file name will be opened. name can be either a file name or a relative or absolute path name. This will be mapped in any case to an absolute relation file path on a specific host machine and server.

On success a relation file resource (cursor) is returned which must be used in any subsequent commands referencing the relation. Failure leads to a zero return value, the actual error code may be asked for by calling dbplus_errno().

后退 | 起点 | 前进
dbplus_next | 上一级 | dbplus_prev


dbplus_prev

(4.1.0 - 4.2.3 only)

dbplus_prev -- Get previous tuple from relation

Description

int dbplus_prev ( resource relation, array tuple)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_curr() will read the data for the next tuple for the given relation, will make it the current tuple and will pass it back as an associative array in tuple.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_first(),
dbplus_curr(),
dbplus_next(), and
dbplus_last().

后退 | 起点 | 前进
dbplus_open | 上一级 | dbplus_rchperm


dbplus_rchperm

(4.1.0 - 4.2.3 only)

dbplus_rchperm -- Change relation permissions

Description

int dbplus_rchperm ( resource relation, int mask, string user, string group)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_rchperm() will change access permissions as specified by mask, user and group. The values for these are operating system specific.

后退 | 起点 | 前进
dbplus_prev | 上一级 | dbplus_rcreate


dbplus_rcreate

(4.1.0 - 4.2.3 only)

dbplus_rcreate -- Creates a new DB++ relation

Description

resource dbplus_rcreate ( string name, mixed domlist [, boolean overwrite])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_rcreate() will create a new relation named name. An existing relation by the same name will only be overwritten if the relation is currently not in use and overwrite is set to TRUE.

domlist should contain the domain specification for the new relation within an array of domain description strings. ( dbplus_rcreate() will also accept a string with space delimited domain description strings, but it is recommended to use an array). A domain description string consists of a domain name unique to this relation, a slash and a type specification character. See the db++ documentation, especially the dbcreate(1) manpage, for a description of available type specifiers and their meanings.

后退 | 起点 | 前进
dbplus_rchperm | 上一级 | dbplus_rcrtexact


dbplus_rcrtexact

(4.1.0 - 4.2.3 only)

dbplus_rcrtexact -- Creates an exact but empty copy of a relation including indices

Description

resource dbplus_rcrtexact ( string name, resource relation, boolean overwrite)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_rcrtexact() will create an exact but empty copy of the given relation under a new name. An existing relation by the same name will only be overwritten if overwrite is TRUE and no other process is currently using the relation.

后退 | 起点 | 前进
dbplus_rcreate | 上一级 | dbplus_rcrtlike


dbplus_rcrtlike

(4.1.0 - 4.2.3 only)

dbplus_rcrtlike -- Creates an empty copy of a relation with default indices

Description

resource dbplus_rcrtlike ( string name, resource relation, int flag)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 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.

后退 | 起点 | 前进
dbplus_rcrtexact | 上一级 | dbplus_resolve


dbplus_resolve

(4.1.0 - 4.2.3 only)

dbplus_resolve -- Resolve host information for relation

Description

int dbplus_resolve ( string relation_name)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_resolve() will try to resolve the given relation_name and find out internal server id, real hostname and the database path on this host. The function will return an array containing these values under the keys 'sid', 'host' and 'host_path' or FALSE on error.

See also dbplus_tcl().

后退 | 起点 | 前进
dbplus_rcrtlike | 上一级 | dbplus_restorepos


dbplus_restorepos

(4.1.0 - 4.2.3 only)

dbplus_restorepos -- ???

Description

int dbplus_restorepos ( resource relation, array tuple)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Not implemented yet.

后退 | 起点 | 前进
dbplus_resolve | 上一级 | dbplus_rkeys


dbplus_rkeys

(4.1.0 - 4.2.3 only)

dbplus_rkeys -- Specify new primary key for a relation

Description

resource dbplus_rkeys ( resource relation, mixed domlist)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_rkeys() will replace the current primary key for relation with the combination of domains specified by domlist.

domlist may be passed as a single domain name string or as an array of domain names.

后退 | 起点 | 前进
dbplus_restorepos | 上一级 | dbplus_ropen


dbplus_ropen

(4.1.0 - 4.2.3 only)

dbplus_ropen -- Open relation file local

Description

resource dbplus_ropen ( string name)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_ropen() will open the relation file locally for quick access without any client/server overhead. Access is read only and only dbplus_current() and dbplus_next() may be applied to the returned relation.

后退 | 起点 | 前进
dbplus_rkeys | 上一级 | dbplus_rquery


dbplus_rquery

(4.1.0 - 4.2.3 only)

dbplus_rquery -- Perform local (raw) AQL query

Description

int dbplus_rquery ( string query, string dbpath)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_rquery() performs a local (raw) AQL query using an AQL interpreter embedded into the db++ client library. dbplus_rquery() is faster than dbplus_aql() but will work on local data only.

后退 | 起点 | 前进
dbplus_ropen | 上一级 | dbplus_rrename


dbplus_rrename

(4.1.0 - 4.2.3 only)

dbplus_rrename -- Rename a relation

Description

int dbplus_rrename ( resource relation, string name)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_rrename() will change the name of relation to name.

后退 | 起点 | 前进
dbplus_rquery | 上一级 | dbplus_rsecindex


dbplus_rsecindex

(4.1.0 - 4.2.3 only)

dbplus_rsecindex -- Create a new secondary index for a relation

Description

resource dbplus_rsecindex ( resource relation, mixed domlist, int type)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_rsecindex() will create a new secondary index for relation with consists of the domains specified by domlist and is of type type

domlist may be passed as a single domain name string or as an array of domain names.

后退 | 起点 | 前进
dbplus_rrename | 上一级 | dbplus_runlink


dbplus_runlink

(4.1.0 - 4.2.3 only)

dbplus_runlink -- Remove relation from filesystem

Description

int dbplus_runlink ( resource relation)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_unlink() will close and remove the relation.

后退 | 起点 | 前进
dbplus_rsecindex | 上一级 | dbplus_rzap


dbplus_rzap

(4.1.0 - 4.2.3 only)

dbplus_rzap -- Remove all tuples from relation

Description

int dbplus_rzap ( resource relation)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_rzap() will remove all tuples from relation.

后退 | 起点 | 前进
dbplus_runlink | 上一级 | dbplus_savepos


dbplus_savepos

(4.1.0 - 4.2.3 only)

dbplus_savepos -- ???

Description

int dbplus_savepos ( resource relation)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Not implemented yet.

后退 | 起点 | 前进
dbplus_rzap | 上一级 | dbplus_setindex


dbplus_setindex

(4.1.0 - 4.2.3 only)

dbplus_setindex -- ???

Description

int dbplus_setindex ( resource relation, string idx_name)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Not implemented yet.

后退 | 起点 | 前进
dbplus_savepos | 上一级 | dbplus_setindexbynumber


dbplus_setindexbynumber

(4.1.0 - 4.2.3 only)

dbplus_setindexbynumber -- ???

Description

int dbplus_setindexbynumber ( resource relation, int idx_number)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Not implemented yet.

后退 | 起点 | 前进
dbplus_setindex | 上一级 | dbplus_sql


dbplus_sql

(4.1.0 - 4.2.3 only)

dbplus_sql -- Perform SQL query

Description

resource dbplus_sql ( string query, string server, string dbpath)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Not implemented yet.

后退 | 起点 | 前进
dbplus_setindexbynumber | 上一级 | dbplus_tcl


dbplus_tcl

(4.1.0 - 4.2.3 only)

dbplus_tcl -- Execute TCL code on server side

Description

int dbplus_tcl ( int sid, string script)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

A db++ server will prepare a TCL interpreter for each client connection. This interpreter will enable the server to execute TCL code provided by the client as a sort of stored procedures to improve the performance of database operations by avoiding client/server data transfers and context switches.

dbplus_tcl() needs to pass the client connection id the TCL script code should be executed by. dbplus_resolve() will provide this connection id. The function will return whatever the TCL code returns or a TCL error message if the TCL code fails.

See also dbplus_resolve().

后退 | 起点 | 前进
dbplus_sql | 上一级 | dbplus_tremove


dbplus_tremove

(4.1.0 - 4.2.3 only)

dbplus_tremove -- Remove tuple and return new current tuple

Description

int dbplus_tremove ( resource relation, array tuple [, array current])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_tremove() removes tuple from relation if it perfectly matches a tuple within the relation. current, if given, will contain the data of the new current tuple after calling dbplus_tremove().

后退 | 起点 | 前进
dbplus_tcl | 上一级 | dbplus_undo


dbplus_undo

(4.1.0 - 4.2.3 only)

dbplus_undo -- ???

Description

int dbplus_undo ( resource relation)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Not implemented yet.

后退 | 起点 | 前进
dbplus_tremove | 上一级 | dbplus_undoprepare


dbplus_undoprepare

(4.1.0 - 4.2.3 only)

dbplus_undoprepare -- ???

Description

int dbplus_undoprepare ( resource relation)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Not implemented yet.

后退 | 起点 | 前进
dbplus_undo | 上一级 | dbplus_unlockrel


dbplus_unlockrel

(4.1.0 - 4.2.3 only)

dbplus_unlockrel -- Give up write lock on relation

Description

int dbplus_unlockrel ( resource relation)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_unlockrel() will release a write lock previously obtained by dbplus_lockrel().

后退 | 起点 | 前进
dbplus_undoprepare | 上一级 | dbplus_unselect


dbplus_unselect

(4.1.0 - 4.2.3 only)

dbplus_unselect -- Remove a constraint from relation

Description

int dbplus_unselect ( resource relation)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Calling dbplus_unselect() will remove a constraint previously set by dbplus_find() on relation.

后退 | 起点 | 前进
dbplus_unlockrel | 上一级 | dbplus_update


dbplus_update

(4.1.0 - 4.2.3 only)

dbplus_update -- Update specified tuple in relation

Description

int dbplus_update ( resource relation, array old, array new)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_update() replaces the tuple given by old with the data from new if and only if old completely matches a tuple within relation.

后退 | 起点 | 前进
dbplus_unselect | 上一级 | dbplus_xlockrel


dbplus_xlockrel

(4.1.0 - 4.2.3 only)

dbplus_xlockrel -- Request exclusive lock on relation

Description

int dbplus_xlockrel ( resource relation)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_xlockrel() will request an exclusive lock on relation preventing even read access from other clients.

See also dbplus_xunlockrel().

后退 | 起点 | 前进
dbplus_update | 上一级 | dbplus_xunlockrel


dbplus_xunlockrel

(4.1.0 - 4.2.3 only)

dbplus_xunlockrel -- Free exclusive lock on relation

Description

int dbplus_xunlockrel ( resource relation)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

dbplus_xunlockrel() will release an exclusive lock on relation previously obtained by dbplus_xlockrel().

后退 | 起点 | 前进
dbplus_xlockrel | 上一级 | Direct IO functions


Direct IO functions

PHP 手册
后退 前进

XXIII. Direct IO functions

介绍

PHP supports the direct io functions as described in the Posix Standard (Section 6) for performing I/O functions at a lower level than the C-Language stream I/O functions (fopen, fread,..).

需求

无需外部库文件就可以加入本扩展模块的支持。

Installation

To get these functions to work, you have to configure PHP with --enable-dio.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

One resource type is defined by this extension: a file descriptor returnded by dio_open().

预定义常量

该扩展模块未定义任何常量。

目录
dio_close — Closes the file descriptor given by fd
dio_fcntl — Performs a c library fcntl on fd
dio_open — Opens a new filename with specified permissions of flags and creation permissions of mode
dio_read — Reads n bytes from fd and returns them, if n is not specified, reads 1k block
dio_seek — Seeks to pos on fd from whence
dio_stat — Gets stat information about the file descriptor fd
dio_tcsetattr — Sets terminal attributes and baud rate for a serial port
dio_truncate — Truncates file descriptor fd to offset bytes
dio_write — Writes data to fd with optional truncation at length

后退 | 起点 | 前进
dbplus_xunlockrel | 上一级 | dio_close


dio_close

(PHP 4 >= 4.2.0)

dio_close -- Closes the file descriptor given by fd

Description

void dio_close ( resource fd)

The function dio_close() closes the file descriptor resource.

后退 | 起点 | 前进
Direct IO functions | 上一级 | dio_fcntl


dio_fcntl

(PHP 4 >= 4.2.0)

dio_fcntl -- Performs a c library fcntl on fd

Description

mixed dio_fcntl ( resource fd, int cmd [, mixed arg])

The dio_fcntl() function performs the operation specified by cmd on the file descriptor fd. Some commands require additional arguments args to be supplied.

arg 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)

cmd can be one of the following operations:

  • F_SETLK - Lock is set or cleared. If the lock is held by someone else dio_fcntl() returns -1.

  • F_SETLKW - like F_SETLK, but in case the lock is held by someone else, dio_fcntl() waits until the lock is released.

  • F_GETLK - dio_fcntl() returns an associative array (as described above) if someone else prevents lock. If there is no obstruction key "type" will set to F_UNLCK.

  • F_DUPFD - finds the lowest numbered available file descriptor greater or equal than arg and returns them.

  • F_SETFL - Sets the file descriptors flags to the value specified by arg, Which can be O_APPEND,O_NONBLOCK or O_ASYNC . To use O_ASYNC you will need to use the pcntl extension.

后退 | 起点 | 前进
dio_close | 上一级 | dio_open


dio_open

(PHP 4 >= 4.2.0)

dio_open -- Opens a new filename with specified permissions of flags and creation permissions of mode

Description

resource dio_open ( string filename, int flags [, int mode])

dio_open() opens a file and returns a new file descriptor for it, or -1 if any error occurred. If flags is O_CREAT, optional third parameter mode will set the mode of the file (creation permissions). The flags parameter can be one of the following options:

  • 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 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 file already exists

  • O_TRUNC - if file exists, and its opened for write access, file will be truncated to zero length.

  • O_APPEND - write operations write data at the end of file

  • O_NONBLOCK - sets non blocking mode

后退 | 起点 | 前进
dio_fcntl | 上一级 | dio_read


dio_read

(PHP 4 >= 4.2.0)

dio_read -- Reads n bytes from fd and returns them, if n is not specified, reads 1k block

Description

string dio_read ( resource fd [, int n])

The function dio_read() reads and returns n bytes from file with descriptor resource. If n is not specified, dio_read() reads 1K sized block and returns them.

后退 | 起点 | 前进
dio_open | 上一级 | dio_seek


dio_seek

(PHP 4 >= 4.2.0)

dio_seek -- Seeks to pos on fd from whence

Description

int dio_seek ( resource fd, int pos, int whence)

The function dio_seek() is used to change the file position of the file with descriptor resource. The parameter whence specifies how the position pos should be interpreted:

  • SEEK_SET - 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

后退 | 起点 | 前进
dio_read | 上一级 | dio_stat


dio_stat

(PHP 4 >= 4.2.0)

dio_stat -- Gets stat information about the file descriptor fd

Description

array dio_stat ( resource fd)

Function dio_stat() returns information about the file with file descriptor fd. dio_stat() returns an associative array with the following keys:

  • "device" - device

  • "inode" - inode

  • "mode" - mode

  • "nlink" - number of hard links

  • "uid" - user id

  • "gid" - group id

  • "device_type" - device type (if inode device)

  • "size" - total size in bytes

  • "blocksize" - blocksize

  • "blocks" - number of blocks allocated

  • "atime" - time of last access

  • "mtime" - time of last modification

  • "ctime" - time of last change

On error dio_stat() returns NULL.

后退 | 起点 | 前进
dio_seek | 上一级 | dio_tcsetattr


dio_tcsetattr

(PHP 4 CVS only)

dio_tcsetattr -- Sets terminal attributes and baud rate for a serial port

Description

dio_tcsetattr ( resource fd, array options)

The function dio_tcsetattr() sets the terminal attributes and baud rate of the open resource. The currently available options are

  • 'baud' - baud rate of the port - can be 38400,19200,9600,4800,2400,1800,1200,600,300,200,150,134,110,75 or 50, default value is 9600

  • 'bits' - data bits - can be 8,7,6 or 5 default value is 8

  • 'stop' - stop bits - can be 1 or 2 default value is 1

  • 'parity' - can be 0,1 or 2 default value is 0

例子 1. Setting the baud rate on a serial port

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK);

dio_fcntl($fd,F_SETFL, O_SYNC );

dio_tcsetattr($fd, array(
  'baud' => 9600,
  'bits' => 8,
  'stop'  =>1,
  'parity' => 0
));

while (1) {

  $data = dio_read($fd,256);

  if ($data) {
      echo $data;
  }
}

?>

注: This function was introduced in PHP 4.3.0.

后退 | 起点 | 前进
dio_stat | 上一级 | dio_truncate


dio_truncate

(PHP 4 >= 4.2.0)

dio_truncate -- Truncates file descriptor fd to offset bytes

Description

bool dio_truncate ( resource fd, int offset)

Function dio_truncate() causes the file referenced by fd to be truncated 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. Returns 0 on success, otherwise -1.

后退 | 起点 | 前进
dio_tcsetattr | 上一级 | dio_write


dio_write

(PHP 4 >= 4.2.0)

dio_write -- Writes data to fd with optional truncation at length

Description

int dio_write ( resource fd, string data [, int len])

The function dio_write() writes up to len bytes from data to file fd. If len is not specified, dio_write() writes all data to the specified file. dio_write() returns the number of bytes written to fd.

后退 | 起点 | 前进
dio_truncate | 上一级 | Directory functions


Directory functions

PHP 手册
后退 前进

XXIV. Directory functions

介绍

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

这些函数作为 PHP 核心的一部分，无需被安装即可使用。

运行时配置

该扩展模块未定义任何设置指令。

资源类型

预定义常量

该扩展模块未定义任何常量。

相关参考

For related functions such as dirname(),
is_dir(), mkdir(), and
rmdir(), see the
Filesystem section.

目录
chdir — change directory
chroot — change the root directory
dir — directory class
closedir — close directory handle
getcwd — gets the current working directory
opendir — open directory handle
readdir — read entry from directory handle
rewinddir — rewind directory handle

后退 | 起点 | 前进
dio_write | 上一级 | chdir


chdir

(PHP 3, PHP 4 )

chdir -- change directory

Description

bool chdir ( string directory)

Changes PHP's current directory to directory. Returns FALSE if unable to change directory, TRUE otherwise.

See also getcwd().

后退 | 起点 | 前进
Directory functions | 上一级 | chroot


chroot

(PHP 4 >= 4.0.5)

chroot -- change the root directory

Description

bool chroot ( string directory)

Changes the root directory of the current process to directory. Returns FALSE if unable to change the root directory, TRUE otherwise.

注: It's not wise to use this function when running in a webserver environment, because it's not possible to reset the root directory to / again at the end of the request. This function will only function correct when running as CGI this way.

注: 该函数不适用于 Windows 平台！

后退 | 起点 | 前进
chdir | 上一级 | dir


dir

dir -- directory class

Description

 class dir {

  dir(string directory);
  string path;

  string read();
  void rewind();
  void close();
}

A pseudo-object oriented mechanism for reading a directory. The given directory is opened. Two properties are available once the directory has been opened. The handle property can be used with other directory functions such as readdir(), rewinddir() and closedir(). The path property is set to path the directory that was opened. Three methods are available: read, rewind and close.

Please note the fashion in which dir()'s return value is checked in the example below. We are explicitly testing whether the return value is identical to (equal to and of the same type as--see Comparison Operators for more information) FALSE since otherwise, any directory entry whose name evaluates to FALSE will stop the loop.

例子 1. dir() example

$d = dir("/etc");
echo "Handle: ".$d->handle."<br>\n";
echo "Path: ".$d->path."<br>\n";
while (false !== ($entry = $d->read())) {
    echo $entry."<br>\n";
}
$d->close();

注: The order in which directory entries are returned by the read method is system-dependent.

注: This defines the internal class Directory, meaning that you will not be able to define your own classes with that name. For a full list of predefined classes in PHP, please see Predefined Classes.

后退 | 起点 | 前进
chroot | 上一级 | closedir


closedir

(PHP 3, PHP 4 )

closedir -- close directory handle

Description

void closedir ( resource dir_handle)

Closes the directory stream indicated by dir_handle. The stream must have previously been opened by opendir().

后退 | 起点 | 前进
dir | 上一级 | getcwd


getcwd

(PHP 4 )

getcwd -- gets the current working directory

Description

string getcwd ( void)

Returns the current working directory.

See also chdir().

后退 | 起点 | 前进
closedir | 上一级 | opendir


opendir

(PHP 3, PHP 4 )

opendir -- open directory handle

Description

resource opendir ( string path)

Returns a directory handle to be used in subsequent closedir(), readdir(), and rewinddir() calls.

If path is not a valid directory or the directory can not be opened due to permission restrictions or filesystem errors, opendir() returns FALSE and generates a PHP error. You can suppress the error output of opendir() by prepending `@' to the front of the function name.

例子 1. opendir() example

<?php

if ($dir = @opendir("/tmp")) {
  while (($file = readdir($dir)) !== false) {
    echo "$file\n";
  }
  closedir($dir);
}

?>

See also is_dir().

后退 | 起点 | 前进
getcwd | 上一级 | readdir


readdir

(PHP 3, PHP 4 )

readdir -- read entry from directory handle

Description

string readdir ( resource dir_handle)

Returns the filename of the next file from the directory. The filenames are returned in the order in which they are stored by the filesystem.

Please note the fashion in which readdir()'s return value is checked in the examples below. We are explicitly testing whether the return value is identical to (equal to and of the same type as--see Comparison Operators for more information) FALSE since otherwise, any directory entry whose name evaluates to FALSE will stop the loop (e.g. a directory named "0").

例子 1. List all files in a directory

// Note that !== did not exist until 4.0.0-RC2
<?php
if ($handle = opendir('/path/to/files')) {
    echo "Directory handle: $handle\n";
    echo "Files:\n";

    /* This is the correct way to loop over the directory. */
    while (false !== ($file = readdir($handle))) {
        echo "$file\n";
    }

    /* This is the WRONG way to loop over the directory. */
    while ($file = readdir($handle)) {
        echo "$file\n";
    }

    closedir($handle);
}
?>

Note that readdir() will return the . and .. entries. If you don't want these, simply strip them out:

例子 2. List all files in the current directory and strip out . and ..

<?php
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            echo "$file\n";
        }
    }
    closedir($handle);
}
?>

See also is_dir().

后退 | 起点 | 前进
opendir | 上一级 | rewinddir


rewinddir

(PHP 3, PHP 4 )

rewinddir -- rewind directory handle

Description

void rewinddir ( resource dir_handle)

Resets the directory stream indicated by dir_handle to the beginning of the directory.

后退 | 起点 | 前进
readdir | 上一级 | DOM XML functions


DOM XML functions

PHP 手册
后退 前进

XXV. DOM XML functions

介绍

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

The domxml extension has been overhauled in PHP 4.3.0 to provide a better compliance with the DOM standard. The extension still contains many old functions, but they should not be used anymore. Especially those non object oriented functions 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 the DomDocument_create_element(), DomDocument_create_text_node(), set_attribute(), etc. and finally DomDocument_dump_mem() functions.

需求

This extension make use of the GNOME xml library. Download and install this library. You will need at least libxml-2.4.14

安装

This extension is only available if PHP was configured with --with-dom=[DIR].

Deprecated functions

There are quite a few functions that do not fit into the DOM standard and should not be used anymore as listed in the following table. The function DomNode_append_child() has changed its behaviour. It now actually 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() und 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() und add it with DomNode_append_child().
DomNode_set_content | Create a new node with e.g. DomDocument_create_text_node() und 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 &nbsp;
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) |  |

Classes

The API of the module follows the DOM Level 2 standard as close 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 function are mainly to retain compatibilty to older versions of the extension but are not encouraged to use anymore in new developments.

This API differs from the official DOM API in two points. First, all class attributes are implemented as functions with the same name and 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_elemnent | 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() |

表格 9. Parser class

Method name | Function name | Remark
add_chunk | Parser_add_chunk() |
end | Parser_end() |

表格 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 any example it will be put into a file and be included by each example. This include file is shown in the following example section. You could also create an XML document read it with DomDocument_open_file().

例子 1. Include file example.inc with XML string

<?php
$xmlstr = "<?xml version='1.0' standalone='yes'?>
<!DOCTYPE chapter SYSTEM '/share/sgml/Norman_Walsh/db3xml10/db3xml10.dtd'
[ <!ENTITY sp \"spanish\">
]>
<!-- lsfj  -->
<chapter language='en'><title language='en'>Title</title>
 <para language='ge'>
  &amp;sp;
  <!-- comment -->
  <informaltable ID='findme' language='&amp;sp;'>
   <tgroup cols='3'>
    <tbody>
     <row><entry>a1</entry><entry
morerows='1'>b1</entry><entry>c1</entry></row>
<row><entry>a2</entry><entry>c2</entry></row>
     <row><entry>a3</entry><entry>b3</entry><entry>c3</entry></row>
    </tbody>
   </tgroup>
  </informaltable>
 </para>
</chapter>";
?>

目录
DomAttribute->name — Returns name of attribute
DomAttribute->specified — Checks if attribute is specified
DomAttribute->value — Returns value of attribute
DomDocument->add_root [deprecated] — Adds a root node
DomDocument->create_attribute — Create new attribute
DomDocument->create_cdata_section — Create new cdata node
DomDocument->create_comment — Create new comment node
DomDocument->create_element_ns — Create new element node with an associated namespace
DomDocument->create_element — Create new element node
DomDocument->create_entity_reference —
DomDocument->create_processing_instruction — Creates new PI node
DomDocument->create_text_node — Create new text node
DomDocument->doctype — Returns the document type
DomDocument->document_element — Returns root element node
DomDocument->dump_file — Dumps the internal XML tree back into a file
DomDocument->dump_mem — Dumps the internal XML tree back into a string
DomDocument->get_element_by_id — Searches for an element with a certain id
DomDocument->get_elements_by_tagname —
DomDocument->html_dump_mem — Dumps the internal XML tree back into a string as HTML
DomDocument->xinclude — Substitutes XIncludes in a DomDocument Object.
DomDocumentType->entities — Returns list of entities
DomDocumentType->internal_subset — Returns internal subset
DomDocumentType->name — Returns name of document type
DomDocumentType->notations — Returns list of notations
DomDocumentType->public_id — Returns public id of document type
DomDocumentType->system_id — Returns system id of document type
DomElement->get_attribute_node — Returns value of attribute
DomElement->get_attribute — Returns value of attribute
DomElement->get_elements_by_tagname — Adds new attribute
DomElement->has_attribute — Adds new attribute
DomElement->remove_attribute — Adds new attribute
DomElement->set_attribute — Adds new attribute
DomElement->tagname — Returns name of element
DomNode->add_namespace — Adds a namespace declaration to a node.
DomNode->append_child — Adds new child at the end of the children
DomNode->append_sibling — Adds new sibling to a node
DomNode->attributes — Returns list of attributes
DomNode->child_nodes — Returns children of node
DomNode->clone_node — Clones a node
DomNode->dump_node — Dumps a single node
DomNode->first_child — Returns first child of node
DomNode->get_content — Gets content of node
DomNode->has_attributess — Checks if node has attributes
DomNode->has_child_nodes — Checks if node has children
DomNode->insert_before — Inserts new node as child
DomNode->is_blank_node — Checks if node is blank
DomNode->last_child — Returns last child of node
DomNode->next_sibling — Returns the next sibling of node
DomNode->node_name — Returns name of node
DomNode->node_type — Returns type of node
DomNode->node_value — Returns value of a node
DomNode->owner_document — Returns the document this node belongs to
DomNode->parent_node — Returns the parent of the node
DomNode->prefix — Returns name space prefix of node
DomNode->previous_sibling — Returns the previous sibling of node
DomNode->remove_child — Removes child from list of children
DomNode->replace_child — Replaces a child
DomNode->replace_node — Replaces node
DomNode->set_content — Sets content of node
DomNode->set_name — Sets name of node
DomNode->set_namespace — Sets namespace of a node.
DomNode->unlink_node — Deletes node
DomProcessingInstruction->data — Returns data of pi node
DomProcessingInstruction->target — Returns target of pi node
DomXsltStylesheet->process — Applies the XSLT-Transformation on a DomDocument Object.
domxml_new_doc — Creates new empty XML document
domxml_open_file — Creates a DOM object from XML file
domxml_open_mem — Creates a DOM object of an XML document
domxml_version — Get XML library version
domxml_xmltree — Creates a tree of PHP objects from an XML document
domxml_xslt_stylesheet_doc — Creates a DomXsltStylesheet Object from a DomDocument Object.
domxml_xslt_stylesheet_file — Creates a DomXsltStylesheet Object from a xsl document in a file.
domxml_xslt_stylesheet — Creates a DomXsltStylesheet Object from a xml document in a string.
xpath_eval_expression — Evaluates the XPath Location Path in the given string
xpath_eval — Evaluates the XPath Location Path in the given string
xpath_new_context — Creates new xpath context
xptr_eval — Evaluate the XPtr Location Path in the given string
xptr_new_context — Create new XPath Context

后退 | 起点 | 前进
rewinddir | 上一级 | DomAttribute->name


DomAttribute->name

(no version information, might be only in CVS)

DomAttribute->name -- Returns name of attribute

Description

bool DomAttribute->name ( void)

This function returns the name of the attribute.

See also DomAttribute_value().

后退 | 起点 | 前进
DOM XML functions | 上一级 | DomAttribute->specified


DomAttribute->specified

(no version information, might be only in CVS)

DomAttribute->specified -- Checks if attribute is specified

Description

bool DomAttribute->specified ( void)

Check DOM standard for a detailed explanation.

后退 | 起点 | 前进
DomAttribute->name | 上一级 | DomAttribute->value


DomAttribute->value

(no version information, might be only in CVS)

DomAttribute->value -- Returns value of attribute

Description

bool DomAttribute->value ( void)

This function returns the value of the attribute.

See also DomAttribute_name().

后退 | 起点 | 前进
DomAttribute->specified | 上一级 | DomDocument->add_root [deprecated]


DomDocument->add_root [deprecated]

(no version information, might be only in CVS)

DomDocument->add_root [deprecated] -- Adds a root node

Description

resource DomDocument->add_root ( string name)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Adds a root element node to a dom document and returns the new node. The element name is given in the passed parameter.

例子 1. Creating a simple HTML document header

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->add_root("HTML");
$head = $root->new_child("HEAD", "");
$head->new_child("TITLE", "Hier der Titel");
echo htmlentities($doc->dump_mem());
?>

后退 | 起点 | 前进
DomAttribute->value | 上一级 | DomDocument->create_attribute


DomDocument->create_attribute

(no version information, might be only in CVS)

DomDocument->create_attribute -- Create new attribute

Description

object DomDocument->create_attribute ( string name, string value)

This function returns a new instance of class DomAttribute. The name of the attribute is the value of the first parameter. The value of the attribute is the value of the second parameter. This node will not show up in the document unless it is inserted with e.g. DomNode_append_child().

The return value is false if an error occured.

See also DomNode_append_child(),
         DomDocument_create_element(),
         DomDocument_create_text(),
         DomDocument_create_cdata_section(),
         DomDocument_create_processing_instruction(),
         DomDocument_create_entity_reference(),
         DomNode_insert_before().

后退 | 起点 | 前进
DomDocument->add_root [deprecated] | 上一级 | DomDocument->create_cdata_section


DomDocument->create_cdata_section

(no version information, might be only in CVS)

DomDocument->create_cdata_section -- Create new cdata node

Description

string DomDocument->create_cdata_section ( string content)

This function returns a new instance of class DomCData. The content of the cdata is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. DomNode_append_child().

The return value is false if an error occured.

See also DomNode_append_child(),
         DomDocument_create_element(),
         DomDocument_create_text(),
         DomDocument_create_attribute(),
         DomDocument_create_processing_instruction(),
         DomDocument_create_entity_reference(),
         DomNode_insert_before().

后退 | 起点 | 前进
DomDocument->create_attribute | 上一级 | DomDocument->create_comment


DomDocument->create_comment

(no version information, might be only in CVS)

DomDocument->create_comment -- Create new comment node

Description

object DomDocument->create_comment ( string content)

This function returns a new instance of class DomComment. The content of the comment is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. DomNode_append_child().

The return value is false if an error occured.

See also DomNode_append_child(),
         DomDocument_create_element(),
         DomDocument_create_text(),
         DomDocument_create_attribute(),
         DomDocument_create_processing_instruction(),
         DomDocument_create_entity_reference(),
         DomNode_insert_before().

后退 | 起点 | 前进
DomDocument->create_cdata_section | 上一级 | DomDocument->create_element_ns


DomDocument->create_element_ns

(no version information, might be only in CVS)

DomDocument->create_element_ns -- Create new element node with an associated namespace

Description

object DomDocument->create_element_ns ( string uri, string name [, string prefix])

This function returns a new instance of class DomElement. The tag name of the element is the value of the passed parameter name. The URI of the namespace is the value of the passed parameter uri. If there is already a namespace declaration with the same uri in the root-node of the document, the prefix of this is taken, otherwise it will take the one provided in the optional parameter prefix or generate a random one. This node will not show up in the document unless it is inserted with e.g. DomNode_append_child().

The return value is false if an error occured.

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(),
         DomNode_insert_before().

后退 | 起点 | 前进
DomDocument->create_comment | 上一级 | DomDocument->create_element


DomDocument->create_element

(no version information, might be only in CVS)

DomDocument->create_element -- Create new element node

Description

object DomDocument->create_element ( string name)

This function returns a new instance of class DomElement. The tag name of the element is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. DomNode_append_child().

The return value is false if an error occured.

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(),
         DomNode_insert_before().

后退 | 起点 | 前进
DomDocument->create_element_ns | 上一级 | DomDocument->create_entity_reference


DomDocument->create_entity_reference

(no version information, might be only in CVS)

DomDocument->create_entity_reference --

Description

object DomDocument->create_entity_reference ( string content)

This function returns a new instance of class DomEntityReference. The content of the entity reference is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. DomNode_append_child().

The return value is false if an error occured.

See also DomNode_append_child(),
         DomDocument_create_element(),
         DomDocument_create_text(),
         DomDocument_create_cdata_section(),
         DomDocument_create_processing_instruction(),
         DomDocument_create_attribute(),
         DomNode_insert_before().

后退 | 起点 | 前进
DomDocument->create_element | 上一级 | DomDocument->create_processing_instruction


DomDocument->create_processing_instruction

(no version information, might be only in CVS)

DomDocument->create_processing_instruction -- Creates new PI node

Description

string DomDocument->create_processing_instruction ( string content)

This function returns a new instance of class DomCData. The content of the pi is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. DomNode_append_child().

The return value is false if an error occured.

See also DomNode_append_child(),
         DomDocument_create_element(),
         DomDocument_create_text(),
         DomDocument_create_cdata_section(),
         DomDocument_create_attribute(),
         DomDocument_create_entity_reference(),
         DomNode_insert_before().

后退 | 起点 | 前进
DomDocument->create_entity_reference | 上一级 | DomDocument->create_text_node


DomDocument->create_text_node

(no version information, might be only in CVS)

DomDocument->create_text_node -- Create new text node

Description

object DomDocument->create_text_node ( string content)

This function returns a new instance of class DomText. The content of the text is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. DomNode_append_child().

The return value is false if an error occured.

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(),
         DomNode_insert_before().

后退 | 起点 | 前进
DomDocument->create_processing_instruction | 上一级 | DomDocument->doctype


DomDocument->doctype

(no version information, might be only in CVS)

DomDocument->doctype -- Returns the document type

Description

object DomDocument->doctype ( void)

This function returns an object of class DomDocumentType. In versions of PHP before 4.3 this has been the class Dtd, but the DOM Standard does not know such a class.

See also the methods of class DomDocumentType.

后退 | 起点 | 前进
DomDocument->create_text_node | 上一级 | DomDocument->document_element


DomDocument->document_element

(no version information, might be only in CVS)

DomDocument->document_element -- Returns root element node

Description

object DomDocument->document_element ( void)

This function returns the root element node of a document.

The following example returns just the element with name CHAPTER and prints it. The other node -- the comment -- is not returned.

例子 1. Retrieving root element

<?php
include("example.inc");

if(!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();
print_r($root);
?>

后退 | 起点 | 前进
DomDocument->doctype | 上一级 | DomDocument->dump_file


DomDocument->dump_file

(no version information, might be only in CVS)

DomDocument->dump_file -- Dumps the internal XML tree back into a file

Description

string DomDocument->dump_file ( string filename [, bool compressionmode [, bool format]])

Creates an XML document from the dom representation. This function usually is called after building a new dom document from scratch as in the example below. The format specifies whether the output should be neatly formatted, or not. The first parameter specifies the name of the filename and the second parameter, whether it should be compressed or not.

例子 1. Creating a simple HTML document header

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->create_element("HTML");
$root = $doc->append_child($root);
$head = $doc->create_element("HEAD");
$head = $root->append_child($head);
$title = $doc->create_element("TITLE");
$title = $head->append_child($title);
$text = $doc->create_text_node("This is the title");
$text = $title->append_child($text);
$doc->dump_file("/tmp/test.xml", false, true);
?>

See also DomDocument_dump_mem() DomDocument_html_dump_mem().

后退 | 起点 | 前进
DomDocument->document_element | 上一级 | DomDocument->dump_mem


DomDocument->dump_mem

(no version information, might be only in CVS)

DomDocument->dump_mem -- Dumps the internal XML tree back into a string

Description

string DomDocument->dump_mem ( [bool format [, string encoding]])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Creates an XML document from the dom representation. This function usually is called after building a new dom document from scratch as in the example below. The format specifies whether the output should be neatly formatted, or not.

例子 1. Creating a simple HTML document header

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->create_element("HTML");
$root = $doc->append_child($root);
$head = $doc->create_element("HEAD");
$head = $root->append_child($head);
$title = $doc->create_element("TITLE");
$title = $head->append_child($title);
$text = $doc->create_text_node("This is the title");
$text = $title->append_child($text);
echo "<PRE>";
echo htmlentities($doc->dump_mem(true));
echo "</PRE>";
?>

注: The first parameter was added in PHP 4.3.0.

See also DomDocument_dump_file(), DomDocument_html_dump_mem().

后退 | 起点 | 前进
DomDocument->dump_file | 上一级 | DomDocument->get_element_by_id


DomDocument->get_element_by_id

(no version information, might be only in CVS)

DomDocument->get_element_by_id -- Searches for an element with a certain id

Description

object DomDocument->get_element_by_id ( string id)

This function is similar to DomDocument_get_elements_by_tagname() but searches for an element with a given id. According to the DOM standard this requires a DTD which defines the attribute ID to be of type ID, though the current implementation simply does an xpath search for "//*[@ID = '%s']". This does not comply to the DOM standard which requires to return null if it is not known which attribute is of type id. This behaviour is likely to be fixed, so do not rely on the current behaviour.

See also DomDocument_get_elements_by_tagname()

后退 | 起点 | 前进
DomDocument->dump_mem | 上一级 | DomDocument->get_elements_by_tagname


DomDocument->get_elements_by_tagname

(no version information, might be only in CVS)

DomDocument->get_elements_by_tagname --

Description

array DomDocument->get_elements_by_tagname ( string name)

See also DomDocument_add_root()

后退 | 起点 | 前进
DomDocument->get_element_by_id | 上一级 | DomDocument->html_dump_mem


DomDocument->html_dump_mem

(no version information, might be only in CVS)

DomDocument->html_dump_mem -- Dumps the internal XML tree back into a string as HTML

Description

string DomDocument->html_dump_mem ( void)

Creates an HTML document from the dom representation. This function usually is called after building a new dom document from scratch as in the example below.

例子 1. Creating a simple HTML document header

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->create_element("HTML");
$root = $doc->append_child($root);
$head = $doc->create_element("HEAD");
$head = $root->append_child($head);
$title = $doc->create_element("TITLE");
$title = $head->append_child($title);
$text = $doc->create_text_node("This is the title");
$text = $title->append_child($text);
echo "<PRE>";
echo htmlentities($doc->html_dump_mem());
echo "</PRE>";
?>

See also DomDocument_dump_file(), DomDocument_html_dump_mem().

后退 | 起点 | 前进
DomDocument->get_elements_by_tagname | 上一级 | DomDocument->xinclude


DomDocument->xinclude

(no version information, might be only in CVS)

DomDocument->xinclude -- Substitutes XIncludes in a DomDocument Object.

Description

int DomDocument->xinclude ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
DomDocument->html_dump_mem | 上一级 | DomDocumentType->entities


DomDocumentType->entities

(no version information, might be only in CVS)

DomDocumentType->entities -- Returns list of entities

Description

array DomDocumentType->entities ( void)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
DomDocument->xinclude | 上一级 | DomDocumentType->internal_subset


DomDocumentType->internal_subset

(no version information, might be only in CVS)

DomDocumentType->internal_subset -- Returns internal subset

Description

bool DomDocumentType->internal_subset ( void)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
DomDocumentType->entities | 上一级 | DomDocumentType->name


DomDocumentType->name

(no version information, might be only in CVS)

DomDocumentType->name -- Returns name of document type

Description

string DomDocumentType->name ( void)

This function returns the name of the document type.

后退 | 起点 | 前进
DomDocumentType->internal_subset | 上一级 | DomDocumentType->notations


DomDocumentType->notations

(no version information, might be only in CVS)

DomDocumentType->notations -- Returns list of notations

Description

array DomDocumentType->notations ( void)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
DomDocumentType->name | 上一级 | DomDocumentType->public_id


DomDocumentType->public_id

(no version information, might be only in CVS)

DomDocumentType->public_id -- Returns public id of document type

Description

string DomDocumentType->public_id ( void)

This function returns the public id of the document type.

The following example echos nothing.

例子 1. Retrieving the public id

<?php
include("example.inc");

if(!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$doctype = $dom->doctype();
echo $doctype->public_id();
?>

后退 | 起点 | 前进
DomDocumentType->notations | 上一级 | DomDocumentType->system_id


DomDocumentType->system_id

(no version information, might be only in CVS)

DomDocumentType->system_id -- Returns system id of document type

Description

string DomDocumentType->system_id ( void)

Returns the system id of the document type.

The following example echos '/share/sgml/Norman_Walsh/db3xml10/db3xml10.dtd'.

例子 1. Retrieving the system id

<?php
include("example.inc");

if(!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$doctype = $dom->doctype();
echo $doctype->system_id();
?>

后退 | 起点 | 前进
DomDocumentType->public_id | 上一级 | DomElement->get_attribute_node


DomElement->get_attribute_node

(no version information, might be only in CVS)

DomElement->get_attribute_node -- Returns value of attribute

Description

object DomElement->get_attribute_node ( object attr)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
DomDocumentType->system_id | 上一级 | DomElement->get_attribute


DomElement->get_attribute

(no version information, might be only in CVS)

DomElement->get_attribute -- Returns value of attribute

Description

object DomElement->get_attribute ( string name)

Returns the attribute with name name of the current node.

(PHP >= 4.3 only) If no attribute with given name is found, an empty string is returned.

See also DomElement_set_attribute()

后退 | 起点 | 前进
DomElement->get_attribute_node | 上一级 | DomElement->get_elements_by_tagname


DomElement->get_elements_by_tagname

(no version information, might be only in CVS)

DomElement->get_elements_by_tagname -- Adds new attribute

Description

bool DomElement->get_elements_by_tagname ( string name)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
DomElement->get_attribute | 上一级 | DomElement->has_attribute


DomElement->has_attribute

(no version information, might be only in CVS)

DomElement->has_attribute -- Adds new attribute

Description

bool DomElement->has_attribute ( string name)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
DomElement->get_elements_by_tagname | 上一级 | DomElement->remove_attribute


DomElement->remove_attribute

(no version information, might be only in CVS)

DomElement->remove_attribute -- Adds new attribute

Description

bool DomElement->remove_attribute ( string name)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
DomElement->has_attribute | 上一级 | DomElement->set_attribute


DomElement->set_attribute

(no version information, might be only in CVS)

DomElement->set_attribute -- Adds new attribute

Description

bool DomElement->set_attribute ( string name, string value)

Sets an attribute with name name ot the given value. If the attribute does not exist, it will be created.

例子 1. Setting an attribute

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$newnode = $doc->append_child($node);
$newnode->set_attribute("align", "left");
?>

See also DomElement_get_attribute()

后退 | 起点 | 前进
DomElement->remove_attribute | 上一级 | DomElement->tagname


DomElement->tagname

(no version information, might be only in CVS)

DomElement->tagname -- Returns name of element

Description

string DomElement->tagname ( void)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
DomElement->set_attribute | 上一级 | DomNode->add_namespace


DomNode->add_namespace

(no version information, might be only in CVS)

DomNode->add_namespace -- Adds a namespace declaration to a node.

Description

bool DomNode->add_namespace ( string uri, string prefix)

See also DomDocument_create_element_ns(), DomNode_set_namespace()

后退 | 起点 | 前进
DomElement->tagname | 上一级 | DomNode->append_child


DomNode->append_child

(no version information, might be only in CVS)

DomNode->append_child -- Adds new child at the end of the children

Description

object DomNode->append_child ( object newnode)

This functions appends a child to an existing list of children or creates a new list of children. The child can be created with e.g. DomDocument_create_element(), DomDocument_create_text() etc. or simply by using any other node.

(PHP < 4.3) Before a new child is appended 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 a 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.

(PHP >= 4.3) The new child newnode is first unlinked from its existing context, if it already existed in a document. Therefore the node is moved and not copies anymore. This is the behaviour according to the W3C specifications. If you want to duplicate large parts of a xml document, use DomNode->clone_node() before appending.

The following example will add a new element node to a fresh document and sets the attribute "align" to "left".

例子 1. Adding a child

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$newnode = $doc->append_child($node);
$newnode->set_attribute("align", "left");
?>
The above example could also be written as the following:

例子 2. Adding a child

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$node->set_attribute("align", "left");
$newnode = $doc->append_child($node);
?>
A more comples example is the one below. It first searches for a certain element, duplicates it including its children and adds it as a sibling. Finally a new attribute is added to one of the children of the new sibling and the whole document is dumped.

例子 3. Adding a child

<?php
include("example.inc");

if(!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("informaltable");
print_r($elements);
$element = $elements[0];

$parent = $element->parent_node();
$newnode = $parent->append_child($element);
$children = $newnode->children();
$attr = $children[1]->set_attribute("align", "left");

echo "<PRE>";
$xmlfile = $dom->dump_mem();
echo htmlentities($xmlfile);
echo "</PRE>";
?>
The above example could also be done with DomNode_insert_before() instead of DomNode_append_child().

See also DomNode_insert_before(), DomNode_clone_node().

后退 | 起点 | 前进
DomNode->add_namespace | 上一级 | DomNode->append_sibling


DomNode->append_sibling

(no version information, might be only in CVS)

DomNode->append_sibling -- Adds new sibling to a node

Description

object DomNode->append_sibling ( object newnode)

This functions appends a sibling to an existing node. The child can be created with e.g. DomDocument_create_element(), DomDocument_create_text() etc. or simply by using any other node.

Before a new sibling is added it is first duplicated. Therefore the new child is a completely new copy which can be modified without changing the node which was passed to this function. If the node passed has children itself, they will be duplicated as well, which makes it quite easy to duplicate large parts of a xml document. The return value is the added sibling. If you plan to do further modifications on the added sibling you must use the returned node.

This function has been added to provide the behaviour of DomNode_append_child() as it works till PHP 4.2.

See also DomNode_append_before().

后退 | 起点 | 前进
DomNode->append_child | 上一级 | DomNode->attributes


DomNode->attributes

(no version information, might be only in CVS)

DomNode->attributes -- Returns list of attributes

Description

array DomNode->attributes ( void)

This function only returns an array of attributes if the node is of type XML_ELEMENT_NODE.

(PHP >= 4.3 only) If no attributes are found, NULL is returned.

后退 | 起点 | 前进
DomNode->append_sibling | 上一级 | DomNode->child_nodes


DomNode->child_nodes

(no version information, might be only in CVS)

DomNode->child_nodes -- Returns children of node

Description

array DomNode->child_nodes ( void)

Returns all children of the node.

See also DomNode_next_sibling(), DomNode_previous_sibling().

后退 | 起点 | 前进
DomNode->attributes | 上一级 | DomNode->clone_node


DomNode->clone_node

(no version information, might be only in CVS)

DomNode->clone_node -- Clones a node

Description

object DomNode->clone_node ( void)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
DomNode->child_nodes | 上一级 | DomNode->dump_node


DomNode->dump_node

(no version information, might be only in CVS)

DomNode->dump_node -- Dumps a single node

Description

string DomNode->dump_node ( void)

警告

该文档目前尚无参考文档；仅参数列表可用。

See also DomDocument_dump_mem().

后退 | 起点 | 前进
DomNode->clone_node | 上一级 | DomNode->first_child


DomNode->first_child

(no version information, might be only in CVS)

DomNode->first_child -- Returns first child of node

Description

bool DomNode->first_child ( void)

Returns the first child of the node.

(PHP >= 4.3 only) If no first child is found, NULL is returned.

See also DomNode_last_child(),
         DomNode_next_sibling(),
         DomNode_previous_sibling().

后退 | 起点 | 前进
DomNode->dump_node | 上一级 | DomNode->get_content


DomNode->get_content

(no version information, might be only in CVS)

DomNode->get_content -- Gets content of node

Description

string DomNode->get_content ( void)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
DomNode->first_child | 上一级 | DomNode->has_attributess


DomNode->has_attributess

(no version information, might be only in CVS)

DomNode->has_attributess -- Checks if node has attributes

Description

bool DomNode->has_attributes ( void)

This function checks if the node has attributes.

See also DomNode_has_child_nodes().

后退 | 起点 | 前进
DomNode->get_content | 上一级 | DomNode->has_child_nodes


DomNode->has_child_nodes

(no version information, might be only in CVS)

DomNode->has_child_nodes -- Checks if node has children

Description

bool DomNode->has_child_nodes ( void)

This function checks if the node has children.

See also DomNode_child_nodes().

后退 | 起点 | 前进
DomNode->has_attributess | 上一级 | DomNode->insert_before


DomNode->insert_before

(no version information, might be only in CVS)

DomNode->insert_before -- Inserts new node as child

Description

object DomNode->insert_before ( object newnode, object refnode)

This function inserts the new node newnode right before the node refnode. The return value is the inserted node. If you plan to do further modifications on the appended child you must use the returned node.

(PHP >= 4.3 only) If newnode already is part of a document, it will be first unlinked from its existing context. If refnode is NULL, then newnode will be inserted at the end of the list of children.

DomNode_insert_before() is very similar to DomNode_append_child() as the following example shows which does the same as the example at DomNode_append_child().

例子 1. Adding a child

include("example.inc");

if(!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("informaltable");
print_r($elements);
$element = $elements[0];

$newnode = $element->insert_before($element, $element);
$children = $newnode->children();
$attr = $children[1]->set_attribute("align", "left");

echo "<PRE>";
$xmlfile = $dom->dump_mem();
echo htmlentities($xmlfile);
echo "</PRE>";

See also DomNode_append_child().

后退 | 起点 | 前进
DomNode->has_child_nodes | 上一级 | DomNode->is_blank_node


DomNode->is_blank_node

(no version information, might be only in CVS)

DomNode->is_blank_node -- Checks if node is blank

Description

bool DomNode->is_blank_node ( void)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
DomNode->insert_before | 上一级 | DomNode->last_child


DomNode->last_child

(no version information, might be only in CVS)

DomNode->last_child -- Returns last child of node

Description

object DomNode->last_child ( void)

Returns the last child of the node.

(PHP >= 4.3 only) If no last child is found, NULL is returned.

See also DomNode_first_child(),
         DomNode_next_sibling(),
         DomNode_previous_sibling().

后退 | 起点 | 前进
DomNode->is_blank_node | 上一级 | DomNode->next_sibling


DomNode->next_sibling

(no version information, might be only in CVS)

DomNode->next_sibling -- Returns the next sibling of node

Description

object DomNode->next_sibling ( void)

This function returns the next sibling of the current node. If there is no next sibling it returns false (< 4.3) or null (>= 4.3). You can use this function to iterate over all children of a node as shown in the example.

例子 1. Iterate over children

<?php
include("example.inc");

if(!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("tbody");
$element = $elements[0];
$child = $element->first_child();

while($child) {
   print_r($child);
   $child = $child->next_sibling();
}
?>

See also DomNode_previous_sibling().

后退 | 起点 | 前进
DomNode->last_child | 上一级 | DomNode->node_name


DomNode->node_name

(no version information, might be only in CVS)

DomNode->node_name -- Returns name of node

Description

string DomNode->node_name ( void)

Returns name of the node. The name has different meanings for the different types of nodes as illustrated in the following table.

表格 1. Meaning of value

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

后退 | 起点 | 前进
DomNode->next_sibling | 上一级 | DomNode->node_type


DomNode->node_type

(no version information, might be only in CVS)

DomNode->node_type -- Returns type of node

Description

int DomNode->node_type ( void)

Returns the type of the node. All possible types are listed in the table in the introduction.

后退 | 起点 | 前进
DomNode->node_name | 上一级 | DomNode->node_value


DomNode->node_value

(no version information, might be only in CVS)

DomNode->node_value -- Returns value of a node

Description

string DomNode->node_value ( void)

Returns value of the node. The value has different meanings for the different types of nodes as illustrated in the following table.

表格 1. Meaning of value

Type | Meaning
DomAttribute | value of attribute
DomAttribute |
DomCDataSection | content
DomComment | content of comment
DomDocument | null
DomDocumentType | null
DomElement | null
DomEntity | null
DomEntityReference | null
DomNotation | null
DomProcessingInstruction | entire content without target
DomText | content of text

后退 | 起点 | 前进
DomNode->node_type | 上一级 | DomNode->owner_document


DomNode->owner_document

(no version information, might be only in CVS)

DomNode->owner_document -- Returns the document this node belongs to

Description

object DomNode->owner_document ( void)

This function returns the document the current node belongs to.

The following example will create two identical lists of children.

例子 1. Finding the document of a node

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$node = $doc->append_child($node);
$children = $doc->children();
print_r($children);

$doc2 = $node->owner_document();
$children = $doc2->children();
print_r($children);
?>

See also DomNode_insert_before().

后退 | 起点 | 前进
DomNode->node_value | 上一级 | DomNode->parent_node


DomNode->parent_node

(no version information, might be only in CVS)

DomNode->parent_node -- Returns the parent of the node

Description

object DomNode->parent_node ( void)

This function returns the parent node.

(PHP >= 4.3 only) If no parent is found, NULL is returned.

The following example will show two identical lists of children.

例子 1. Finding the document of a node

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$node = $doc->append_child($node);
$children = $doc->children();
print_r($children);

$doc2 = $node->parent_node();
$children = $doc2->children();
print_r($children);
?>

后退 | 起点 | 前进
DomNode->owner_document | 上一级 | DomNode->prefix


DomNode->prefix

(no version information, might be only in CVS)

DomNode->prefix -- Returns name space prefix of node

Description

string DomNode->prefix ( void)

Returns the name space prefix of the node.

后退 | 起点 | 前进
DomNode->parent_node | 上一级 | DomNode->previous_sibling


DomNode->previous_sibling

(no version information, might be only in CVS)

DomNode->previous_sibling -- Returns the previous sibling of node

Description

object DomNode->previous_sibling ( void)

This function returns the previous sibling of the current node. If there is no previous sibling it returns false (< 4.3) or null (>= 4.3). You can use this function to iterate over all children of a node as shown in the example.

See also DomNode_next_sibling().

后退 | 起点 | 前进
DomNode->prefix | 上一级 | DomNode->remove_child


DomNode->remove_child

(no version information, might be only in CVS)

DomNode->remove_child -- Removes child from list of children

Description

object DomNode->remove_child ( object oldchild)

This functions removes a child from a list of children. If child cannot be removed or is not a child the function will return false. If the child could be removed the functions returns the old child.

例子 1. Removing a child

<?php
include("example.inc");

if(!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("tbody");
$element = $elements[0];
$children = $element->child_nodes();
$child = $element->remove_child($children[0]);

echo "<PRE>";
$xmlfile = $dom->dump_mem(true);
echo htmlentities($xmlfile);
echo "</PRE>";
?>

See also DomNode_append_child().

后退 | 起点 | 前进
DomNode->previous_sibling | 上一级 | DomNode->replace_child


DomNode->replace_child

(no version information, might be only in CVS)

DomNode->replace_child -- Replaces a child

Description

object DomNode->replace_child ( object oldnode, object newnode)

(PHP 4.2) This function replaces the child oldnode with the passed new node. If the new node is already a child it will not be added a second time. If the old node cannot be found the function returns false. If the replacement succeds 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 succeds the old node is returned. (This behaviour is according to the W3C specs).

See also DomNode_append_child()

后退 | 起点 | 前进
DomNode->remove_child | 上一级 | DomNode->replace_node


DomNode->replace_node

(no version information, might be only in CVS)

DomNode->replace_node -- Replaces node

Description

object DomNode->replace_node ( object newnode)

(PHP 4.2) This function replaces an existing node with the passed new node. Before the replacement newnode is copied if it has a parent to make sure a node which is already in the document will not be inserted a second time. This behaviour enforces doing all modifications on the node before the replacement or to refetch the inserted node afterwards with functions like DomNode_first_child(), DomNode_child_nodes() etc..

(PHP 4.3) This function replaces an existing node with the passed new node. It is not copied anymore. If newnode was already inserted in the document it is first unlinked from its existing context. If the replacement succeds the old node is returned.

See also DomNode_append_child()

后退 | 起点 | 前进
DomNode->replace_child | 上一级 | DomNode->set_content


DomNode->set_content

(no version information, might be only in CVS)

DomNode->set_content -- Sets content of node

Description

bool DomNode->set_content ( void)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
DomNode->replace_node | 上一级 | DomNode->set_name


DomNode->set_name

(no version information, might be only in CVS)

DomNode->set_name -- Sets name of node

Description

bool DomNode->set_name ( void)

Sets name of node.

See also DomNode_node_name().

后退 | 起点 | 前进
DomNode->set_content | 上一级 | DomNode->set_namespace


DomNode->set_namespace

(no version information, might be only in CVS)

DomNode->set_namespace -- Sets namespace of a node.

Description

void DomNode->set_namespace ( string uri [, string prefix])

Sets the namespace of a node to uri. If there is already a namespace declaration with the same uri in one of the parent nodes of the node, the prefix of this is taken, otherwise it will take the one provided in the optional parameter prefix or generate a random one.

See also DomDocument_create_element_ns(), DomNode_add_namespace()

后退 | 起点 | 前进
DomNode->set_name | 上一级 | DomNode->unlink_node


DomNode->unlink_node

(no version information, might be only in CVS)

DomNode->unlink_node -- Deletes node

Description

object DomNode->unlink_node ( void)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
DomNode->set_namespace | 上一级 | DomProcessingInstruction->data


DomProcessingInstruction->data

(no version information, might be only in CVS)

DomProcessingInstruction->data -- Returns data of pi node

Description

string DomProcessingInstruction->data ( void)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
DomNode->unlink_node | 上一级 | DomProcessingInstruction->target


DomProcessingInstruction->target

(no version information, might be only in CVS)

DomProcessingInstruction->target -- Returns target of pi node

Description

string DomProcessingInstruction->target ( void)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
DomProcessingInstruction->data | 上一级 | DomXsltStylesheet->process


DomXsltStylesheet->process

(no version information, might be only in CVS)

DomXsltStylesheet->process -- Applies the XSLT-Transformation on a DomDocument Object.

Description

object DomXsltStylesheet->process ( object DomDocument [, array xslt_parameters [, bool param_is_xpath]])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

See also domxml_xslt_stylesheet(), domxml_xslt_stylesheet_file(), domxml_xslt_stylesheet_doc()

后退 | 起点 | 前进
DomProcessingInstruction->target | 上一级 | domxml_new_doc


domxml_new_doc

(PHP 4 >= 4.2.1)

domxml_new_doc -- Creates new empty XML document

Description

object domxml_new_doc ( string version)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Creates a new dom document from scratch and returns it.

See also DomDocument_add_root()

后退 | 起点 | 前进
DomXsltStylesheet->process | 上一级 | domxml_open_file


domxml_open_file

(PHP 4 >= 4.2.1)

domxml_open_file -- Creates a DOM object from XML file

Description

object domxml_open_file ( string filename)

The function parses the XML document in the file named filename and returns an object of class "Dom document", having the properties as listed above. The file is accessed read-only.

例子 1. Opening a xml document from a file

<?php

if(!$dom = domxml_open_file("example.xml")) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();
?>

See also domxml_open_mem(), domxml_new_doc().

后退 | 起点 | 前进
domxml_new_doc | 上一级 | domxml_open_mem


domxml_open_mem

(PHP 4 >= 4.2.1)

domxml_open_mem -- Creates a DOM object of an XML document

Description

object domxml_open_mem ( string str)

The function parses the XML document in str and returns an object of class "Dom document", having the properties as listed above. This function, domxml_open_file() or domxml_new_doc() must be called before any other function calls.

例子 1. Opening a xml document in a string

<?php
include("example.inc");

if(!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();
?>

See also domxml_open_file(), domxml_new_doc().

后退 | 起点 | 前进
domxml_open_file | 上一级 | domxml_version


domxml_version

(PHP 4 >= 4.1.0)

domxml_version -- Get XML library version

Description

string domxml_version ( void)

This function returns the version of the XML library version currently used.

后退 | 起点 | 前进
domxml_open_mem | 上一级 | domxml_xmltree


domxml_xmltree

(PHP 4 >= 4.2.1)

domxml_xmltree -- Creates a tree of PHP objects from an XML document

Description

object domxml_xmltree ( string str)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

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.

后退 | 起点 | 前进
domxml_version | 上一级 | domxml_xslt_stylesheet_doc


domxml_xslt_stylesheet_doc

(PHP 4 >= 4.2.0)

domxml_xslt_stylesheet_doc -- Creates a DomXsltStylesheet Object from a DomDocument Object.

Description

object domxml_xslt_stylesheet_doc ( object DocDocument Object)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

See also DomXsltStylesheet->process(), domxml_xslt_stylesheet(), domxml_xslt_stylesheet_file()

后退 | 起点 | 前进
domxml_xmltree | 上一级 | domxml_xslt_stylesheet_file


domxml_xslt_stylesheet_file

(PHP 4 >= 4.2.0)

domxml_xslt_stylesheet_file -- Creates a DomXsltStylesheet Object from a xsl document in a file.

Description

object domxml_xslt_stylesheet_file ( string xsl file)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

See also DomXsltStylesheet->process(), domxml_xslt_stylesheet(), domxml_xslt_stylesheet_doc()

后退 | 起点 | 前进
domxml_xslt_stylesheet_doc | 上一级 | domxml_xslt_stylesheet


domxml_xslt_stylesheet

(PHP 4 >= 4.2.0)

domxml_xslt_stylesheet -- Creates a DomXsltStylesheet Object from a xml document in a string.

Description

object domxml_xslt_stylesheet ( string xsl document)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

See also DomXsltStylesheet->process(), domxml_xslt_stylesheet_file(), domxml_xslt_stylesheet_doc()

后退 | 起点 | 前进
domxml_xslt_stylesheet_file | 上一级 | xpath_eval_expression


xpath_eval_expression

(PHP 4 >= 4.0.4)

xpath_eval_expression -- Evaluates the XPath Location Path in the given string

Description

array xpath_eval_expression ( object xpath_context)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

See also xpath_eval()

后退 | 起点 | 前进
domxml_xslt_stylesheet | 上一级 | xpath_eval


xpath_eval

(PHP 4 >= 4.0.4)

xpath_eval -- Evaluates the XPath Location Path in the given string

Description

array xpath_eval ( object xpath context)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

See also xpath_new_context()

后退 | 起点 | 前进
xpath_eval_expression | 上一级 | xpath_new_context


xpath_new_context

(PHP 4 >= 4.0.4)

xpath_new_context -- Creates new xpath context

Description

object xpath_new_context ( object dom document)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

See also xpath_eval()

后退 | 起点 | 前进
xpath_eval | 上一级 | xptr_eval


xptr_eval

(PHP 4 >= 4.0.4)

xptr_eval -- Evaluate the XPtr Location Path in the given string

Description

int xptr_eval ( [object xpath_context, string eval_str])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
xpath_new_context | 上一级 | xptr_new_context


xptr_new_context

(PHP 4 >= 4.0.4)

xptr_new_context -- Create new XPath Context

Description

string xptr_new_context ( [object doc_handle])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
xptr_eval | 上一级 | .NET functions


.NET functions

PHP 手册
后退 前进

XXVI. .NET functions

介绍

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

目录
dotnet_load — Loads a DOTNET module

后退 | 起点 | 前进
xptr_new_context | 上一级 | dotnet_load


dotnet_load

(no version information, might be only in CVS)

dotnet_load -- Loads a DOTNET module

Description

int dotnet_load ( string assembly_name [, string datatype_name [, int codepage]])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
.NET functions | 上一级 | Error Handling and Logging Functions


Error Handling and Logging Functions

PHP 手册
后退 前进

XXVII. Error Handling and Logging Functions

介绍

These are functions dealing with error handling and logging. They allow you to define your own error handling rules, as well as modify the way the errors can be logged. This allows you to change and enhance error reporting to suit your needs.

With the logging functions, you can send messages directly to other machines, to an email (or email to pager gateway!), to system logs, etc., so you can selectively log and monitor the most important parts of your applications and websites.

The error reporting functions allow you to customize what level and kind of error feedback is given, ranging from simple notices to customized functions returned during errors.

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

这些函数作为 PHP 核心的一部分，无需被安装即可使用。

预定义常量

这里列出的所有常量将作为 PHP 核心的一部分一直有效。

注: 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.

表格 1. Errors and Logging

Value | Constant | Description
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.
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. PHP 4 only.
64 | E_COMPILE_ERROR (integer) | Fatal compile-time errors. This is like an E_ERROR, except it is generated by the Zend Scripting Engine. PHP 4 only.
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. PHP 4 only.
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(). PHP 4 only.
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(). PHP 4 only.
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(). PHP 4 only.
2047 | E_ALL (integer) | All errors and warnings, as supported.

相关参考

Fore more Information see the section Error Handling.

目录
error_log — send an error message somewhere
error_reporting — set which PHP errors are reported
restore_error_handler — Restores the previous error handler function
set_error_handler — Sets a user-defined error handler function.
trigger_error — Generates a user-level error/warning/notice message
user_error — Generates a user-level error/warning/notice message

后退 | 起点 | 前进
dotnet_load | 上一级 | error_log


error_log

(PHP 3, PHP 4 )

error_log -- send an error message somewhere

Description

int error_log ( string message [, int message_type [, string destination [, string extra_headers]]])

Sends an error message to the web server's error log, a TCP port or to a file. The first parameter, message, is the error message that should be logged. The second parameter, message_type says where the message should go:

表格 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.
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. This message type uses the same internal function as mail() does.
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.
3 | message is appended to the file destination.

警告

Remote debugging via TCP/IP is a PHP 3 feature that is not available in PHP 4.

例子 1. error_log() examples

// Send notification through the server log if we can not
// connect to the database.
if (!Ora_Logon ($username, $password)) {
    error_log ("Oracle database not available!", 0);
}

// Notify administrator by email if we run out of FOO
if (!($foo = allocate_new_foo()) {
    error_log ("Big trouble, we're all out of FOOs!", 1,
               "operator@mydomain.com");
}

// other ways of calling error_log():
error_log ("You messed up!", 2, "127.0.0.1:7000");
error_log ("You messed up!", 2, "loghost");
error_log ("You messed up!", 3, "/var/tmp/my-errors.log");

后退 | 起点 | 前进
Error Handling and Logging Functions | 上一级 | error_reporting


error_reporting

(PHP 3, PHP 4 )

error_reporting -- set which PHP errors are reported

Description

int error_reporting ( [int level])

The error_reporting() function sets the error_reporting directive at runtime. PHP has many levels of errors, using this function sets that level for the duration (runtime) of your script.

error_reporting() sets PHP's error reporting level, and returns the old level. The level parameter 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.

Some example uses:

例子 1. error_reporting() examples

<?php

// Turn off all error reporting
error_reporting(0);

// Report simple running errors
error_reporting  (E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting (E_ALL ^ E_NOTICE);

// Report all PHP errors (bitwise 63 may be used in PHP 3)
error_reporting (E_ALL);

// Same as error_reporting(E_ALL);
ini_set ('error_reporting', E_ALL);

?>

The available error level constants are listed below. The actual meanings of these error levels are described in the error handling section of the manual.

表格 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

See also the display_errors directive and ini_set().

后退 | 起点 | 前进
error_log | 上一级 | restore_error_handler


restore_error_handler

(PHP 4 >= 4.0.1)

restore_error_handler -- Restores the previous error handler function

Description

void restore_error_handler ( void)

Used after changing the error handler function using set_error_handler(), to revert to the previous error handler (which could be the built-in or a user defined function)

See also error_reporting(),
set_error_handler(),
trigger_error(), user_error()

后退 | 起点 | 前进
error_reporting | 上一级 | set_error_handler


set_error_handler

(PHP 4 >= 4.0.1)

set_error_handler -- Sets a user-defined error handler function.

Description

string set_error_handler ( string error_handler)

Sets a user function (error_handler) to handle errors in a script. Returns the previously defined error handler (if any), or FALSE on error. 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())

The user function needs to accept 2 parameters: the error code, and a string describing the error. From PHP 4.0.2, an additional 3 optional parameters are 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 following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR and E_COMPILE_WARNING.

The example below shows the handling of internal exceptions by triggering errors and handling them with a user defined function:

例子 1. Error handling with set_error_handler() and trigger_error()

<?php

// redefine the user error constants - PHP 4 only
define ("FATAL",E_USER_ERROR);
define ("ERROR",E_USER_WARNING);
define ("WARNING",E_USER_NOTICE);

// set the error reporting level for this script
error_reporting (FATAL | ERROR | WARNING);

// error handler function
function myErrorHandler ($errno, $errstr, $errfile, $errline) {
  switch ($errno) {
  case FATAL:
    echo "<b>FATAL</b> [$errno] $errstr<br>\n";
    echo "  Fatal error in line ".$errline." of file ".$errfile;
    echo ", PHP ".PHP_VERSION." (".PHP_OS.")<br>\n";
    echo "Aborting...<br>\n";
    exit(1);
    break;
  case ERROR:
    echo "<b>ERROR</b> [$errno] $errstr<br>\n";
    break;
  case WARNING:
    echo "<b>WARNING</b> [$errno] $errstr<br>\n";
    break;
    default:
    echo "Unkown error type: [$errno] $errstr<br>\n";
    break;
  }
}

// function to test the error handling
function scale_by_log ($vect, $scale) {
  if ( !is_numeric($scale) || $scale <= 0 )
    trigger_error("log(x) for x <= 0 is undefined, you used: scale = $scale",
      FATAL);
  if (!is_array($vect)) {
    trigger_error("Incorrect input vector, array of values expected", ERROR);
    return null;
  }
  for ($i=0; $i<count($vect); $i++) {
    if (!is_numeric($vect[$i]))
      trigger_error("Value at position $i is not a number, using 0 (zero)",
        WARNING);
    $temp[$i] = log($scale) * $vect[$i];
  }
  return $temp;
}

// set to the user defined error handler
$old_error_handler = set_error_handler("myErrorHandler");

// trigger some errors, first define a mixed array with a non-numeric item
echo "vector a\n";
$a = array(2,3,"foo",5.5,43.3,21.11);
print_r($a);

// now generate second array, generating a warning
echo "----\nvector b - a warning (b = log(PI) * a)\n";
$b = scale_by_log($a, M_PI);
print_r($b);

// this is trouble, we pass a string instead of an array
echo "----\nvector c - an error\n";
$c = scale_by_log("not array",2.3);
var_dump($c);

// this is a critical error, log of zero or negative number is undefined
echo "----\nvector d - fatal error\n";
$d = scale_by_log($a, -2.5);

?>
And when you run this sample script, the output will be

vector a
Array
(
    [0] => 2
    [1] => 3
    [2] => foo
    [3] => 5.5
    [4] => 43.3
    [5] => 21.11
)
----
vector b - a warning (b = log(PI) * a)
<b>WARNING</b> [1024] Value at position 2 is not a number, using 0 (zero)<br>
Array
(
    [0] => 2.2894597716988
    [1] => 3.4341896575482
    [2] => 0
    [3] => 6.2960143721717
    [4] => 49.566804057279
    [5] => 24.165247890281
)
----
vector c - an error
<b>ERROR</b> [512] Incorrect input vector, array of values expected<br>
NULL
----
vector d - fatal error
<b>FATAL</b> [256] log(x) for x <= 0 is undefined, you used: scale = -2.5<br>
  Fatal error in line 36 of file trigger_error.php, PHP 4.0.2 (Linux)<br>
Aborting...<br>

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.

注: 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.

See also error_reporting(),
restore_error_handler(),
trigger_error(), user_error()

后退 | 起点 | 前进
restore_error_handler | 上一级 | trigger_error


trigger_error

(PHP 4 >= 4.0.1)

trigger_error -- Generates a user-level error/warning/notice message

Description

void trigger_error ( string error_msg [, int error_type])

Used to trigger a user error condition, it can be used by in conjunction with the built-in error handler, or with a user defined function that has been set as the new error handler (set_error_handler()). It only works with the E_USER family of constants, and will default to E_USER_NOTICE.

This function is useful when you need to generate a particular response to an exception at runtime. For example:

if (assert ($divisor == 0))
   trigger_error ("Cannot divide by zero", E_USER_ERROR);

注: See set_error_handler() for a more extensive example.

See also error_reporting(),
set_error_handler(),
restore_error_handler(),
user_error()

后退 | 起点 | 前进
set_error_handler | 上一级 | user_error


user_error

(PHP 4 )

user_error -- Generates a user-level error/warning/notice message

Description

void user_error ( string error_msg [, int error_type])

This is an alias for the function trigger_error().

See also error_reporting(),
set_error_handler(),
restore_error_handler(), and
trigger_error()

后退 | 起点 | 前进
trigger_error | 上一级 | FrontBase Functions


FrontBase Functions

PHP 手册
后退 前进

XXVIII. FrontBase Functions

介绍

These functions allow you to access FrontBase database servers. More information about FrontBase can be found at http://www.frontbase.com/.

Documentation for FrontBase can be found at http://www.frontbase.com/cgi-bin/WebObjects/FrontBase.woa/wa/productsPage?currentPage=Documentation.

Frontbase support has been added to PHP 4.0.6.

需求

You must install the FrontBase database server or at least the fbsql client libraries to use this functions. You can get FrontBase from http://www.frontbase.com/.

安装

In order to have these functions available, you must compile PHP with fbsql support by using the --with-fbsql option. If you use this option without specifying the path to fbsql, PHP will search for the fbsql client libraries in the default installation location for the platform. Users who installed FrontBase in a non standard directory should always specify the path to fbsql: --with-fbsql=/path/to/fbsql. This will force PHP to use the client libraries installed by FrontBase, avoiding any conflicts.

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. FrontBase configuration options

Name | Default | Changeable
fbsql.allow_persistent | "1" | PHP_INI_SYSTEM
fbsql.generate_warnings | "0" | PHP_INI_SYSTEM
fbsql.autocommit | "1" | PHP_INI_SYSTEM
fbsql.max_persistent | "-1" | PHP_INI_SYSTEM
fbsql.max_links | "128" | PHP_INI_SYSTEM
fbsql.max_connections | "128" | PHP_INI_SYSTEM
fbsql.max_results | "128" | PHP_INI_SYSTEM
fbsql.batchSize | "1000" | PHP_INI_SYSTEM
fbsql.default_host | NULL | PHP_INI_SYSTEM
fbsql.default_user | "_SYSTEM" | PHP_INI_SYSTEM
fbsql.default_password | "" | PHP_INI_SYSTEM
fbsql.default_database | "" | PHP_INI_SYSTEM
fbsql.default_database_password | "" | PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().

资源类型

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

FBSQL_ASSOC (integer)

FBSQL_NUM (integer)

FBSQL_BOTH (integer)

FBSQL_LOCK_DEFERRED (integer)

FBSQL_LOCK_OPTIMISTIC (integer)

FBSQL_LOCK_PESSIMISTIC (integer)

FBSQL_ISO_READ_UNCOMMITTED (integer)

FBSQL_ISO_READ_COMMITTED (integer)

FBSQL_ISO_REPEATABLE_READ (integer)

FBSQL_ISO_SERIALIZABLE (integer)

FBSQL_ISO_VERSIONED (integer)

FBSQL_UNKNOWN (integer)

FBSQL_STOPPED (integer)

FBSQL_STARTING (integer)

FBSQL_RUNNING (integer)

FBSQL_STOPPING (integer)

FBSQL_NOEXEC (integer)

FBSQL_LOB_DIRECT (integer)

FBSQL_LOB_HANDLE (integer)

目录
fbsql_affected_rows — Get number of affected rows in previous FrontBase operation
fbsql_autocommit — Enable or disable autocommit
fbsql_change_user — Change logged in user of the active connection
fbsql_close — Close FrontBase connection
fbsql_commit — Commits a transaction to the database
fbsql_connect — Open a connection to a FrontBase Server
fbsql_create_blob — Create a BLOB
fbsql_create_clob — Create a CLOB
fbsql_create_db — Create a FrontBase database
fbsql_data_seek — Move internal result pointer
fbsql_database_password — Sets or retrieves the password for a FrontBase database
fbsql_database — Get or set the database name used with a connection
fbsql_db_query — Send a FrontBase query
fbsql_db_status — Get the status for a given database
fbsql_drop_db — Drop (delete) a FrontBase database
fbsql_errno — Returns the numerical value of the error message from previous FrontBase operation
fbsql_error — Returns the text of the error message from previous FrontBase operation
fbsql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
fbsql_fetch_assoc — Fetch a result row as an associative array
fbsql_fetch_field — Get column information from a result and return as an object
fbsql_fetch_lengths — Get the length of each output in a result
fbsql_fetch_object — Fetch a result row as an object
fbsql_fetch_row — Get a result row as an enumerated array
fbsql_field_flags — Get the flags associated with the specified field in a result
fbsql_field_len — Returns the length of the specified field
fbsql_field_name — Get the name of the specified field in a result
fbsql_field_seek — Set result pointer to a specified field offset
fbsql_field_table — Get name of the table the specified field is in
fbsql_field_type — Get the type of the specified field in a result
fbsql_free_result — Free result memory
fbsql_get_autostart_info — No description given yet
fbsql_hostname — Get or set the host name used with a connection
fbsql_insert_id — Get the id generated from the previous INSERT operation
fbsql_list_dbs — List databases available on a FrontBase server
fbsql_list_fields — List FrontBase result fields
fbsql_list_tables — List tables in a FrontBase database
fbsql_next_result — Move the internal result pointer to the next result
fbsql_num_fields — Get number of fields in result
fbsql_num_rows — Get number of rows in result
fbsql_password — Get or set the user password used with a connection
fbsql_pconnect — Open a persistent connection to a FrontBase Server
fbsql_query — Send a FrontBase query
fbsql_read_blob — Read a BLOB from the database
fbsql_read_clob — Read a CLOB from the database
fbsql_result — Get result data
fbsql_rollback — Rollback a transaction to the database
fbsql_select_db — Select a FrontBase database
fbsql_set_lob_mode — Set the LOB retrieve mode for a FrontBase result set
fbsql_set_transaction — Set the transaction locking and isolation
fbsql_start_db — Start a database on local or remote server
fbsql_stop_db — Stop a database on local or remote server
fbsql_tablename — Get table name of field
fbsql_username — Get or set the host user used with a connection
fbsql_warnings — Enable or disable FrontBase warnings

后退 | 起点 | 前进
user_error | 上一级 | fbsql_affected_rows


fbsql_affected_rows

(PHP 4 >= 4.0.6)

fbsql_affected_rows -- Get number of affected rows in previous FrontBase operation

Description

int fbsql_affected_rows ( [resource link_identifier])

fbsql_affected_rows() returns the number of rows affected by the last INSERT, UPDATE or DELETE query associated with link_identifier. If the link identifier isn't specified, the last link opened by fbsql_connect() is assumed.

注: If you are using transactions, you need to call fbsql_affected_rows() after your INSERT, UPDATE, or DELETE query, not after the commit.

If the last query was a DELETE query with no WHERE clause, all of the records will have been deleted from the table but this function will return zero.

注: When using UPDATE, FrontBase will not update columns where the new value is the same as the old value. This creates the possibility that fbsql_affected_rows() may not actually equal the number of rows matched, only the number of rows that were literally affected by the query.

If the last query failed, this function will return -1.

See also: fbsql_num_rows().

后退 | 起点 | 前进
FrontBase Functions | 上一级 | fbsql_autocommit


fbsql_autocommit

(PHP 4 >= 4.0.6)

fbsql_autocommit -- Enable or disable autocommit

Description

bool fbsql_autocommit ( resource link_identifier [, bool OnOff])

fbsql_autocommit() returns the current autocommit status. if the optional OnOff parameter is given the auto commit status will be changed. With OnOff set to TRUE each statement will be committed automatically, if no errors was found. With OnOff set to FALSE the user must commit or rollback the transaction using either fbsql_commit() or fbsql_rollback().

See also: fbsql_commit() and fbsql_rollback()

后退 | 起点 | 前进
fbsql_affected_rows | 上一级 | fbsql_change_user


fbsql_change_user

(no version information, might be only in CVS)

fbsql_change_user -- Change logged in user of the active connection

Description

resource fbsql_change_user ( string user, string password [, string database [, resource link_identifier]])

fbsql_change_user() changes the logged in user of the current active connection, or the connection given by the optional parameter link_identifier. If a database is specified, this will default or current database after the user has been changed. If the new user and password authorization fails, the current connected user stays active.

后退 | 起点 | 前进
fbsql_autocommit | 上一级 | fbsql_close


fbsql_close

(PHP 4 >= 4.0.6)

fbsql_close -- Close FrontBase connection

Description

boolean fbsql_close ( [resource link_identifier])

Returns: TRUE on success, FALSE on error.

fbsql_close() closes the connection to the FrontBase server that's associated with the specified link identifier. If link_identifier isn't specified, the last opened link is used.

Using fbsql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

例子 1. fbsql_close() example

<?php
    $link = fbsql_connect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    print ("Connected successfully");
    fbsql_close ($link);
?>

See also: fbsql_connect() and fbsql_pconnect().

后退 | 起点 | 前进
fbsql_change_user | 上一级 | fbsql_commit


fbsql_commit

(PHP 4 >= 4.0.6)

fbsql_commit -- Commits a transaction to the database

Description

bool fbsql_commit ( [resource link_identifier])

如果成功则返回 TRUE，失败则返回 FALSE。

fbsql_commit() ends the current transaction by writing all inserts, updates and deletes to the disk and unlocking all row and table locks held by the transaction. This command is only needed if autocommit is set to false.

See also: fbsql_autocommit() and fbsql_rollback()

后退 | 起点 | 前进
fbsql_close | 上一级 | fbsql_connect


fbsql_connect

(PHP 4 >= 4.0.6)

fbsql_connect -- Open a connection to a FrontBase Server

Description

resource fbsql_connect ( [string hostname [, string username [, string password]]])

Returns a positive FrontBase link identifier on success, or an error message on failure.

fbsql_connect() establishes a connection to a
FrontBase server.  The following defaults are assumed for missing
optional parameters: hostname = 'NULL',
username = '_SYSTEM' and
password = empty password.

If a second call is made to fbsql_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 fbsql_close().

例子 1. fbsql_connect() example

<?php

    $link = fbsql_connect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    print ("Connected successfully");
    fbsql_close ($link);

?>

See also fbsql_pconnect() and fbsql_close().

后退 | 起点 | 前进
fbsql_commit | 上一级 | fbsql_create_blob


fbsql_create_blob

(PHP 4 >= 4.2.0)

fbsql_create_blob -- Create a BLOB

Description

string fbsql_create_blob ( string blob_data [, resource link_identifier])

Returns: A resource handle to the newly created blob.

fbsql_create_blob() creates a blob from blob_data. The returned resource handle can be used with insert and update commands to store the blob in the database.

例子 1. fbsql_create_blob() example

<?php
    $link = fbsql_pconnect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    $filename = "blobfile.bin";
    $fp = fopen($filename, "rb");
    $blobdata = fread($fp, filesize($filename));
    fclose($fp);

    $blobHandle = fbsql_create_blob($blobdata, $link);

    $sql = "INSERT INTO BLOB_TABLE (BLOB_COLUMN) VALUES ($blobHandle);";
    $rs = fbsql_query($sql, $link);
?>

See also: fbsql_create_clob(),
fbsql_read_blob(),
fbsql_read_clob(), and
fbsql_set_lob_mode().

后退 | 起点 | 前进
fbsql_connect | 上一级 | fbsql_create_clob


fbsql_create_clob

(PHP 4 >= 4.2.0)

fbsql_create_clob -- Create a CLOB

Description

string fbsql_create_clob ( string clob_data [, resource link_identifier])

Returns: A resource handle to the newly created CLOB.

fbsql_create_clob() creates a clob from clob_data. The returned resource handle can be used with insert and update commands to store the clob in the database.

例子 1. fbsql_create_clob() example

<?php
    $link = fbsql_pconnect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    $filename = "clob_file.txt";
    $fp = fopen($filename, "rb");
    $clobdata = fread($fp, filesize($filename));
    fclose($fp);

    $clobHandle = fbsql_create_clob($clobdata, $link);

    $sql = "INSERT INTO CLOB_TABLE (CLOB_COLUMN) VALUES ($clobHandle);";
    $rs = fbsql_query($sql, $link);
?>

See also: fbsql_create_blob(),
fbsql_read_blob(),
fbsql_read_clob(), and
fbsql_set_lob_mode().

后退 | 起点 | 前进
fbsql_create_blob | 上一级 | fbsql_create_db


fbsql_create_db

(PHP 4 >= 4.0.6)

fbsql_create_db -- Create a FrontBase database

Description

bool fbsql_create_db ( string database name [, resource link_identifier])

fbsql_create_db() attempts to create a new database on the server associated with the specified link identifier.

例子 1. fbsql_create_db() example

<?php
    $link = fbsql_pconnect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    if (fbsql_create_db ("my_db")) {
        print("Database created successfully\n");
    } else {
        printf("Error creating database: %s\n", fbsql_error ());
    }
?>

See also: fbsql_drop_db().

后退 | 起点 | 前进
fbsql_create_clob | 上一级 | fbsql_data_seek


fbsql_data_seek

(PHP 4 >= 4.0.6)

fbsql_data_seek -- Move internal result pointer

Description

bool fbsql_data_seek ( resource result_identifier, int row_number)

如果成功则返回 TRUE，失败则返回 FALSE。

fbsql_data_seek() moves the internal row pointer of the FrontBase result associated with the specified result identifier to point to the specified row number. The next call to fbsql_fetch_row() would return that row.

Row_number starts at 0.

例子 1. fbsql_data_seek() example

<?php
    $link = fbsql_pconnect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");

    fbsql_select_db ("samp_db")
        or die ("Could not select database");

    $query = "SELECT last_name, first_name FROM friends;";
    $result = fbsql_query ($query)
        or die ("Query failed");

    # fetch rows in reverse order

    for ($i = fbsql_num_rows ($result) - 1; $i >=0; $i--) {
        if (!fbsql_data_seek ($result, $i)) {
            printf ("Cannot seek to row %d\n", $i);
            continue;
        }

        if(!($row = fbsql_fetch_object ($result)))
            continue;

        printf("%s %s<BR>\n", $row->last_name, $row->first_name);
    }

    fbsql_free_result ($result);
?>

后退 | 起点 | 前进
fbsql_create_db | 上一级 | fbsql_database_password


fbsql_database_password

(PHP 4 >= 4.0.6)

fbsql_database_password -- Sets or retrieves the password for a FrontBase database

Description

string fbsql_database_password ( resource link_identifier [, string database_password])

Returns: The database password associated with the link identifier.

fbsql_database_password() sets and retrieves the database password used by the connection. if a database is protected by a database password, the user must call this function before calling fbsql_select_db(). if the second optional parameter is given the function sets the database password for the specified link identifier. If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if fbsql_connect() was called, and use it.

This function does not change the database password in the database nor can it be used to retrive the database password for a database.

例子 1. fbsql_create_clob() example

<?php
    $link = fbsql_pconnect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    fbsql_database_password($link, "secret db password");
    fbsql_select_db($database, $link);
?>

See also: fbsql_connect(),
fbsql_pconnect() and
fbsql_select_db().

后退 | 起点 | 前进
fbsql_data_seek | 上一级 | fbsql_database


fbsql_database

(PHP 4 >= 4.0.6)

fbsql_database -- Get or set the database name used with a connection

Description

string fbsql_database ( resource link_identifier [, string database])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
fbsql_database_password | 上一级 | fbsql_db_query


fbsql_db_query

(PHP 4 >= 4.0.6)

fbsql_db_query -- Send a FrontBase query

Description

resource fbsql_db_query ( string database, string query [, resource link_identifier])

Returns: A positive FrontBase result identifier to the query result, or FALSE on error.

fbsql_db_query() selects a database and executes a query on it. If the optional link identifier isn't specified, the function will try to find an open link to the FrontBase server and if no such link is found it'll try to create one as if fbsql_connect() was called with no arguments

See also fbsql_connect().

后退 | 起点 | 前进
fbsql_database | 上一级 | fbsql_db_status


fbsql_db_status

(PHP 4 >= 4.1.0)

fbsql_db_status -- Get the status for a given database

Description

int fbsql_db_status ( string database_name [, resource link_identifier])

Returns: An integer value with the current status.

fbsql_db_status() requests the current status of the database specified by database_name. If the link_identifier is omitted the default link_identifier will be used.

The return value can be one of the following constants:

  • FALSE - The exec handler for the host was invalid. This error will occur when the link_identifier connects directly to a database by using a port number. FBExec can be available on the server but no connection has been made for it.

  • FBSQL_UNKNOWN - The Status is unknown.

  • FBSQL_STOPPED - The database is not running. Use fbsql_start_db() to start the database.

  • FBSQL_STARTING - The database is starting.

  • FBSQL_RUNNING - The database is running and can be used to perform SQL operations.

  • FBSQL_STOPPING - The database is stopping.

  • FBSQL_NOEXEC - FBExec is not running on the server and it is not possible to get the status of the database.

See also: fbsql_start_db() and fbsql_stop_db().

后退 | 起点 | 前进
fbsql_db_query | 上一级 | fbsql_drop_db


fbsql_drop_db

(PHP 4 >= 4.0.6)

fbsql_drop_db -- Drop (delete) a FrontBase database

Description

bool fbsql_drop_db ( string database_name [, resource link_identifier])

如果成功则返回 TRUE，失败则返回 FALSE。

fbsql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier.

后退 | 起点 | 前进
fbsql_db_status | 上一级 | fbsql_errno


fbsql_errno

(PHP 4 >= 4.0.6)

fbsql_errno -- Returns the numerical value of the error message from previous FrontBase operation

Description

int fbsql_errno ( [resource link_identifier])

Returns the error number from the last fbsql function, or 0 (zero) if no error occurred.

Errors coming back from the fbsql database backend don't issue warnings. Instead, use fbsql_errno() to retrieve the error code. Note that this function only returns the error code from the most recently executed fbsql function (not including fbsql_error() and fbsql_errno()), so if you want to use it, make sure you check the value before calling another fbsql function.

<?php
fbsql_connect("marliesle");
echo fbsql_errno().": ".fbsql_error()."<BR>";
fbsql_select_db("nonexistentdb");
echo fbsql_errno().": ".fbsql_error()."<BR>";
$conn = fbsql_query("SELECT * FROM nonexistenttable;");
echo fbsql_errno().": ".fbsql_error()."<BR>";
?>

See also: fbsql_error() and fbsql_warnings().

后退 | 起点 | 前进
fbsql_drop_db | 上一级 | fbsql_error


fbsql_error

(PHP 4 >= 4.0.6)

fbsql_error -- Returns the text of the error message from previous FrontBase operation

Description

string fbsql_error ( [resource link_identifier])

Returns the error text from the last fbsql function, or '' (the empty string) if no error occurred.

Errors coming back from the fbsql database backend don't issue warnings. Instead, use fbsql_error() to retrieve the error text. Note that this function only returns the error text from the most recently executed fbsql function (not including fbsql_error() and fbsql_errno()), so if you want to use it, make sure you check the value before calling another fbsql function.

<?php
fbsql_connect("marliesle");
echo fbsql_errno().": ".fbsql_error()."<BR>";
fbsql_select_db("nonexistentdb");
echo fbsql_errno().": ".fbsql_error()."<BR>";
$conn = fbsql_query("SELECT * FROM nonexistenttable;");
echo fbsql_errno().": ".fbsql_error()."<BR>";
?>

See also: fbsql_errno() and fbsql_warnings().

后退 | 起点 | 前进
fbsql_errno | 上一级 | fbsql_fetch_array


fbsql_fetch_array

(PHP 4 >= 4.0.6)

fbsql_fetch_array -- Fetch a result row as an associative array, a numeric array, or both

Description

array fbsql_fetch_array ( resource result [, int result_type])

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

fbsql_fetch_array() is an extended version of fbsql_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

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 must the numeric index of the column or make an alias for the column.

select t1.f1 as foo t2.f1 as bar from t1, t2

An important thing to note is that using fbsql_fetch_array() is NOT significantly slower than using fbsql_fetch_row(), while it provides a significant added value.

The optional second argument result_type in fbsql_fetch_array() is a constant and can take the following values: FBSQL_ASSOC, FBSQL_NUM, and FBSQL_BOTH.

For further details, see also fbsql_fetch_row() and fbsql_fetch_assoc().

例子 1. fbsql_fetch_array() example

<?php
fbsql_connect ($host, $user, $password);
$result = fbsql_db_query ("database","select user_id, fullname from table");
while ($row = fbsql_fetch_array ($result)) {
    echo "user_id: ".$row["user_id"]."<br>\n";
    echo "user_id: ".$row[0]."<br>\n";
    echo "fullname: ".$row["fullname"]."<br>\n";
    echo "fullname: ".$row[1]."<br>\n";
}
fbsql_free_result ($result);
?>

后退 | 起点 | 前进
fbsql_error | 上一级 | fbsql_fetch_assoc


fbsql_fetch_assoc

(PHP 4 >= 4.0.6)

fbsql_fetch_assoc -- Fetch a result row as an associative array

Description

array fbsql_fetch_assoc ( resource result)

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.

fbsql_fetch_assoc() is equivalent to calling fbsql_fetch_array() with FBSQL_ASSOC for the optional second parameter. It only returns an associative array. This is the way fbsql_fetch_array() originally worked. If you need the numeric indices as well as the associative, use fbsql_fetch_array().

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 must use fbsql_fetch_array() and have it return the numeric indices as well.

An important thing to note is that using fbsql_fetch_assoc() is NOT significantly slower than using fbsql_fetch_row(), while it provides a significant added value.

For further details, see also fbsql_fetch_row() and fbsql_fetch_array().

例子 1. fbsql_fetch_assoc() example

<?php
fbsql_connect ($host, $user, $password);
$result = fbsql_db_query ("database","select * from table");
while ($row = fbsql_fetch_assoc ($result)) {
    echo $row["user_id"];
    echo $row["fullname"];
}
fbsql_free_result ($result);
?>

后退 | 起点 | 前进
fbsql_fetch_array | 上一级 | fbsql_fetch_field


fbsql_fetch_field

(PHP 4 >= 4.0.6)

fbsql_fetch_field -- Get column information from a result and return as an object

Description

object fbsql_fetch_field ( resource result [, int field_offset])

Returns an object containing field information.

fbsql_fetch_field() can be used in order to obtain information about fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by fbsql_fetch_field() is retrieved.

The properties of the object are:

  • name - column name

  • table - name of the table the column belongs to

  • max_length - maximum length of the column

  • not_null - 1 if the column cannot be NULL

  • type - the type of the column

例子 1. fbsql_fetch_field() example

<?php
fbsql_connect ($host, $user, $password)
    or die ("Could not connect");
$result = fbsql_db_query ("database", "select * from table")
    or die ("Query failed");
# get column metadata
$i = 0;
while ($i < fbsql_num_fields ($result)) {
    echo "Information for column $i:<BR>\n";
    $meta = fbsql_fetch_field ($result);
    if (!$meta) {
        echo "No information available<BR>\n";
    }
    echo "<PRE>
max_length:   $meta->max_length
name:         $meta->name
not_null:     $meta->not_null
table:        $meta->table
type:         $meta->type
</PRE>";
    $i++;
}
fbsql_free_result ($result);
?>

See also fbsql_field_seek().

后退 | 起点 | 前进
fbsql_fetch_assoc | 上一级 | fbsql_fetch_lengths


fbsql_fetch_lengths

(PHP 4 >= 4.0.6)

fbsql_fetch_lengths -- Get the length of each output in a result

Description

array fbsql_fetch_lengths ( [resource result])

Returns: An array that corresponds to the lengths of each field in the last row fetched by fbsql_fetch_row(), or FALSE on error.

fbsql_fetch_lengths() stores the lengths of
each result column in the last row returned by
fbsql_fetch_row(),
fbsql_fetch_array() and
fbsql_fetch_object() in an array, starting at
offset 0.

See also: fbsql_fetch_row().

后退 | 起点 | 前进
fbsql_fetch_field | 上一级 | fbsql_fetch_object


fbsql_fetch_object

(PHP 4 >= 4.0.6)

fbsql_fetch_object -- Fetch a result row as an object

Description

object fbsql_fetch_object ( resource result [, int result_type])

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

fbsql_fetch_object() is similar to fbsql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

The optional argument result_type is a constant and can take the following values: FBSQL_ASSOC, FBSQL_NUM, and FBSQL_BOTH.

Speed-wise, the function is identical to fbsql_fetch_array(), and almost as quick as fbsql_fetch_row() (the difference is insignificant).

例子 1. fbsql_fetch_object() example

<?php
fbsql_connect ($host, $user, $password);
$result = fbsql_db_query ("database", "select * from table");
while ($row = fbsql_fetch_object ($result)) {
    echo $row->user_id;
    echo $row->fullname;
}
fbsql_free_result ($result);
?>

See also: fbsql_fetch_array() and fbsql_fetch_row().

后退 | 起点 | 前进
fbsql_fetch_lengths | 上一级 | fbsql_fetch_row


fbsql_fetch_row

(PHP 4 >= 4.0.6)

fbsql_fetch_row -- Get a result row as an enumerated array

Description

array fbsql_fetch_row ( resource result)

Returns: An array that corresponds to the fetched row, or FALSE if there are no more rows.

fbsql_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 call to fbsql_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

See also: fbsql_fetch_array(),
fbsql_fetch_object(),
fbsql_data_seek(),
fbsql_fetch_lengths(), and
fbsql_result().

后退 | 起点 | 前进
fbsql_fetch_object | 上一级 | fbsql_field_flags


fbsql_field_flags

(PHP 4 >= 4.0.6)

fbsql_field_flags -- Get the flags associated with the specified field in a result

Description

string fbsql_field_flags ( resource result, int field_offset)

fbsql_field_flags() returns the field flags of the specified field. The flags are reported as a single word per flag separated by a single space, so that you can split the returned value using explode().

后退 | 起点 | 前进
fbsql_fetch_row | 上一级 | fbsql_field_len


fbsql_field_len

(PHP 4 >= 4.0.6)

fbsql_field_len -- Returns the length of the specified field

Description

int fbsql_field_len ( resource result, int field_offset)

fbsql_field_len() returns the length of the specified field.

后退 | 起点 | 前进
fbsql_field_flags | 上一级 | fbsql_field_name


fbsql_field_name

(PHP 4 >= 4.0.6)

fbsql_field_name -- Get the name of the specified field in a result

Description

string fbsql_field_name ( resource result, int field_index)

fbsql_field_name() returns the name of the specified field index. result must be a valid result identifier and field_index is the numerical offset of the field.

注: field_index starts at 0.

e.g. The index of the third field would actually be 2, the index of the fourth field would be 3 and so on.

例子 1. fbsql_field_name() example

// The users table consists of three fields:
//   user_id
//   username
//   password.

$res = fbsql_db_query("users", "select * from users", $link);

echo fbsql_field_name($res, 0) . "\n";
echo fbsql_field_name($res, 2);

The above example would produce the following output:

user_id
password

后退 | 起点 | 前进
fbsql_field_len | 上一级 | fbsql_field_seek


fbsql_field_seek

(PHP 4 >= 4.0.6)

fbsql_field_seek -- Set result pointer to a specified field offset

Description

bool fbsql_field_seek ( resource result, int field_offset)

Seeks to the specified field offset. If the next call to fbsql_fetch_field() doesn't include a field offset, the field offset specified in fbsql_field_seek() will be returned.

See also: fbsql_fetch_field().

后退 | 起点 | 前进
fbsql_field_name | 上一级 | fbsql_field_table


fbsql_field_table

(PHP 4 >= 4.0.6)

fbsql_field_table -- Get name of the table the specified field is in

Description

string fbsql_field_table ( resource result, int field_offset)

Returns the name of the table that the specified field is in.

后退 | 起点 | 前进
fbsql_field_seek | 上一级 | fbsql_field_type


fbsql_field_type

(PHP 4 >= 4.0.6)

fbsql_field_type -- Get the type of the specified field in a result

Description

string fbsql_field_type ( resource result, int field_offset)

fbsql_field_type() is similar to the fbsql_field_name() function. The arguments are identical, but the field type is returned instead. The field type will be one of "int", "real", "string", "blob", and others as detailed in the FrontBase documentation.

例子 1. fbsql_field_type() example

<?php

fbsql_connect ("localhost", "_SYSTEM", "");
fbsql_select_db ("wisconsin");
$result = fbsql_query ("SELECT * FROM onek;");
$fields = fbsql_num_fields ($result);
$rows   = fbsql_num_rows ($result);
$i = 0;
$table = fbsql_field_table ($result, $i);
echo "Your '".$table."' table has ".$fields." fields and ".$rows." records <BR>";
echo "The table has the following fields <BR>";
while ($i < $fields) {
    $type  = fbsql_field_type  ($result, $i);
    $name  = fbsql_field_name  ($result, $i);
    $len   = fbsql_field_len   ($result, $i);
    $flags = fbsql_field_flags ($result, $i);
    echo $type." ".$name." ".$len." ".$flags."<BR>";
    $i++;
}
fbsql_close();

?>

后退 | 起点 | 前进
fbsql_field_table | 上一级 | fbsql_free_result


fbsql_free_result

(PHP 4 >= 4.0.6)

fbsql_free_result -- Free result memory

Description

bool fbsql_free_result ( resource result)

fbsql_free_result() will free all memory associated with the result identifier result.

fbsql_free_result() only needs to be called if you are concerned about how much memory is being used for queries that return large result sets. All associated result memory is automatically freed at the end of the script's execution.

后退 | 起点 | 前进
fbsql_field_type | 上一级 | fbsql_get_autostart_info


fbsql_get_autostart_info

(PHP 4 >= 4.1.0)

fbsql_get_autostart_info -- No description given yet

Description

array fbsql_get_autostart_info ( [resource link_identifier])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
fbsql_free_result | 上一级 | fbsql_hostname


fbsql_hostname

(PHP 4 >= 4.0.6)

fbsql_hostname -- Get or set the host name used with a connection

Description

string fbsql_hostname ( resource link_identifier [, string host_name])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
fbsql_get_autostart_info | 上一级 | fbsql_insert_id


fbsql_insert_id

(PHP 4 >= 4.0.6)

fbsql_insert_id -- Get the id generated from the previous INSERT operation

Description

int fbsql_insert_id ( [resource link_identifier])

fbsql_insert_id() returns the ID generated for an column defined as DEFAULT UNIQUE by the previous INSERT query using the given link_identifier. If link_identifier isn't specified, the last opened link is assumed.

fbsql_insert_id() returns 0 if the previous query does not generate an DEFAULT UNIQUE value. If you need to save the value for later, be sure to call fbsql_insert_id() immediately after the query that generates the value.

注: The value of the FrontBase SQL function LAST_INSERT_ID() always contains the most recently generated DEFAULT UNIQUE value, and is not reset between queries.

后退 | 起点 | 前进
fbsql_hostname | 上一级 | fbsql_list_dbs


fbsql_list_dbs

(PHP 4 >= 4.0.6)

fbsql_list_dbs -- List databases available on a FrontBase server

Description

resource fbsql_list_dbs ( [resource link_identifier])

fbsql_list_dbs() will return a result pointer containing the databases available from the current fbsql daemon. Use the fbsql_tablename() function to traverse this result pointer.

例子 1. fbsql_list_dbs() example

$link = fbsql_connect('localhost', 'myname', 'secret');
$db_list = fbsql_list_dbs($link);

while ($row = fbsql_fetch_object($db_list)) {
    echo $row->Database . "\n";
}

The above example would produce the following output:

database1
database2
database3
...

注: The above code would just as easily work with fbsql_fetch_row() or other similar functions.

后退 | 起点 | 前进
fbsql_insert_id | 上一级 | fbsql_list_fields


fbsql_list_fields

(PHP 4 >= 4.0.6)

fbsql_list_fields -- List FrontBase result fields

Description

resource fbsql_list_fields ( string database_name, string table_name [, resource link_identifier])

fbsql_list_fields() retrieves information
about the given tablename. Arguments are the database name and
the table name. A result pointer is returned which can be used
with fbsql_field_flags(),
fbsql_field_len(),
fbsql_field_name(), and
fbsql_field_type().

A result identifier is a positive integer. The function returns -1 if a error occurs. A string describing the error will be placed in $phperrmsg, and unless the function was called as @fbsql() then this error string will also be printed out.

例子 1. fbsql_list_fields() example

$link = fbsql_connect('localhost', 'myname', 'secret');

$fields = fbsql_list_fields("database1", "table1", $link);
$columns = fbsql_num_fields($fields);

for ($i = 0; $i < $columns; $i++) {
    echo fbsql_field_name($fields, $i) . "\n";;
}

The above example would produce the following output:

field1
field2
field3
...

后退 | 起点 | 前进
fbsql_list_dbs | 上一级 | fbsql_list_tables


fbsql_list_tables

(PHP 4 >= 4.0.6)

fbsql_list_tables -- List tables in a FrontBase database

Description

resource fbsql_list_tables ( string database [, resource link_identifier])

fbsql_list_tables() takes a database name and returns a result pointer much like the fbsql_db_query() function. The fbsql_tablename() function should be used to extract the actual table names from the result pointer.

后退 | 起点 | 前进
fbsql_list_fields | 上一级 | fbsql_next_result


fbsql_next_result

(PHP 4 >= 4.0.6)

fbsql_next_result -- Move the internal result pointer to the next result

Description

bool fbsql_next_result ( resource result_id)

When sending more than one SQL statement to the server or executing a stored procedure with multiple results will cause the server to return multiple result sets. This function will test for additional results available form the server. If an additional result set exists it will free the existing result set and prepare to fetch the words from the new result set. The function will return TRUE if an additional result set was available or FALSE otherwise.

例子 1. fbsql_next_result() example

<?php
    $link = fbsql_connect ("localhost", "_SYSTEM", "secret");
    fbsql_select_db("MyDB", $link);
    $SQL = "Select * from table1; select * from table2;";
    $rs = fbsql_query($SQL, $link);
    do {
        while ($row = fbsql_fetch_row($rs)) {
        }
    } while (fbsql_next_result($rs));
    fbsql_free_result($rs);
    fbsql_close ($link);
?>

后退 | 起点 | 前进
fbsql_list_tables | 上一级 | fbsql_num_fields


fbsql_num_fields

(PHP 4 >= 4.0.6)

fbsql_num_fields -- Get number of fields in result

Description

int fbsql_num_fields ( resource result)

fbsql_num_fields() returns the number of fields in a result set.

See also:
fbsql_db_query(),
fbsql_query(),
fbsql_fetch_field(), and
fbsql_num_rows().

后退 | 起点 | 前进
fbsql_next_result | 上一级 | fbsql_num_rows


fbsql_num_rows

(PHP 4 >= 4.0.6)

fbsql_num_rows -- Get number of rows in result

Description

int fbsql_num_rows ( resource result)

fbsql_num_rows() returns the number of rows in a result set. This command is only valid for SELECT statements. To retrieve the number of rows returned from a INSERT, UPDATE or DELETE query, use fbsql_affected_rows().

例子 1. fbsql_num_rows() example

<?php

$link = fbsql_connect("localhost", "username", "password");
fbsql_select_db("database", $link);

$result = fbsql_query("SELECT * FROM table1;", $link);
$num_rows = fbsql_num_rows($result);

echo "$num_rows Rows\n";

?>

See also: fbsql_affected_rows(),
fbsql_connect(),
fbsql_select_db(), and
fbsql_query().

后退 | 起点 | 前进
fbsql_num_fields | 上一级 | fbsql_password


fbsql_password

(PHP 4 >= 4.0.6)

fbsql_password -- Get or set the user password used with a connection

Description

string fbsql_password ( resource link_identifier [, string password])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
fbsql_num_rows | 上一级 | fbsql_pconnect


fbsql_pconnect

(PHP 4 >= 4.0.6)

fbsql_pconnect -- Open a persistent connection to a FrontBase Server

Description

resource fbsql_pconnect ( [string hostname [, string username [, string password]]])

Returns: A positive FrontBase persistent link identifier on success, or FALSE on error.

fbsql_pconnect() establishes a connection to a FrontBase server. The following defaults are assumed for missing optional parameters: host = 'localhost', username = "_SYSTEM" and password = empty password.

fbsql_pconnect() acts very much like fbsql_connect() with two major differences.

To set Frontbase server port number, use fbsql_select_db().

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use.

This type of links is therefore called 'persistent'.

后退 | 起点 | 前进
fbsql_password | 上一级 | fbsql_query


fbsql_query

(PHP 4 >= 4.0.6)

fbsql_query -- Send a FrontBase query

Description

resource fbsql_query ( string query [, resource link_identifier])

fbsql_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If link_identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if fbsql_connect() was called with no arguments, and use it.

注: The query string shall always end with a semicolon.

fbsql_query() returns TRUE (non-zero) or FALSE to indicate whether or not the query succeeded. A return value of TRUE means that the query was legal and could be executed by the server. It does not indicate anything about the number of rows affected or returned. It is perfectly possible for a query to succeed but affect no rows or return no rows.

The following query is syntactically invalid, so fbsql_query() fails and returns FALSE:

例子 1. fbsql_query() example

<?php
$result = fbsql_query ("SELECT * WHERE 1=1")
    or die ("Invalid query");
?>

The following query is semantically invalid if my_col is not a column in the table my_tbl, so fbsql_query() fails and returns FALSE:

例子 2. fbsql_query() example

<?php
$result = fbsql_query ("SELECT my_col FROM my_tbl")
    or die ("Invalid query");
?>

fbsql_query() will also fail and return FALSE if you don't have permission to access the table(s) referenced by the query.

Assuming the query succeeds, you can call fbsql_num_rows() to find out how many rows were returned for a SELECT statement or fbsql_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.

For SELECT statements, fbsql_query() returns a new result identifier that you can pass to fbsql_result(). When you are done with the result set, you can free the resources associated with it by calling fbsql_free_result(). Although, the memory will automatically be freed at the end of the script's execution.

See also: fbsql_affected_rows(),
fbsql_db_query(),
fbsql_free_result(),
fbsql_result(),
fbsql_select_db(), and
fbsql_connect().

后退 | 起点 | 前进
fbsql_pconnect | 上一级 | fbsql_read_blob


fbsql_read_blob

(PHP 4 >= 4.2.0)

fbsql_read_blob -- Read a BLOB from the database

Description

string fbsql_read_blob ( string blob_handle [, resource link_identifier])

Returns: A string containing the BLOB specified by blob_handle.

fbsql_read_blob() reads BLOB data from the database. If a select statement contains BLOB and/or BLOB columns FrontBase will return the data directly when data is fetched. This default behavior can be changed with fbsql_set_lob_mode() so the fetch functions will return handles to BLOB and CLOB data. If a handle is fetched a user must call fbsql_read_blob() to get the actual BLOB data from the database.

例子 1. fbsql_read_blob() example

<?php
    $link = fbsql_pconnect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    $sql = "SELECT BLOB_COLUMN FROM BLOB_TABLE;";
    $rs = fbsql_query($sql, $link);
    $row_data = fbsql_fetch_row($rs);
    // $row_data[0] will now contain the blob data for teh first row
    fbsql_free_result($rs);

    $rs = fbsql_query($sql, $link);
    fbsql_set_lob_mode($rs, FBSQL_LOB_HANDLE);
    $row_data = fbsql_fetch_row($rs);
    // $row_data[0] will now contain a handle to the BLOB data in the first row
    $blob_data = fbsql_read_blob($row_data[0]);
    fbsql_free_result($rs);

?>

See also: fbsql_create_blob(),
fbsql_read_blob(),
fbsql_read_clob(), and
fbsql_set_lob_mode().

后退 | 起点 | 前进
fbsql_query | 上一级 | fbsql_read_clob


fbsql_read_clob

(PHP 4 >= 4.2.0)

fbsql_read_clob -- Read a CLOB from the database

Description

string fbsql_read_clob ( string clob_handle [, resource link_identifier])

Returns: A string containing the CLOB specified by clob_handle.

fbsql_read_clob() reads CLOB data from the database. If a select statement contains BLOB and/or CLOB columns FrontBase will return the data directly when data is fetched. This default behavior can be changed with fbsql_set_lob_mode() so the fetch functions will return handles to BLOB and CLOB data. If a handle is fetched a user must call fbsql_read_clob() to get the actual CLOB data from the database.

例子 1. fbsql_read_clob() example

<?php
    $link = fbsql_pconnect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    $sql = "SELECT CLOB_COLUMN FROM CLOB_TABLE;";
    $rs = fbsql_query($sql, $link);
    $row_data = fbsql_fetch_row($rs);
    // $row_data[0] will now contain the clob data for teh first row
    fbsql_free_result($rs);

    $rs = fbsql_query($sql, $link);
    fbsql_set_lob_mode($rs, FBSQL_LOB_HANDLE);
    $row_data = fbsql_fetch_row($rs);
    // $row_data[0] will now contain a handle to the CLOB data in the first row
    $clob_data = fbsql_read_clob($row_data[0]);
    fbsql_free_result($rs);

?>

See also: fbsql_create_blob(),
fbsql_read_blob(),
fbsql_read_clob(), and
fbsql_set_lob_mode().

后退 | 起点 | 前进
fbsql_read_blob | 上一级 | fbsql_result


fbsql_result

(PHP 4 >= 4.0.6)

fbsql_result -- Get result data

Description

mixed fbsql_result ( resource result, int row [, mixed field])

fbsql_result() returns the contents of one cell from a FrontBase result set. The field argument can be the field's offset, or the field's name, or the field's table dot field's name (tabledname.fieldname). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name.

When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than fbsql_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Calls to fbsql_result() should not be mixed with calls to other functions that deal with the result set.

Recommended high-performance alternatives:
fbsql_fetch_row(),
fbsql_fetch_array(), and
fbsql_fetch_object().

后退 | 起点 | 前进
fbsql_read_clob | 上一级 | fbsql_rollback


fbsql_rollback

(PHP 4 >= 4.0.6)

fbsql_rollback -- Rollback a transaction to the database

Description

bool fbsql_rollback ( [resource link_identifier])

如果成功则返回 TRUE，失败则返回 FALSE。

fbsql_rollback() ends the current transaction by rolling back all statements issued since last commit. This command is only needed if autocommit is set to false.

See also: fbsql_autocommit() and fbsql_commit()

后退 | 起点 | 前进
fbsql_result | 上一级 | fbsql_select_db


fbsql_select_db

(PHP 4 >= 4.0.6)

fbsql_select_db -- Select a FrontBase database

Description

bool fbsql_select_db ( string database_name [, resource link_identifier])

Returns: TRUE on success, FALSE on error.

fbsql_select_db() sets the current active database on the server that's associated with the specified link identifier. If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if fbsql_connect() was called, and use it.

The client contacts FBExec to obtain the port number to use for the connection to the database. If the database name is a number the system will use that as a port number and it will not ask FBExec for the port number. The FrontBase server can be stared as FRontBase -FBExec=No -port=<port number> <database name>.

Every subsequent call to fbsql_query() will be made on the active database.

if the database is protected with a database password, the user must call fbsql_database_password() before selecting the database.

See also:
    fbsql_connect(),
    fbsql_pconnect(),
    fbsql_database_password() and
    fbsql_query().

后退 | 起点 | 前进
fbsql_rollback | 上一级 | fbsql_set_lob_mode


fbsql_set_lob_mode

(PHP 4 >= 4.2.0)

fbsql_set_lob_mode -- Set the LOB retrieve mode for a FrontBase result set

Description

bool fbsql_set_lob_mode ( resource result, string database_name)

Returns: TRUE on success, FALSE on error.

fbsql_set_lob_mode() sets the mode for retrieving LOB data from the database. When BLOB and CLOB data is stored in FrontBase it can be stored direct or indirect. Direct stored LOB data will always be fetched no matter the setting of the lob mode. If the LOB data is less than 512 bytes it will always be stored directly.

  • FBSQL_LOB_DIRECT - LOB data is retrieved directly. When data is fetched from the database with fbsql_fetch_row(), and other fetch functions, all CLOB and BLOB columns will be returned as ordinary columns. This is the default value on a new FrontBase result.

  • FBSQL_LOB_HANDLE - LOB data is retrieved as handles to the data. When data is fetched from the database with fbsql_fetch_row (), and other fetch functions, LOB data will be returned as a handle to the data if the data is stored indirect or the data if it is stored direct. If a handle is returned it will be a 27 byte string formatted as "@'000000000000000000000000'".

See also:
    fbsql_create_blob(),
    fbsql_create_clob(),
    fbsql_read_blob(), and
    fbsql_read_clob().

后退 | 起点 | 前进
fbsql_select_db | 上一级 | fbsql_set_transaction


fbsql_set_transaction

(PHP 4 >= 4.2.0)

fbsql_set_transaction -- Set the transaction locking and isolation

Description

void fbsql_set_transaction ( resource link_identifier, int Locking, int Isolation)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
fbsql_set_lob_mode | 上一级 | fbsql_start_db


fbsql_start_db

(PHP 4 >= 4.0.6)

fbsql_start_db -- Start a database on local or remote server

Description

bool fbsql_start_db ( string database_name [, resource link_identifier])

如果成功则返回 TRUE，失败则返回 FALSE。

fbsql_start_db()

See also: fbsql_db_status() and fbsql_stop_db().

后退 | 起点 | 前进
fbsql_set_transaction | 上一级 | fbsql_stop_db


fbsql_stop_db

(PHP 4 >= 4.0.6)

fbsql_stop_db -- Stop a database on local or remote server

Description

bool fbsql_stop_db ( string database_name [, resource link_identifier])

如果成功则返回 TRUE，失败则返回 FALSE。

fbsql_stop_db()

See also: fbsql_db_status() and fbsql_start_db().

后退 | 起点 | 前进
fbsql_start_db | 上一级 | fbsql_tablename


fbsql_tablename

(PHP 4 >= 4.2.0)

fbsql_tablename -- Get table name of field

Description

string fbsql_tablename ( resource result, int i)

fbsql_tablename() takes a result pointer returned by the fbsql_list_tables() function as well as an integer index and returns the name of a table. The fbsql_num_rows() function may be used to determine the number of tables in the result pointer.

例子 1. fbsql_tablename() example

<?php
fbsql_connect ("localhost", "_SYSTEM", "");
$result = fbsql_list_tables ("wisconsin");
$i = 0;
while ($i < fbsql_num_rows ($result)) {
    $tb_names[$i] = fbsql_tablename ($result, $i);
    echo $tb_names[$i] . "<BR>";
    $i++;
}
?>

后退 | 起点 | 前进
fbsql_stop_db | 上一级 | fbsql_username


fbsql_username

(PHP 4 >= 4.0.6)

fbsql_username -- Get or set the host user used with a connection

Description

string fbsql_username ( resource link_identifier [, string username])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
fbsql_tablename | 上一级 | fbsql_warnings


fbsql_warnings

(PHP 4 >= 4.0.6)

fbsql_warnings -- Enable or disable FrontBase warnings

Description

bool fbsql_warnings ( [bool OnOff])

Returns TRUE if warnings is turned on otherwise FALSE.

fbsql_warnings() enables or disables FrontBase warnings.

后退 | 起点 | 前进
fbsql_username | 上一级 | filePro functions


filePro functions

PHP 手册
后退 前进

XXIX. filePro functions

介绍

These functions allow read-only access to data stored in filePro databases.

filePro is a registered trademark of fP Technologies, Inc. You can find more information about filePro at http://www.fptech.com/.

目录
filepro_fieldcount — Find out how many fields are in a filePro database
filepro_fieldname — Gets the name of a field
filepro_fieldtype — Gets the type of a field
filepro_fieldwidth — Gets the width of a field
filepro_retrieve — Retrieves data from a filePro database
filepro_rowcount — Find out how many rows are in a filePro database
filepro — Read and verify the map file

后退 | 起点 | 前进
fbsql_warnings | 上一级 | filepro_fieldcount


filepro_fieldcount

(PHP 3, PHP 4 )

filepro_fieldcount -- Find out how many fields are in a filePro database

Description

int filepro_fieldcount ( void)

Returns the number of fields (columns) in the opened filePro database.

See also filepro().

后退 | 起点 | 前进
filePro functions | 上一级 | filepro_fieldname


filepro_fieldname

(PHP 3, PHP 4 )

filepro_fieldname -- Gets the name of a field

Description

string filepro_fieldname ( int field_number)

Returns the name of the field corresponding to field_number.

后退 | 起点 | 前进
filepro_fieldcount | 上一级 | filepro_fieldtype


filepro_fieldtype

(PHP 3, PHP 4 )

filepro_fieldtype -- Gets the type of a field

Description

string filepro_fieldtype ( int field_number)

Returns the edit type of the field corresponding to field_number.

后退 | 起点 | 前进
filepro_fieldname | 上一级 | filepro_fieldwidth


filepro_fieldwidth

(PHP 3, PHP 4 )

filepro_fieldwidth -- Gets the width of a field

Description

int filepro_fieldwidth ( int field_number)

Returns the width of the field corresponding to field_number.

后退 | 起点 | 前进
filepro_fieldtype | 上一级 | filepro_retrieve


filepro_retrieve

(PHP 3, PHP 4 )

filepro_retrieve -- Retrieves data from a filePro database

Description

string filepro_retrieve ( int row_number, int field_number)

Returns the data from the specified location in the database.

注: 当 安全模式（safe mode） 被激活，PHP 将检查您将要操作的文件或者目录与正在执行的脚本是否有相同的 UID。

后退 | 起点 | 前进
filepro_fieldwidth | 上一级 | filepro_rowcount


filepro_rowcount

(PHP 3, PHP 4 )

filepro_rowcount -- Find out how many rows are in a filePro database

Description

int filepro_rowcount ( void)

Returns the number of rows in the opened filePro database.

注: 当 安全模式（safe mode） 被激活，PHP 将检查您将要操作的文件或者目录与正在执行的脚本是否有相同的 UID。

See also filepro().

后退 | 起点 | 前进
filepro_retrieve | 上一级 | filepro


filepro

(PHP 3, PHP 4 )

filepro -- Read and verify the map file

Description

bool filepro ( string directory)

This reads and verifies the map file, storing the field count and info.

No locking is done, so you should avoid modifying your filePro database while it may be opened in PHP.

注: 当 安全模式（safe mode） 被激活，PHP 将检查您将要操作的文件或者目录与正在执行的脚本是否有相同的 UID。

后退 | 起点 | 前进
filepro_rowcount | 上一级 | Filesystem functions


Filesystem functions

PHP 手册
后退 前进

XXX. Filesystem functions

介绍

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

这些函数作为 PHP 核心的一部分，无需被安装即可使用。

运行时配置

该扩展模块未定义任何设置指令。

资源类型

预定义常量

该扩展模块未定义任何常量。

相关参考

For related functions, see also the Directory and Program Execution sections.

目录
basename — Returns filename component of path
chgrp — Changes file group
chmod — Changes file mode
chown — Changes file owner
clearstatcache — Clears file status cache
copy — Copies file
delete — A dummy manual entry
dirname — Returns directory name component of path
disk_free_space — Returns available space in directory
disk_total_space — Returns the total size of a directory
diskfreespace — Alias of disk_free_space()
fclose — Closes an open file pointer
feof — Tests for end-of-file on a file pointer
fflush — Flushes the output to a file
fgetc — Gets character from file pointer
fgetcsv — Gets line from file pointer and parse for CSV fields
fgets — Gets line from file pointer
fgetss — Gets line from file pointer and strip HTML tags
file_exists — Checks whether a file exists
file_get_contents — Reads entire file into a string
file_get_wrapper_data — Retrieves header/meta data from "wrapped" file pointers
file_register_wrapper — Register a URL wrapper implemented as a PHP class
file — Reads entire file into an array
fileatime — Gets last access time of file
filectime — Gets inode change time of file
filegroup — Gets file group
fileinode — Gets file inode
filemtime — Gets file modification time
fileowner — Gets file owner
fileperms — Gets file permissions
filesize — Gets file size
filetype — Gets file type
flock — Portable advisory file locking
fopen — Opens file or URL
fpassthru — Output all remaining data on a file pointer
fputs — Writes to a file pointer
fread — Binary-safe file read
fscanf — Parses input from a file according to a format
fseek — Seeks on a file pointer
fstat — Gets information about a file using an open file pointer
ftell — Tells file pointer read/write position
ftruncate — Truncates a file to a given length
fwrite — Binary-safe file write
glob — Find pathnames matching a pattern
is_dir — Tells whether the filename is a directory
is_executable — Tells whether the filename is executable
is_file — Tells whether the filename is a regular file
is_link — Tells whether the filename is a symbolic link
is_readable — Tells whether the filename is readable
is_uploaded_file — Tells whether the file was uploaded via HTTP POST
is_writable — Tells whether the filename is writable
is_writeable — Tells whether the filename is writable
link — Create a hard link
linkinfo — Gets information about a link
lstat — Gives information about a file or symbolic link
mkdir — Makes directory
move_uploaded_file — Moves an uploaded file to a new location
parse_ini_file — Parse a configuration file
pathinfo — Returns information about a file path
pclose — Closes process file pointer
popen — Opens process file pointer
readfile — Outputs a file
readlink — Returns the target of a symbolic link
realpath — Returns canonicalized absolute pathname
rename — Renames a file
rewind — Rewind the position of a file pointer
rmdir — Removes directory
set_file_buffer — Sets file buffering on the given file pointer
stat — Gives information about a file
symlink — Creates a symbolic link
tempnam — Create file with unique file name
tmpfile — Creates a temporary file
touch — Sets access and modification time of file
umask — Changes the current umask
unlink — Deletes a file

后退 | 起点 | 前进
filepro | 上一级 | basename


basename

(PHP 3, PHP 4 )

basename -- Returns filename component of path

Description

string basename ( string path [, string suffix])

Given a string containing a path to a file, this function will return the base name of the file. If the filename ends in suffix this will also be cut off.

On Windows, both slash (/) and backslash (\) are used as path separator character. In other environments, it is the forward slash (/).

例子 1. basename() example

$path = "/home/httpd/html/index.php";
$file = basename ($path);        // $file is set to "index.php"
$file = basename ($path,".php"); // $file is set to "index"

注: The suffix parameter was added in PHP 4.1.0.

See also: dirname()

后退 | 起点 | 前进
Filesystem functions | 上一级 | chgrp


chgrp

(PHP 3, PHP 4 )

chgrp -- Changes file group

Description

int chgrp ( string filename, mixed group)

Attempts to change the group of the file filename to group (specified by name or number). Only the superuser may change the group of a file arbitrarily; other users may change the group of a file to any group of which that user is a member.

如果成功则返回 TRUE，失败则返回 FALSE。

See also chown() and chmod().

后退 | 起点 | 前进
basename | 上一级 | chmod


chmod

(PHP 3, PHP 4 )

chmod -- Changes file mode

Description

int chmod ( string filename, int mode)

Attempts to change the mode of the file specified by filename to that given in mode.

Note that mode is not automatically assumed to be an octal value, so strings (such as "g+w") will not work properly. To ensure the expected operation, you need to prefix mode with a zero (0):

chmod ("/somedir/somefile", 755);   // decimal; probably incorrect
chmod ("/somedir/somefile", "u+rwx,go+rx"); // string; incorrect
chmod ("/somedir/somefile", 0755);  // octal; correct value of mode

如果成功则返回 TRUE，失败则返回 FALSE。

See also chown() and chgrp().

后退 | 起点 | 前进
chgrp | 上一级 | chown


chown

(PHP 3, PHP 4 )

chown -- Changes file owner

Description

int chown ( string filename, mixed user)

Attempts to change the owner of the file filename to user user (specified by name or number). Only the superuser may change the owner of a file.

如果成功则返回 TRUE，失败则返回 FALSE。

See also chmod().

后退 | 起点 | 前进
chmod | 上一级 | clearstatcache


clearstatcache

(PHP 3, PHP 4 )

clearstatcache -- Clears file status cache

Description

void clearstatcache ( void)

When you use stat(), lstat(), or any of the other functions listed in the affected functions list (below), PHP caches the information those functions return in order to provide faster performance. However, in certain cases, you may want to clear the cached information. For instance, if the same file is being checked multiple times within a single script, and that file is in danger of being removed or changed during that script's operation, you may elect to clear the status cache. In these cases, you can use the clearstatcache() function to clear the information that PHP caches about a file.

注: This function caches information about specific filenames, so you only need to call clearstatcache() if you are performing multiple operations on the same filename and require the information about that particular file to not be cached.

Affected functions include stat(),
lstat(),
file_exists(),
is_writable(),
is_readable(),
is_executable(),
is_file(),
is_dir(),
is_link(),
filectime(),
fileatime(),
filemtime(),
fileinode(),
filegroup(),
fileowner(),
filesize(),
filetype(), and
fileperms().

后退 | 起点 | 前进
chown | 上一级 | copy


copy

(PHP 3, PHP 4 )

copy -- Copies file

Description

int copy ( string source, string dest)

Makes a copy of a file. Returns TRUE if the copy succeeded, FALSE otherwise.

例子 1. copy() example

if (!copy($file, $file.'.bak')) {
    print ("failed to copy $file...<br>\n");
}

注: As of PHP 4.3.0, both source and dest may be URLs if the "fopen wrappers" have been enabled. See fopen() for more details.

警告

If the destination file already exists, it will be overwritten.

See also move_uploaded_file(), rename(), and the section of the manual about handling file uploads.

后退 | 起点 | 前进
clearstatcache | 上一级 | delete


delete

(no version information, might be only in CVS)

delete -- A dummy manual entry

Description

void delete ( string file)

This is a dummy manual entry to satisfy those people who are looking for unlink() or unset() in the wrong place.

See also: unlink() to delete files, unset() to delete variables.

后退 | 起点 | 前进
copy | 上一级 | dirname


dirname

(PHP 3, PHP 4 )

dirname -- Returns directory name component of path

Description

string dirname ( string path)

Given a string containing a path to a file, this function will return the name of the directory.

On Windows, both slash (/) and backslash (\) are used as path separator character. In other environments, it is the forward slash (/).

例子 1. dirname() example

$path = "/etc/passwd";
$file = dirname ($path); // $file is set to "/etc"

注: In PHP 4.0.3, dirname() was fixed to be POSIX-compliant. Essentially, this means that if there are no slashes in path , a dot ('.') is returned, indicating the current directory. Otherwise, the returned string is path with any trailing /component removed. Note that this means that you will often get a slash or a dot back from dirname() in situations where the older functionality would have given you the empty string.

See also: basename(), pathinfo(), and realpath().

后退 | 起点 | 前进
delete | 上一级 | disk_free_space


disk_free_space

(PHP 4 >= 4.1.0)

disk_free_space -- Returns available space in directory

Description

float disk_free_space ( string directory)

Given a string containing a directory, this function will return the number of bytes available on the corresponding filesystem or disk partition.

例子 1. disk_free_space() example

$df = disk_free_space("/"); // $df contains the number of bytes
                            // available on "/"

后退 | 起点 | 前进
dirname | 上一级 | disk_total_space


disk_total_space

(PHP 4 >= 4.1.0)

disk_total_space -- Returns the total size of a directory

Description

float disk_total_space ( string directory)

Given a string containing a directory, this function will return the total number of bytes on the corresponding filesystem or disk partition.

例子 1. disk_total_space() example

$df = disk_total_space("/"); // $df contains the total number of
                             // bytes available on "/"

后退 | 起点 | 前进
disk_free_space | 上一级 | diskfreespace


diskfreespace

(PHP 3>= 3.0.7, PHP 4 )

diskfreespace -- Alias of disk_free_space()

Description

float diskfreespace ( string directory)

This is a deprecated alias of disk_free_space(). Use that function instead.

后退 | 起点 | 前进
disk_total_space | 上一级 | fclose


fclose

(PHP 3, PHP 4 )

fclose -- Closes an open file pointer

Description

bool fclose ( int fp)

The file pointed to by fp is closed.

如果成功则返回 TRUE，失败则返回 FALSE。

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().

后退 | 起点 | 前进
diskfreespace | 上一级 | feof


feof

(PHP 3, PHP 4 )

feof -- Tests for end-of-file on a file pointer

Description

int feof ( int fp)

Returns TRUE if the file pointer is at EOF or an error occurs; otherwise returns FALSE.

The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen().

后退 | 起点 | 前进
fclose | 上一级 | fflush


fflush

(PHP 4 >= 4.0.1)

fflush -- Flushes the output to a file

Description

int fflush ( int fp)

This function forces a write of all buffered output to the resource pointed to by the file handle fp. Returns TRUE if successful, FALSE otherwise.

The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen().

后退 | 起点 | 前进
feof | 上一级 | fgetc


fgetc

(PHP 3, PHP 4 )

fgetc -- Gets character from file pointer

Description

string fgetc ( int fp)

Returns a string containing a single character read from the file pointed to by fp. Returns FALSE on EOF.

The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen().

See also fread(), fopen(),
popen(), fsockopen(), and
fgets().

后退 | 起点 | 前进
fflush | 上一级 | fgetcsv


fgetcsv

(PHP 3>= 3.0.8, PHP 4 )

fgetcsv -- Gets line from file pointer and parse for CSV fields

Description

array fgetcsv ( int fp, int length [, string delimiter [, string enclosure]])

Similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read. The field delimiter is a comma, unless you specify another delimiter with the optional third parameter. The enclosure character is double quote, unless it is specified. Delimiter and enclosure cannot be null and only first character is used when they are specified.

Fp must be a valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen()

Length must be greater than the longest line to be found in the CSV file (allowing for trailing line-end characters).

fgetcsv() returns FALSE on error, including end of file.

注: A blank line in a CSV file will be returned as an array comprising a single NULL field, and will not be treated as an error.

enclosure is added from PHP 4.3.0.

例子 1. fgetcsv() example - Read and print entire contents of a CSV file

$row = 1;
$fp = fopen ("test.csv","r");
while ($data = fgetcsv ($fp, 1000, ",")) {
    $num = count ($data);
    print "<p> $num fields in line $row: <br>";
    $row++;
    for ($c=0; $c < $num; $c++) {
        print $data[$c] . "<br>";
    }
}
fclose ($fp);

后退 | 起点 | 前进
fgetc | 上一级 | fgets


fgets

(PHP 3, PHP 4 )

fgets -- Gets line from file pointer

Description

string fgets ( int fp [, int length])

Returns a string of up to length - 1 bytes read from the file pointed to by fp. Reading ends when length - 1 bytes have been read, on a newline (which is included in the return value), or on EOF (whichever comes first). If no length is specified, the length defaults to 1k, or 1024 bytes.

If an error occurs, returns FALSE.

Common Pitfalls:

People used to the 'C' semantics of fgets() should note the difference in how EOF is returned.

The file pointer must be valid, and must point to a file
successfully opened by fopen(),
popen(), or
fsockopen().

A simple example follows:

例子 1. Reading a file line by line

$fd = fopen ("/tmp/inputfile.txt", "r");
while (!feof ($fd)) {
    $buffer = fgets($fd, 4096);
    echo $buffer;
}
fclose ($fd);

注: The length parameter became optional in PHP 4.2.0

See also fread(), fopen(),
popen(), fgetc(),
fsockopen(), and
socket_set_timeout().

后退 | 起点 | 前进
fgetcsv | 上一级 | fgetss


fgetss

(PHP 3, PHP 4 )

fgetss -- Gets line from file pointer and strip HTML tags

Description

string fgetss ( int fp, int length [, string allowable_tags])

Identical to fgets(), except that fgetss attempts to strip any HTML and PHP tags from the text it reads.

You can use the optional third parameter to specify tags which should not be stripped.

注: allowable_tags was added in PHP 3.0.13, PHP 4.0.0.

See also fgets(), fopen(),
fsockopen(), popen(), and
strip_tags().

后退 | 起点 | 前进
fgets | 上一级 | file_exists


file_exists

(PHP 3, PHP 4 )

file_exists -- Checks whether a file exists

Description

bool file_exists ( string filename)

Returns TRUE if the file specified by filename exists; FALSE otherwise.

This function will not work on remote files; the file to be examined must be accessible via the server's filesystem.

The results of this function are cached. See clearstatcache() for more details.

On windows use "//computername/share/filename" or "\\\\computername\share\filename" to check files on network shares.

后退 | 起点 | 前进
fgetss | 上一级 | file_get_contents


file_get_contents

(PHP 4 CVS only)

file_get_contents -- Reads entire file into a string

Description

string file_get_contents ( string filename [, int use_include_path])

Identical to readfile(), except that file_get_contents() returns the file in a string.

注: 该函数适用于二进制对象！

提示: 如果 "fopen wrappers" 已经被激活，则您在使用该函数的时候，可以把 URL 作为文件名来使用。请参阅 fopen() 获取详细信息。

See also: fgets(), file(),
fread(), include(),
and readfile().

后退 | 起点 | 前进
file_exists | 上一级 | file_get_wrapper_data


file_get_wrapper_data

(PHP 4 CVS only)

file_get_wrapper_data -- Retrieves header/meta data from "wrapped" file pointers

Description

mixed file_get_wrapper_data ( int fp)

This function returns header or meta data from files opened with fopen(). This is useful to return the response headers for HTTP connections, or some other statistics for other resources.

The format of the returned data is deliberately undocumented at this time, and depends on which wrapper(s) were used to open the file.

注: This function was introduced in PHP 4.3.0.

后退 | 起点 | 前进
file_get_contents | 上一级 | file_register_wrapper


file_register_wrapper

(PHP 4 CVS only)

file_register_wrapper -- Register a URL wrapper implemented as a PHP class

Description

boolean file_register_wrapper ( string protocol, string classname)

This function is currently only documented by the example below:

例子 1. Implementing a base64 encoding protocol

class Base64EncodingStream {
    var $fp = null;

    function stream_open($path, $mode, $options, &$opened_path)
    {
        $this->fp = fopen($path, $mode);
        return is_resource($this->fp);
    }
    function stream_close()
    {
        fclose($this->fp);
    }
    function stream_read($count)
    {
        return false; // We only allow writing
    }
    function stream_write($data)
    {
        return fwrite($this->fp, base64_encode($data));
    }
    function stream_flush()
    {
        fflush($this->fp);
        return true;
    }
    function stream_seek($offset, $whence)
    {
        return false;
    }
    function stream_gets()
    {
        return false;
    }
    function stream_tell()
    {
        return false;
    }
    function stream_eof()
    {
        return false;
    }
}
file_register_wrapper("base64", "Base64EncodingStream")
    or die("Failed to register protocol");

copy("/tmp/inputfile.txt", "base64:///tmp/outputfile.txt");
readfile("/tmp/outputfile");

file_register_wrapper() will return FALSE if the protocol already has a handler, or if "fopen wrappers" are disabled.

注: This function was introduced in PHP 4.3.0.

后退 | 起点 | 前进
file_get_wrapper_data | 上一级 | file


file

(PHP 3, PHP 4 )

file -- Reads entire file into an array

Description

array file ( string filename [, int use_include_path])

Identical to readfile(), except that file() returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached.

注: Each line in the resulting array will include the line ending, so you still need to use trim() if you do not want the line ending present.

You can use the optional second parameter and set it to "1", if you want to search for the file in the include_path, too.

<?php
// get a web page into an array and print it out
$fcontents = file ('http://www.example.com/');
while (list ($line_num, $line) = each ($fcontents)) {
    echo "<b>Line $line_num:</b>; ", htmlspecialchars ($line), "<br>\n";
}

// get a web page into a string
$fcontents = implode ('', file ('http://www.example.com/'));
?>

注: As of PHP 4.3.0 you can use file_get_contents() to return the contents of a file as a string in a binary safe manner.

警告

该函数（到目前为止）不适用于二进制对象！

提示: 如果 "fopen wrappers" 已经被激活，则您在使用该函数的时候，可以把 URL 作为文件名来使用。请参阅 fopen() 获取详细信息。

See also readfile(),
fopen(), fsockopen(), and
popen().

后退 | 起点 | 前进
file_register_wrapper | 上一级 | fileatime


fileatime

(PHP 3, PHP 4 )

fileatime -- Gets last access time of file

Description

int fileatime ( string filename)

Returns the time the file was last accessed, or FALSE in case of an error. The time is returned as a Unix timestamp.

The results of this function are cached. See clearstatcache() for more details.

Note: The atime of a file is supposed to change whenever the data blocks of a file are being read. This can be costly performancewise when an application regularly accesses a very large number of files or directories. Some Unix filesystems can be mounted with atime updates disabled to increase the performance of such applications; USENET news spools are a common example. On such filesystems this function will be useless.

This function will not work on remote files; the file to be examined must be accessible via the server's filesystem.

后退 | 起点 | 前进
file | 上一级 | filectime


filectime

(PHP 3, PHP 4 )

filectime -- Gets inode change time of file

Description

int filectime ( string filename)

Returns the time the file was last changed, or FALSE in case of an error. The time is returned as a Unix timestamp.

The results of this function are cached. See clearstatcache() for more details.

Note: In most Unix filesystems, a file is considered changed when its inode data is changed; that is, when the permissions, owner, group, or other metadata from the inode is updated. See also filemtime() (which is what you want to use when you want to create "Last Modified" footers on web pages) and fileatime().

Note also that in some Unix texts the ctime of a file is referred to as being the creation time of the file. This is wrong. There is no creation time for Unix files in most Unix filesystems.

This function will not work on remote files; the file to be examined must be accessible via the server's filesystem.

后退 | 起点 | 前进
fileatime | 上一级 | filegroup


filegroup

(PHP 3, PHP 4 )

filegroup -- Gets file group

Description

int filegroup ( string filename)

Returns the group ID of the owner of the file, or FALSE in case of an error. The group ID is returned in numerical format, use posix_getgrgid() to resolve it to a group name.

The results of this function are cached. See clearstatcache() for more details.

注: This function will not work on remote files; the file to be examined must be accessible via the server's filesystem.

后退 | 起点 | 前进
filectime | 上一级 | fileinode


fileinode

(PHP 3, PHP 4 )

fileinode -- Gets file inode

Description

int fileinode ( string filename)

Returns the inode number of the file, or FALSE in case of an error.

The results of this function are cached. See clearstatcache() for more details.

This function will not work on remote files; the file to be examined must be accessible via the server's filesystem.

后退 | 起点 | 前进
filegroup | 上一级 | filemtime


filemtime

(PHP 3, PHP 4 )

filemtime -- Gets file modification time

Description

int filemtime ( string filename)

Returns the time the file was last modified, or FALSE in case of an error. The time is returned as a Unix timestamp.

The results of this function are cached. See clearstatcache() for more details.

This function will not work on remote files; the file to be examined must be accessible via the server's filesystem.

Note: This function returns the time when the data blocks of a file were being written to, that is, the time when the content of the file was changed. Use date() on the result of this function to get a printable modification date for use in page footers.

See also filectime() and touch().

后退 | 起点 | 前进
fileinode | 上一级 | fileowner


fileowner

(PHP 3, PHP 4 )

fileowner -- Gets file owner

Description

int fileowner ( string filename)

Returns the user ID of the owner of the file, or FALSE in case of an error. The user ID is returned in numerical format, use posix_getpwuid() to resolve it to a username.

The results of this function are cached. See clearstatcache() for more details.

This function will not work on remote files; the file to be examined must be accessible via the server's filesystem.

后退 | 起点 | 前进
filemtime | 上一级 | fileperms


fileperms

(PHP 3, PHP 4 )

fileperms -- Gets file permissions

Description

int fileperms ( string filename)

Returns the permissions on the file, or FALSE in case of an error.

This function will not work on remote files; the file to be examined must be accessible via the server's filesystem.

The results of this function are cached. See clearstatcache() for more details.

后退 | 起点 | 前进
fileowner | 上一级 | filesize


filesize

(PHP 3, PHP 4 )

filesize -- Gets file size

Description

int filesize ( string filename)

Returns the size of the file in bytes, or FALSE in case of an error.

The results of this function are cached. See clearstatcache() for more details.

This function will not work on remote files; the file to be examined must be accessible via the server's filesystem.

后退 | 起点 | 前进
fileperms | 上一级 | filetype


filetype

(PHP 3, PHP 4 )

filetype -- Gets file type

Description

string filetype ( string filename)

Returns the type of the file. Possible values are fifo, char, dir, block, link, file, and unknown.

Returns FALSE if an error occurs.

The results of this function are cached. See clearstatcache() for more details.

This function will not work on remote files; the file to be examined must be accessible via the server's filesystem.

See also: is_dir(), is_file(),
is_link(), file_exists(), and
stat().

后退 | 起点 | 前进
filesize | 上一级 | flock


flock

(PHP 3>= 3.0.7, PHP 4 )

flock -- Portable advisory file locking

Description

bool flock ( int fp, int operation [, int &wouldblock])

PHP supports a portable way of locking complete files in an advisory way (which means all accessing programs have to use the same way of locking or it will not work).

flock() operates on fp which must be an open file pointer. operation is one of the following values:

  • To acquire a shared lock (reader), set operation to LOCK_SH (set to 1 prior to PHP 4.0.1).

  • To acquire an exclusive lock (writer), set operation to LOCK_EX (set to 2 prior to PHP 4.0.1).

  • To release a lock (shared or exclusive), set operation to LOCK_UN (set to 3 prior to PHP 4.0.1).

  • If you don't want flock() to block while locking, add LOCK_NB (4 prior to PHP 4.0.1) to operation.

flock() allows you to perform a simple reader/writer model which can be used on virtually every platform (including most Unix derivatives and even Windows). The optional third argument is set to TRUE if the lock would block (EWOULDBLOCK errno condition)

flock() returns TRUE on success and FALSE on error (e.g. when a lock could not be acquired).

注: Because flock() requires a file pointer, you may have to use a special lock file to protect access to a file that you intend to truncate by opening it in write mode (with a "w" or "w+" argument to fopen()).

警告

flock() will not work on NFS and many other networked file systems. Check your operating system documentation for more details.

On some operating systems flock() is implemented at the process level. When using a multithreaded server API like ISAPI you may not be able to rely on flock() to protect files against other PHP scripts running in parallel threads of the same server instance!

flock() is not supported on antiquated filesystems like FAT and its derivates and will therefore always return FALSE under this environments (this is especially true for Windows 98 users).

后退 | 起点 | 前进
filetype | 上一级 | fopen


fopen

(PHP 3, PHP 4 )

fopen -- Opens file or URL

Description

int fopen ( string filename, string mode [, int use_include_path [, resource zcontext]])

If filename begins with "http://" (not case sensitive), an HTTP 1.0 connection is opened to the specified server, the page is requested using the HTTP GET method, and a file pointer is returned to the beginning of the body of the response. A 'Host:' header is sent with the request in order to handle name-based virtual hosts.

As of PHP 4.3.0, if you have compiled in support for OpenSSL, you may use "https://" to open an HTTP connection over SSL.

Note that the file pointer allows you to retrieve only the body of the response; to retrieve the HTTP response header you need to be using PHP 4.0.5 or later; The headers will be stored in the $http_response_header variable. As of PHP 4.3.0, the header information can be retrieved using file_get_wrapper_data().

HTTP connections are read-only; you cannot write data or copy files to an HTTP resource.

Versions prior to PHP 4.0.5 do not handle HTTP redirects. Because of this, directories must include trailing slashes.

If filename begins with "ftp://" (not case sensitive), an ftp connection to the specified server is opened and a pointer to the requested file is returned. If the server does not support passive mode ftp, this will fail. You can open files for either reading or writing via ftp (but not both simultaneously). If the remote file already exists on the ftp server and you attempt to open it for writing, this will fail. If you need to update existing files over ftp, use ftp_connect().

As of PHP 4.3.0, if you have compiled in support for OpenSSL, you may use "ftps://" to open an FTP connection that will use SSL to encrypt the connection. PHP will fall-back and work just like regular ftp:// if the server does not support SSL.

If filename is one of "php://stdin", "php://stdout", or "php://stderr", the corresponding stdio stream will be opened. (This was introduced in PHP 3.0.13; in earlier versions, a filename such as "/dev/stdin" or "/dev/fd/0" must be used to access the stdio streams.)

If filename begins with anything else, the file will be opened from the filesystem, and a file pointer to the file opened is returned.

If the open fails, the function returns FALSE.

mode may be any of the following:

  • 'r' - Open for reading only; place the file pointer at the beginning of the file.

  • 'r+' - Open for reading and writing; place the file pointer at the beginning of the file.

  • 'w' - Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

  • 'w+' - Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

  • 'a' - Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

  • 'a+' - Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

注: The mode may contain the letter 'b'. This is useful only on systems which differentiate between binary and text files (i.e. Windows. It's useless on Unix). If not needed, this will be ignored.

The optional third use_include_path parameter can be set to '1' or TRUE if you want to search for the file in the include_path, too.

The optional fourth zcontext is used for specifying tuning parameters and callbacks.

例子 1. fopen() example

<?php
$fp = fopen ("/home/rasmus/file.txt", "r");
$fp = fopen ("/home/rasmus/file.gif", "wb");
$fp = fopen ("http://www.example.com/", "r");
$fp = fopen ("ftp://user:password@example.com/", "w");
?>

If you are experiencing problems with reading and writing to files and you're using the server module version of PHP, remember to make sure that the files and directories you're using are accessible to the server process.

On the Windows platform, be careful to escape any backslashes used in the path to the file, or use forward slashes.

<?php
$fp = fopen ("c:\\data\\info.txt", "r");
?>

See also 附录 I
fclose(),
fgets(),
fsockopen(),
file(),
file_exists(),
is_readable(),
socket_set_timeout(), and
popen().

后退 | 起点 | 前进
flock | 上一级 | fpassthru


fpassthru

(PHP 3, PHP 4 )

fpassthru -- Output all remaining data on a file pointer

Description

int fpassthru ( int fp)

Reads to EOF on the given file pointer from the current position and writes the results to standard output.

If an error occurs, fpassthru() returns FALSE.

The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen(). You may need to call rewind() to reset the file pointer to the beginning of the file if you have already written data to the file. The file is closed when fpassthru() is done reading it (leaving fp useless).

If you just want to dump the contents of a file to stdout you may want to use the readfile(), which saves you the fopen() call.

注: When using fpassthru() on a binary file on Windows systems, you should make sure to open the file in binary mode by appending a b to the mode used in the call to fopen().

See also readfile(),
fopen(), popen(), and
fsockopen()

后退 | 起点 | 前进
fopen | 上一级 | fputs


fputs

(PHP 3, PHP 4 )

fputs -- Writes to a file pointer

Description

int fputs ( int fp, string str [, int length])

fputs() is an alias to fwrite(), and is identical in every way. Note that the length parameter is optional and if not specified the entire string will be written.

后退 | 起点 | 前进
fpassthru | 上一级 | fread


fread

(PHP 3, PHP 4 )

fread -- Binary-safe file read

Description

string fread ( int fp, int length)

fread() reads up to length bytes from the file pointer referenced by fp. Reading stops when length bytes have been read or EOF is reached, whichever comes first.

// get contents of a file into a string
$filename = "/usr/local/something.txt";
$fd = fopen ($filename, "r");
$contents = fread ($fd, filesize ($filename));
fclose ($fd);

注: On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.

$filename = "c:\\files\\somepic.gif";
$fd = fopen ($filename, "rb");
$contents = fread ($fd, filesize ($filename));
fclose ($fd);

See also fwrite(), fopen(),
fsockopen(), popen(),
fgets(), fgetss(),
fscanf(), file(), and
fpassthru().

后退 | 起点 | 前进
fputs | 上一级 | fscanf


fscanf

(PHP 4 >= 4.0.1)

fscanf -- Parses input from a file according to a format

Description

mixed fscanf ( int handle, string format [, string var1])

The function fscanf() is similar to sscanf(), but it takes its input from a file associated with handle and interprets the input according to the specified format. If only two parameters were passed to this function, the values parsed will be returned as an array. Otherwise, if optional parameters are passed, the function will return the number of assigned values. The optional parameters must be passed by reference.

Any whitespace in the format string matches any whitespace in the input stream. This means that even a tab \t in the format string can match a single space character in the input stream.

例子 1. fscanf() Example

$fp = fopen ("users.txt","r");
while ($userinfo = fscanf ($fp, "%s\t%s\t%s\n")) {
    list ($name, $profession, $countrycode) = $userinfo;
    //... do something with the values
}
fclose($fp);

例子 2. users.txt

javier  argonaut        pe
hiroshi sculptor        jp
robert  slacker us
luigi   florist it

See also fread(), fgets(),
fgetss(), sscanf(),
printf(), and sprintf().

后退 | 起点 | 前进
fread | 上一级 | fseek


fseek

(PHP 3, PHP 4 )

fseek -- Seeks on a file pointer

Description

int fseek ( int fp, int offset [, int whence])

Sets the file position indicator for the file referenced by fp.The new position, measured in bytes from the beginning of the file, is obtained by adding offset to the position specified by whence, whose values are defined as follows:

SEEK_SET - Set position equal to offset bytes.
SEEK_CUR - Set position to current location plus offset.
SEEK_END - Set position to end-of-file plus offset. (To move to a position before the end-of-file, you need to pass a negative value in offset.)

If whence is not specified, it is assumed to be SEEK_SET.

Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF is not considered an error.

May not be used on file pointers returned by fopen() if they use the "http://" or "ftp://" formats.

注: The whence argument was added after PHP 4.0.0.

See also ftell() and rewind().

后退 | 起点 | 前进
fscanf | 上一级 | fstat


fstat

(PHP 4 )

fstat -- Gets information about a file using an open file pointer

Description

array fstat ( int fp)

Gathers the statistics of the file opened by the file pointer fp. This function is similar to the stat() function except that it operates on an open file pointer instead of a filename.

Returns an array with the statistics of the file with the following elements:

  1. device

  2. inode

  3. number of links

  4. user id of owner

  5. group id owner

  6. device type if inode device *

  7. size in bytes

  8. time of last access

  9. time of last modification

  10. time of last change

  11. blocksize for filesystem I/O *

  12. number of blocks allocated

* - only valid on systems supporting the st_blksize type--other systems (i.e. Windows) return -1

The results of this function are cached. See clearstatcache() for more details.

后退 | 起点 | 前进
fseek | 上一级 | ftell


ftell

(PHP 3, PHP 4 )

ftell -- Tells file pointer read/write position

Description

int ftell ( int fp)

Returns the position of the file pointer referenced by fp; i.e., its offset into the file stream.

If an error occurs, returns FALSE.

The file pointer must be valid, and must point to a file successfully opened by fopen() or popen().

See also fopen(), popen(), fseek(), and rewind().

后退 | 起点 | 前进
fstat | 上一级 | ftruncate


ftruncate

(PHP 4 )

ftruncate -- Truncates a file to a given length

Description

int ftruncate ( int fp, int size)

Takes the filepointer, fp, and truncates the file to length, size. This function returns TRUE on success and FALSE on failure.

后退 | 起点 | 前进
ftell | 上一级 | fwrite


fwrite

(PHP 3, PHP 4 )

fwrite -- Binary-safe file write

Description

int fwrite ( int fp, string string [, int length])

fwrite() writes the contents of string to the file stream pointed to by fp. If the length argument is given, writing will stop after length bytes have been written or the end of string is reached, whichever comes first.

fwrite() returns the number of bytes written, or -1 on error.

Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string.

注: On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.

See also fread(), fopen(),
fsockopen(), popen(), and
fputs().

后退 | 起点 | 前进
ftruncate | 上一级 | glob


glob

(PHP 4 CVS only)

glob -- Find pathnames matching a pattern

Description

array glob ( string pattern [, int flags])

The glob() function searches for all the pathnames matching pattern according to the rules used by the shell. No tilde expansion or parameter substitution is done.

Returns an array containing the matched files/directories or FALSE on error.

注: This function is disabled in safe mode and therefore will always return FALSE in safe mode.

例子 1. Convenient way how glob() can replace opendir() and friends.

foreach (glob("*.txt") as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
}

This could result in the following output:

funclist.txt size 44686
funcsummary.txt size 267625
quickref.txt size 137820

See also opendir(),
readdir() and
closedir().

后退 | 起点 | 前进
fwrite | 上一级 | is_dir


is_dir

(PHP 3, PHP 4 )

is_dir -- Tells whether the filename is a directory

Description

bool is_dir ( string filename)

Returns TRUE if the filename exists and is a directory. If filename is a relative filename, it will be checked relative to the current working directory.

The results of this function are cached. See clearstatcache() for more details.

This function will not work on remote files; the file to be examined must be accessible via the server's filesystem.

See also chdir(), dir,
opendir(), is_file() and
is_link().

后退 | 起点 | 前进
glob | 上一级 | is_executable


is_executable

(PHP 3, PHP 4 )

is_executable -- Tells whether the filename is executable

Description

bool is_executable ( string filename)

Returns TRUE if the filename exists and is executable.

The results of this function are cached. See clearstatcache() for more details.

This function will not work on remote files; the file to be examined must be accessible via the server's filesystem.

See also is_file() and is_link().

后退 | 起点 | 前进
is_dir | 上一级 | is_file


is_file

(PHP 3, PHP 4 )

is_file -- Tells whether the filename is a regular file

Description

bool is_file ( string filename)

Returns TRUE if the filename exists and is a regular file.

The results of this function are cached. See clearstatcache() for more details.

This function will not work on remote files; the file to be examined must be accessible via the server's filesystem.

See also is_dir() and is_link().

后退 | 起点 | 前进
is_executable | 上一级 | is_link


is_link

(PHP 3, PHP 4 )

is_link -- Tells whether the filename is a symbolic link

Description

bool is_link ( string filename)

Returns TRUE if the filename exists and is a symbolic link.

The results of this function are cached. See clearstatcache() for more details.

See also is_dir(), is_file(), and readlink().

This function will not work on remote files; the file to be examined must be accessible via the server's filesystem.

后退 | 起点 | 前进
is_file | 上一级 | is_readable


is_readable

(PHP 3, PHP 4 )

is_readable -- Tells whether the filename is readable

Description

bool is_readable ( string filename)

Returns TRUE if the filename exists and is readable.

Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account.

The results of this function are cached. See clearstatcache() for more details.

This function will not work on remote files; the file to be examined must be accessible via the server's filesystem.

See also is_writable().

后退 | 起点 | 前进
is_link | 上一级 | is_uploaded_file


is_uploaded_file

(PHP 3>= 3.0.17, PHP 4 >= 4.0.3)

is_uploaded_file -- Tells whether the file was uploaded via HTTP POST

Description

bool is_uploaded_file ( string filename)

Returns TRUE if the file named by filename was uploaded via HTTP POST. This is useful to help ensure that a malicious user hasn't tried to trick the script into working on files upon which it should not be working--for instance, /etc/passwd.

This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.

is_uploaded_file() is available only in versions of PHP 3 after PHP 3.0.16, and in versions of PHP 4 after 4.0.2. If you are stuck using an earlier version, you can use the following function to help protect yourself:

注: The following example will not work in versions of PHP 4 after 4.0.2. It depends on internal functionality of PHP which changed after that version.

<?php
/* Userland test for uploaded file. */
function is_uploaded_file($filename) {
    if (!$tmp_file = get_cfg_var('upload_tmp_dir')) {
        $tmp_file = dirname(tempnam('', ''));
    }
    $tmp_file .= '/' . basename($filename);
    /* User might have trailing slash in php.ini... */
    return (ereg_replace('/+', '/', $tmp_file) == $filename);
}

/* This is how to use it, since you also don't have
 * move_uploaded_file() in these older versions: */
if (is_uploaded_file($HTTP_POST_FILES['userfile'])) {
    copy($HTTP_POST_FILES['userfile'], "/place/to/put/uploaded/file");
} else {
    echo "Possible file upload attack: filename '$HTTP_POST_FILES[userfile]'.";
}
?>

See also move_uploaded_file(), and the section Handling file uploads for a simple usage example.

后退 | 起点 | 前进
is_readable | 上一级 | is_writable


is_writable

(PHP 4 )

is_writable -- Tells whether the filename is writable

Description

bool is_writable ( string filename)

Returns TRUE if the filename exists and is writable. The filename argument may be a directory name allowing you to check if a directory is writeable.

Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account.

The results of this function are cached. See clearstatcache() for more details.

This function will not work on remote files; the file to be examined must be accessible via the server's filesystem.

See also is_readable().

后退 | 起点 | 前进
is_uploaded_file | 上一级 | is_writeable


is_writeable

(PHP 3, PHP 4 )

is_writeable -- Tells whether the filename is writable

Description

bool is_writeable ( string filename)

This is an alias for is_writable()

后退 | 起点 | 前进
is_writable | 上一级 | link


link

(PHP 3, PHP 4 )

link -- Create a hard link

Description

int link ( string target, string link)

link() creates a hard link.

See also the symlink() to create soft links, and readlink() along with linkinfo().

后退 | 起点 | 前进
is_writeable | 上一级 | linkinfo


linkinfo

(PHP 3, PHP 4 )

linkinfo -- Gets information about a link

Description

int linkinfo ( string path)

linkinfo() returns the st_dev field of the UNIX C stat structure returned by the lstat system call. This function is used to verify if a link (pointed to by path) really exists (using the same method as the S_ISLNK macro defined in stat.h). Returns 0 or FALSE in case of error.

See also symlink(), link(), and readlink().

后退 | 起点 | 前进
link | 上一级 | lstat


lstat

(PHP 3>= 3.0.4, PHP 4 )

lstat -- Gives information about a file or symbolic link

Description

array lstat ( string filename)

Gathers the statistics of the file or symbolic link named by filename. This function is identical to the stat() function except that if the filename parameter is a symbolic link, the status of the symbolic link is returned, not the status of the file pointed to by the symbolic link.

Returns an array with the statistics of the file with the following elements:

  1. device

  2. inode

  3. inode protection mode

  4. number of links

  5. user id of owner

  6. group id owner

  7. device type if inode device *

  8. size in bytes

  9. time of last access

  10. time of last modification

  11. time of last change

  12. blocksize for filesystem I/O *

  13. number of blocks allocated

* - only valid on systems supporting the st_blksize type--other systems (i.e. Windows) return -1.

lstat() cannot be used on remote files.

The results of this function are cached. See clearstatcache() for more details.

后退 | 起点 | 前进
linkinfo | 上一级 | mkdir


mkdir

(PHP 3, PHP 4 )

mkdir -- Makes directory

Description

int mkdir ( string pathname, int mode)

Attempts to create the directory specified by pathname.

Note that you probably want to specify the mode as an octal number, which means it should have a leading zero. The mode is also modified by the current umask, which you can change using umask().

mkdir ("/path/to/my/dir", 0700);

如果成功则返回 TRUE，失败则返回 FALSE。

See also rmdir().

后退 | 起点 | 前进
lstat | 上一级 | move_uploaded_file


move_uploaded_file

(PHP 4 >= 4.0.3)

move_uploaded_file -- Moves an uploaded file to a new location

Description

bool move_uploaded_file ( string filename, string destination)

This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.

If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.

If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued.

This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.

注: 当 安全模式（safe mode） 被激活，PHP 将检查您将要操作的文件或者目录与正在执行的脚本是否有相同的 UID。

注: move_uploaded_file() is not affected by the normal safe-mode UID-restrictions. This is not unsafe because move_uploaded_file() only operates on files uploaded via PHP.

警告

If the destination file already exists, it will be overwritten.

See also is_uploaded_file(), and the section Handling file uploads for a simple usage example.

后退 | 起点 | 前进
mkdir | 上一级 | parse_ini_file


parse_ini_file

(PHP 4 )

parse_ini_file -- Parse a configuration file

Description

array parse_ini_file ( string filename [, bool process_sections])

parse_ini_file() loads in the ini file specified in filename, and returns the settings in it in an associative array. By setting the last process_sections parameter to TRUE, you get a multidimensional array, with the section names and settings included. The default for process_sections is FALSE

注: This function has nothing to do with the php.ini file. It is already processed, the time you run your script. This function can be used to read in your own application's configuration files.

注: If a value in the ini file contains any non-alphanumeric characters it needs to be enclosed in double-quotes (").

注: Since PHP 4.2.1 this function is also affected by safe_mode and open_basedir.

The structure of the ini file is similar to that of the php.ini's.

警告

If the ini file you are trying to parse is malformed, PHP will exit.

例子 1. Contents of sample.ini

; This is a sample configuration file
; Comments start with ';', as in php.ini

[first_section]
one = 1
five = 5

[second_section]
path = /usr/local/bin
URL = "http://www.example.com/~username"

例子 2. parse_ini_file() example

<?php

// Parse without sections
$ini_array = parse_ini_file("sample.ini");
print_r($ini_array);

// Parse with sections
$ini_array = parse_ini_file("sample.ini", TRUE);
print_r($ini_array);

?>

Would produce:

Array
(
    [one] => 1
    [five] => 5
    [path] => /usr/local/bin
    [URL] => http://www.example.com/~username
)
Array
(
    [first_section] => Array
        (
            [one] => 1
            [five] => 5
        )

    [second_section] => Array
        (
            [path] => /usr/local/bin
            [URL] => http://www.example.com/~username
        )

)

后退 | 起点 | 前进
move_uploaded_file | 上一级 | pathinfo


pathinfo

(PHP 4 >= 4.0.3)

pathinfo -- Returns information about a file path

Description

array pathinfo ( string path)

pathinfo() returns an associative array containing information about path. The following array elements are returned: dirname, basename and extension.

例子 1. pathinfo() Example

<?php

$path_parts = pathinfo("/www/htdocs/index.html");

echo $path_parts["dirname"] . "\n";
echo $path_parts["basename"] . "\n";
echo $path_parts["extension"] . "\n";

?>

Would produce:

/www/htdocs
index.html
html

See also dirname(),
basename(), parse_url()
and realpath().

后退 | 起点 | 前进
parse_ini_file | 上一级 | pclose


pclose

(PHP 3, PHP 4 )

pclose -- Closes process file pointer

Description

int pclose ( int fp)

Closes a file pointer to a pipe opened by popen().

The file pointer must be valid, and must have been returned by a successful call to popen().

Returns the termination status of the process that was run.

See also popen().

后退 | 起点 | 前进
pathinfo | 上一级 | popen


popen

(PHP 3, PHP 4 )

popen -- Opens process file pointer

Description

int popen ( string command, string mode)

Opens a pipe to a process executed by forking the command given by command.

Returns a file pointer identical to that returned by fopen(), except that it is unidirectional (may only be used for reading or writing) and must be closed with pclose(). This pointer may be used with fgets(), fgetss(), and fputs().

If an error occurs, returns FALSE.

$fp = popen ("/bin/ls", "r");

注: If the command to be executed could not be found, a valid resource is returned. This may seem odd, but makes sense; it allows you to access any error message returned by the shell:

<?php
error_reporting(E_ALL);

/* Add redirection so we can get stderr. */
$fp = popen('/path/to/spooge 2>&1', 'r');
echo "'$fp'; " . gettype($fp) . "\n";
$read = fread($fp, 2096);
echo $read;
pclose($fp);
?>

See also pclose().

后退 | 起点 | 前进
pclose | 上一级 | readfile


readfile

(PHP 3, PHP 4 )

readfile -- Outputs a file

Description

int readfile ( string filename [, int use_include_path])

Reads a file and writes it to standard output.

Returns the number of bytes read from the file. If an error occurs, FALSE is returned and unless the function was called as @readfile, an error message is printed.

If filename begins with "http://" (not case sensitive), an HTTP 1.0 connection is opened to the specified server and the text of the response is written to standard output.

Versions prior to PHP 4.0.5 do not handle HTTP redirects. Because of this, directories must include trailing slashes.

If filename begins with "ftp://" (not case sensitive), an ftp connection to the specified server is opened and the requested file is written to standard output. If the server does not support passive mode ftp, this will fail.

If filename begins with neither of these strings, the file will be opened from the filesystem and its contents written to standard output.

You can use the optional second parameter and set it to "1", if you want to search for the file in the include_path, too.

See also fpassthru(),
file(), fopen(),
include(), require(), and
virtual().

后退 | 起点 | 前进
popen | 上一级 | readlink


readlink

(PHP 3, PHP 4 )

readlink -- Returns the target of a symbolic link

Description

string readlink ( string path)

readlink() does the same as the readlink C function and returns the contents of the symbolic link path or 0 in case of error.

See also is_link(),
symlink(), and
linkinfo().

后退 | 起点 | 前进
readfile | 上一级 | realpath


realpath

(PHP 4 )

realpath -- Returns canonicalized absolute pathname

Description

string realpath ( string path)

realpath() expands all symbolic links and resolves references to '/./', '/../' and extra '/' characters in the input path and return the canonicalized absolute pathname. The resulting path will have no symbolic link, '/./' or '/../' components.

realpath() returns FALSE on failure, e.g. if the file does not exists.

例子 1. realpath() example

$real_path = realpath ("../../index.php");

See also: basename(),
dirname(), and
pathinfo().

后退 | 起点 | 前进
readlink | 上一级 | rename


rename

(PHP 3, PHP 4 )

rename -- Renames a file

Description

bool rename ( string oldname, string newname)

Attempts to rename oldname to newname.

如果成功则返回 TRUE，失败则返回 FALSE。

例子 1. Example with rename()

<?php
  rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt");
?>

后退 | 起点 | 前进
realpath | 上一级 | rewind


rewind

(PHP 3, PHP 4 )

rewind -- Rewind the position of a file pointer

Description

int rewind ( int fp)

Sets the file position indicator for fp to the beginning of the file stream.

If an error occurs, returns 0, otherwise it returns 1.

The file pointer must be valid, and must point to a file successfully opened by fopen().

注: If you have opened the file in append ("a") mode, any data you write to the file will always be appended, regardless of the file position.

See also fseek() and ftell().

后退 | 起点 | 前进
rename | 上一级 | rmdir


rmdir

(PHP 3, PHP 4 )

rmdir -- Removes directory

Description

bool rmdir ( string dirname)

Attempts to remove the directory named by dirname. The directory must be empty, and the relevant permissions must permit this. 如果成功则返回 TRUE，失败则返回 FALSE。

See also mkdir() and unlink().

后退 | 起点 | 前进
rewind | 上一级 | set_file_buffer


set_file_buffer

(PHP 3>= 3.0.8, PHP 4 >= 4.0.1)

set_file_buffer -- Sets file buffering on the given file pointer

Description

int set_file_buffer ( int fp, int buffer)

Output using fwrite() is normally buffered at 8K. This means that if there are two processes wanting to write to the same output stream (a file), each is paused after 8K of data to allow the other to write. set_file_buffer() sets the buffering for write operations on the given filepointer fp to buffer bytes. If buffer is 0 then write operations are unbuffered. This ensures that all writes with fwrite() are completed before other processes are allowed to write to that output stream.

The function returns 0 on success, or EOF if the request cannot be honored.

The following example demonstrates how to use set_file_buffer() to create an unbuffered stream.

例子 1. set_file_buffer() example

$fp=fopen($file, "w");
if($fp){
  set_file_buffer($fp, 0);
  fputs($fp, $output);
  fclose($fp);
}

See also fopen(), fwrite().

后退 | 起点 | 前进
rmdir | 上一级 | stat


stat

(PHP 3, PHP 4 )

stat -- Gives information about a file

Description

array stat ( string filename)

Gathers the statistics of the file named by filename.

Returns an array with the statistics of the file with the following elements:

  1. device

  2. inode

  3. inode protection mode

  4. number of links

  5. user id of owner

  6. group id owner

  7. device type if inode device *

  8. size in bytes

  9. time of last access

  10. time of last modification

  11. time of last change

  12. blocksize for filesystem I/O *

  13. number of blocks allocated

* - only valid on systems supporting the st_blksize type--other systems (i.e. Windows) return -1.

Returns FALSE in case of error.

stat() cannot be used on remote files.

The results of this function are cached. See clearstatcache() for more details.

后退 | 起点 | 前进
set_file_buffer | 上一级 | symlink


symlink

(PHP 3, PHP 4 )

symlink -- Creates a symbolic link

Description

int symlink ( string target, string link)

symlink() creates a symbolic link from the existing target with the specified name link.

See also link() to create hard links, and readlink() along with linkinfo().

后退 | 起点 | 前进
stat | 上一级 | tempnam


tempnam

(PHP 3, PHP 4 )

tempnam -- Create file with unique file name

Description

string tempnam ( string dir, string prefix)

Creates a file with a unique filename in the specified directory. If the directory does not exist, tempnam() may generate a file in the system's temporary directory, and return the name of that.

Prior to PHP 4.0.6, the behaviour of the tempnam() function was system dependent. On Windows the TMP environment variable will override the dir parameter, on Linux the TMPDIR environment variable has precedence, while SVR4 will always use your dir parameter if the directory it points to exists. Consult your system documentation on the tempnam(3) function if in doubt.

Returns the new temporary filename, or the FALSE string on failure.

例子 1. tempnam() example

$tmpfname = tempnam ("/tmp", "FOO");

$fp = fopen($tmpfname, "w");
fwrite($fp, "writing to tempfile");
fclose($fp);

// do here something

unlink($tmpfname);

注: This function's behavior changed in 4.0.3. The temporary file is also created to avoid a race condition where the file might appear in the filesystem between the time the string was generated and before the the script gets around to creating the file. Note, that you need to remove the file in case you need it no more, it is not done automatically.

See also tmpfile() and unlink().

后退 | 起点 | 前进
symlink | 上一级 | tmpfile


tmpfile

(PHP 3>= 3.0.13, PHP 4 )

tmpfile -- Creates a temporary file

Description

int tmpfile ( void)

Creates a temporary file with an unique name in write mode, returning a file handle similar to the one returned by fopen(). The file is automatically removed when closed (using fclose()), or when the script ends.

For details, consult your system documentation on the tmpfile(3) function, as well as the stdio.h header file.

例子 1. tmpfile() example

$temp = tmpfile();
fwrite($temp, "writing to tempfile");
fclose($temp); // this removes the file

See also tempnam().

后退 | 起点 | 前进
tempnam | 上一级 | touch


touch

(PHP 3, PHP 4 )

touch -- Sets access and modification time of file

Description

int touch ( string filename [, int time [, int atime]])

Attempts to set the access and modification time of the file named by filename to the value given by time. If the option time is not given, uses the present time. This is equivalent to what utime (sometimes referred to as utimes) does. If the third option atime is present, the access time of the given filename is also modified.

If the file does not exist, it is created.

如果成功则返回 TRUE，失败则返回 FALSE。

例子 1. touch() example

if (touch ($FileName)) {
    print "$FileName modification time has been
           changed to todays date and time";
} else {
    print "Sorry Could Not change modification time of $FileName";
}

后退 | 起点 | 前进
tmpfile | 上一级 | umask


umask

(PHP 3, PHP 4 )

umask -- Changes the current umask

Description

int umask ( int mask)

umask() sets PHP's umask to mask & 0777 and returns the old umask. When PHP is being used as a server module, the umask is restored when each request is finished.

umask() without arguments simply returns the current umask.

后退 | 起点 | 前进
touch | 上一级 | unlink


unlink

(PHP 3, PHP 4 )

unlink -- Deletes a file

Description

int unlink ( string filename)

Deletes filename. Similar to the Unix C unlink() function.

如果成功则返回 TRUE，失败则返回 FALSE。

See also rmdir() for removing directories.

后退 | 起点 | 前进
umask | 上一级 | Forms Data Format functions


Forms Data Format functions

PHP 手册
后退 前进

XXXI. Forms Data Format functions

介绍

Forms Data Format (FDF) is a format for handling forms within PDF documents. You should read the documentation at http://partners.adobe.com/asn/developer/acrosdk/forms.html for more information on what FDF is and how it is used in general.

The general idea of FDF is similar to HTML forms. The difference is basically the format how data is transmitted to the server when the submit button is pressed (this is actually the Form Data Format) and the format of the form itself (which is the Portable Document Format, PDF). Processing the FDF data is one of the features provided by the fdf functions. But there is more. One may as well take an existing PDF form and populated the input fields with data without modifying the form itself. In such a case one would create a FDF document (fdf_create()) set the values of each input field (fdf_set_value()) and associate it with a PDF form (fdf_set_file()). Finally it has to be sent to the browser with MimeType application/vnd.fdf. The Acrobat reader plugin of your browser recognizes the MimeType, reads the associated PDF form and fills in the data from the FDF document.

If you look at an FDF-document with a text editor you will find a catalogue object with the name FDF. Such an object may contain a number of entries like Fields, F, Status etc.. The most commonly used entries are Fields which points to a list of input fields, and F which contains the filename of the PDF-document this data belongs to. Those entries are referred to in the FDF documentation as /F-Key or /Status-Key. Modifying this entries is done by functions like fdf_set_file() and fdf_set_status(). Fields are modified with fdf_set_value(), fdf_set_opt() etc..

需求

You must download the FDF toolkit from http://partners.adobe.com/asn/developer/acrosdk/forms.html.

安装

You must compile PHP with --with-fdftk[=DIR].

注: If you run into problems configuring PHP with fdftk support, check whether the header file FdfTk.h and the library libFdfTk.so are at the right place. They should be in fdftk-dir/include and fdftk-dir/lib. This will not be the case if you just unpack the FdfTk distribution.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

FDFValue (integer)

FDFStatus (integer)

FDFFile (integer)

FDFID (integer)

FDFFf (integer)

FDFSetFf (integer)

FDFClearFf (integer)

FDFFlags (integer)

FDFSetF (integer)

FDFClrF (integer)

FDFAP (integer)

FDFAS (integer)

FDFAction (integer)

FDFAA (integer)

FDFAPRef (integer)

FDFIF (integer)

FDFEnter (integer)

FDFExit (integer)

FDFDown (integer)

FDFUp (integer)

FDFFormat (integer)

FDFValidate (integer)

FDFKeystroke (integer)

FDFCalculate (integer)

范例

The following examples shows just the evaluation of form data.

例子 1. Evaluating a FDF document

<?php
// Save the FDF data into a temp file
$fdffp = fopen("test.fdf", "w");
fwrite($fdffp, $HTTP_FDF_DATA, strlen($HTTP_FDF_DATA));
fclose($fdffp);

// Open temp file and evaluate data
// The pdf form contained several input text fields with the names
// volume, date, comment, publisher, preparer, and two checkboxes
// show_publisher and show_preparer.
$fdf = fdf_open("test.fdf");
$volume = fdf_get_value($fdf, "volume");
echo "The volume field has the value '<B>$volume</B>'<BR>";

$date = fdf_get_value($fdf, "date");
echo "The date field has the value '<B>$date</B>'<BR>";

$comment = fdf_get_value($fdf, "comment");
echo "The comment field has the value '<B>$comment</B>'<BR>";

if(fdf_get_value($fdf, "show_publisher") == "On") {
  $publisher = fdf_get_value($fdf, "publisher");
  echo "The publisher field has the value '<B>$publisher</B>'<BR>";
} else
  echo "Publisher shall not be shown.<BR>";

if(fdf_get_value($fdf, "show_preparer") == "On") {
  $preparer = fdf_get_value($fdf, "preparer");
  echo "The preparer field has the value '<B>$preparer</B>'<BR>";
} else
  echo "Preparer shall not be shown.<BR>";
fdf_close($fdf);
?>

目录
fdf_add_template — Adds a template into the FDF document
fdf_close — Close an FDF document
fdf_create — Create a new FDF document
fdf_get_file — Get the value of the /F key
fdf_get_status — Get the value of the /STATUS key
fdf_get_value — Get the value of a field
fdf_next_field_name — Get the next field name
fdf_open — Open a FDF document
fdf_save — Save a FDF document
fdf_set_ap — Set the appearance of a field
fdf_set_encoding — Sets FDF character encoding
fdf_set_file — Set the value of the /F key
fdf_set_flags — Sets a flag of a field
fdf_set_javascript_action — Sets an javascript action of a field
fdf_set_opt — Sets an option of a field
fdf_set_status — Set the value of the /STATUS key
fdf_set_submit_form_action — Sets a submit form action of a field
fdf_set_value — Set the value of a field

后退 | 起点 | 前进
unlink | 上一级 | fdf_add_template


fdf_add_template

(PHP 3>= 3.0.13, PHP 4 )

fdf_add_template -- Adds a template into the FDF document

Description

bool fdf_add_template ( int fdfdoc, int newpage, string filename, string template, int rename)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
Forms Data Format functions | 上一级 | fdf_close


fdf_close

(PHP 3>= 3.0.6, PHP 4 )

fdf_close -- Close an FDF document

Description

bool fdf_close ( int fdf_document)

The fdf_close() function closes the FDF document.

See also fdf_open().

后退 | 起点 | 前进
fdf_add_template | 上一级 | fdf_create


fdf_create

(PHP 3>= 3.0.6, PHP 4 )

fdf_create -- Create a new FDF document

Description

int fdf_create ( void)

The fdf_create() creates a new FDF document. This function is needed if one would like to populate input fields in a PDF document with data.

例子 1. Populating a PDF document

<?php
$outfdf = fdf_create();
fdf_set_value($outfdf, "volume", $volume, 0);

fdf_set_file($outfdf, "http:/testfdf/resultlabel.pdf");
fdf_save($outfdf, "outtest.fdf");
fdf_close($outfdf);
Header("Content-type: application/vnd.fdf");
$fp = fopen("outtest.fdf", "r");
fpassthru($fp);
unlink("outtest.fdf");
?>

See also fdf_close(),
         fdf_save(),
         fdf_open().

后退 | 起点 | 前进
fdf_close | 上一级 | fdf_get_file


fdf_get_file

(PHP 3>= 3.0.6, PHP 4 )

fdf_get_file -- Get the value of the /F key

Description

string fdf_get_file ( int fdf_document)

The fdf_set_file() returns the value of the /F key.

See also fdf_set_file().

后退 | 起点 | 前进
fdf_create | 上一级 | fdf_get_status


fdf_get_status

(PHP 3>= 3.0.6, PHP 4 )

fdf_get_status -- Get the value of the /STATUS key

Description

string fdf_get_status ( int fdf_document)

The fdf_get_status() returns the value of the /STATUS key.

See also fdf_set_status().

后退 | 起点 | 前进
fdf_get_file | 上一级 | fdf_get_value


fdf_get_value

(PHP 3>= 3.0.6, PHP 4 )

fdf_get_value -- Get the value of a field

Description

string fdf_get_value ( int fdf_document, string fieldname)

The fdf_get_value() function returns the value of a field.

See also fdf_set_value().

后退 | 起点 | 前进
fdf_get_status | 上一级 | fdf_next_field_name


fdf_next_field_name

(PHP 3>= 3.0.6, PHP 4 )

fdf_next_field_name -- Get the next field name

Description

string fdf_next_field_name ( int fdf_document [, string fieldname])

The fdf_next_field_name() function returns the name of the field after the field in fieldname or the field name of the first field if the second parameter is NULL.

See also fdf_set_value(), fdf_get_value().

后退 | 起点 | 前进
fdf_get_value | 上一级 | fdf_open


fdf_open

(PHP 3>= 3.0.6, PHP 4 )

fdf_open -- Open a FDF document

Description

int fdf_open ( string filename)

The fdf_open() function opens a file with form data. This file must contain the data as returned from a PDF form. Currently, the file has to be created 'manually' by using fopen() and writing the content of HTTP_FDF_DATA with fwrite() into it. A mechanism like for HTML form data where for each input field a variable is created does not exist.

例子 1. Accessing the form data

<?php
// Save the FDF data into a temp file
$fdffp = fopen("test.fdf", "w");
fwrite($fdffp, $HTTP_FDF_DATA, strlen($HTTP_FDF_DATA));
fclose($fdffp);

// Open temp file and evaluate data
$fdf = fdf_open("test.fdf");
...
fdf_close($fdf);
?>

See also fdf_close().

后退 | 起点 | 前进
fdf_next_field_name | 上一级 | fdf_save


fdf_save

(PHP 3>= 3.0.6, PHP 4 )

fdf_save -- Save a FDF document

Description

int fdf_save ( string filename)

The fdf_save() function saves a FDF document. The FDF Toolkit provides a way to output the document to stdout if the parameter filename is '.'. This does not work if PHP is used as an apache module. In such a case one will have to write to a file and use e.g. fpassthru() to output it.

See also fdf_close() and example for fdf_create().

后退 | 起点 | 前进
fdf_open | 上一级 | fdf_set_ap


fdf_set_ap

(PHP 3>= 3.0.6, PHP 4 )

fdf_set_ap -- Set the appearance of a field

Description

bool fdf_set_ap ( int fdf_document, string field_name, int face, string filename, int page_number)

The fdf_set_ap() function sets the appearance of a field (i.e. the value of the /AP key). The possible values of face are 1=FDFNormalAP, 2=FDFRolloverAP, 3=FDFDownAP.

后退 | 起点 | 前进
fdf_save | 上一级 | fdf_set_encoding


fdf_set_encoding

(PHP 4 >= 4.1.0)

fdf_set_encoding -- Sets FDF character encoding

Description

bool fdf_set_encoding ( int fdf_document, string encoding)

fdf_set_encoding() sets the character encoding in FDF document fdf_document. encoding should be the valid encoding name. The valid encoding name in Acrobat 5.0 are "Shift-JIS", "UHC", "GBK","BigFive".

The fdf_set_encoding() is available in PHP 4.1.0 or later.

后退 | 起点 | 前进
fdf_set_ap | 上一级 | fdf_set_file


fdf_set_file

(PHP 3>= 3.0.6, PHP 4 )

fdf_set_file -- Set the value of the /F key

Description

bool fdf_set_file ( int fdf_document, string filename)

The fdf_set_file() sets the value of the /F key. The /F key is just a reference to a PDF form which is to be populated with data. In a web environment it is a URL (e.g. http:/testfdf/resultlabel.pdf).

See also fdf_get_file() and example for fdf_create().

后退 | 起点 | 前进
fdf_set_encoding | 上一级 | fdf_set_flags


fdf_set_flags

(PHP 4 >= 4.0.2)

fdf_set_flags -- Sets a flag of a field

Description

bool fdf_set_flags ( int fdf_document, string fieldname, int whichFlags, int newFlags)

The fdf_set_flags() sets certain flags of the given field fieldname.

See also fdf_set_opt().

后退 | 起点 | 前进
fdf_set_file | 上一级 | fdf_set_javascript_action


fdf_set_javascript_action

(PHP 4 >= 4.0.2)

fdf_set_javascript_action -- Sets an javascript action of a field

Description

bool fdf_set_javascript_action ( int fdf_document, string fieldname, int trigger, string script)

fdf_set_javascript_action() sets a javascript action for the given field fieldname.

See also fdf_set_submit_form_action().

后退 | 起点 | 前进
fdf_set_flags | 上一级 | fdf_set_opt


fdf_set_opt

(PHP 4 >= 4.0.2)

fdf_set_opt -- Sets an option of a field

Description

bool fdf_set_opt ( int fdf_document, string fieldname, int element, string str1, string str2)

The fdf_set_opt() sets options of the given field fieldname.

See also fdf_set_flags().

后退 | 起点 | 前进
fdf_set_javascript_action | 上一级 | fdf_set_status


fdf_set_status

(PHP 3>= 3.0.6, PHP 4 )

fdf_set_status -- Set the value of the /STATUS key

Description

bool fdf_set_status ( int fdf_document, string status)

The fdf_set_status() sets the value of the /STATUS key.

See also fdf_get_status().

后退 | 起点 | 前进
fdf_set_opt | 上一级 | fdf_set_submit_form_action


fdf_set_submit_form_action

(PHP 4 >= 4.0.2)

fdf_set_submit_form_action -- Sets a submit form action of a field

Description

bool fdf_set_submit_form_action ( int fdf_document, string fieldname, int trigger, string script, int flags)

The fdf_set_submit_form_action() sets a submit form action for the given field fieldname.

See also fdf_set_javascript_action().

后退 | 起点 | 前进
fdf_set_status | 上一级 | fdf_set_value


fdf_set_value

(PHP 3>= 3.0.6, PHP 4 )

fdf_set_value -- Set the value of a field

Description

bool fdf_set_value ( int fdf_document, string fieldname, string value, int isName)

The fdf_set_value() function sets the value of a field. The last parameter determines if the field value is to be converted to a PDF Name (isName = 1) or set to a PDF String (isName = 0).

See also fdf_get_value().

后退 | 起点 | 前进
fdf_set_submit_form_action | 上一级 | FriBiDi functions


FriBiDi functions

PHP 手册
后退 前进

XXXII. FriBiDi functions

介绍

需求

安装

运行时配置

资源类型

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

FRIBIDI_CHARSET_UTF8 (integer)

FRIBIDI_CHARSET_8859_6 (integer)

FRIBIDI_CHARSET_8859_8 (integer)

FRIBIDI_CHARSET_CP1255 (integer)

FRIBIDI_CHARSET_CP1256 (integer)

FRIBIDI_CHARSET_ISIRI_3342 (integer)

目录
fribidi_log2vis — Convert a logical string to a visual one

后退 | 起点 | 前进
fdf_set_value | 上一级 | fribidi_log2vis


fribidi_log2vis

(PHP 4 >= 4.0.4)

fribidi_log2vis -- Convert a logical string to a visual one

Description

string fribidi_log2vis ( string str, string direction, int charset)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
FriBiDi functions | 上一级 | FTP functions


FTP functions

PHP 手册
后退 前进

XXXIII. FTP functions

介绍

The functions in this extension implement client access to file servers speaking the File Transfer Protocol (FTP) as defined in http://www.faqs.org/rfcs/rfc959.html.

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

In order to use FTP functions with your PHP configuration, you should add the --enable-ftp option when installing PHP 4 or --with-ftp when using PHP 3.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

This extension uses one resource type, which is the link identifier of the FTP connection.

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

FTP_ASCII (integer)

FTP_TEXT (integer)

FTP_BINARY (integer)

FTP_IMAGE (integer)

FTP_TIMEOUT_SEC (integer)

See ftp_set_option() for information.

The following constants were introduced in PHP 4.3.0.

FTP_AUTOSEEK (integer)

See ftp_set_option() for information.

FTP_AUTORESUME (integer)

Automatically determine resume position and start position for GET and PUT requests (only works if FTP_AUTOSEEK is enabled)

FTP_FAILED (integer)

Asynchronous transfer has failed

FTP_FINISHED (integer)

Asynchronous transfer has finished

FTP_MOREDATA (integer)

Asynchronous transfer is still active

范例

例子 1. FTP example

<?php
// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// check connection
if ((!$conn_id) || (!$login_result)) {
        echo "FTP connection has failed!";
        echo "Attempted to connect to $ftp_server for user $ftp_user_name";
        die;
    } else {
        echo "Connected to $ftp_server, for user $ftp_user_name";
    }

// upload the file
$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY);

// check upload status
if (!$upload) {
        echo "FTP upload has failed!";
    } else {
        echo "Uploaded $source_file to $ftp_server as $destination_file";
    }

// close the FTP stream
ftp_close($conn_id);
?>

目录
ftp_async_continue — Continues retrieving/sending a file asynchronously
ftp_async_fget — Retrieves a file from the FTP server asynchronously and writes it to an open file
ftp_async_fput — Stores a file from an open file to the FTP server asynchronously
ftp_async_get — Retrieves a file from the FTP server asynchronously and writes it to a local file
ftp_async_put — Stores a file on the FTP server asynchronously
ftp_cdup — Changes to the parent directory
ftp_chdir — Changes directories on a FTP server
ftp_close — Closes an FTP connection
ftp_connect — Opens an FTP connection
ftp_delete — Deletes a file on the FTP server
ftp_exec — Requests execution of a program on the FTP server
ftp_fget — Downloads a file from the FTP server and saves to an open file
ftp_fput — Uploads from an open file to the FTP server
ftp_get_option — Retrieves various runtime behaviours of the current FTP stream
ftp_get — Downloads a file from the FTP server
ftp_login — Logs in to an FTP connection
ftp_mdtm — Returns the last modified time of the given file
ftp_mkdir — Creates a directory
ftp_nlist — Returns a list of files in the given directory
ftp_pasv — Turns passive mode on or off
ftp_put — Uploads a file to the FTP server
ftp_pwd — Returns the current directory name
ftp_quit — Closes an FTP connection
ftp_rawlist — Returns a detailed list of files in the given directory
ftp_rename — Renames a file on the FTP server
ftp_rmdir — Removes a directory
ftp_set_option — Set miscellaneous runtime FTP options
ftp_site — Sends a SITE command to the server
ftp_size — Returns the size of the given file
ftp_systype — Returns the system type identifier of the remote FTP server

后退 | 起点 | 前进
fribidi_log2vis | 上一级 | ftp_async_continue


ftp_async_continue

(PHP 4 CVS only)

ftp_async_continue -- Continues retrieving/sending a file asynchronously

Description

bool ftp_async_continue ( resource ftp_stream)

Continues retrieving/sending a file asynchronously

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

后退 | 起点 | 前进
FTP functions | 上一级 | ftp_async_fget


ftp_async_fget

(PHP 4 CVS only)

ftp_async_fget -- Retrieves a file from the FTP server asynchronously and writes it to an open file

Description

bool ftp_async_fget ( resource ftp_stream, resource fp, string remote_file, int mode [, int resumepos])

ftp_async_fget() retrieves remote_file from the FTP server, and writes it to the given file pointer, fp. The transfer mode specified must be either FTP_ASCII or FTP_BINARY. The difference between this function and the ftp_fget() is that this function retrieves the file asynchronously, so your program can perform other operations while the file is being downloaded.

Returns TRUE on success or FALSE on error.

See also ftp_async_get().

后退 | 起点 | 前进
ftp_async_continue | 上一级 | ftp_async_fput


ftp_async_fput

(PHP 4 CVS only)

ftp_async_fput -- Stores a file from an open file to the FTP server asynchronously

Description

bool ftp_async_fput ( resource ftp_stream, string remote_file, resource fp, int mode [, int startpos])

ftp_async_fput() uploads the data from the file pointer fp until it reaches the end of the file. The results are stored in remote_file on the FTP server. The transfer mode specified must be either FTP_ASCII or FTP_BINARY. The difference between this function and the ftp_fput() is that this function uploads the file asynchronously, so your program can perform other operations while the file is being downloaded.

Returns TRUE on success or FALSE on error.

See also ftp_async_put(),
ftp_async_continue(), ftp_put()
and ftp_fput().

后退 | 起点 | 前进
ftp_async_fget | 上一级 | ftp_async_get


ftp_async_get

(PHP 4 CVS only)

ftp_async_get -- Retrieves a file from the FTP server asynchronously and writes it to a local file

Description

bool ftp_async_get ( resource ftp_stream, string local_file, string remote_file, int mode [, int resumepos])

ftp_async_get() retrieves remote_file from the FTP server, and saves it to local_file locally. The transfer mode specified must be either FTP_ASCII or FTP_BINARY. The difference between this function and the ftp_get() is that this function retrieves the file asynchronously, so your program can perform other operations while the file is being downloaded.

Returns TRUE on success or FALSE on error.

例子 1. ftp_async_get() example

// Initate the download
$ret = ftp_async_get($my_connection, "test", "README", FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue downloading...
   $ret = ftp_async_continue ($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}

例子 2. Resuming a download with ftp_async_get()

// Initate
$ret = ftp_async_get ($my_connection, "test", "README", FTP_BINARY,
                      filesize("test"));
// OR: $ret = ftp_async_get ($my_connection, "test", "README",
//                           FTP_BINARY, FTP_AUTORESUME);
while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue downloading...
   $ret = ftp_async_continue ($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}

例子 3. Resuming a download at position 100 to a new file with ftp_async_get()

// Disable Autoseek
ftp_set_option ($my_connection, FTP_AUTOSEEK, FALSE);

// Initiate
$ret = ftp_async_get ($my_connection, "newfile", "README", FTP_BINARY, 100);
while ($ret == FTP_MOREDATA) {

   ...

   // Continue downloading...
   $ret = ftp_async_continue ($my_connection);
}

In the example above, "newfile" is 100 bytes smaller than "README" on the FTP server because we started reading at offset 100. If we have not have disabled FTP_AUTOSEEK, the first 100 bytes of newfile will be '\0'.

See also ftp_async_fget(),
ftp_async_continue(),
ftp_get() and ftp_fget().

后退 | 起点 | 前进
ftp_async_fput | 上一级 | ftp_async_put


ftp_async_put

(PHP 4 CVS only)

ftp_async_put -- Stores a file on the FTP server asynchronously

Description

bool ftp_async_put ( resource ftp_stream, string remote_file, string local_file, int mode [, int startpos])

ftp_async_put() stores local_file on the FTP server, as remote_file. The transfer mode specified must be either FTP_ASCII or FTP_BINARY. The difference between this function and the ftp_put() is that this function uploads the file asynchronously, so your program can perform other operations while the file is being downloaded.

Returns TRUE on success or FALSE on error.

例子 1. ftp_async_put() example

// Initiate the Upload
$ret = ftp_async_put($my_connection, "test.remote", "test.local", FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue uploading...
   $ret = ftp_async_continue ($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error uploading the file...";
   exit(1);
}

例子 2. Resuming an upload with ftp_async_put()

// Initiate
$ret = ftp_async_put ($my_connection, "test.remote", "test.local",
                      FTP_BINARY, ftp_size("test.remote"));
// OR: $ret = ftp_async_put ($my_connection, "test.remote", "test.local",
//                           FTP_BINARY, FTP_AUTORESUME);

while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue uploading...
   $ret = ftp_async_continue ($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error uploading the file...";
   exit(1);
}

See also ftp_async_fput(),
ftp_async_continue(), ftp_put()
and ftp_fput().

后退 | 起点 | 前进
ftp_async_get | 上一级 | ftp_cdup


ftp_cdup

(PHP 3>= 3.0.13, PHP 4 )

ftp_cdup -- Changes to the parent directory

Description

bool ftp_cdup ( resource ftp_stream)

Changes to the parent directory.

Returns TRUE on success or FALSE on error.

后退 | 起点 | 前进
ftp_async_put | 上一级 | ftp_chdir


ftp_chdir

(PHP 3>= 3.0.13, PHP 4 )

ftp_chdir -- Changes directories on a FTP server

Description

bool ftp_chdir ( resource ftp_stream, string directory)

Changes to the specified directory.

Returns TRUE on success or FALSE on error.

后退 | 起点 | 前进
ftp_cdup | 上一级 | ftp_close


ftp_close

(PHP 4 >= 4.2.0)

ftp_close -- Closes an FTP connection

Description

void ftp_close ( resource ftp_stream)

注: This function is only available in CVS.

ftp_close() closes ftp_stream and releases the resource. After calling this function, you can no longer use the FTP connection and must create a new one with ftp_connect().

后退 | 起点 | 前进
ftp_chdir | 上一级 | ftp_connect


ftp_connect

(PHP 3>= 3.0.13, PHP 4 )

ftp_connect -- Opens an FTP connection

Description

resource ftp_connect ( string host [, int port [, int timeout]])

Returns a FTP stream on success or FALSE on error.

ftp_connect() opens an FTP connection to the specified host. The port parameter specifies an alternate port to connect to. If it is omitted or set to zero, then the default FTP port, 21, will be used.

The timeout parameter specifies the timeout for all subsequent network operations. If omitted, the default value is 90 seconds. The timeout can be changed and queried at any time with ftp_set_option() and ftp_get_option().

注: This parameter is available beginning with PHP 4.2.0.

后退 | 起点 | 前进
ftp_close | 上一级 | ftp_delete


ftp_delete

(PHP 3>= 3.0.13, PHP 4 )

ftp_delete -- Deletes a file on the FTP server

Description

bool ftp_delete ( resource ftp_stream, string path)

ftp_delete() deletes the file specified by path from the FTP server.

Returns TRUE on success or FALSE on error.

后退 | 起点 | 前进
ftp_connect | 上一级 | ftp_exec


ftp_exec

(PHP 4 >= 4.0.3)

ftp_exec -- Requests execution of a program on the FTP server

Description

bool ftp_exec ( resource ftp_stream, string command)

Sends a SITE EXEC command request to the FTP server. Returns the output of the command if successful; otherwise returns FALSE.

后退 | 起点 | 前进
ftp_delete | 上一级 | ftp_fget


ftp_fget

(PHP 3>= 3.0.13, PHP 4 )

ftp_fget -- Downloads a file from the FTP server and saves to an open file

Description

bool ftp_fget ( resource ftp_stream, resource fp, string remote_file, int mode [, int resumepos])

ftp_fget() retrieves remote_file from the FTP server, and writes it to the given file pointer, fp. The transfer mode specified must be either FTP_ASCII or FTP_BINARY.

注: The resumepos parameter was added in PHP 4.3.0.

Returns TRUE on success or FALSE on error.

See also ftp_get().

后退 | 起点 | 前进
ftp_exec | 上一级 | ftp_fput


ftp_fput

(PHP 3>= 3.0.13, PHP 4 )

ftp_fput -- Uploads from an open file to the FTP server

Description

bool ftp_fput ( resource ftp_stream, string remote_file, resource fp, int mode [, int startpos])

ftp_fput() uploads the data from the file pointer fp until the end of the file is reached. The results are stored in remote_file on the FTP server. The transfer mode specified must be either FTP_ASCII or FTP_BINARY.

注: The startpos parameter was added in PHP 4.3.0.

Returns TRUE on success or FALSE on error.

后退 | 起点 | 前进
ftp_fget | 上一级 | ftp_get_option


ftp_get_option

(PHP 4 >= 4.2.0)

ftp_get_option -- Retrieves various runtime behaviours of the current FTP stream

Description

mixed ftp_get_option ( resource ftp_stream, int option)

注: This function is only available in CVS.

Returns the value on success or FALSE if the given option is not supported. In the latter case, a warning message is also thrown.

This function returns the value for the requested option from the specified ftp_stream . Currently, the following options are supported:

表格 1. Supported runtime FTP options

FTP_TIMEOUT_SEC Returns the current timeout used for network related operations.

例子 1. ftp_get_option() example

// Get the timeout of the given FTP stream
$timeout = ftp_get_option($conn_id, FTP_TIMEOUT_SEC);

后退 | 起点 | 前进
ftp_fput | 上一级 | ftp_get


ftp_get

(PHP 3>= 3.0.13, PHP 4 )

ftp_get -- Downloads a file from the FTP server

Description

bool ftp_get ( resource ftp_stream, string local_file, string remote_file, int mode [, int resumepos])

ftp_get() retrieves remote_file from the FTP server, and saves it to local_file locally. The transfer mode specified must be either FTP_ASCII or FTP_BINARY.

注: The resumepos parameter was added in PHP 4.3.0.

Returns TRUE on success or FALSE on error.

See also ftp_fget() and ftp_async_get().

后退 | 起点 | 前进
ftp_get_option | 上一级 | ftp_login


ftp_login

(PHP 3>= 3.0.13, PHP 4 )

ftp_login -- Logs in to an FTP connection

Description

bool ftp_login ( resource ftp_stream, string username, string password)

Logs in to the given FTP stream.

Returns TRUE on success or FALSE on error.

后退 | 起点 | 前进
ftp_get | 上一级 | ftp_mdtm


ftp_mdtm

(PHP 3>= 3.0.13, PHP 4 )

ftp_mdtm -- Returns the last modified time of the given file

Description

int ftp_mdtm ( resource ftp_stream, string remote_file)

ftp_mdtm() checks the last modified time for a file, and returns it as a UNIX timestamp. If an error occurs, or the file does not exist, -1 is returned.

Returns a UNIX timestamp on success, or -1 on error.

注: Not all servers support this feature!

注: ftp_mdtm() does not work with directories.

后退 | 起点 | 前进
ftp_login | 上一级 | ftp_mkdir


ftp_mkdir

(PHP 3>= 3.0.13, PHP 4 )

ftp_mkdir -- Creates a directory

Description

string ftp_mkdir ( resource ftp_stream, string directory)

Creates the specified directory.

Returns the newly created directory name on success or FALSE on error.

后退 | 起点 | 前进
ftp_mdtm | 上一级 | ftp_nlist


ftp_nlist

(PHP 3>= 3.0.13, PHP 4 )

ftp_nlist -- Returns a list of files in the given directory

Description

array ftp_nlist ( resource ftp_stream, string directory)

Returns an array of filenames from the specified directory on success or FALSE on error.

后退 | 起点 | 前进
ftp_mkdir | 上一级 | ftp_pasv


ftp_pasv

(PHP 3>= 3.0.13, PHP 4 )

ftp_pasv -- Turns passive mode on or off

Description

bool ftp_pasv ( resource ftp_stream, bool pasv)

ftp_pasv() turns on passive mode if the pasv parameter is TRUE. It turns off passive mode if pasv is FALSE. In passive mode, data connections are initiated by the client, rather than by the server.

Returns TRUE on success or FALSE on error.

后退 | 起点 | 前进
ftp_nlist | 上一级 | ftp_put


ftp_put

(PHP 3>= 3.0.13, PHP 4 )

ftp_put -- Uploads a file to the FTP server

Description

bool ftp_put ( resource ftp_stream, string remote_file, string local_file, int mode [, int startpos])

ftp_put() stores local_file on the FTP server, as remote_file. The transfer mode specified must be either FTP_ASCII or FTP_BINARY.

注: The startpos parameter was added in PHP 4.3.0.

Returns TRUE on success or FALSE on error.

例子 1. ftp_put() example

$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_ASCII);

后退 | 起点 | 前进
ftp_pasv | 上一级 | ftp_pwd


ftp_pwd

(PHP 3>= 3.0.13, PHP 4 )

ftp_pwd -- Returns the current directory name

Description

string ftp_pwd ( resource ftp_stream)

Returns the current directory or FALSE on error.

后退 | 起点 | 前进
ftp_put | 上一级 | ftp_quit


ftp_quit

(PHP 3>= 3.0.13, PHP 4 )

ftp_quit -- Closes an FTP connection

Description

void ftp_quit ( resource ftp_stream)

ftp_quit() is an alias for ftp_close().

后退 | 起点 | 前进
ftp_pwd | 上一级 | ftp_rawlist


ftp_rawlist

(PHP 3>= 3.0.13, PHP 4 )

ftp_rawlist -- Returns a detailed list of files in the given directory

Description

array ftp_rawlist ( resource ftp_stream, string directory)

ftp_rawlist() executes the FTP LIST command, and returns the result as an array. Each array element corresponds to one line of text. The output is not parsed in any way. The system type identifier returned by ftp_systype() can be used to determine how the results should be interpreted.

后退 | 起点 | 前进
ftp_quit | 上一级 | ftp_rename


ftp_rename

(PHP 3>= 3.0.13, PHP 4 )

ftp_rename -- Renames a file on the FTP server

Description

bool ftp_rename ( resource ftp_stream, string from, string to)

ftp_rename() renames the file or directory that is currently named from to the new name to, using the FTP stream ftp_stream.

Returns TRUE on success or FALSE on error.

后退 | 起点 | 前进
ftp_rawlist | 上一级 | ftp_rmdir


ftp_rmdir

(PHP 3>= 3.0.13, PHP 4 )

ftp_rmdir -- Removes a directory

Description

bool ftp_rmdir ( resource ftp_stream, string directory)

Removes the specified directory.

Returns TRUE on success or FALSE on error.

后退 | 起点 | 前进
ftp_rename | 上一级 | ftp_set_option


ftp_set_option

(PHP 4 >= 4.2.0)

ftp_set_option -- Set miscellaneous runtime FTP options

Description

bool ftp_set_option ( resource ftp_stream, int option, mixed value)

注: This function is only available in CVS.

Returns TRUE if the option could be set; FALSE if not. A warning message will be thrown if the option is not supported or the passed value doesn't match the expected value for the given option.

This function controls various runtime options for the specified FTP stream. The value parameter depends on which option parameter is chosen to be altered. Currently, the following options are supported:

表格 1. Supported runtime FTP options

FTP_TIMEOUT_SEC | Changes the timeout in seconds used for all network related functions. value must be an integer that is greater than 0. The default timeout is 90 seconds.
FTP_AUTOSEEK | When enabled, GET or PUT requests with a resumepos or startpos parameter will first seek to the requested position within the file. This is enabled by default.

例子 1. ftp_set_option() example

// Set the network timeout to 10 seconds
ftp_set_option($conn_id, FTP_TIMEOUT_SEC, 10);

后退 | 起点 | 前进
ftp_rmdir | 上一级 | ftp_site


ftp_site

(PHP 3>= 3.0.15, PHP 4 )

ftp_site -- Sends a SITE command to the server

Description

bool ftp_site ( resource ftp_stream, string cmd)

ftp_site() sends the command specified by cmd to the FTP server. SITE commands are not standardized, and vary from server to server. They are useful for handling such things as file permissions and group membership.

Returns TRUE on success or FALSE on error.

后退 | 起点 | 前进
ftp_set_option | 上一级 | ftp_size


ftp_size

(PHP 3>= 3.0.13, PHP 4 )

ftp_size -- Returns the size of the given file

Description

int ftp_size ( resource ftp_stream, string remote_file)

ftp_size() returns the size of a file in bytes. If an error occurs, of if the file does not exist, -1 is returned. Not all servers support this feature.

Returns the file size on success, or -1 on error.

后退 | 起点 | 前进
ftp_site | 上一级 | ftp_systype


ftp_systype

(PHP 3>= 3.0.13, PHP 4 )

ftp_systype -- Returns the system type identifier of the remote FTP server

Description

string ftp_systype ( resource ftp_stream)

Returns the remote system type, or FALSE on error.

后退 | 起点 | 前进
ftp_size | 上一级 | Function Handling functions


Function Handling functions

PHP 手册
后退 前进

XXXIV. Function Handling functions

介绍

These functions all handle various operations involved in working with functions.

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

这些函数作为 PHP 核心的一部分，无需被安装即可使用。

运行时配置

该扩展模块未定义任何设置指令。

预定义常量

该扩展模块未定义任何常量。

目录
call_user_func_array — Call a user function given with an array of parameters
call_user_func — Call a user function given by the first parameter
create_function — Create an anonymous (lambda-style) function
func_get_arg — Return an item from the argument list
func_get_args — Returns an array comprising a function's argument list
func_num_args — Returns the number of arguments passed to the function
function_exists — Return TRUE if the given function has been defined
get_defined_functions — Returns an array of all defined functions
register_shutdown_function — Register a function for execution on shutdown
register_tick_function — Register a function for execution on each tick
unregister_tick_function — De-register a function for execution on each tick

后退 | 起点 | 前进
ftp_systype | 上一级 | call_user_func_array


call_user_func_array

(PHP 4 >= 4.0.4)

call_user_func_array -- Call a user function given with an array of parameters

Description

mixed call_user_func_array ( string function_name [, array paramarr])

Call a user defined function given by function_name, with the parameters in paramarr. For example:

function debug($var, $val)
    echo "***DEBUGGING\nVARIABLE: $var\nVALUE:";
    if (is_array($val) || is_object($val) || is_resource($val))
        print_r($val);
    else
        echo "\n$val\n";
    echo "***\n";
}

$c = mysql_connect();
$host = $_SERVER["SERVER_NAME"];

call_user_func_array ('debug', array("host", $host));
call_user_func_array ('debug', array("c", $c));
call_user_func_array ('debug', array("_POST", $_POST));

See also:
call_user_func(),
call_user_method(),
call_user_method_array().

注: This function was added to the CVS code after release of PHP 4.0.4pl1

后退 | 起点 | 前进
Function Handling functions | 上一级 | call_user_func


call_user_func

(PHP 3>= 3.0.3, PHP 4 )

call_user_func -- Call a user function given by the first parameter

Description

mixed call_user_func ( string function_name [, mixed parameter [, mixed ...]])

Call a user defined function given by the function_name parameter. Take the following:

function barber ($type) {
    print "You wanted a $type haircut, no problem";
}
call_user_func ('barber', "mushroom");
call_user_func ('barber', "shave");

See also:
call_user_func_array(),
call_user_method(),
call_user_method_array().

后退 | 起点 | 前进
call_user_func_array | 上一级 | create_function


create_function

(PHP 4 >= 4.0.1)

create_function -- Create an anonymous (lambda-style) function

Description

string create_function ( string args, string code)

Creates an anonymous function from the parameters passed, and returns a unique name for it. Usually the args will be passed as a single quote delimited string, and this is also recommended for the code. The reason for using single quoted strings, is to protect the variable names from parsing, otherwise, if you use double quotes there will be a need to escape the variable names, e.g. \$avar.

You can use this function, to (for example) create a function from information gathered at run time:

例子 1. Creating an anonymous function with create_function()

$newfunc = create_function('$a,$b','return "ln($a) + ln($b) = ".log($a * $b);');
echo "New anonymous function: $newfunc\n";
echo $newfunc(2,M_E)."\n";
// outputs
// New anonymous function: lambda_1
// ln(2) + ln(2.718281828459) = 1.6931471805599
Or, perhaps to have general handler function that can apply a set of operations to a list of parameters:

例子 2. Making a general processing function with create_function()

function process($var1, $var2, $farr) {
    for ($f=0; $f < count($farr); $f++)
    echo $farr[$f]($var1,$var2)."\n";
}

// create a bunch of math functions
$f1 = 'if ($a >=0) {return "b*a^2 = ".$b*sqrt($a);} else {return false;}';
$f2 = "return \"min(b^2+a, a^2,b) = \".min(\$a*\$a+\$b,\$b*\$b+\$a);";
$f3 = 'if ($a > 0 && $b != 0) {return "ln(a)/b = ".log($a)/$b; } else { return false; }';
$farr = array(
    create_function('$x,$y', 'return "some trig: ".(sin($x) + $x*cos($y));'),
    create_function('$x,$y', 'return "a hypotenuse: ".sqrt($x*$x + $y*$y);'),
    create_function('$a,$b', $f1),
    create_function('$a,$b', $f2),
    create_function('$a,$b', $f3)
    );

echo "\nUsing the first array of anonymous functions\n";
echo "parameters: 2.3445, M_PI\n";
process(2.3445, M_PI, $farr);

// now make a bunch of string processing functions
$garr = array(
    create_function('$b,$a','if (strncmp($a,$b,3) == 0) return "** \"$a\" '.
    'and \"$b\"\n** Look the same to me! (looking at the first 3 chars)";'),
    create_function('$a,$b','; return "CRCs: ".crc32($a)." , ".crc32(b);'),
    create_function('$a,$b','; return "similar(a,b) = ".similar_text($a,$b,&$p)."($p%)";')
    );
echo "\nUsing the second array of anonymous functions\n";
process("Twas brilling and the slithy toves", "Twas the night", $garr);
and when you run the code above, the output will be:

Using the first array of anonymous functions
parameters: 2.3445, M_PI
some trig: -1.6291725057799
a hypotenuse: 3.9199852871011
b*a^2 = 4.8103313314525
min(b^2+a, a^2,b) = 8.6382729035898
ln(a/b) = 0.27122299212594

Using the second array of anonymous functions
** "Twas the night" and "Twas brilling and the slithy toves"
** Look the same to me! (looking at the first 3 chars)
CRCs: -725381282 , 1908338681
similar(a,b) = 11(45.833333333333%)

But perhaps the most common use for of lambda-style (anonymous) functions is to create callback functions, for example when using array_walk() or usort()

例子 3. Using anonymous functions as callback functions

$av = array("the ","a ","that ","this ");
array_walk($av, create_function('&$v,$k','$v = $v."mango";'));
print_r($av);  // for PHP 3 use var_dump()
// outputs:
// Array
// (
//   [0] => the mango
//   [1] => a mango
//   [2] => that mango
//   [3] => this mango
// )

// an array of strings ordered from shorter to longer
$sv = array("small","larger","a big string","it is a string thing");
print_r($sv);
// outputs:
// Array
// (
//   [0] => small
//   [1] => larger
//   [2] => a big string
//   [3] => it is a string thing
// )

// sort it from longer to shorter
usort($sv, create_function('$a,$b','return strlen($b) - strlen($a);'));
print_r($sv);
// outputs:
// Array
// (
//   [0] => it is a string thing
//   [1] => a big string
//   [2] => larger
//   [3] => small
// )

后退 | 起点 | 前进
call_user_func | 上一级 | func_get_arg


func_get_arg

(PHP 4 )

func_get_arg -- Return an item from the argument list

Description

mixed func_get_arg ( int arg_num)

Returns the argument which is at the arg_num'th offset into a user-defined function's argument list. Function arguments are counted starting from zero. func_get_arg() will generate a warning if called from outside of a function definition.

If arg_num is greater than the number of arguments actually passed, a warning will be generated and func_get_arg() will return FALSE.

<?php
function foo() {
     $numargs = func_num_args();
     echo "Number of arguments: $numargs<br>\n";
     if ($numargs >= 2) {
     echo "Second argument is: " . func_get_arg (1) . "<br>\n";
     }
}

foo (1, 2, 3);
?>

func_get_arg() may be used in conjunction with func_num_args() and func_get_args() to allow user-defined functions to accept variable-length argument lists.

注: This function was added in PHP 4.

后退 | 起点 | 前进
create_function | 上一级 | func_get_args


func_get_args

(PHP 4 )

func_get_args -- Returns an array comprising a function's argument list

Description

array func_get_args ( void)

Returns an array in which each element is the corresponding member of the current user-defined function's argument list. func_get_args() will generate a warning if called from outside of a function definition.

<?php
function foo() {
    $numargs = func_num_args();
    echo "Number of arguments: $numargs<br>\n";
    if ($numargs >= 2) {
    echo "Second argument is: " . func_get_arg (1) . "<br>\n";
    }
    $arg_list = func_get_args();
    for ($i = 0; $i < $numargs; $i++) {
    echo "Argument $i is: " . $arg_list[$i] . "<br>\n";
    }
}

foo (1, 2, 3);
?>

func_get_args() may be used in conjunction
with func_num_args() and
func_get_arg() to allow user-defined functions
to accept variable-length argument lists.

注: This function was added in PHP 4.

后退 | 起点 | 前进
func_get_arg | 上一级 | func_num_args


func_num_args

(PHP 4 )

func_num_args -- Returns the number of arguments passed to the function

Description

int func_num_args ( void)

Returns the number of arguments passed into the current user-defined function. func_num_args() will generate a warning if called from outside of a user-defined function.

<?php
function foo() {
    $numargs = func_num_args();
    echo "Number of arguments: $numargs\n";
}

foo (1, 2, 3);    // Prints 'Number of arguments: 3'
?>

func_num_args() may be used in conjunction
with func_get_arg() and
func_get_args() to allow user-defined
functions to accept variable-length argument lists.

后退 | 起点 | 前进
func_get_args | 上一级 | function_exists


function_exists

(PHP 3>= 3.0.7, PHP 4 )

function_exists -- Return TRUE if the given function has been defined

Description

bool function_exists ( string function_name)

Checks the list of defined functions, both built-in (internal) and user-defined, for function_name. 如果成功则返回 TRUE，失败则返回 FALSE。

if (function_exists('imap_open')) {
    echo "IMAP functions are available.<br>\n";
} else {
    echo "IMAP functions are not available.<br>\n";
}

Note that a function name may exist even if the function itself is unusable due to configuration or compiling options (with the image functions being an example). Also note that function_exists() will return FALSE for constructs, such as include_once() and echo().

See also method_exists() and get_defined_functions().

后退 | 起点 | 前进
func_num_args | 上一级 | get_defined_functions


get_defined_functions

(PHP 4 >= 4.0.4)

get_defined_functions -- Returns an array of all defined functions

Description

array get_defined_functions ( void)

This function returns an multidimensional array containing a list of all defined functions, both built-in (internal) and user-defined. The internal functions will be accessible via $arr["internal"], and the user defined ones using $arr["user"] (see example below).

function myrow($id, $data) {
    return "<tr><th>$id</th><td>$data</td></tr>\n";
}

$arr = get_defined_functions();

print_r($arr);

Will output something along the lines of:

Array
(
    [internal] => Array
        (
            [0] => zend_version
            [1] => func_num_args
            [2] => func_get_arg
            [3] => func_get_args
            [4] => strlen
            [5] => strcmp
            [6] => strncmp
            ...
            [750] => bcscale
            [751] => bccomp
        )

    [user] => Array
        (
            [0] => myrow
        )

)

See also get_defined_vars() and get_defined_constants().

后退 | 起点 | 前进
function_exists | 上一级 | register_shutdown_function


register_shutdown_function

(PHP 3>= 3.0.4, PHP 4 )

register_shutdown_function -- Register a function for execution on shutdown

Description

int register_shutdown_function ( string func)

Registers the function named by func to be executed when script processing is complete.

Multiple calls to register_shutdown_function() can be made, and each will be called in the same order as they were registered. If you call exit() within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called.

The registered shutdown functions are called after the request has been completed (including sending any output buffers), so it is not possible to send output to the browser using echo() or print(), or retrieve the contents of any output buffers using ob_get_contents().

注: 第二个参数函数名可以替换为一个数组，该数组由一个对象名和该对象名的一个方法名两个元素组成。

后退 | 起点 | 前进
get_defined_functions | 上一级 | register_tick_function


register_tick_function

(PHP 4 >= 4.0.3)

register_tick_function -- Register a function for execution on each tick

Description

void register_tick_function ( string func [, mixed arg])

Registers the function named by func to be executed when a tick is called.

后退 | 起点 | 前进
register_shutdown_function | 上一级 | unregister_tick_function


unregister_tick_function

(PHP 4 >= 4.0.3)

unregister_tick_function -- De-register a function for execution on each tick

Description

void unregister_tick_function ( string func [, mixed arg])

De-registers the function named by func so it is no longer executed when a tick is called.

后退 | 起点 | 前进
register_tick_function | 上一级 | Gettext


Gettext

PHP 手册
后退 前进

XXXV. Gettext

介绍

The gettext functions implement an NLS (Native Language Support) API which can be used to internationalize your PHP applications. Please see the gettext documentation for your system for a thorough explanation of these functions or view the docs at http://www.gnu.org/manual/gettext/index.html.

需求

To use these functions you must download and install the GNU gettext package from http://www.gnu.org/software/gettext/gettext.html

安装

To include GNU gettext support in your PHP build you must add the option --with-gettext[=DIR] where DIR is the gettext install directory, defaults to /usr/local.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

目录
bind_textdomain_codeset — Specify the character encoding in which the messages from the DOMAIN message catalog will be returned
bindtextdomain — Sets the path for a domain
dcgettext — Overrides the domain for a single lookup
dcngettext — Plural version of dcgettext
dgettext — Override the current domain
dngettext — Plural version of dgettext
gettext — Lookup a message in the current domain
ngettext — Plural version of gettext
textdomain — Sets the default domain

后退 | 起点 | 前进
unregister_tick_function | 上一级 | bind_textdomain_codeset


bind_textdomain_codeset

(PHP 4 >= 4.2.0)

bind_textdomain_codeset -- Specify the character encoding in which the messages from the DOMAIN message catalog will be returned

Description

string bind_textdomain_codeset ( string domain, string codeset)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
Gettext | 上一级 | bindtextdomain


bindtextdomain

(PHP 3>= 3.0.7, PHP 4 )

bindtextdomain -- Sets the path for a domain

Description

string bindtextdomain ( string domain, string directory)

The bindtextdomain() function sets the path for a domain.

后退 | 起点 | 前进
bind_textdomain_codeset | 上一级 | dcgettext


dcgettext

(PHP 3>= 3.0.7, PHP 4 )

dcgettext -- Overrides the domain for a single lookup

Description

string dcgettext ( string domain, string message, int category)

This function allows you to override the current domain for a single message lookup. It also allows you to specify a category.

后退 | 起点 | 前进
bindtextdomain | 上一级 | dcngettext


dcngettext

(PHP 4 >= 4.2.0)

dcngettext -- Plural version of dcgettext

Description

string dcngettext ( string domain, string msgid1, string msgid2, int n, int category)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
dcgettext | 上一级 | dgettext


dgettext

(PHP 3>= 3.0.7, PHP 4 )

dgettext -- Override the current domain

Description

string dgettext ( string domain, string message)

The dgettext() function allows you to override the current domain for a single message lookup.

后退 | 起点 | 前进
dcngettext | 上一级 | dngettext


dngettext

(PHP 4 >= 4.2.0)

dngettext -- Plural version of dgettext

Description

string dngettext ( string domain, string msgid1, string msgid2, int n)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
dgettext | 上一级 | gettext


gettext

(PHP 3>= 3.0.7, PHP 4 )

gettext -- Lookup a message in the current domain

Description

string gettext ( string message)

This function returns a translated string if one is found in the translation table, or the submitted message if not found. You may use the underscore character '_' as an alias to this function.

例子 1. gettext()-check

<?php
// Set language to German
setlocale(LC_ALL, 'de');

// Specify location of translation tables
bindtextdomain("myPHPApp", "./locale");

// Choose domain
textdomain("myPHPApp");

// Print a test message
print gettext("Welcome to My PHP Application");

// Or use the alias _() for gettext()
print _("Have a nice day");
?>

后退 | 起点 | 前进
dngettext | 上一级 | ngettext


ngettext

(PHP 4 >= 4.2.0)

ngettext -- Plural version of gettext

Description

string ngettext ( string msgid1, string msgid2, int n)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
gettext | 上一级 | textdomain


textdomain

(PHP 3>= 3.0.7, PHP 4 )

textdomain -- Sets the default domain

Description

string textdomain ( string text_domain)

This function sets the domain to search within when calls are made to gettext(), usually the named after an application. The previous default domain is returned. Call it with NULL as parameter to get the current setting without changing it.

后退 | 起点 | 前进
ngettext | 上一级 | GMP functions


GMP functions

PHP 手册
后退 前进

XXXVI. GMP functions

介绍

These functions allow you to work with arbitrary-length integers using the GNU MP library.

These functions have been added in PHP 4.0.4.

注: Most GMP functions accept GMP number arguments, defined as resource below. However, most of these functions will also accept numeric and string arguments, given that it is possible to convert the latter to a number. Also, if there is a faster function that can operate on integer arguments, it would be used instead of the slower function when the supplied arguments are integers. This is done transparently, so the bottom line is that you can use integers in every function that expects GMP number. See also the gmp_init() function.

警告

If you want to explicitly specify a large integer, specify it as a string. If you don't do that, PHP will interpret the integer-literal first, possibly resulting in loss of precision, even before GMP comes into play.

需求

You can download the GMP library from http://www.swox.com/gmp/. This site also has the GMP manual available.

You will need GMP version 2 or better to use these functions. Some functions may require more recent version of the GMP library.

安装

In order to have these functions available, you must compile PHP with GMP support by using the --with-gmp option.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

GMP_ROUND_ZERO (integer)

GMP_ROUND_PLUSINF (integer)

GMP_ROUND_MINUSINF (integer)

范例

例子 1. Factorial function using GMP

<?php
function fact ($x) {
    if ($x <= 1)
        return 1;
    else
        return gmp_mul ($x, fact ($x-1));
}

print gmp_strval (fact (1000)) . "\n";
?>

This will calculate factorial of 1000 (pretty big number) very fast.

相关参考

More mathmatical functions can be found in the sections BCMath Arbitrary Precision Mathematics Functions and Mathematical Functions.

目录
gmp_abs — Absolute value
gmp_add — Add numbers
gmp_and — Logical AND
gmp_clrbit — Clear bit
gmp_cmp — Compare numbers
gmp_com — Calculates one's complement of a
gmp_div_q — Divide numbers
gmp_div_qr — Divide numbers and get quotient and remainder
gmp_div_r — Remainder of the division of numbers
gmp_div — Divide numbers
gmp_divexact — Exact division of numbers
gmp_fact — Factorial
gmp_gcd — Calculate GCD
gmp_gcdext — Calculate GCD and multipliers
gmp_hamdist — Hamming distance
gmp_init — Create GMP number
gmp_intval — Convert GMP number to integer
gmp_invert — Inverse by modulo
gmp_jacobi — Jacobi symbol
gmp_legendre — Legendre symbol
gmp_mod — Modulo operation
gmp_mul — Multiply numbers
gmp_neg — Negate number
gmp_or — Logical OR
gmp_perfect_square — Perfect square check
gmp_popcount — Population count
gmp_pow — Raise number into power
gmp_powm — Raise number into power with modulo
gmp_prob_prime — Check if number is "probably prime"
gmp_random — Random number
gmp_scan0 — Scan for 0
gmp_scan1 — Scan for 1
gmp_setbit — Set bit
gmp_sign — Sign of number
gmp_sqrt — Square root
gmp_sqrtrm — Square root with remainder
gmp_strval — Convert GMP number to string
gmp_sub — Subtract numbers
gmp_xor — Logical XOR

后退 | 起点 | 前进
textdomain | 上一级 | gmp_abs


gmp_abs

(PHP 4 >= 4.0.4)

gmp_abs -- Absolute value

Description

resource gmp_abs ( resource a)

Returns absolute value of a.

后退 | 起点 | 前进
GMP functions | 上一级 | gmp_add


gmp_add

(PHP 4 >= 4.0.4)

gmp_add -- Add numbers

Description

resource gmp_add ( resource a, resource b)

Add two GMP numbers. The result will be a GMP number representing the sum of the arguments.

后退 | 起点 | 前进
gmp_abs | 上一级 | gmp_and


gmp_and

(PHP 4 >= 4.0.4)

gmp_and -- Logical AND

Description

resource gmp_and ( resource a, resource b)

Calculates logical AND of two GMP numbers.

后退 | 起点 | 前进
gmp_add | 上一级 | gmp_clrbit


gmp_clrbit

(PHP 4 >= 4.0.4)

gmp_clrbit -- Clear bit

Description

resource gmp_clrbit ( resource &a, int index)

Clears (sets to 0) bit index in a.

后退 | 起点 | 前进
gmp_and | 上一级 | gmp_cmp


gmp_cmp

(PHP 4 >= 4.0.4)

gmp_cmp -- Compare numbers

Description

int gmp_cmp ( resource a, resource b)

Returns a positive value if a > b, zero if a = b and negative value if a < b.

后退 | 起点 | 前进
gmp_clrbit | 上一级 | gmp_com


gmp_com

(PHP 4 >= 4.0.4)

gmp_com -- Calculates one's complement of a

Description

resource gmp_com ( resource a)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
gmp_cmp | 上一级 | gmp_div_q


gmp_div_q

(PHP 4 >= 4.0.4)

gmp_div_q -- Divide numbers

Description

resource gmp_div_q ( resource a, resource b [, int round])

Divides a by b and returns the integer result. The result rounding is defined by the round, which can have the following values:

  • GMP_ROUND_ZERO: The result is truncated towards 0.

  • GMP_ROUND_PLUSINF: The result is rounded towards +infinity.

  • GMP_ROUND_MINUSINF: The result is rounded towards -infinity.

This function can also be called as gmp_div().

See also gmp_div_r(), gmp_div_qr()

后退 | 起点 | 前进
gmp_com | 上一级 | gmp_div_qr


gmp_div_qr

(PHP 4 >= 4.0.4)

gmp_div_qr -- Divide numbers and get quotient and remainder

Description

array gmp_div_qr ( resource n, resource d [, int round])

The function divides n by d and returns array, with the first element being [n/d] (the integer result of the division) and the second being (n - [n/d] * d) (the remainder of the division).

See the gmp_div_q() function for description of the round argument.

例子 1. Division of GMP numbers

<?php
    $a = gmp_init ("0x41682179fbf5");
    $res = gmp_div_qr ($a, "0xDEFE75");
    printf("Result is: q - %s, r - %s",
            gmp_strval ($res[0]), gmp_strval ($res[1]));
?>

See also gmp_div_q(), gmp_div_r().

后退 | 起点 | 前进
gmp_div_q | 上一级 | gmp_div_r


gmp_div_r

(PHP 4 >= 4.0.4)

gmp_div_r -- Remainder of the division of numbers

Description

resource gmp_div_r ( resource n, resource d [, int round])

Calculates remainder of the integer division of n by d. The remainder has the sign of the n argument, if not zero.

See the gmp_div_q() function for description of the round argument.

See also gmp_div_q(), gmp_div_qr()

后退 | 起点 | 前进
gmp_div_qr | 上一级 | gmp_div


gmp_div

(PHP 4 >= 4.0.4)

gmp_div -- Divide numbers

Description

resource gmp_div ( resource a, resource b)

This function is an alias to gmp_div_q().

后退 | 起点 | 前进
gmp_div_r | 上一级 | gmp_divexact


gmp_divexact

(PHP 4 >= 4.0.4)

gmp_divexact -- Exact division of numbers

Description

resource gmp_divexact ( resource n, resource d)

Divides n by d, using fast "exact division" algorithm. This function produces correct results only when it is known in advance that d divides n.

后退 | 起点 | 前进
gmp_div | 上一级 | gmp_fact


gmp_fact

(PHP 4 >= 4.0.4)

gmp_fact -- Factorial

Description

resource gmp_fact ( int a)

Calculates factorial (a!) of a.

后退 | 起点 | 前进
gmp_divexact | 上一级 | gmp_gcd


gmp_gcd

(PHP 4 >= 4.0.4)

gmp_gcd -- Calculate GCD

Description

resource gmp_gcd ( resource a, resource b)

Calculate greatest common divisor of a and b. The result is always positive even if either of, or both, input operands are negative.

后退 | 起点 | 前进
gmp_fact | 上一级 | gmp_gcdext


gmp_gcdext

(PHP 4 >= 4.0.4)

gmp_gcdext -- Calculate GCD and multipliers

Description

array gmp_gcdext ( resource a, resource b)

Calculates g, s, and t, such that a*s + b*t = g = gcd(a,b), where gcd is the greatest common divisor. Returns an array with respective elements g, s and t.

后退 | 起点 | 前进
gmp_gcd | 上一级 | gmp_hamdist


gmp_hamdist

(PHP 4 >= 4.0.4)

gmp_hamdist -- Hamming distance

Description

int gmp_hamdist ( resource a, resource b)

Returns the hamming distance between a and b. Both operands should be non-negative.

后退 | 起点 | 前进
gmp_gcdext | 上一级 | gmp_init


gmp_init

(PHP 4 >= 4.0.4)

gmp_init -- Create GMP number

Description

resource gmp_init ( mixed number)

Creates a GMP number from an integer or string. String representation can be decimal or hexadecimal. In the latter case, the string should start with 0x.

例子 1. Creating GMP number

<?php
    $a = gmp_init (123456);
    $b = gmp_init ("0xFFFFDEBACDFEDF7200");
?>

注: It is not necessary to call this function if you want to use integer or string in place of GMP number in GMP functions, like gmp_add(). Function arguments are automatically converted to GMP numbers, if such conversion is possible and needed, using the same rules as gmp_init().

后退 | 起点 | 前进
gmp_hamdist | 上一级 | gmp_intval


gmp_intval

(PHP 4 >= 4.0.4)

gmp_intval -- Convert GMP number to integer

Description

int gmp_intval ( resource gmpnumber)

This function allows to convert GMP number to integer.

警告

This function returns a useful result only if the number actually fits the PHP integer (i.e., signed long type). If you want just to print the GMP number, use gmp_strval().

后退 | 起点 | 前进
gmp_init | 上一级 | gmp_invert


gmp_invert

(PHP 4 >= 4.0.4)

gmp_invert -- Inverse by modulo

Description

resource gmp_invert ( resource a, resource b)

Computes the inverse of a modulo b. Returns FALSE if an inverse does not exist.

后退 | 起点 | 前进
gmp_intval | 上一级 | gmp_jacobi


gmp_jacobi

(PHP 4 >= 4.0.4)

gmp_jacobi -- Jacobi symbol

Description

int gmp_jacobi ( resource a, resource p)

Computes Jacobi symbol of a and p. p should be odd and must be positive.

后退 | 起点 | 前进
gmp_invert | 上一级 | gmp_legendre


gmp_legendre

(PHP 4 >= 4.0.4)

gmp_legendre -- Legendre symbol

Description

int gmp_legendre ( resource a, resource p)

Compute the Legendre symbol of a and p. p should be odd and must be positive.

后退 | 起点 | 前进
gmp_jacobi | 上一级 | gmp_mod


gmp_mod

(PHP 4 >= 4.0.4)

gmp_mod -- Modulo operation

Description

resource gmp_mod ( resource n, resource d)

Calculates n modulo d. The result is always non-negative, the sign of d is ignored.

后退 | 起点 | 前进
gmp_legendre | 上一级 | gmp_mul


gmp_mul

(PHP 4 >= 4.0.4)

gmp_mul -- Multiply numbers

Description

resource gmp_mul ( resource a, resource b)

Multiplies a by b and returns the result.

后退 | 起点 | 前进
gmp_mod | 上一级 | gmp_neg


gmp_neg

(PHP 4 >= 4.0.4)

gmp_neg -- Negate number

Description

resource gmp_neg ( resource a)

Returns -a.

后退 | 起点 | 前进
gmp_mul | 上一级 | gmp_or


gmp_or

(PHP 4 >= 4.0.4)

gmp_or -- Logical OR

Description

resource gmp_or ( resource a, resource b)

Calculates logical inclusive OR of two GMP numbers.

后退 | 起点 | 前进
gmp_neg | 上一级 | gmp_perfect_square


gmp_perfect_square

(PHP 4 >= 4.0.4)

gmp_perfect_square -- Perfect square check

Description

bool gmp_perfect_square ( resource a)

Returns TRUE if a is a perfect square, FALSE otherwise.

See also: gmp_sqrt(), gmp_sqrtrm().

后退 | 起点 | 前进
gmp_or | 上一级 | gmp_popcount


gmp_popcount

(PHP 4 >= 4.0.4)

gmp_popcount -- Population count

Description

int gmp_popcount ( resource a)

Return the population count of a.

后退 | 起点 | 前进
gmp_perfect_square | 上一级 | gmp_pow


gmp_pow

(PHP 4 >= 4.0.4)

gmp_pow -- Raise number into power

Description

resource gmp_pow ( resource base, int exp)

Raise base into power exp. The case of 0^0 yields 1. exp cannot be negative.

后退 | 起点 | 前进
gmp_popcount | 上一级 | gmp_powm


gmp_powm

(PHP 4 >= 4.0.4)

gmp_powm -- Raise number into power with modulo

Description

resource gmp_powm ( resource base, resource exp, resource mod)

Calculate (base raised into power exp) modulo mod. If exp is negative, result is undefined.

后退 | 起点 | 前进
gmp_pow | 上一级 | gmp_prob_prime


gmp_prob_prime

(PHP 4 >= 4.0.4)

gmp_prob_prime -- Check if number is "probably prime"

Description

int gmp_prob_prime ( resource a [, int reps])

If this function returns 0, a is definitely not prime. If it returns 1, then a is "probably" prime. If it returns 2, then a is surely prime. Reasonable values of reps vary from 5 to 10 (default being 10); a higher value lowers the probability for a non-prime to pass as a "probable" prime.

The function uses Miller-Rabin's probabilistic test.

后退 | 起点 | 前进
gmp_powm | 上一级 | gmp_random


gmp_random

(PHP 4 >= 4.0.4)

gmp_random -- Random number

Description

resource gmp_random ( int limiter)

Generate a random number. The number will be between limiter and zero in value. If limiter is negative, negative numbers are generated.

后退 | 起点 | 前进
gmp_prob_prime | 上一级 | gmp_scan0


gmp_scan0

(PHP 4 >= 4.0.4)

gmp_scan0 -- Scan for 0

Description

int gmp_scan0 ( resource a, int start)

Scans a, starting with bit start, towards more significant bits, until the first clear bit is found. Returns the index of the found bit.

后退 | 起点 | 前进
gmp_random | 上一级 | gmp_scan1


gmp_scan1

(PHP 4 >= 4.0.4)

gmp_scan1 -- Scan for 1

Description

int gmp_scan1 ( resource a, int start)

Scans a, starting with bit start, towards more significant bits, until the first set bit is found. Returns the index of the found bit.

后退 | 起点 | 前进
gmp_scan0 | 上一级 | gmp_setbit


gmp_setbit

(PHP 4 >= 4.0.4)

gmp_setbit -- Set bit

Description

resource gmp_setbit ( resource &a, int index [, bool set_clear])

Sets bit index in a. set_clear defines if the bit is set to 0 or 1. By default the bit is set to 1.

后退 | 起点 | 前进
gmp_scan1 | 上一级 | gmp_sign


gmp_sign

(PHP 4 >= 4.0.4)

gmp_sign -- Sign of number

Description

int gmp_sign ( resource a)

Return sign of a - 1 if a is positive and -1 if it's negative.

后退 | 起点 | 前进
gmp_setbit | 上一级 | gmp_sqrt


gmp_sqrt

(PHP 4 >= 4.0.4)

gmp_sqrt -- Square root

Description

resource gmp_sqrt ( resource a)

Calculates square root of a.

后退 | 起点 | 前进
gmp_sign | 上一级 | gmp_sqrtrm


gmp_sqrtrm

(no version information, might be only in CVS)

gmp_sqrtrm -- Square root with remainder

Description

array gmp_sqrtrm ( resource a)

Returns array where first element is the integer square root of a (see also gmp_sqrt()), and the second is the remainder (i.e., the difference between a and the first element squared).

后退 | 起点 | 前进
gmp_sqrt | 上一级 | gmp_strval


gmp_strval

(PHP 4 >= 4.0.4)

gmp_strval -- Convert GMP number to string

Description

string gmp_strval ( resource gmpnumber [, int base])

Convert GMP number to string representation in base base. The default base is 10. Allowed values for the base are from 2 to 36.

例子 1. Converting a GMP number to a string

<?php
    $a = gmp_init("0x41682179fbf5");
    printf ("Decimal: %s, 36-based: %s", gmp_strval($a), gmp_strval($a,36));
?>

后退 | 起点 | 前进
gmp_sqrtrm | 上一级 | gmp_sub


gmp_sub

(PHP 4 >= 4.0.4)

gmp_sub -- Subtract numbers

Description

resource gmp_sub ( resource a, resource b)

Subtracts b from a and returns the result.

后退 | 起点 | 前进
gmp_strval | 上一级 | gmp_xor


gmp_xor

(PHP 4 >= 4.0.4)

gmp_xor -- Logical XOR

Description

resource gmp_xor ( resource a, resource b)

Calculates logical exclusive OR (XOR) of two GMP numbers.

后退 | 起点 | 前进
gmp_sub | 上一级 | HTTP functions


HTTP functions

PHP 手册
后退 前进

XXXVII. HTTP functions

介绍

These functions let you manipulate the output sent back to the remote browser right down to the HTTP protocol level.

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

这些函数作为 PHP 核心的一部分，无需被安装即可使用。

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

目录
header — Send a raw HTTP header
headers_sent — Returns TRUE if headers have been sent
setcookie — Send a cookie

后退 | 起点 | 前进
gmp_xor | 上一级 | header


header

(PHP 3, PHP 4 )

header -- Send a raw HTTP header

Description

int header ( string string [, bool replace [, int http_reponse_code]])

header() is used to send raw HTTP headers. See the HTTP/1.1 specification for more information on HTTP headers.

The optional replace parameter indicates whether the header should replace a previous similar header, or add a second header of the same type. By default it will replace, but if you pass in FALSE as the second argument you can force multiple headers of the same type. For example:

header('WWW-Authenticate: Negotiate');
header('WWW-Authenticate: NTLM', FALSE);

The second optional http_response_code force the HTTP response code to the specified value. (This parameter is available in PHP 4.3.0 and higher.)

There are two special-case header calls. The first is a header that starts with the string "HTTP/" (case is not significant), which will be used to figure out the HTTP status code to send. For example, if you have configured Apache to use a PHP script to handle requests for missing files (using the ErrorDocument directive), you may want to make sure that your script generates the proper status code.

<?php
  header("HTTP/1.0 404 Not Found");
?>

注: The HTTP status header line will always be the first sent to the client, regardless of the actual header() call beeing the first or not. The status may be overridden by calling header() with a new status line at any time unless the HTTP headers have already been sent.

注: In PHP 3, this only works when PHP is compiled as an Apache module. You can achieve the same effect using the Status header.

header("Status: 404 Not Found");

The second special case is the "Location:" header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless some 3xx status code has already been set.

header("Location: http://www.example.com/"); /* Redirect browser */
exit;                 /* Make sure that code below does
                         not get executed when we redirect. */

注: HTTP/1.1 requires an absolute URI as argument to Location: including the scheme, hostname and absolute path, but some clients accept relative URIs. You can usually use $_SERVER['HTTP_HOST'], $_SERVER['PHP_SELF'] and dirname() to make an absolute URI from a relative one yourself:

header("Location: http://".$_SERVER['HTTP_HOST']
                      .dirname($_SERVER['PHP_SELF'])
                      ."/".$relative_url);

PHP scripts often generate dynamic content that must not be cached by the client browser or any proxy caches between the server and the client browser. Many proxies and clients can be forced to disable caching with

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");    // Date in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
                                                     // always modified
header("Cache-Control: no-store, no-cache, must-revalidate");  // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");                          // HTTP/1.0

注: You may find that your pages aren't cached even if you don't output all of the headers above. There are a number of options that users may be able to set for their browser that change its default caching behavior. By sending the headers above, you should override any settings that may otherwise cause the output of your script to be cached.

Additionally, session_cache_limiter() and the session.cache_limiter configuration setting can be used to automatically generate the correct caching-related headers when sessions are being used.

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.

<?php header ("Content-type: audio/x-pn-realaudio"); ?>
// Broken, note the blank line above

注: In PHP 4, you can use output buffering to get around this problem, with the overhead of all of your output to the browser being buffered in the server until you send it. You can do this by calling ob_start() and ob_end_flush() in your script, or setting the output_buffering configuration directive on in your php.ini or server configuration files.

If you want the user to be prompted to save the data you are sending, such as a generated PDF file, you can use the Content-Disposition header to supply a recommended filename and force the browser to display the save dialog.

<?php
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=downloaded.pdf");

/* ... output pdf file ... */

注: There is a bug in Microsoft Internet Explorer 4.01 that prevents this from working. There is no workaround. There is also a bug in Microsoft Internet Explorer 5.5 that interferes with this, which can be resolved by upgrading to Service Pack 2 or later.

注: If safe mode is enabled the uid of the script is added to the realm part of the WWW-Authenticate header if you set this header (used for HTTP Authentication).

See also headers_sent(), setcookie(), and the section on HTTP authentication.

后退 | 起点 | 前进
HTTP functions | 上一级 | headers_sent


headers_sent

(PHP 3>= 3.0.8, PHP 4 )

headers_sent -- Returns TRUE if headers have been sent

Description

bool headers_sent ( string &file [, int &line])

This function returns TRUE if the HTTP headers have already been sent, FALSE otherwise. You can't add any more header lines using the header() function once the header block has already been sent. Using this function you can at least prevent getting the "Duplicate headers ..." error messages.

The function will return the php source file and line number where output started in the optional file and line parameters if these are given.

注: file and line where added for PHP 4.3.0.

See also header() for a more detailed discussion of the matters involved.

后退 | 起点 | 前进
header | 上一级 | setcookie


setcookie

(PHP 3, PHP 4 )

setcookie -- Send a cookie

Description

boolean setcookie ( string name [, string value [, int expire [, string path [, string domain [, int secure]]]]])

setcookie() defines a cookie to be sent along with the rest of the header information. Cookies must be sent before any other headers are sent (this is a restriction of cookies, not PHP). This requires you to place calls to this function before any <html> or <head> tags. If headers exist prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE This does not mean the user accepted the cookie or not.

All the arguments except the name argument are optional. If only the name argument is present, the cookie by that name will be deleted from the remote client. You may also replace any argument with an empty string ("") in order to skip that argument. The expire and secure arguments are integers and cannot be skipped with an empty string. Use a zero (0) instead. The expire argument is a regular Unix time integer as returned by the time() or mktime() functions. The secure indicates that the cookie should only be transmitted over a secure HTTPS connection.

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, autoglobals such as $_COOKIE became available in PHP 4.1.0. $HTTP_COOKIE_VARS has existed since PHP 3.

Common Pitfalls:

  • Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter.

  • Cookies must be deleted with the same parameters as they were set with.

  • Cookies names can be set as array names and will be available to your PHP scripts as arrays but seperate cookies are stored on the users system. Consider explode() or serialize() to set one cookie with multiple names and values.

In PHP 3, multiple calls to setcookie() in the same script will be performed in reverse order. If you are trying to delete one cookie before inserting another you should put the insert before the delete. In PHP 4, multiple calls to setcookie() are performed in the order called.

Some examples follow how to send cookies:

例子 1. setcookie() send examples

setcookie ("TestCookie", $value);
setcookie ("TestCookie", $value,time()+3600);  /* expire in 1 hour */
setcookie ("TestCookie", $value,time()+3600, "/~rasmus/", ".utoronto.ca", 1);

When deleting a cookie you should assure that the expiration date is in the past, to trigger the removal mechanism in your browser. Examples follow how to delete cookies sent in previous example:

例子 2. setcookie() delete examples

// set the expiration date to one hour ago
setcookie ("TestCookie", "", time() - 3600);
setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", ".utoronto.ca", 1);

Note that the value portion of the cookie will automatically be urlencoded when you send the cookie, and when it is received, it is automatically decoded and assigned to a variable by the same name as the cookie name. To see the contents of our test cookie in a script, simply use one of the following examples:

echo $TestCookie;
echo $_COOKIE["TestCookie"];

You may also set array cookies by using array notation in the cookie name. This has the effect of setting as many cookies as you have array elements, but when the cookie is received by your script, the values are all placed in an array with the cookie's name:

setcookie ("cookie[three]", "cookiethree");
setcookie ("cookie[two]", "cookietwo");
setcookie ("cookie[one]", "cookieone");
if (isset ($cookie)) {
    while (list ($name, $value) = each ($cookie)) {
        echo "$name == $value<br>\n";
    }
}

For more information on cookies, see Netscape's cookie specification at http://www.netscape.com/newsref/std/cookie_spec.html.

Microsoft Internet Explorer 4 with Service Pack 1 applied does not correctly deal with cookies that have their path parameter set.

Netscape Communicator 4.05 and Microsoft Internet Explorer 3.x appear to handle cookies incorrectly when the path and time are not set.

后退 | 起点 | 前进
headers_sent | 上一级 | Hyperwave functions


Hyperwave functions

PHP 手册
后退 前进

XXXVIII. Hyperwave functions

介绍

Hyperwave has been developed at IICM in Graz. It started with the name Hyper-G and changed to Hyperwave when it was commercialised (in 1996).

Hyperwave is not free software. The current version, 5.5 is available at http://www.hyperwave.com/. A time limited version can be ordered for free (30 days).

See also the Hyperwave API module.

Hyperwave is an information system similar to a database (HIS, Hyperwave Information Server). Its focus is the storage and management of documents. A document can be any possible piece of data that may as well be stored in file. Each document is accompanied by its object record. The object record contains meta data for the document. The meta data is a list of attributes which can be extended by the user. Certain attributes are always set by the Hyperwave server, other may be modified by the user. An attribute is a name/value pair of the form name=value. The complete object record contains as many of those pairs as the user likes. The name of an attribute does not have to be unique, e.g. a title may appear several times within an object record. This makes sense if you want to specify a title in several languages. In such a case there is a convention, that each title value is preceded by the two letter language abbreviation followed by a colon, e.g. 'en:Title in English' or 'ge:Titel in deutsch'. Other attributes like a description or keywords are potential candidates. You may also replace the language abbreviation by any other string as long as it separated by colon from the rest of the attribute value.

Each object record has native a string representation with each name/value pair separated by a newline. The Hyperwave extension also knows a second representation which is an associated array with the attribute name being the key. Multilingual attribute values itself form another associated array with the key being the language abbreviation. Actually any multiple attribute forms an associated array with the string left to the colon in the attribute value being the key. (This is not fully implemented. Only the attributes Title, Description and Keyword are treated properly yet.)

Besides the documents, all hyper links contained in a document are stored as object records as well. Hyper links which are in a document will be removed from it and stored as individual objects, when the document is inserted into the database. The object record of the link contains information about where it starts and where it ends. In order to gain the original document you will have to retrieve the plain document without the links and the list of links and reinsert them. The functions hw_pipedocument() and hw_gettext() do this for you. The advantage of separating links from the document is obvious. Once a document to which a link is pointing to changes its name, the link can easily be modified accordingly. The document containing the link is not affected at all. You may even add a link to a document without modifying the document itself.

Saying that hw_pipedocument() and hw_gettext() do the link insertion automatically is not as simple as it sounds. Inserting links implies a certain hierarchy of the documents. On a web server this is given by the file system, but Hyperwave has its own hierarchy and names do not reflect the position of an object in that hierarchy. Therefore creation of links first of all requires a mapping from the Hyperwave hierarchy and namespace into a web hierarchy respective web namespace. The fundamental difference between Hyperwave and the web is the clear distinction between names and hierarchy in Hyperwave. The name does not contain any information about the objects position in the hierarchy. In the web the name also contains the information on where the object is located in the hierarchy. This leads to two possibles ways of mapping. Either the Hyperwave hierarchy and name of the Hyperwave object is reflected in the URL or the name only. To make things simple the second approach is used. Hyperwave object with name my_object is mapped to http://host/my_object disregarding where it resides in the Hyperwave hierarchy. An object with name parent/my_object could be the child of my_object in the Hyperwave hierarchy, though in a web namespace it appears to be just the opposite and the user might get confused. This can only be prevented by selecting reasonable object names.

Having made this decision a second problem arises. How do you involve PHP? The URL http://host/my_object will not call any PHP script unless you tell your web server to rewrite it to e.g. http://host/php_script/my_object and the script php_script evaluates the $PATH_INFO variable and retrieves the object with name my_object from the Hyperwave server. Their is just one little drawback which can be fixed easily. Rewriting any URL would not allow any access to other document on the web server. A PHP script for searching in the Hyperwave server would be impossible. Therefore you will need at least a second rewriting rule to exclude certain URLs like all e.g. starting with http://host/Hyperwave This is basically sharing of a namespace by the web and Hyperwave server.

Based on the above mechanism links are insert into documents.

It gets more complicated if PHP is not run as a server module or CGI script but as a standalone application e.g. to dump the content of the Hyperwave server on a CD-ROM. In such a case it makes sense to retain the Hyperwave hierarchy and map in onto the file system. This conflicts with the object names if they reflect its own hierarchy (e.g. by choosing names including '/'). Therefore '/' has to be replaced by another character, e.g. '_'.

The network protocol to communicate with the Hyperwave server is called HG-CSP (Hyper-G Client/Server Protocol). It is based on messages to initiate certain actions, e.g. get object record. In early versions of the Hyperwave Server two native clients (Harmony, Amadeus) were provided for communication with the server. Those two disappeared when Hyperwave was commercialised. As a replacement a so called wavemaster was provided. The wavemaster is like a protocol converter from HTTP to HG-CSP. The idea is to do all the administration of the database and visualisation of documents by a web interface. The wavemaster implements a set of placeholders for certain actions to customise the interface. This set of placeholders is called the PLACE Language. PLACE lacks a lot of features of a real programming language and any extension to it only enlarges the list of placeholders. This has led to the use of JavaScript which IMO does not make life easier.

Adding Hyperwave support to PHP should fill in the gap of a missing programming language for interface customisation. It implements all the messages as defined by the HG-CSP but also provides more powerful commands to e.g. retrieve complete documents.

Hyperwave has its own terminology to name certain pieces of information. This has widely been taken over and extended. Almost all functions operate on one of the following data types.

  • object ID: An unique integer value for each object in the Hyperwave server. It is also one of the attributes of the object record (ObjectID). Object ids are often used as an input parameter to specify an object.

  • object record: A string with attribute-value pairs of the form attribute=value. The pairs are separated by a carriage return from each other. An object record can easily be converted into an object array with hw_object2array(). Several functions return object records. The names of those functions end with obj.

  • object array: An associative array with all attributes of an object. The keys are the attribute names. If an attribute occurs more than once in an object record it will result in another indexed or associative array. Attributes which are language depended (like the title, keyword, description) will form an associative array with the keys set to the language abbreviations. All other multiple attributes will form an indexed array. PHP functions never return object arrays.

  • hw_document: This is a complete new data type which holds the actual document, e.g. HTML, PDF etc. It is somewhat optimized for HTML documents but may be used for any format.

Several functions which return an array of object records do also return an associative array with statistical information about them. The array is the last element of the object record array. The statistical array contains the following entries:

Hidden

Number of object records with attribute PresentationHints set to Hidden.

CollectionHead

Number of object records with attribute PresentationHints set to CollectionHead.

FullCollectionHead

Number of object records with attribute PresentationHints set to FullCollectionHead.

CollectionHeadNr

Index in array of object records with attribute PresentationHints set to CollectionHead.

FullCollectionHeadNr

Index in array of object records with attribute PresentationHints set to FullCollectionHead.

Total

Total: Number of object records.

需求

This extension needs a Hyperwave server downloadable from http://www.hyperwave.com/.

安装

Integration with Apache

The Hyperwave extension is best used when PHP is compiled as an Apache module. In such a case the underlying Hyperwave server can be hidden from users almost completely if Apache uses its rewriting engine. The following instructions will explain this.

Since PHP with Hyperwave support built into Apache is intended to replace the native Hyperwave solution based on Wavemaster, we will assume that the Apache server will only serve as a Hyperwave web interface for these examples. This is not necessary but it simplifies the configuration. The concept is quite simple. First of all you need a PHP script which evaluates the $_ENV['PATH_INFO'] variable and treats its value as the name of a Hyperwave object. Let's call this script 'Hyperwave'. The URL http://your.hostname/Hyperwave/name_of_object would than return the Hyperwave object with the name 'name_of_object'. Depending on the type of the object the script has to react accordingly. If it is a collection, it will probably return a list of children. If it is a document it will return the mime type and the content. A slight improvement can be achieved if the Apache rewriting engine is used. From the users point of view it would be more straight forward if the URL http://your.hostname/name_of_object would return the object. The rewriting rule is quite easy:

RewriteRule ^/(.*) /usr/local/apache/htdocs/HyperWave/$1 [L]

Now every URL relates to an object in the Hyperwave server. This causes a simple to solve problem. There is no way to execute a different script, e.g. for searching, than the 'Hyperwave' script. This can be fixed with another rewriting rule like the following:

RewriteRule ^/hw/(.*) /usr/local/apache/htdocs/hw/$1 [L]

This will reserve the directory /usr/local/apache/htdocs/hw for additional scripts and other files. Just make sure this rule is evaluated before the one above. There is just a little drawback: all Hyperwave objects whose name starts with 'hw/' will be shadowed. So, make sure you don't use such names. If you need more directories, e.g. for images just add more rules or place them all in one directory. Before you put those instructions, don't forget to turn on the rewriting engine with

RewriteEngine on

You will need scripts:

  • to return the object itself

  • to allow searching

  • to identify yourself

  • to set your profile

  • one for each additional function like to show the object attributes, to show information about users, to show the status of the server, etc.

As an alternative to the Rewrite Engine, you can also consider using the Apache ErrorDocument directive, but be aware, that ErrorDocument redirected pages cannot receive POST data.

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. Hyperwave configuration options

Name | Default | Changeable
hyerwave.allow_persistent | "0" | PHP_INI_SYSTEM
hyperwave.default_port | "418" | PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

资源类型

该扩展模块未定义任何资源类型。

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

HW_ATTR_LANG (integer)

HW_ATTR_NR (integer)

HW_ATTR_NONE (integer)

Todo

There are still some things to do:

  • The hw_InsertDocument has to be split into hw_insertobject() and hw_putdocument().

  • The names of several functions are not fixed, yet.

  • Most functions require the current connection as its first parameter. This leads to a lot of typing, which is quite often not necessary if there is just one open connection. A default connection will improve this.

  • Conversion form object record into object array needs to handle any multiple attribute.

目录
hw_Array2Objrec — convert attributes from object array to object record
hw_changeobject — Changes attributes of an object (obsolete)
hw_Children — object ids of children
hw_ChildrenObj — object records of children
hw_Close — closes the Hyperwave connection
hw_Connect — opens a connection
hw_connection_info — Prints information about the connection to Hyperwave server
hw_Cp — copies objects
hw_Deleteobject — deletes object
hw_DocByAnchor — object id object belonging to anchor
hw_DocByAnchorObj — object record object belonging to anchor
hw_Document_Attributes — object record of hw_document
hw_Document_BodyTag — body tag of hw_document
hw_Document_Content — returns content of hw_document
hw_Document_SetContent — sets/replaces content of hw_document
hw_Document_Size — size of hw_document
hw_dummy — Hyperwave dummy function
hw_EditText — retrieve text document
hw_Error — error number
hw_ErrorMsg — returns error message
hw_Free_Document — frees hw_document
hw_GetAnchors — object ids of anchors of document
hw_GetAnchorsObj — object records of anchors of document
hw_GetAndLock — return bject record and lock object
hw_GetChildColl — object ids of child collections
hw_GetChildCollObj — object records of child collections
hw_GetChildDocColl — object ids of child documents of collection
hw_GetChildDocCollObj — object records of child documents of collection
hw_GetObject — object record
hw_GetObjectByQuery — search object
hw_GetObjectByQueryColl — search object in collection
hw_GetObjectByQueryCollObj — search object in collection
hw_GetObjectByQueryObj — search object
hw_GetParents — object ids of parents
hw_GetParentsObj — object records of parents
hw_getrellink — Get link from source to dest relative to rootid
hw_GetRemote — Gets a remote document
hw_GetRemoteChildren — Gets children of remote document
hw_GetSrcByDestObj — Returns anchors pointing at object
hw_GetText — retrieve text document
hw_getusername — name of currently logged in user
hw_Identify — identifies as user
hw_InCollections — check if object ids in collections
hw_Info — info about connection
hw_InsColl — insert collection
hw_InsDoc — insert document
hw_insertanchors — Inserts only anchors into text
hw_InsertDocument — upload any document
hw_InsertObject — inserts an object record
hw_mapid — Maps global id on virtual local id
hw_Modifyobject — modifies object record
hw_Mv — moves objects
hw_New_Document — create new document
hw_Objrec2Array — convert attributes from object record to object array
hw_Output_Document — prints hw_document
hw_pConnect — make a persistent database connection
hw_PipeDocument — retrieve any document
hw_Root — root object id
hw_setlinkroot — Set the id to which links are calculated
hw_stat — Returns status string
hw_Unlock — unlock object
hw_Who — List of currently logged in users

后退 | 起点 | 前进
setcookie | 上一级 | hw_Array2Objrec


hw_Array2Objrec

(PHP 3>= 3.0.4, PHP 4 )

hw_Array2Objrec -- convert attributes from object array to object record

Description

strin hw_array2objrec ( array object_array)

Converts an object_array into an object record. Multiple attributes like 'Title' in different languages are treated properly.

See also hw_objrec2array().

后退 | 起点 | 前进
Hyperwave functions | 上一级 | hw_changeobject


hw_changeobject

(PHP 3>= 3.0.3, PHP 4 )

hw_changeobject -- Changes attributes of an object (obsolete)

Description

void hw_changeobject ( int link, int objid, array attributes)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
hw_Array2Objrec | 上一级 | hw_Children


hw_Children

(PHP 3>= 3.0.3, PHP 4 )

hw_Children -- object ids of children

Description

array hw_children ( int connection, int objectID)

Returns an array of object ids. Each id belongs to a child of the collection with ID objectID. The array contains all children both documents and collections.

后退 | 起点 | 前进
hw_changeobject | 上一级 | hw_ChildrenObj


hw_ChildrenObj

(PHP 3>= 3.0.3, PHP 4 )

hw_ChildrenObj -- object records of children

Description

array hw_childrenobj ( int connection, int objectID)

Returns an array of object records. Each object record belongs to a child of the collection with ID objectID. The array contains all children both documents and collections.

后退 | 起点 | 前进
hw_Children | 上一级 | hw_Close


hw_Close

(PHP 3>= 3.0.3, PHP 4 )

hw_Close -- closes the Hyperwave connection

Description

int hw_close ( int connection)

Returns FALSE if connection is not a valid connection index, otherwise TRUE. Closes down the connection to a Hyperwave server with the given connection index.

后退 | 起点 | 前进
hw_ChildrenObj | 上一级 | hw_Connect


hw_Connect

(PHP 3>= 3.0.3, PHP 4 )

hw_Connect -- opens a connection

Description

int hw_connect ( string host, int port, string username, string password)

Opens a connection to a Hyperwave server and returns a connection index on success, or FALSE if the connection could not be made. Each of the arguments should be a quoted string, except for the port number. The username and password arguments are optional and can be left out. In such a case no identification with the server will be done. It is similar to identify as user anonymous. This function returns a connection index that is needed by other Hyperwave functions. You can have multiple connections open at once. Keep in mind, that the password is not encrypted.

See also hw_pconnect().

后退 | 起点 | 前进
hw_Close | 上一级 | hw_connection_info


hw_connection_info

(PHP 3>= 3.0.3, PHP 4 )

hw_connection_info -- Prints information about the connection to Hyperwave server

Description

void hw_connection_info ( int link)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
hw_Connect | 上一级 | hw_Cp


hw_Cp

(PHP 3>= 3.0.3, PHP 4 )

hw_Cp -- copies objects

Description

int hw_cp ( int connection, array object_id_array, int destination id)

Copies the objects with object ids as specified in the second parameter to the collection with the id destination id.

The value return is the number of copied objects.

See also hw_mv().

后退 | 起点 | 前进
hw_connection_info | 上一级 | hw_Deleteobject


hw_Deleteobject

(PHP 3>= 3.0.3, PHP 4 )

hw_Deleteobject -- deletes object

Description

int hw_deleteobject ( int connection, int object_to_delete)

Deletes the object with the given object id in the second parameter. It will delete all instances of the object.

Returns TRUE if no error occurs otherwise FALSE.

See also hw_mv().

后退 | 起点 | 前进
hw_Cp | 上一级 | hw_DocByAnchor


hw_DocByAnchor

(PHP 3>= 3.0.3, PHP 4 )

hw_DocByAnchor -- object id object belonging to anchor

Description

int hw_docbyanchor ( int connection, int anchorID)

Returns an th object id of the document to which anchorID belongs.

后退 | 起点 | 前进
hw_Deleteobject | 上一级 | hw_DocByAnchorObj


hw_DocByAnchorObj

(PHP 3>= 3.0.3, PHP 4 )

hw_DocByAnchorObj -- object record object belonging to anchor

Description

string hw_docbyanchorobj ( int connection, int anchorID)

Returns an th object record of the document to which anchorID belongs.

后退 | 起点 | 前进
hw_DocByAnchor | 上一级 | hw_Document_Attributes


hw_Document_Attributes

(PHP 3>= 3.0.3, PHP 4 )

hw_Document_Attributes -- object record of hw_document

Description

string hw_document_attributes ( int hw_document)

Returns the object record of the document.

For backward compatibility, hw_documentattributes() is also accepted. This is deprecated, however.

See also hw_document_bodytag(), and hw_document_size().

后退 | 起点 | 前进
hw_DocByAnchorObj | 上一级 | hw_Document_BodyTag


hw_Document_BodyTag

(PHP 3>= 3.0.3, PHP 4 )

hw_Document_BodyTag -- body tag of hw_document

Description

string hw_document_bodytag ( int hw_document)

Returns the BODY tag of the document. If the document is an HTML document the BODY tag should be printed before the document.

See also hw_document_attributes(), and hw_document_size().

For backward compatibility, hw_documentbodytag() is also accepted. This is deprecated, however.

后退 | 起点 | 前进
hw_Document_Attributes | 上一级 | hw_Document_Content


hw_Document_Content

(PHP 3>= 3.0.3, PHP 4 )

hw_Document_Content -- returns content of hw_document

Description

string hw_document_content ( int hw_document)

Returns the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record.

See also hw_document_attributes(),
hw_document_size(),
and hw_document_setcontent().

后退 | 起点 | 前进
hw_Document_BodyTag | 上一级 | hw_Document_SetContent


hw_Document_SetContent

(PHP 4 )

hw_Document_SetContent -- sets/replaces content of hw_document

Description

string hw_document_setcontent ( int hw_document, string content)

Sets or replaces the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record. If you provide this information in the content of the document too, the Hyperwave server will change the object record accordingly when the document is inserted. Probably not a very good idea. If this functions fails the document will retain its old content.

See also hw_document_attributes(),
hw_document_size(),
and hw_document_content().

后退 | 起点 | 前进
hw_Document_Content | 上一级 | hw_Document_Size


hw_Document_Size

(PHP 3>= 3.0.3, PHP 4 )

hw_Document_Size -- size of hw_document

Description

int hw_document_size ( int hw_document)

Returns the size in bytes of the document.

See also hw_document_bodytag(), and hw_document_attributes().

For backward compatibility, hw_documentsize() is also accepted. This is deprecated, however.

后退 | 起点 | 前进
hw_Document_SetContent | 上一级 | hw_dummy


hw_dummy

(PHP 3>= 3.0.3, PHP 4 )

hw_dummy -- Hyperwave dummy function

Description

string hw_dummy ( int link, int id, int msgid)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
hw_Document_Size | 上一级 | hw_EditText


hw_EditText

(PHP 3>= 3.0.3, PHP 4 )

hw_EditText -- retrieve text document

Description

int hw_edittext ( int connection, int hw_document)

Uploads the text document to the server. The object record of the document may not be modified while the document is edited. This function will only works for pure text documents. It will not open a special data connection and therefore blocks the control connection during the transfer.

See also hw_pipedocument(),
hw_free_document(),
hw_document_bodytag(),
hw_document_size(),
hw_output_document(),
hw_gettext().

后退 | 起点 | 前进
hw_dummy | 上一级 | hw_Error


hw_Error

(PHP 3>= 3.0.3, PHP 4 )

hw_Error -- error number

Description

int hw_error ( int connection)

Returns the last error number. If the return value is 0 no error has occurred. The error relates to the last command.

后退 | 起点 | 前进
hw_EditText | 上一级 | hw_ErrorMsg


hw_ErrorMsg

(PHP 3>= 3.0.3, PHP 4 )

hw_ErrorMsg -- returns error message

Description

string hw_errormsg ( int connection)

Returns a string containing the last error message or 'No Error'. If FALSE is returned, this function failed. The message relates to the last command.

后退 | 起点 | 前进
hw_Error | 上一级 | hw_Free_Document


hw_Free_Document

(PHP 3>= 3.0.3, PHP 4 )

hw_Free_Document -- frees hw_document

Description

int hw_free_document ( int hw_document)

Frees the memory occupied by the Hyperwave document.

后退 | 起点 | 前进
hw_ErrorMsg | 上一级 | hw_GetAnchors


hw_GetAnchors

(PHP 3>= 3.0.3, PHP 4 )

hw_GetAnchors -- object ids of anchors of document

Description

array hw_getanchors ( int connection, int objectID)

Returns an array of object ids with anchors of the document with object ID objectID.

后退 | 起点 | 前进
hw_Free_Document | 上一级 | hw_GetAnchorsObj


hw_GetAnchorsObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetAnchorsObj -- object records of anchors of document

Description

array hw_getanchorsobj ( int connection, int objectID)

Returns an array of object records with anchors of the document with object ID objectID.

后退 | 起点 | 前进
hw_GetAnchors | 上一级 | hw_GetAndLock


hw_GetAndLock

(PHP 3>= 3.0.3, PHP 4 )

hw_GetAndLock -- return bject record and lock object

Description

string hw_getandlock ( int connection, int objectID)

Returns the object record for the object with ID objectID. It will also lock the object, so other users cannot access it until it is unlocked.

See also hw_unlock(), and hw_getobject().

后退 | 起点 | 前进
hw_GetAnchorsObj | 上一级 | hw_GetChildColl


hw_GetChildColl

(PHP 3>= 3.0.3, PHP 4 )

hw_GetChildColl -- object ids of child collections

Description

array hw_getchildcoll ( int connection, int objectID)

Returns an array of object ids. Each object ID belongs to a child collection of the collection with ID objectID. The function will not return child documents.

See also hw_children(), and hw_getchilddoccoll().

后退 | 起点 | 前进
hw_GetAndLock | 上一级 | hw_GetChildCollObj


hw_GetChildCollObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetChildCollObj -- object records of child collections

Description

array hw_getchildcollobj ( int connection, int objectID)

Returns an array of object records. Each object records belongs to a child collection of the collection with ID objectID. The function will not return child documents.

See also hw_childrenobj(), and hw_getchilddoccollobj().

后退 | 起点 | 前进
hw_GetChildColl | 上一级 | hw_GetChildDocColl


hw_GetChildDocColl

(PHP 3>= 3.0.3, PHP 4 )

hw_GetChildDocColl -- object ids of child documents of collection

Description

array hw_getchilddoccoll ( int connection, int objectID)

Returns array of object ids for child documents of a collection.

See also hw_children(), and hw_getchildcoll().

后退 | 起点 | 前进
hw_GetChildCollObj | 上一级 | hw_GetChildDocCollObj


hw_GetChildDocCollObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetChildDocCollObj -- object records of child documents of collection

Description

array hw_getchilddoccollobj ( int connection, int objectID)

Returns an array of object records for child documents of a collection.

See also hw_childrenobj(), and hw_getchildcollobj().

后退 | 起点 | 前进
hw_GetChildDocColl | 上一级 | hw_GetObject


hw_GetObject

(PHP 3>= 3.0.3, PHP 4 )

hw_GetObject -- object record

Description

array hw_getobject ( int connection, [int|array] objectID, string query)

Returns the object record for the object with ID objectID if the second parameter is an integer. If the second parameter is an array of integer the function will return an array of object records. In such a case the last parameter is also evaluated which is a query string.

The query string has the following syntax:

<expr> ::= "(" <expr> ")" |

"!" <expr> | /* NOT */

<expr> "||" <expr> | /* OR */

<expr> "&&" <expr> | /* AND */

<attribute> <operator> <value>

<attribute> ::= /* any attribute name (Title, Author, DocumentType ...) */

<operator> ::= "=" | /* equal */

"<" | /* less than (string compare) */

">" | /* greater than (string compare) */

"~" /* regular expression matching */

The query allows to further select certain objects from the list of given objects. Unlike the other query functions, this query may use not indexed attributes. How many object records are returned depends on the query and if access to the object is allowed.

See also hw_getandlock(), and hw_getobjectbyquery().

后退 | 起点 | 前进
hw_GetChildDocCollObj | 上一级 | hw_GetObjectByQuery


hw_GetObjectByQuery

(PHP 3>= 3.0.3, PHP 4 )

hw_GetObjectByQuery -- search object

Description

array hw_getobjectbyquery ( int connection, string query, int max_hits)

Searches for objects on the whole server and returns an array of object ids. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyqueryobj().

后退 | 起点 | 前进
hw_GetObject | 上一级 | hw_GetObjectByQueryColl


hw_GetObjectByQueryColl

(PHP 3>= 3.0.3, PHP 4 )

hw_GetObjectByQueryColl -- search object in collection

Description

array hw_getobjectbyquerycoll ( int connection, int objectID, string query, int max_hits)

Searches for objects in collection with ID objectID and returns an array of object ids. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyquerycollobj().

后退 | 起点 | 前进
hw_GetObjectByQuery | 上一级 | hw_GetObjectByQueryCollObj


hw_GetObjectByQueryCollObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetObjectByQueryCollObj -- search object in collection

Description

array hw_getobjectbyquerycollobj ( int connection, int objectID, string query, int max_hits)

Searches for objects in collection with ID objectID and returns an array of object records. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyquerycoll().

后退 | 起点 | 前进
hw_GetObjectByQueryColl | 上一级 | hw_GetObjectByQueryObj


hw_GetObjectByQueryObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetObjectByQueryObj -- search object

Description

array hw_getobjectbyqueryobj ( int connection, string query, int max_hits)

Searches for objects on the whole server and returns an array of object records. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyquery().

后退 | 起点 | 前进
hw_GetObjectByQueryCollObj | 上一级 | hw_GetParents


hw_GetParents

(PHP 3>= 3.0.3, PHP 4 )

hw_GetParents -- object ids of parents

Description

array hw_getparents ( int connection, int objectID)

Returns an indexed array of object ids. Each object id belongs to a parent of the object with ID objectID.

后退 | 起点 | 前进
hw_GetObjectByQueryObj | 上一级 | hw_GetParentsObj


hw_GetParentsObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetParentsObj -- object records of parents

Description

array hw_getparentsobj ( int connection, int objectID)

Returns an indexed array of object records plus an associated array with statistical information about the object records. The associated array is the last entry of the returned array. Each object record belongs to a parent of the object with ID objectID.

后退 | 起点 | 前进
hw_GetParents | 上一级 | hw_getrellink


hw_getrellink

(PHP 3>= 3.0.3, PHP 4 )

hw_getrellink -- Get link from source to dest relative to rootid

Description

string hw_getrellink ( int link, int rootid, int sourceid, int destid)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
hw_GetParentsObj | 上一级 | hw_GetRemote


hw_GetRemote

(PHP 3>= 3.0.3, PHP 4 )

hw_GetRemote -- Gets a remote document

Description

int hw_getremote ( int connection, int objectID)

Returns a remote document. Remote documents in Hyperwave notation are documents retrieved from an external source. Common remote documents are for example external web pages or queries in a database. In order to be able to access external sources throught remote documents Hyperwave introduces the HGI (Hyperwave Gateway Interface) which is similar to the CGI. Currently, only ftp, http-servers and some databases can be accessed by the HGI. Calling hw_getremote() returns the document from the external source. If you want to use this function you should be very familiar with HGIs. You should also consider to use PHP instead of Hyperwave to access external sources. Adding database support by a Hyperwave gateway should be more difficult than doing it in PHP.

See also hw_getremotechildren().

后退 | 起点 | 前进
hw_getrellink | 上一级 | hw_GetRemoteChildren


hw_GetRemoteChildren

(PHP 3>= 3.0.3, PHP 4 )

hw_GetRemoteChildren -- Gets children of remote document

Description

int hw_getremotechildren ( int connection, string object record)

Returns the children of a remote document. Children of a remote document are remote documents itself. This makes sense if a database query has to be narrowed and is explained in Hyperwave Programmers' Guide. If the number of children is 1 the function will return the document itself formated by the Hyperwave Gateway Interface (HGI). If the number of children is greater than 1 it will return an array of object record with each maybe the input value for another call to hw_getremotechildren(). Those object records are virtual and do not exist in the Hyperwave server, therefore they do not have a valid object ID. How exactely such an object record looks like is up to the HGI. If you want to use this function you should be very familiar with HGIs. You should also consider to use PHP instead of Hyperwave to access external sources. Adding database support by a Hyperwave gateway should be more difficult than doing it in PHP.

See also hw_getremote().

后退 | 起点 | 前进
hw_GetRemote | 上一级 | hw_GetSrcByDestObj


hw_GetSrcByDestObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetSrcByDestObj -- Returns anchors pointing at object

Description

array hw_getsrcbydestobj ( int connection, int objectID)

Returns the object records of all anchors pointing to the object with ID objectID. The object can either be a document or an anchor of type destination.

See also hw_getanchors().

后退 | 起点 | 前进
hw_GetRemoteChildren | 上一级 | hw_GetText


hw_GetText

(PHP 3>= 3.0.3, PHP 4 )

hw_GetText -- retrieve text document

Description

int hw_gettext ( int connection, int objectID [, mixed rootID/prefix])

Returns the document with object ID objectID. If the document has anchors which can be inserted, they will be inserted already. The optional parameter rootID/prefix can be a string or an integer. If it is an integer it determines how links are inserted into the document. The default is 0 and will result in links that are constructed from the name of the link's destination object. This is useful for web applications. If a link points to an object with name 'internet_movie' the HTML link will be <A HREF="/internet_movie">. The actual location of the source and destination object in the document hierachy is disregarded. You will have to set up your web browser, to rewrite that URL to for example '/my_script.php3/internet_movie'. 'my_script.php3' will have to evaluate $PATH_INFO and retrieve the document. All links will have the prefix '/my_script.php3/'. If you do not want this you can set the optional parameter rootID/prefix to any prefix which is used instead. Is this case it has to be a string.

If rootID/prefix is an integer and unequal to 0 the link is constructed from all the names starting at the object with the id rootID/prefix separated by a slash relative to the current object. If for example the above document 'internet_movie' is located at 'a-b-c-internet_movie' with '-' being the seperator between hierachy levels on the Hyperwave server and the source document is located at 'a-b-d-source' the resulting HTML link would be: <A HREF="../c/internet_movie">. This is useful if you want to download the whole server content onto disk and map the document hierachy onto the file system.

This function will only work for pure text documents. It will not open a special data connection and therefore blocks the control connection during the transfer.

See also hw_pipedocument(),
hw_free_document(),
hw_document_bodytag(),
hw_document_size(),
and hw_output_document().

后退 | 起点 | 前进
hw_GetSrcByDestObj | 上一级 | hw_getusername


hw_getusername

(PHP 3>= 3.0.3, PHP 4 )

hw_getusername -- name of currently logged in user

Description

string hw_getusername ( int connection)

Returns the username of the connection.

后退 | 起点 | 前进
hw_GetText | 上一级 | hw_Identify


hw_Identify

(PHP 3>= 3.0.3, PHP 4 )

hw_Identify -- identifies as user

Description

int hw_identify ( string username, string password)

Identifies as user with username and password. Identification is only valid for the current session. I do not thing this function will be needed very often. In most cases it will be easier to identify with the opening of the connection.

See also hw_connect().

后退 | 起点 | 前进
hw_getusername | 上一级 | hw_InCollections


hw_InCollections

(PHP 3>= 3.0.3, PHP 4 )

hw_InCollections -- check if object ids in collections

Description

array hw_incollections ( int connection, array object_id_array, array collection_id_array, int return_collections)

Checks whether a set of objects (documents or collections) specified by the object_id_array is part of the collections listed in collection_id_array. When the fourth parameter return_collections is 0, the subset of object ids that is part of the collections (i.e., the documents or collections that are children of one or more collections of collection ids or their subcollections, recursively) is returned as an array. When the fourth parameter is 1, however, the set of collections that have one or more objects of this subset as children are returned as an array. This option allows a client to, e.g., highlight the part of the collection hierarchy that contains the matches of a previous query, in a graphical overview.

后退 | 起点 | 前进
hw_Identify | 上一级 | hw_Info


hw_Info

(PHP 3>= 3.0.3, PHP 4 )

hw_Info -- info about connection

Description

string hw_info ( int connection)

Returns information about the current connection. The returned string has the following format: <Serverstring>, <Host>, <Port>, <Username>, <Port of Client>, <Byte swapping>

后退 | 起点 | 前进
hw_InCollections | 上一级 | hw_InsColl


hw_InsColl

(PHP 3>= 3.0.3, PHP 4 )

hw_InsColl -- insert collection

Description

int hw_inscoll ( int connection, int objectID, array object_array)

Inserts a new collection with attributes as in object_array into collection with object ID objectID.

后退 | 起点 | 前进
hw_Info | 上一级 | hw_InsDoc


hw_InsDoc

(PHP 3>= 3.0.3, PHP 4 )

hw_InsDoc -- insert document

Description

int hw_insdoc ( int connection, int parentID, string object_record, string text)

Inserts a new document with attributes as in object_record into collection with object ID parentID. This function inserts either an object record only or an object record and a pure ascii text in text if text is given. If you want to insert a general document of any kind use hw_insertdocument() instead.

See also hw_insertdocument(), and hw_inscoll().

后退 | 起点 | 前进
hw_InsColl | 上一级 | hw_insertanchors


hw_insertanchors

(PHP 4 >= 4.0.4)

hw_insertanchors -- Inserts only anchors into text

Description

string hw_insertanchors ( int hwdoc, array anchorecs, array dest [, array urlprefixes])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
hw_InsDoc | 上一级 | hw_InsertDocument


hw_InsertDocument

(PHP 3>= 3.0.3, PHP 4 )

hw_InsertDocument -- upload any document

Description

int hw_insertdocument ( int connection, int parent_id, int hw_document)

Uploads a document into the collection with parent_id. The document has to be created before with hw_new_document(). Make sure that the object record of the new document contains at least the attributes: Type, DocumentType, Title and Name. Possibly you also want to set the MimeType. The functions returns the object id of the new document or FALSE.

See also hw_pipedocument().

后退 | 起点 | 前进
hw_insertanchors | 上一级 | hw_InsertObject


hw_InsertObject

(PHP 3>= 3.0.3, PHP 4 )

hw_InsertObject -- inserts an object record

Description

int hw_insertobject ( int connection, string object rec, string parameter)

Inserts an object into the server. The object can be any valid hyperwave object. See the HG-CSP documentation for a detailed information on how the parameters have to be.

Note: If you want to insert an Anchor, the attribute Position has always been set either to a start/end value or to 'invisible'. Invisible positions are needed if the annotation has no correspondig link in the annotation text.

See also hw_pipedocument(),
hw_insertdocument(),
hw_insdoc(),
and hw_inscoll().

后退 | 起点 | 前进
hw_InsertDocument | 上一级 | hw_mapid


hw_mapid

(PHP 3>= 3.0.13, PHP 4 )

hw_mapid -- Maps global id on virtual local id

Description

int hw_mapid ( int connection, int server id, int object id)

Maps a global object id on any hyperwave server, even those you did not connect to with hw_connect(), onto a virtual object id. This virtual object id can then be used as any other object id, e.g. to obtain the object record with hw_getobject(). The server id is the first part of the global object id (GOid) of the object which is actually the IP number as an integer.

Note: In order to use this function you will have to set the F_DISTRIBUTED flag, which can currently only be set at compile time in hg_comm.c. It is not set by default. Read the comment at the beginning of hg_comm.c

后退 | 起点 | 前进
hw_InsertObject | 上一级 | hw_Modifyobject


hw_Modifyobject

(PHP 3>= 3.0.7, PHP 4 )

hw_Modifyobject -- modifies object record

Description

int hw_modifyobject ( int connection, int object_to_change, array remove, array add, int mode)

This command allows to remove, add, or modify individual attributes of an object record. The object is specified by the Object ID object_to_change. The first array remove is a list of attributes to remove. The second array add is a list of attributes to add. In order to modify an attribute one will have to remove the old one and add a new one. hw_modifyobject() will always remove the attributes before it adds attributes unless the value of the attribute to remove is not a string or array.

The last parameter determines if the modification is performed recursively. 1 means recurive modification. If some of the objects cannot be modified they will be skiped without notice. hw_error() may not indicate an error though some of the objects could not be modified.

The keys of both arrays are the attributes name. The value of each array element can either be an array, a string or anything else. If it is an array each attribute value is constructed by the key of each element plus a colon and the value of each element. If it is a string it is taken as the attribute value. An empty string will result in a complete removal of that attribute. If the value is neither a string nor an array but something else, e.g. an integer, no operation at all will be performed on the attribute. This is neccessary if you want to to add a completely new attribute not just a new value for an existing attribute. If the remove array contained an empty string for that attribute, the attribute would be tried to be removed which would fail since it doesn't exist. The following addition of a new value for that attribute would also fail. Setting the value for that attribute to e.g. 0 would not even try to remove it and the addition will work.

If you would like to change the attribute 'Name' with the current value 'books' into 'articles' you will have to create two arrays and call hw_modifyobject().

例子 1. modifying an attribute

// $connect is an existing connection to the Hyperwave server
       // $objid is the ID of the object to modify
       $remarr = array("Name" => "books");
       $addarr = array("Name" => "articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
In order to delete/add a name=value pair from/to the object record just pass the remove/add array and set the last/third parameter to an empty array. If the attribute is the first one with that name to add, set attribute value in the remove array to an integer.

例子 2. adding a completely new attribute

// $connect is an existing connection to the Hyperwave server
       // $objid is the ID of the object to modify
       $remarr = array("Name" => 0);
       $addarr = array("Name" => "articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);

注: Multilingual attributes, e.g. 'Title', can be modified in two ways. Either by providing the attributes value in its native form 'language':'title' or by providing an array with elements for each language as described above. The above example would than be:

例子 3. modifying Title attribute

$remarr = array("Title" => "en:Books");
       $addarr = array("Title" => "en:Articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
or

例子 4. modifying Title attribute

$remarr = array("Title" => array("en" => "Books"));
       $addarr = array("Title" => array("en" => "Articles", "ge"=>"Artikel"));
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
This removes the english title 'Books' and adds the english title 'Articles' and the german title 'Artikel'.

例子 5. removing attribute

$remarr = array("Title" => "");
       $addarr = array("Title" => "en:Articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);

注: This will remove all attributes with the name 'Title' and adds a new 'Title' attribute. This comes in handy if you want to remove attributes recursively.

注: If you need to delete all attributes with a certain name you will have to pass an empty string as the attribute value.

注: Only the attributes 'Title', 'Description' and 'Keyword' will properly handle the language prefix. If those attributes don't carry a language prefix, the prefix 'xx' will be assigned.

注: The 'Name' attribute is somewhat special. In some cases it cannot be complete removed. You will get an error message 'Change of base attribute' (not clear when this happens). Therefore you will always have to add a new Name first and than remove the old one.

注: You may not suround this function by calls to hw_getandlock() and hw_unlock(). hw_modifyobject() does this internally.

Returns TRUE if no error occurs otherwise FALSE.

后退 | 起点 | 前进
hw_mapid | 上一级 | hw_Mv


hw_Mv

(PHP 3>= 3.0.3, PHP 4 )

hw_Mv -- moves objects

Description

int hw_mv ( int connection, array object id array, int source id, int destination id)

Moves the objects with object ids as specified in the second parameter from the collection with id source id to the collection with the id destination id. If the destination id is 0 the objects will be unlinked from the source collection. If this is the last instance of that object it will be deleted. If you want to delete all instances at once, use hw_deleteobject().

The value return is the number of moved objects.

See also hw_cp(), and hw_deleteobject().

后退 | 起点 | 前进
hw_Modifyobject | 上一级 | hw_New_Document


hw_New_Document

(PHP 3>= 3.0.3, PHP 4 )

hw_New_Document -- create new document

Description

int hw_new_document ( string object_record, string document_data, int document_size)

Returns a new Hyperwave document with document data set to document_data and object record set to object_record. The length of the document_data has to passed in document_sizeThis function does not insert the document into the Hyperwave server.

See also hw_free_document(),
hw_document_size(),
hw_document_bodytag(),
hw_output_document(),
and hw_insertdocument().

后退 | 起点 | 前进
hw_Mv | 上一级 | hw_Objrec2Array


hw_Objrec2Array

(PHP 3>= 3.0.3, PHP 4 )

hw_Objrec2Array -- convert attributes from object record to object array

Description

array hw_objrec2array ( string object_record [, array format])

Converts an object_record into an object array. The keys of the resulting array are the attributes names. Multi-value attributes like 'Title' in different languages form its own array. The keys of this array are the left part to the colon of the attribute value. This left part must be two characters long. Other multi-value attributes without a prefix form an indexed array. If the optional parameter is missing the attributes 'Title', 'Description' and 'Keyword' are treated as language attributes and the attributes 'Group', 'Parent' and 'HtmlAttr' as non-prefixed multi-value attributes. By passing an array holding the type for each attribute you can alter this behaviour. The array is an associated array with the attribute name as its key and the value being one of HW_ATTR_LANG or HW_ATTR_NONE

See also hw_array2objrec().

后退 | 起点 | 前进
hw_New_Document | 上一级 | hw_Output_Document


hw_Output_Document

(PHP 3>= 3.0.3, PHP 4 )

hw_Output_Document -- prints hw_document

Description

int hw_output_document ( int hw_document)

Prints the document without the BODY tag.

For backward compatibility, hw_outputdocument() is also accepted. This is deprecated, however.

后退 | 起点 | 前进
hw_Objrec2Array | 上一级 | hw_pConnect


hw_pConnect

(PHP 3>= 3.0.3, PHP 4 )

hw_pConnect -- make a persistent database connection

Description

int hw_pconnect ( string host, int port, string username, string password)

Returns a connection index on success, or FALSE if the connection could not be made. Opens a persistent connection to a Hyperwave server. Each of the arguments should be a quoted string, except for the port number. The username and password arguments are optional and can be left out. In such a case no identification with the server will be done. It is similar to identify as user anonymous. This function returns a connection index that is needed by other Hyperwave functions. You can have multiple persistent connections open at once.

See also hw_connect().

后退 | 起点 | 前进
hw_Output_Document | 上一级 | hw_PipeDocument


hw_PipeDocument

(PHP 3>= 3.0.3, PHP 4 )

hw_PipeDocument -- retrieve any document

Description

int hw_pipedocument ( int connection, int objectID)

Returns the Hyperwave document with object ID objectID. If the document has anchors which can be inserted, they will have been inserted already. The document will be transfered via a special data connection which does not block the control connection.

See also hw_gettext() for more on link insertion,
hw_free_document(),
hw_document_size(),
hw_document_bodytag(),
and hw_output_document().

后退 | 起点 | 前进
hw_pConnect | 上一级 | hw_Root


hw_Root

(PHP 3>= 3.0.3, PHP 4 )

hw_Root -- root object id

Description

int hw_root ( )

Returns the object ID of the hyperroot collection. Currently this is always 0. The child collection of the hyperroot is the root collection of the connected server.

后退 | 起点 | 前进
hw_PipeDocument | 上一级 | hw_setlinkroot


hw_setlinkroot

(PHP 3>= 3.0.3, PHP 4 )

hw_setlinkroot -- Set the id to which links are calculated

Description

void hw_setlinkroot ( int link, int rootid)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
hw_Root | 上一级 | hw_stat


hw_stat

(PHP 3>= 3.0.3, PHP 4 )

hw_stat -- Returns status string

Description

string hw_stat ( int link)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
hw_setlinkroot | 上一级 | hw_Unlock


hw_Unlock

(PHP 3>= 3.0.3, PHP 4 )

hw_Unlock -- unlock object

Description

int hw_unlock ( int connection, int objectID)

Unlocks a document, so other users regain access.

See also hw_getandlock().

后退 | 起点 | 前进
hw_stat | 上一级 | hw_Who


hw_Who

(PHP 3>= 3.0.3, PHP 4 )

hw_Who -- List of currently logged in users

Description

int hw_who ( int connection)

Returns an array of users currently logged into the Hyperwave server. Each entry in this array is an array itself containing the elements id, name, system, onSinceDate, onSinceTime, TotalTime and self. 'self' is 1 if this entry belongs to the user who initianted the request.

后退 | 起点 | 前进
hw_Unlock | 上一级 | Hyperwave API functions


Hyperwave API functions

PHP 手册
后退 前进

XXXIX. Hyperwave API functions

介绍

Hyperwave has been developed at IICM in Graz. It started with the name Hyper-G and changed to Hyperwave when it was commercialised (in 1996).

Hyperwave is not free software. The current version, 5.5, is available at http://www.hyperwave.com/. A time limited version can be ordered for free (30 days).

See also the Hyperwave module.

Hyperwave is an information system similar to a database (HIS, Hyperwave Information Server). Its focus is the storage and management of documents. A document can be any possible piece of data that may as well be stored in file. Each document is accompanied by its object record. The object record contains meta data for the document. The meta data is a list of attributes which can be extended by the user. Certain attributes are always set by the Hyperwave server, other may be modified by the user.

需求

Since 2001 there is a Hyperwave SDK available. It supports Java, JavaScript and C++. This PHP Extension is based on the C++ interface. In order to activate the hwapi support in PHP you will have to install the Hyperwave SDK first.

安装

After installing the Hyperwave SDK, configure PHP with --with-hwapi=<dir$gt;.

Integration with Apache

The integration with Apache and possible other servers is already described in the Hyperwave module which has been the first extension to connect a Hyperwave Server.

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. Hyperwave API configuration options

Name | Default | Changeable
hwapi.allow_persistent | "0" | PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

Classes

The API provided by the HW_API extension is fully object oriented. It is very similar to the C++ interface of the Hyperwave SDK. It consist of the following classes.

  • HW_API

  • HW_API_Object

  • HW_API_Attribute

  • HW_API_Error

  • HW_API_Content

  • HW_API_Reason

Some basic classes like HW_API_String, HW_API_String_Array, etc., which exist in the Hyperwave SDK have not been implemented since PHP has powerful replacements for them.

Each class has certain method, whose names are identical to its counterparts in the Hyperwave SDK. Passing arguments to this function differs from all the other PHP extensions but is close to the C++ API of the HW SDK. Instead of passing serval parameters they are all put into an associated array and passed as one paramter. The names of the keys are identical to those documented in the HW SDK. The common parameters are listed below. If other parameters are required they will be documented if needed.

  • objectIdentifier The name or id of an object, e.g. "rootcollection", "0x873A8768 0x00000002".

  • parentIdentifier The name or id of an object which is considered to be a parent.

  • object An instance of class HW_API_Object.

  • parameters An instance of class HW_API_Object.

  • version The version of an object.

  • mode An integer value determine the way an operation is executed.

  • attributeSelector Any array of strings, each containing a name of an attribute. This is used if you retrieve the object record and want to include certain attributes.

  • objectQuery A query to select certain object out of a list of objects. This is used to reduce the number of objects which was delivered by a function like hw_api->children() or hw_api->find().

目录
hw_api_attribute->key — Returns key of the attribute
hw_api_attribute->langdepvalue — Returns value for a given language
hw_api_attribute->value — Returns value of the attribute
hw_api_attribute->values — Returns all values of the attribute
hw_api_attribute — Creates instance of class hw_api_attribute
hw_api->checkin — Checks in an object
hw_api->checkout — Checks out an object
hw_api->children — Returns children of an object
hw_api_content->mimetype — Returns mimetype
hw_api_content->read — Read content
hw_api->content — Returns content of an object
hw_api->copy — Copies physically
hw_api->dbstat — Returns statistics about database server
hw_api->dcstat — Returns statistics about document cache server
hw_api->dstanchors — Returns a list of all destination anchors
hw_api->dstofsrcanchors — Returns destination of a source anchor
hw_api_error->count — Returns number of reasons
hw_api_error->reason — Returns reason of error
hw_api->find — Search for objects
hw_api->ftstat — Returns statistics about fulltext server
hwapi_hgcsp — Returns object of class hw_api
hw_api->hwstat — Returns statistics about Hyperwave server
hw_api->identify — Log into Hyperwave Server
hw_api->info — Returns information about server configuration
hw_api->insert — Inserts a new object
hw_api->insertanchor — Inserts a new object of type anchor
hw_api->insertcollection — Inserts a new object of type collection
hw_api->insertdocument — Inserts a new object of type document
hw_api->link — Creates a link to an object
hw_api->lock — Locks an object
hw_api->move — Moves object between collections
hw_api_content — Create new instance of class hw_api_content
hw_api_object->assign — Clones object
hw_api_object->attreditable — Checks whether an attribute is editable
hw_api_object->count — Returns number of attributes
hw_api_object->insert — Inserts new attribute
hw_api_object — Creates a new instance of class hw_api_object
hw_api_object->remove — Removes attribute
hw_api_object->title — Returns the title attribute
hw_api_object->value — Returns value of attribute
hw_api->object — Retrieve attribute information
hw_api->objectbyanchor — Returns the object an anchor belongs to
hw_api->parents — Returns parents of an object
hw_api_reason->description — Returns description of reason
hw_api_reason->type — Returns type of reason
hw_api->remove — Delete an object
hw_api->replace — Replaces an object
hw_api->setcommitedversion — Commits version other than last version
hw_api->srcanchors — Returns a list of all source anchors
hw_api->srcsofdst — Returns source of a destination object
hw_api->unlock — Unlocks a locked object
hw_api->user — Returns the own user object
hw_api->userlist — Returns a list of all logged in users

后退 | 起点 | 前进
hw_Who | 上一级 | hw_api_attribute->key


hw_api_attribute->key

(no version information, might be only in CVS)

hw_api_attribute->key -- Returns key of the attribute

Description

string key ( void )

Returns the name of the attribute.

See also hwapi_attribute_value().

后退 | 起点 | 前进
Hyperwave API functions | 上一级 | hw_api_attribute->langdepvalue


hw_api_attribute->langdepvalue

(no version information, might be only in CVS)

hw_api_attribute->langdepvalue -- Returns value for a given language

Description

string langdepvalue ( string language)

Returns the value in the given language of the attribute.

See also hwapi_attribute_value().

后退 | 起点 | 前进
hw_api_attribute->key | 上一级 | hw_api_attribute->value


hw_api_attribute->value

(no version information, might be only in CVS)

hw_api_attribute->value -- Returns value of the attribute

Description

string value ( void )

Returns the value of the attribute.

See also hwapi_attribute_key(), hwapi_attribute_values().

后退 | 起点 | 前进
hw_api_attribute->langdepvalue | 上一级 | hw_api_attribute->values


hw_api_attribute->values

(no version information, might be only in CVS)

hw_api_attribute->values -- Returns all values of the attribute

Description

array values ( void )

Returns all values of the attribute as an array of strings.

See also hwapi_attribute_value().

后退 | 起点 | 前进
hw_api_attribute->value | 上一级 | hw_api_attribute


hw_api_attribute

(no version information, might be only in CVS)

hw_api_attribute -- Creates instance of class hw_api_attribute

Description

object attribute ( [string name [, string value]])

Creates a new instance of hw_api_attribute with the given name and value.

后退 | 起点 | 前进
hw_api_attribute->values | 上一级 | hw_api->checkin


hw_api->checkin

(no version information, might be only in CVS)

hw_api->checkin -- Checks in an object

Description

object checkin ( array parameter)

This function checks in an object or a whole hiearchie of objects. The parameters array contains the required element 'objectIdentifier' and the optional element 'version', 'comment', 'mode' and 'objectQuery'. 'version' sets the version of the object. It consists of the major and minor version separated by a period. If the version is not set, the minor version is incremented. 'mode' can be one of the following values:

HW_API_CHECKIN_NORMAL

Checks in and commits the object. The object must be a document.

HW_API_CHECKIN_RECURSIVE

If the object to check in is a collection, all children will be checked in recursively if they are documents. Trying to check in a collection would result in an error.

HW_API_CHECKIN_FORCE_VERSION_CONTROL

Checks in an object even if it is not under version control.

HW_API_CHECKIN_REVERT_IF_NOT_CHANGED

Check if the new version is different from the last version. Unless this is the case the object will be checked in.

HW_API_CHECKIN_KEEP_TIME_MODIFIED

Keeps the time modified from the most recent object.

HW_API_CHECKIN_NO_AUTO_COMMIT

The object is not automatically commited on checkin.

See also hwapi_checkout().

后退 | 起点 | 前进
hw_api_attribute | 上一级 | hw_api->checkout


hw_api->checkout

(no version information, might be only in CVS)

hw_api->checkout -- Checks out an object

Description

object checkout ( array parameter)

This function checks out an object or a whole hiearchie of objects. The parameters array contains the required element 'objectIdentifier' and the optional element 'version', 'mode' and 'objectQuery'. 'mode' can be one of the following values:

HW_API_CHECKIN_NORMAL

Checks out an object. The object must be a document.

HW_API_CHECKIN_RECURSIVE

If the object to check out is a collection, all children will be checked out recursively if they are documents. Trying to check out a collection would result in an error.

See also hwapi_checkin().

后退 | 起点 | 前进
hw_api->checkin | 上一级 | hw_api->children


hw_api->children

(no version information, might be only in CVS)

hw_api->children -- Returns children of an object

Description

array children ( array parameter)

Retrieves the children of a collection or the attributes of a document. The children can be further filtered by specifying an object query. The parameter array contains the required elements 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

The return value is an array of objects of type HW_API_Object or HW_API_Error.

See also hwapi_parents().

后退 | 起点 | 前进
hw_api->checkout | 上一级 | hw_api_content->mimetype


hw_api_content->mimetype

(no version information, might be only in CVS)

hw_api_content->mimetype -- Returns mimetype

Description

string mimetype ( void )

Returns the mimetype of the content.

后退 | 起点 | 前进
hw_api->children | 上一级 | hw_api_content->read


hw_api_content->read

(no version information, might be only in CVS)

hw_api_content->read -- Read content

Description

string read ( string buffer, integer len)

Reads len bytes from the content into the given buffer.

后退 | 起点 | 前进
hw_api_content->mimetype | 上一级 | hw_api->content


hw_api->content

(no version information, might be only in CVS)

hw_api->content -- Returns content of an object

Description

object content ( array parameter)

This function returns the content of a document as an object of type hw_api_content. The parameter array contains the required elements 'objectidentifier' and the optional element 'mode'. The mode can be one of the constants HW_API_CONTENT_ALLLINKS, HW_API_CONTENT_REACHABLELINKS or HW_API_CONTENT_PLAIN. HW_API_CONTENT_ALLLINKS means to insert all anchors even if the destination is not reachable. HW_API_CONTENT_REACHABLELINKS tells hw_api_content() to insert only reachable links and HW_API_CONTENT_PLAIN will lead to document without any links.

后退 | 起点 | 前进
hw_api_content->read | 上一级 | hw_api->copy


hw_api->copy

(no version information, might be only in CVS)

hw_api->copy -- Copies physically

Description

object copy ( array parameter)

This function will make a physical copy including the content if it exists and returns the new object or an error object. The parameter array contains the required elements 'objectIdentifier' and 'destinationParentIdentifier'. The optional parameter is 'attributeSelector'`

See also hwapi_move(), hwapi_link().

后退 | 起点 | 前进
hw_api->content | 上一级 | hw_api->dbstat


hw_api->dbstat

(no version information, might be only in CVS)

hw_api->dbstat -- Returns statistics about database server

Description

object dbstat ( array parameter)

See also hwapi_dcstat(),
         hwapi_hwstat(),
         hwapi_ftstat().

后退 | 起点 | 前进
hw_api->copy | 上一级 | hw_api->dcstat


hw_api->dcstat

(no version information, might be only in CVS)

hw_api->dcstat -- Returns statistics about document cache server

Description

object dcstat ( array parameter)

See also hwapi_hwstat(),
         hwapi_dbstat(),
         hwapi_ftstat().

后退 | 起点 | 前进
hw_api->dbstat | 上一级 | hw_api->dstanchors


hw_api->dstanchors

(no version information, might be only in CVS)

hw_api->dstanchors -- Returns a list of all destination anchors

Description

object dstanchors ( array parameter)

Retrieves all destination anchors of an object. The parameter array contains the required element 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

See also hwapi_srcanchors().

后退 | 起点 | 前进
hw_api->dcstat | 上一级 | hw_api->dstofsrcanchors


hw_api->dstofsrcanchors

(no version information, might be only in CVS)

hw_api->dstofsrcanchors -- Returns destination of a source anchor

Description

object dstofsrcanchors ( array parameter)

Retrieves the destination object pointed by the specified source anchors. The destination object can either be a destination anchor or a whole document. The parameters array contains the required element 'objectIdentifier' and the optional element 'attributeSelector'.

See also hwapi_srcanchors(),
         hwapi_dstanchors(),
         hwapi_objectbyanchor().

后退 | 起点 | 前进
hw_api->dstanchors | 上一级 | hw_api_error->count


hw_api_error->count

(no version information, might be only in CVS)

hw_api_error->count -- Returns number of reasons

Description

int count ( void )

Returns the number of error reasons.

See also hwapi_error_reason().

后退 | 起点 | 前进
hw_api->dstofsrcanchors | 上一级 | hw_api_error->reason


hw_api_error->reason

(no version information, might be only in CVS)

hw_api_error->reason -- Returns reason of error

Description

object reason ( void )

Returns the first error reason.

See also hwapi_error_count().

后退 | 起点 | 前进
hw_api_error->count | 上一级 | hw_api->find


hw_api->find

(no version information, might be only in CVS)

hw_api->find -- Search for objects

Description

array find ( array parameter)

This functions searches for objects either by executing a key or/and full text query. The found objects can further be filtered by an optional object query. They are sorted by their importance. The second search operation is relatively slow and its result can be limited to a certain number of hits. This allows to perform an incremental search, each returning just a subset of all found documents, starting at a given index. The parameter array contains the 'keyquery' or/and 'fulltextquery' depending on who you would like to search. Optional parameters are 'objectquery', 'scope', 'lanugages' and 'attributeselector'. In case of an incremental search the optional parameters 'startIndex', numberOfObjectsToGet' and 'exactMatchUnit' can be passed.

后退 | 起点 | 前进
hw_api_error->reason | 上一级 | hw_api->ftstat


hw_api->ftstat

(no version information, might be only in CVS)

hw_api->ftstat -- Returns statistics about fulltext server

Description

object ftstat ( array parameter)

See also hwapi_dcstat(),
         hwapi_dbstat(),
         hwapi_hwstat().

后退 | 起点 | 前进
hw_api->find | 上一级 | hwapi_hgcsp


hwapi_hgcsp

(no version information, might be only in CVS)

hwapi_hgcsp -- Returns object of class hw_api

Description

object hwapi_hgcsp ( string hostname [, int port])

Opens a connection to the Hyperwave server on host hostname. The protocol used is HGCSP. If you do not pass a port number, 418 is used.

See also hwapi_hwtp().

后退 | 起点 | 前进
hw_api->ftstat | 上一级 | hw_api->hwstat


hw_api->hwstat

(no version information, might be only in CVS)

hw_api->hwstat -- Returns statistics about Hyperwave server

Description

object hwstat ( array parameter)

See also hwapi_dcstat(),
         hwapi_dbstat(),
         hwapi_ftstat().

后退 | 起点 | 前进
hwapi_hgcsp | 上一级 | hw_api->identify


hw_api->identify

(no version information, might be only in CVS)

hw_api->identify -- Log into Hyperwave Server

Description

object identify ( array parameter)

Logs into the Hyperwave Server. The parameter array must contain the elements 'username' und 'password'.

The return value will be an object of type HW_API_Error if identification failed or TRUE if it was successful.

后退 | 起点 | 前进
hw_api->hwstat | 上一级 | hw_api->info


hw_api->info

(no version information, might be only in CVS)

hw_api->info -- Returns information about server configuration

Description

object info ( array parameter)

See also hwapi_dcstat(),
         hwapi_dbstat(),
         hwapi_ftstat(),
         hwapi_hwstat().

后退 | 起点 | 前进
hw_api->identify | 上一级 | hw_api->insert


hw_api->insert

(no version information, might be only in CVS)

hw_api->insert -- Inserts a new object

Description

object insert ( array parameter)

Insert a new object. The object type can be user, group, document or anchor. Depending on the type other object attributes has to be set. The parameter array contains the required elements 'object' and 'content' (if the object is a document) and the optional parameters 'parameters', 'mode' and 'attributeSelector'. The 'object' must contain all attributes of the object. 'parameters' is an object as well holding futher attributes like the destination (attribute key is 'Parent'). 'content' is the content of the document. 'mode' can be a combination of the following flags:

HW_API_INSERT_NORMAL

The object in inserted into the server.

HW_API_INSERT_FORCE-VERSION-CONTROL

HW_API_INSERT_AUTOMATIC-CHECKOUT

HW_API_INSERT_PLAIN

HW_API_INSERT_KEEP_TIME_MODIFIED

HW_API_INSERT_DELAY_INDEXING

See also hwapi_replace().

后退 | 起点 | 前进
hw_api->info | 上一级 | hw_api->insertanchor


hw_api->insertanchor

(no version information, might be only in CVS)

hw_api->insertanchor -- Inserts a new object of type anchor

Description

object insertanchor ( array parameter)

This function is a shortcut for hwapi_insert(). It inserts an object of type anchor and sets some of the attributes required for an anchor. The parameter array contains the required elements 'object' and 'documentIdentifier' and the optional elements 'destinationIdentifier', 'parameter', 'hint' and 'attributeSelector'. The 'documentIdentifier' specifies the document where the anchor shall be inserted. The target of the anchor is set in 'destinationIdentifier' if it already exists. If the target does not exists the element 'hint' has to be set to the name of object which is supposed to be inserted later. Once it is inserted the anchor target is resolved automatically.

See also hwapi_insertdocument(),
         hwapi_insertcollection(),
         hwapi_insert().

后退 | 起点 | 前进
hw_api->insert | 上一级 | hw_api->insertcollection


hw_api->insertcollection

(no version information, might be only in CVS)

hw_api->insertcollection -- Inserts a new object of type collection

Description

object insertcollection ( array parameter)

This function is a shortcut for hwapi_insert(). It inserts an object of type collection and sets some of the attributes required for a collection. The parameter array contains the required elements 'object' and 'parentIdentifier' and the optional elements 'parameter' and 'attributeSelector'. See hwapi_insert() for the meaning of each element.

See also hwapi_insertdocument(),
         hwapi_insertanchor(),
         hwapi_insert().

后退 | 起点 | 前进
hw_api->insertanchor | 上一级 | hw_api->insertdocument


hw_api->insertdocument

(no version information, might be only in CVS)

hw_api->insertdocument -- Inserts a new object of type document

Description

object insertdocument ( array parameter)

This function is a shortcut for hwapi_insert(). It inserts an object with content and sets some of the attributes required for a document. The parameter array contains the required elements 'object', 'parentIdentifier' and 'content' and the optional elements 'mode', 'parameter' and 'attributeSelector'. See hwapi_insert() for the meaning of each element.

See also hwapi_insert()
         hwapi_insertanchor(),
         hwapi_insertcollection().

后退 | 起点 | 前进
hw_api->insertcollection | 上一级 | hw_api->link


hw_api->link

(no version information, might be only in CVS)

hw_api->link -- Creates a link to an object

Description

object link ( array parameter)

Creates a link to an object. Accessing this link is like accessing the object to links points to. The parameter array contains the required elements 'objectIdentifier' and 'destinationParentIdentifier'. 'destinationParentIdentifier' is the target collection.

The function returns true on success or an error object.

See also hwapi_copy().

后退 | 起点 | 前进
hw_api->insertdocument | 上一级 | hw_api->lock


hw_api->lock

(no version information, might be only in CVS)

hw_api->lock -- Locks an object

Description

object lock ( array parameter)

Locks an object for exclusive editing by the user calling this function. The object can be only unlocked by this user or the sytem user. The parameter array contains the required element 'objectIdentifier' and the optional parameters 'mode' and 'objectquery'. 'mode' determines how an object is locked. HW_API_LOCK_NORMAL means, an object is locked until it is unlocked. HW_API_LOCK_RECURSIVE is only valid for collection and locks all objects within th collection und possible subcollections. HW_API_LOCK_SESSION means, an object is locked only as long as the session is valid.

See also hwapi_unlock().

后退 | 起点 | 前进
hw_api->link | 上一级 | hw_api->move


hw_api->move

(no version information, might be only in CVS)

hw_api->move -- Moves object between collections

Description

object move ( array parameter)

See also hw_objrec2array().

后退 | 起点 | 前进
hw_api->lock | 上一级 | hw_api_content


hw_api_content

(no version information, might be only in CVS)

hw_api_content -- Create new instance of class hw_api_content

Description

string content ( string content, string mimetype)

Creates a new content object from the string content. The mimetype is set to mimetype.

后退 | 起点 | 前进
hw_api->move | 上一级 | hw_api_object->assign


hw_api_object->assign

(no version information, might be only in CVS)

hw_api_object->assign -- Clones object

Description

object assign ( array parameter)

Clones the attributes of an object.

后退 | 起点 | 前进
hw_api_content | 上一级 | hw_api_object->attreditable


hw_api_object->attreditable

(no version information, might be only in CVS)

hw_api_object->attreditable -- Checks whether an attribute is editable

Description

bool attreditable ( array parameter)

后退 | 起点 | 前进
hw_api_object->assign | 上一级 | hw_api_object->count


hw_api_object->count

(no version information, might be only in CVS)

hw_api_object->count -- Returns number of attributes

Description

int count ( array parameter)

后退 | 起点 | 前进
hw_api_object->attreditable | 上一级 | hw_api_object->insert


hw_api_object->insert

(no version information, might be only in CVS)

hw_api_object->insert -- Inserts new attribute

Description

bool insert ( object attribute)

Adds an attribute to the object. Returns true on success and otherwise false.

See also hwapi_object_remove().

后退 | 起点 | 前进
hw_api_object->count | 上一级 | hw_api_object


hw_api_object

(no version information, might be only in CVS)

hw_api_object -- Creates a new instance of class hw_api_object

Description

object hw_api_object ( array parameter)

See also hwapi_lock().

后退 | 起点 | 前进
hw_api_object->insert | 上一级 | hw_api_object->remove


hw_api_object->remove

(no version information, might be only in CVS)

hw_api_object->remove -- Removes attribute

Description

bool remove ( string name)

Removes the attribute with the given name. Returns true on success and otherwise false.

See also hwapi_object_insert().

后退 | 起点 | 前进
hw_api_object | 上一级 | hw_api_object->title


hw_api_object->title

(no version information, might be only in CVS)

hw_api_object->title -- Returns the title attribute

Description

string title ( array parameter)

后退 | 起点 | 前进
hw_api_object->remove | 上一级 | hw_api_object->value


hw_api_object->value

(no version information, might be only in CVS)

hw_api_object->value -- Returns value of attribute

Description

string value ( string name)

Returns the value of the attribute with the given name or false if an error occured.

后退 | 起点 | 前进
hw_api_object->title | 上一级 | hw_api->object


hw_api->object

(no version information, might be only in CVS)

hw_api->object -- Retrieve attribute information

Description

object hw_api->object ( array parameter)

This function retrieves the attribute information of an object of any version. It will not return the document content. The parameter array contains the required elements 'objectIdentifier' and the optional elements 'attributeSelector' and 'version'.

The returned object is an instance of class HW_API_Object on success or HW_API_Error if an error occured.

This simple example retrieves an object and checks for errors.

例子 1. Retrieve an object

<?php
function handle_error($error) {
  $reason = $error->reason(0);
  echo "Type: <B>";
  switch($reason->type()) {
    case 0:
      echo "Error";
      break;
    case 1:
      echo "Warning";
      break;
    case 2:
      echo "Message";
      break;
  }
  echo "</B><BR>\n";
  echo "Description: ".$reason->description("en")."<BR>\n";
}

function list_attr($obj) {
  echo "<TABLE>\n";
  $count = $obj->count();
  for($i=0; $i<$count; $i++) {
    $attr = $obj->attribute($i);
    printf("  <TR><TD ALIGN=right bgcolor=#c0c0c0><B>%s</B></TD><TD bgcolor=#F0F0F0>%s</TD>\n",
             $attr->key(), $attr->value());
  }
  echo "</TABLE>\n";
}

$hwapi = hwapi_hgcsp($g_config[HOSTNAME]);
$parms = array("objectIdentifier"=>"rootcollection, "attributeSelector"=>array("Title", "Name", "DocumentType"));
$root = $hwapi->object($parms);
if(get_class($root) == "HW_API_Error") {
  handle_error($root);
  exit;
}
list_attr($root);
?>

See also hwapi_content().

后退 | 起点 | 前进
hw_api_object->value | 上一级 | hw_api->objectbyanchor


hw_api->objectbyanchor

(no version information, might be only in CVS)

hw_api->objectbyanchor -- Returns the object an anchor belongs to

Description

object objectbyanchor ( array parameter)

This function retrieves an object the specified anchor belongs to. The parameter array contains the required element 'objectIdentifier' and the optional element 'attributeSelector'.

See also hwapi_dstofsrcanchor(),
         hwapi_srcanchors(),
         hwapi_dstanchors().

后退 | 起点 | 前进
hw_api->object | 上一级 | hw_api->parents


hw_api->parents

(no version information, might be only in CVS)

hw_api->parents -- Returns parents of an object

Description

array parents ( array parameter)

Retrieves the parents of an object. The parents can be further filtered by specifying an object query. The parameter array contains the required elements 'objectidentifier' and the optional elements 'attributeselector' and 'objectquery'.

The return value is an array of objects of type HW_API_Object or HW_API_Error.

See also hwapi_children().

后退 | 起点 | 前进
hw_api->objectbyanchor | 上一级 | hw_api_reason->description


hw_api_reason->description

(no version information, might be only in CVS)

hw_api_reason->description -- Returns description of reason

Description

string description ( void )

Returns the description of a reason

后退 | 起点 | 前进
hw_api->parents | 上一级 | hw_api_reason->type


hw_api_reason->type

(no version information, might be only in CVS)

hw_api_reason->type -- Returns type of reason

Description

object type ( void )

Returns the type of a reason.

后退 | 起点 | 前进
hw_api_reason->description | 上一级 | hw_api->remove


hw_api->remove

(no version information, might be only in CVS)

hw_api->remove -- Delete an object

Description

object remove ( array parameter)

This function removes an object from the specified parent. Collections will be removed recursively. You can pass an optional object query to remove only those objects which match the query. An object will be deleted physically if it is the last instance. The parameter array contains the required elements 'objectidentifier' and 'parentidentifier'. If you want to remove a user or group 'parentidentifier' can be skiped. The optional parameter 'mode' determines how the deletion is performed. In normal mode the object will not be removed physically until all instances are removed. In physical mode all instances of the object will be deleted imediately. In removelinks mode all references to and from the objects will be deleted as well. In nonrecursive the deletion is not performed recursive. Removing a collection which is not empty will cause an error.

See also hwapi_move().

后退 | 起点 | 前进
hw_api_reason->type | 上一级 | hw_api->replace


hw_api->replace

(no version information, might be only in CVS)

hw_api->replace -- Replaces an object

Description

object replace ( array parameter)

Replaces the attributes and the content of an object The parameter array contains the required elements 'objectIdentifier' and 'object' and the optional parameters 'content', 'parameters', 'mode' and 'attributeSelector'. 'objectIdentifier' contains the object to be replaced. 'object' contains the new object. 'content' contains the new content. 'parameters' contain extra information for HTML documents. HTML_Language is the letter abbreviation of the language of the title. HTML_Base sets the base attribute of the HTML document. 'mode' can be a combination of the following flags:

HW_API_REPLACE_NORMAL

The object on the server is replace with the object passed.

HW_API_REPLACE_FORCE_VERSION_CONTROL

HW_API_REPLACE_AUTOMATIC_CHECKOUT

HW_API_REPLACE_AUTOMATIC_CHECKIN

HW_API_REPLACE_PLAIN

HW_API_REPLACE_REVERT_IF_NOT_CHANGED

HW_API_REPLACE_KEEP_TIME_MODIFIED

See also hwapi_insert().

后退 | 起点 | 前进
hw_api->remove | 上一级 | hw_api->setcommitedversion


hw_api->setcommitedversion

(no version information, might be only in CVS)

hw_api->setcommitedversion -- Commits version other than last version

Description

object setcommitedversion ( array parameter)

Commits a version of a docuemnt. The commited version is the one which is visible to users with read access. By default the last version is the commited version.

See also hwapi_checkin(),
         hwapi_checkout(),
         hwapi_revert().

后退 | 起点 | 前进
hw_api->replace | 上一级 | hw_api->srcanchors


hw_api->srcanchors

(no version information, might be only in CVS)

hw_api->srcanchors -- Returns a list of all source anchors

Description

object srcanchors ( array parameter)

Retrieves all source anchors of an object. The parameter array contains the required element 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

See also hwapi_dstanchors().

后退 | 起点 | 前进
hw_api->setcommitedversion | 上一级 | hw_api->srcsofdst


hw_api->srcsofdst

(no version information, might be only in CVS)

hw_api->srcsofdst -- Returns source of a destination object

Description

object srcsofdst ( array parameter)

Retrieves all the source anchors pointing to the specified destination. The destination object can either be a destination anchor or a whole document. The parameters array contains the required element 'objectIdentifier' and the optional element 'attributeSelector' and 'objectQuery'. The function returns an array of objects or an error.

See also hwapi_dstofsrcanchor().

后退 | 起点 | 前进
hw_api->srcanchors | 上一级 | hw_api->unlock


hw_api->unlock

(no version information, might be only in CVS)

hw_api->unlock -- Unlocks a locked object

Description

object unlock ( array parameter)

Unlocks a locked object. Only the user who has locked the object and the system user may unlock an object. The parameter array contains the required element 'objectIdentifier' and the optional parameters 'mode' and 'objectquery'. The meaning of 'mode' is the same as in function hwapi_lock().

Returns true on success or an object of class HW_API_Error.

See also hwapi_lock().

后退 | 起点 | 前进
hw_api->srcsofdst | 上一级 | hw_api->user


hw_api->user

(no version information, might be only in CVS)

hw_api->user -- Returns the own user object

Description

object user ( array parameter)

See also hwapi_userlist().

后退 | 起点 | 前进
hw_api->unlock | 上一级 | hw_api->userlist


hw_api->userlist

(no version information, might be only in CVS)

hw_api->userlist -- Returns a list of all logged in users

Description

object userlist ( array parameter)

See also hwapi_user().

后退 | 起点 | 前进
hw_api->user | 上一级 | iconv functions


iconv functions

PHP 手册
后退 前进

XL. iconv functions

介绍

This module contains an interface to the iconv library functions. The iconv library functions convert strings between various character sets encodings. The supported character sets depend on the iconv() implementation on your system. Note that the iconv() function on some systems may not work as well as you expect. In this case, you should install the libiconv library.

需求

Your systems standard C library must provide the iconv() function or you must have libiconv installed on your system. The libiconv library is available from http://www.gnu.org/software/libiconv/.

安装

To be able to use the functions defined in this module you must compile your PHP interpreter using the configure line --with-iconv[=DIR].

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. Iconv configuration options

Name | Default | Changeable
iconv.input_encoding | ICONV_INPUT_ENCODING | PHP_INI_ALL
iconv.output_encoding | ICONV_OUTPUT_ENCODING | PHP_INI_ALL
iconv.internal_encoding | ICONV_INTERNAL_ENCODING | PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

相关参考

See also the GNU Recode functions.

目录
iconv_get_encoding — Get current setting for character encoding conversion
iconv_set_encoding — Set current setting for character encoding conversion
iconv — Convert string to requested character encoding
ob_iconv_handler — Convert character encoding as output buffer handler

后退 | 起点 | 前进
hw_api->userlist | 上一级 | iconv_get_encoding


iconv_get_encoding

(PHP 4 >= 4.0.5)

iconv_get_encoding -- Get current setting for character encoding conversion

Description

array iconv_get_encoding ( [string type])

It returns the current settings of ob_iconv_handler() as array or FALSE on failure. The value of the optinal type can be:

all
input_encoding
output_encoding
internal_encoding

If type is omitted or not 'all' iconv_get_encoding() returns the current settings of ob_iconv_handler() as string.

例子 1. iconv_get_encoding() example:

<pre>
<?php
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");
var_dump(iconv_get_encoding('all'));
?>
</pre>

The printout of the above program will be:
Array

(

    [input_encoding] => ISO-8859-1

    [output_encoding] => ISO-8859-1

    [internal_encoding] => UTF-8

)

See also: iconv_set_encoding() and ob_iconv_handler().

后退 | 起点 | 前进
iconv functions | 上一级 | iconv_set_encoding


iconv_set_encoding

(PHP 4 >= 4.0.5)

iconv_set_encoding -- Set current setting for character encoding conversion

Description

bool iconv_set_encoding ( string type, string charset)

It changes the value of type to charset. 如果成功则返回 TRUE，失败则返回 FALSE。

The value of type can be:

input_encoding
output_encoding
internal_encoding

例子 1. iconv_set_encoding() example:

iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");

See also: iconv_get_encoding() and ob_iconv_handler().

后退 | 起点 | 前进
iconv_get_encoding | 上一级 | iconv


iconv

(PHP 4 >= 4.0.5)

iconv -- Convert string to requested character encoding

Description

string iconv ( string in_charset, string out_charset, string str)

It converts the string str encoded in in_charset to the string encoded in out_charset. It returns the converted string or FALSE, if it fails.

例子 1. iconv() example:

echo iconv("ISO-8859-1","UTF-8","This is a test.");

后退 | 起点 | 前进
iconv_set_encoding | 上一级 | ob_iconv_handler


ob_iconv_handler

(PHP 4 >= 4.0.5)

ob_iconv_handler -- Convert character encoding as output buffer handler

Description

array ob_iconv_handler ( string contents, int status)

It converts the string encoded in internal_encoding to output_encoding.

internal_encoding and output_encoding should be defined by iconv_set_encoding() or in the configuration file php.ini.

例子 1. ob_iconv_handler() example:

ob_start("ob_iconv_handler"); // start output buffering

See also: iconv_get_encoding(), iconv_set_encoding(), and output-control functions.

后退 | 起点 | 前进
iconv | 上一级 | Image functions


Image functions

PHP 手册
后退 前进

XLI. Image functions

介绍

You can use the image functions in PHP to get the size of JPEG, GIF, PNG, SWF, TIFF and JPEG2000 images.

注: Read requirements section about how to expand image capabilities to read, write and modify images and to read meta data of pictures taken by digital cameras.

需求

If you have the GD library (available at http://www.boutell.com/gd/) you will also be able to create and manipulate images.

The format of images you are able to manipulate depend on the version of GD you install, and any other libraries GD might need to access those image formats. Versions of GD older than gd-1.6 support gif format images, and do not support png, where versions greater than gd-1.6 support png, not gif.

注: Since PHP 4.3 there is a bundeled version of the GD lib. This bundeled version has some additional features like alpha blending and should be used in preference to the external library since it's codebase is better maintained and more stable.

If you have PHP compiled with --enable-exif you are able to work with information stored in headers of JPEG and TIFF images. This way you can read meta data generated by digital cameras as mentioned above. These functions does not require the GD library.

注: PHP does not require any additional library for exif the module.

安装

In order to read and write images in jpeg format, you will need to obtain and install jpeg-6b (available at ftp://ftp.uu.net/graphics/jpeg/), and then recompile GD to make use of jpeg-6b. You will also have to compile PHP with --with-jpeg-dir=/path/to/jpeg-6b.

To add support for Type 1 fonts, you can install t1lib (available at ftp://sunsite.unc.edu/pub/Linux/libs/graphics/), and then add --with-t1lib[=dir].

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

Exif supports automatically conversion for Unicode and JIS character encodings of user comments when module mbstring is available. This is done by first decoding the comment using the specified characterset. The result is then encoded with another characterset which should match your HTTP output.

表格 1. Exif configuration options

Name | Default | Changeable
exif.encode_unicode | "ISO-8859-15" | PHP_INI_ALL
exif.decode_unicode_motorola | "UCS-2BE" | PHP_INI_ALL
exif.decode_unicode_intel | "UCS-2LE" | PHP_INI_ALL
exif.encode_jis | "" | PHP_INI_ALL
exif.decode_jis_motorola | "JIS" | PHP_INI_ALL
exif.decode_jis_intel | "JIS" | PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

Here is a short explanation of the configuration directives.

exif.encode_unicode string

exif.encode_unicode defines the characterset UNICODE user comments are handled. This defaults to ISO-8859-15 which should work for most non asian countries. The setting can be empty or must be an encoding supported by mbstring. If it is empty the current internal encoding of mbstring is used.

exif.decode_unicode_motorola string

exif.decode_unicode_motorola defines the image internal characterset for Unicode encoded user comments if image is in motorola byte order (big-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is UCS-2BE.

exif.decode_unicode_intel string

exif.decode_unicode_intel defines the image internal characterset for Unicode encoded user comments if image is in intel byte order (little-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is UCS-2LE.

exif.encode_jis string

exif.encode_jis defines the characterset JIS user comments are handled. This defaults to an empty value which forces the functions to use the current internal encoding of mbstring.

exif.decode_jis_motorola string

exif.decode_jis_motorola defines the image internal characterset for JIS encoded user comments if image is in motorola byte order (big-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is JIS.

exif.decode_jis_intel string

exif.decode_jis_intel defines the image internal characterset for JIS encoded user comments if image is in intel byte order (little-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is JIS.

资源类型

该扩展模块未定义任何资源类型。

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

IMG_GIF (integer)

IMG_JPG (integer)

IMG_JPEG (integer)

IMG_PNG (integer)

IMG_WBMP (integer)

IMG_XPM (integer)

IMG_COLOR_TILED (integer)

IMG_COLOR_STYLED (integer)

IMG_COLOR_BRUSHED (integer)

IMG_COLOR_STYLEDBRUSHED (integer)

IMG_COLOR_TRANSPARENT (integer)

IMG_ARC_ROUNDED (integer)

IMG_ARC_PIE (integer)

IMG_ARC_CHORD (integer)

IMG_ARC_NOFILL (integer)

IMG_ARC_EDGED (integer)

IMAGETYPE_GIF (integer)

IMAGETYPE_JPG (integer)

IMAGETYPE_PNG (integer)

IMAGETYPE_SWF (integer)

IMAGETYPE_PSD (integer)

IMAGETYPE_BMP (integer)

IMAGETYPE_TIFF_II (integer)

IMAGETYPE_TIFF_MM (integer)

IMAGETYPE_JPC (integer)

IMAGETYPE_JP2 (integer)

IMAGETYPE_JPX (integer)

IMAGETYPE_SWC (integer)

目录
exif_imagetype — Determine the type of an image
exif_read_data — Read the EXIF headers from JPEG or TIFF. This way you can read meta data generated by digital cameras.
exif_thumbnail — Retrieve the embedded thumbnail of a TIFF or JPEG image
getimagesize — Get the size of an image
image_type_to_mime_type — Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
image2wbmp — Output image to browser or file
imagealphablending — Set the blending mode for an image
imagearc — Draw a partial ellipse
imagechar — Draw a character horizontally
imagecharup — Draw a character vertically
imagecolorallocate — Allocate a color for an image
imagecolorat — Get the index of the color of a pixel
imagecolorclosest — Get the index of the closest color to the specified color
imagecolorclosestalpha — Get the index of the closest color to the specified color + alpha
imagecolorclosesthwb — Get the index of the color which has the hue, white and blackness nearest to the given color
imagecolordeallocate — De-allocate a color for an image
imagecolorexact — Get the index of the specified color
imagecolorexactalpha — Get the index of the specified color + alpha
imagecolorresolve — Get the index of the specified color or its closest possible alternative
imagecolorresolvealpha — Get the index of the specified color + alpha or its closest possible alternative
imagecolorset — Set the color for the specified palette index
imagecolorsforindex — Get the colors for an index
imagecolorstotal — Find out the number of colors in an image's palette
imagecolortransparent — Define a color as transparent
imagecopy — Copy part of an image
imagecopymerge — Copy and merge part of an image
imagecopymergegray — Copy and merge part of an image with gray scale
imagecopyresampled — Copy and resize part of an image with resampling
imagecopyresized — Copy and resize part of an image
imagecreate — Create a new palette based image
imagecreatefromgd2 — Create a new image from GD2 file or URL
imagecreatefromgd2part — Create a new image from a given part of GD2 file or URL
imagecreatefromgd — Create a new image from GD file or URL
imagecreatefromgif — Create a new image from file or URL
imagecreatefromjpeg — Create a new image from file or URL
imagecreatefrompng — Create a new image from file or URL
imagecreatefromstring — Create a new image from the image stream in the string
imagecreatefromwbmp — Create a new image from file or URL
imagecreatefromxbm — Create a new image from file or URL
imagecreatefromxpm — Create a new image from file or URL
imagecreatetruecolor — Create a new true color image
imagedashedline — Draw a dashed line
imagedestroy — Destroy an image
imageellipse — Draw an ellipse
imagefill — Flood fill
imagefilledarc — Draw a partial ellipse and fill it
imagefilledellipse — Draw a filled ellipse
imagefilledpolygon — Draw a filled polygon
imagefilledrectangle — Draw a filled rectangle
imagefilltoborder — Flood fill to specific color
imagefontheight — Get font height
imagefontwidth — Get font width
imageftbbox — Give the bounding box of a text using fonts via freetype2
imagefttext — Write text to the image using fonts using FreeType 2
imagegammacorrect — Apply a gamma correction to a GD image
imagegd2 — Output GD2 image to browser or file
imagegd — Output GD image to browser or file
imagegif — Output image to browser or file
imageinterlace — Enable or disable interlace
imagejpeg — Output image to browser or file
imageline — Draw a line
imageloadfont — Load a new font
imagepalettecopy — Copy the palette from one image to another
imagepng — Output a PNG image to either the browser or a file
imagepolygon — Draw a polygon
imagepsbbox — Give the bounding box of a text rectangle using PostScript Type1 fonts
imagepscopyfont — Make a copy of an already loaded font for further modification
imagepsencodefont — Change the character encoding vector of a font
imagepsextendfont — Extend or condense a font
imagepsfreefont — Free memory used by a PostScript Type 1 font
imagepsloadfont — Load a PostScript Type 1 font from file
imagepsslantfont — Slant a font
imagepstext — To draw a text string over an image using PostScript Type1 fonts
imagerectangle — Draw a rectangle
imagesetbrush — Set the brush image for line drawing
imagesetpixel — Set a single pixel
imagesetstyle — Set the style for line drawing
imagesetthickness — Set the thickness for line drawing
imagesettile — Set the tile image for filling
imagestring — Draw a string horizontally
imagestringup — Draw a string vertically
imagesx — Get image width
imagesy — Get image height
imagetruecolortopalette — Convert a true color image to a palette image
imagettfbbox — Give the bounding box of a text using TrueType fonts
imagettftext — Write text to the image using TrueType fonts
imagetypes — Return the image types supported by this PHP build
imagewbmp — Output image to browser or file
iptcembed — Embed binary IPTC data into a JPEG image
iptcparse — Parse a binary IPTC http://www.iptc.org/ block into single tags.
jpeg2wbmp — Convert JPEG image file to WBMP image file
png2wbmp — Convert PNG image file to WBMP image file
read_exif_data — Reads header information stored in TIFF and JPEG images

后退 | 起点 | 前进
ob_iconv_handler | 上一级 | exif_imagetype


exif_imagetype

(PHP 4 CVS only)

exif_imagetype -- Determine the type of an image

Description

int|false exif_imagetype ( string filename)

exif_imagetype() reads the first bytes of an image and checks its signature. When a correct signature is found a constant will be returned otherwise the return value is FALSE. The return value is the same value that getimagesize() returns in index 2 but this function is much faster.

The following constants are defined:
1 = IMAGETYPE_GIF, 2 = IMAGETYPE_JPG, 3 = IMAGETYPE_PNG, 4 = IMAGETYPE_SWF,
5 = IMAGETYPE_PSD, 6 = IMAGETYPE_BMP, 7 = IMAGETYPE_TIFF_II (intel byte order),
8 = IMAGETYPE_TIFF_MM (motorola byte order), 9 = IMAGETYPE_JPC, 10 = IMAGETYPE_JP2,
11 = IMAGETYPE_JPX, 12 = IMAGETYPE_SWC.

This function can be used to avoid calls to other exif functions with unsupported file teypes or in conjunction with $_SERVER['HTTP_ACCEPT'] to check whether or not the viewer is able to see a specific image in his browser.

注: This function is only available in PHP 4 compiled using --enable-exif.

This function does not require the GD image library.

See also getimagesize().

后退 | 起点 | 前进
Image functions | 上一级 | exif_read_data


exif_read_data

(PHP 4 >= 4.2.0)

exif_read_data -- Read the EXIF headers from JPEG or TIFF. This way you can read meta data generated by digital cameras.

Description

array exif_read_data ( string filename [, string sections [, bool arrays [, bool thumbnail]]])

The exif_read_data() function reads the EXIF headers from a JPEG or TIFF image file. It returns an associative array where the indexes are the header names and the values are the values associated with those headers. If no data can be returned the result is FALSE.

filename is the name of the file to read. This cannot be a url.

sections a comma separated list of sections that need to be present in file to produce a result array.

FILE | FileName, FileSize, FileDateTime, SectionsFound
COMPUTED | html, Width, Height, IsColor and some more if available.
ANY_TAG | Any information that has a Tag e.g. IFD0, EXIF, ...
IFD0 | All tagged data of IFD0. In normal imagefiles this contains image size and so forth.
THUMBNAIL | A file is supposed to contain a thumbnail if it has a second IFD. All tagged information about the embedded thumbnail is stored in this section.
COMMENT | Comment headers of JPEG images.
EXIF | The EXIF section is a sub section of IFD0. It contains more detailed information about an image. Most of these entries are digital camera related.

arrays specifies whether or not each section becomes an array. The sections FILE, COMPUTED and THUMBNAIL allways become arrays as they may contain values whose names are conflict with other sections.

thumbnail whether or not to read the thumbnail itself and not only its tagged data.

注: Exif headers tend to be present in JPEG/TIFF images generated by digital cameras, but unfortunately each digital camera maker has a different idea of how to actually tag their images, so you can't always rely on a specific Exif header being present.

例子 1. exif_read_data() example

<?php
echo "test1.jpg:<br />\n";
$exif = exif_read_data ('tests/test1.jpg','IFD0');
echo $exif===false ? "No header data found.<br />\n" : "Image contains headers<br />";
$exif = exif_read_data ('tests/test2.jpg',0,true);
echo "test2.jpg:<br />\n";
foreach($exif as $key=>$section) {
    foreach($section as $name=>$val) {
        echo "$key.$name: $val<br />\n";
    }
}?>

The first call fails because the image has no header information.
test1.jpg:
No header data found.
test2.jpg:
FILE.FileName: test2.jpg
FILE.FileDateTime: 1017666176
FILE.FileSize: 1240
FILE.FileType: 2
FILE.SectionsFound: ANY_TAG, IFD0, THUMBNAIL, COMMENT
COMPUTED.html: width="1" height="1"
COMPUTED.Height: 1
COMPUTED.Width: 1
COMPUTED.IsColor: 1
COMPUTED.ByteOrderMotorola: 1
COMPUTED.UserComment: Exif test image.
COMPUTED.UserCommentEncoding: ASCII
COMPUTED.Copyright: Photo (c) M.Boerger, Edited by M.Boerger.
COMPUTED.Copyright.Photographer: Photo (c) M.Boerger
COMPUTED.Copyright.Editor: Edited by M.Boerger.
IFD0.Copyright: Photo (c) M.Boerger
IFD0.UserComment: ASCII
THUMBNAIL.JPEGInterchangeFormat: 134
THUMBNAIL.JPEGInterchangeFormatLength: 523
COMMENT.0: Comment #1.
COMMENT.1: Comment #2.
COMMENT.2: Comment #3end

THUMBNAIL.JPEGInterchangeFormat: 134
THUMBNAIL.Thumbnail.Height: 1
THUMBNAIL.Thumbnail.Height: 1

注: If the image contains any IFD0 data then COMPUTED contains the entry ByteOrderMotorola which is 0 for little-endian (intel) and 1 for big-endian (motorola) byte order. This was added in PHP 4.3.

When an Exif header contains a Copyright note this itself can contain two values. As the solution is inconsitent in the Exif 2.10 standard the COMPUTED section will return both entries Copyright.Photographer and Copyright.Editor while the IFD0 sections contains the byte array with the NULL character that splits both entries. Or just the first entry if the datatype was wrong (normal behaviour of Exif). The COMPUTED will contain also an entry Copyright Which is either the original copyright string or it is a comma separated list of photo and editor copyright.

注: The tag UserComment has the same problem as the Copyright tag. It can store two values first the encoding used and second the value itself. If so the IFD section only contains the encoding or a byte array. The COMPUTED section will store both in the entries UserCommentEncoding and UserComment. The entry UserComment is available in both cases so it should be used in preference to the value in IFD0 section.

If the user comment uses Unicode or JIS encoding and the module mbstring is available this encoding will automatically changed according to the exif ini settings. This was added in PHP 4.3.

注: Height and Width are computed the same way getimagesize() does so their values must not be part of any header returned. Also html is a height/width text string to be used inside normal HTML.

注: Starting from PHP 4.3 the function can read all embedded IFD data including arrays (returned as such). Also the size of an embedded thumbnail is returned in THUMBNAIL subarray and the function exif_read_data() can return thumbnails in TIFF format. Last but not least there is no longer a maximum legth for returned values (not until memory limit is reached).

注: This function is only available in PHP 4 compiled using --enable-exif. Its functionality and behaviour has changed in PHP 4.2. Earlier versions are very unstable.

Since PHP 4.3 user comment can automatically change encoding if PHP 4 was compiled using --enable-mbstring.

This function does not require the GD image library.

See also exif_thumbnail() and getimagesize().

后退 | 起点 | 前进
exif_imagetype | 上一级 | exif_thumbnail


exif_thumbnail

(PHP 4 >= 4.2.0)

exif_thumbnail -- Retrieve the embedded thumbnail of a TIFF or JPEG image

Description

string exif_thumbnail ( string filename [, int &width [, int &height [, int &imagetype]]])

exif_thumbnail() reads the embedded thumbnail of a TIFF or JPEG image. If the image contains no thumbnail FALSE will be returned.

The parameters width, height and imagetype are available since PHP 4.3 and return the size of the thumbnail as well as its type. It is possible that exif_thumbnail() cannot create an image but determine its size. In this case the return value is FALSE but width and height are set.

If you want to deliver thumbnails through this function you should send the mimetype information using header() function. The following example demonstrates this:

例子 1. exif_thumbnail() example

<?php
if (array_key_exists('file',$_REQUEST)) {
    $image = exif_thumbnail($_REQUEST['file'], $width, $height, $type);
} else {
    $image = false;
}
if ($image!==false) {
    header("Content-type: ".image_type_to_mime_type($type));
    echo $image;
    exit;
} else {
    // no thumbnail available, handle the error here
    echo "No thumbnail available";
}
?>

Starting from version PHP 4.3 the function exif_thumbnail() can return thumbnails in TIFF format.

注: This function is only available in PHP 4 compiled using --enable-exif. Its functionality and behaviour has changed in PHP 4.2

This function does not require the GD image library.

See also exif_read_data() and image_type_to_mime_type().

后退 | 起点 | 前进
exif_read_data | 上一级 | getimagesize


getimagesize

(PHP 3, PHP 4 )

getimagesize -- Get the size of an image

Description

array getimagesize ( string filename [, array imageinfo])

The getimagesize() function will determine the size of any GIF, JPG, PNG, SWF, SWC, PSD, TIFF, BMP or IFF image file and return the dimensions along with the file type and a height/width text string to be used inside a normal HTML IMG tag.

Returns an array with 4 elements. Index 0 contains the width of the image in pixels. Index 1 contains the height. Index 2 is a flag indicating the type of the image: 1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, 5 = PSD, 6 = BMP, 7 = TIFF(intel byte order), 8 = TIFF(motorola byte order), 9 = JPC, 10 = JP2, 11 = JPX, 12 = JB2, 13 = SWC, 14 = IFF. These values correspond to the IMAGETYPE constants that were added in PHP 4.3. Index 3 is a text string with the correct height="yyy" width="xxx" string that can be used directly in an IMG tag.

例子 1. getimagesize (file)

<?php
$size = getimagesize ("img/flag.jpg");
echo "<img src=\"img/flag.jpg\" {$size[3]}>";
?>

例子 2. getimagesize (URL)

<?php $size = getimagesize ("http://www.example.com/gifs/logo.gif"); ?>

With JPG images, two extra indexes are returned: channels and bits. channels will be 3 for RGB pictures and 4 for CMYK pictures. bits is the number of bits for each color.

Beginning with PHP 4.3, bits and channels are present for other image types, too. However, the presence of these values can be a bit confusing. As an example, GIF always uses 3 channels per pixel, but the number of bits per pixel cannot be calculated for an animated GIF with a global color table.

Some formats may contain no image or may contain multiple images. In these cases, getimagesize() might not be able to properly determine the image size. getimagesize() will return zero for width and height in these cases.

Beginning with PHP 4.3, getimagesize() also returns an additional parameter, MIME, that corresponds with the MIME type of the image. This information can be used to deliver images with correct HTTP Content-type headers:

例子 3. getimagesize() and MIME types

<?php
$size = getimagesize ($filename);
$fp=fopen($filename, "rb");
if ($size && $fp) {
  header("Content-type: {$size['mime']}");
  fpassthru($fp);
  exit;
} else {
  // error
}
?>

If accessing the filename image is impossible, or if it isn't a valid picture, getimagesize() will return FALSE and generate a warning.

The optional imageinfo parameter allows you to extract some extended information from the image file. Currently, this will return the different JPG APP markers as an associative array. Some programs use these APP markers to embed text information in images. A very common one is to embed IPTC http://www.iptc.org/ information in the APP13 marker. You can use the iptcparse() function to parse the binary APP13 marker into something readable.

例子 4. getimagesize() returning IPTC

<?php
$size = getimagesize ("testimg.jpg",&$info);
if (isset ($info["APP13"])) {
    $iptc = iptcparse ($info["APP13"]);
    var_dump ($iptc);
}
?>

注: TIFF support was added in PHP 4.2. JPEG2000 support will be added in PHP 4.3.

This function does not require the GD image library.

See also image_type_to_mime_type(),
exif_imagetype(), exif_read_data()
and exif_thumbnail().

URL support was added in PHP 4.0.5.

后退 | 起点 | 前进
exif_thumbnail | 上一级 | image_type_to_mime_type


image_type_to_mime_type

(PHP 4 CVS only)

image_type_to_mime_type -- Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype

Description

string image_type_to_mime_type ( int imagetype)

The image_type_to_mime_type() function will determine the Mime-Type for an IMAGETYPE constant.

例子 1. image_type_to_mime_type (file)

<?php
header ("Content-type: ".image_type_to_mime_type (IMAGETYPE_PNG));
?>

注: This function does not require the GD image library.

See also getimagesize(),
exif_imagetype(), exif_read_data()
and exif_thumbnail().

后退 | 起点 | 前进
getimagesize | 上一级 | image2wbmp


image2wbmp

(PHP 4 >= 4.0.5)

image2wbmp -- Output image to browser or file

Description

int image2wbmp ( resource image [, string filename [, int threshold]])

image2wbmp() creates the WBMP file in filename from the image image. The image argument is the return from imagecreate().

The filename argument is optional, and if left off, the raw image stream will be output directly. By sending an image/vnd.wap.wbmp content-type using header(), you can create a PHP script that outputs WBMP images directly.

注: WBMP support is only available if PHP was compiled against GD-1.8 or later.

See also imagewbmp().

后退 | 起点 | 前进
image_type_to_mime_type | 上一级 | imagealphablending


imagealphablending

(PHP 4 >= 4.0.6)

imagealphablending -- Set the blending mode for an image

Description

int imagealphablending ( resource image, bool blendmode)

imagealphablending() allows for two different modes of drawing on truecolor images. In blending mode, the alpha channel component of the color supplied to all drawing function, such as imagesetpixel() determines how much of the underlying color should be allowed to shine through. As a result, gd automatically blends the existing color at that point with the drawing color, and stores the result in the image. The resulting pixel is opaque. In non-blending mode, the drawing color is copied literally with its alpha channel information, replacing the destination pixel. Blending mode is not available when drawing on palette images. If blendmode is TRUE, then blending mode is enabled, otherwise disabled.

注: This function was added in PHP 4.0.6 and requires GD 2.0.1

后退 | 起点 | 前进
image2wbmp | 上一级 | imagearc


imagearc

(PHP 3, PHP 4 )

imagearc -- Draw a partial ellipse

Description

int imagearc ( resource image, int cx, int cy, int w, int h, int s, int e, int col)

imagearc() draws a partial ellipse centered at cx, cy (top left is 0, 0) in the image represented by image. W and h specifies the ellipse's width and height respectively while the start and end points are specified in degrees indicated by the s and e arguments. 0° is located at the three-o'clock position, and the arc is drawn counter-clockwise.

See also imageellipse(),
imagefilledellipse(), and
imagefilledarc().

后退 | 起点 | 前进
imagealphablending | 上一级 | imagechar


imagechar

(PHP 3, PHP 4 )

imagechar -- Draw a character horizontally

Description

int imagechar ( resource image, int font, int x, int y, string c, int col)

imagechar() draws the first character of c in the image identified by id with its upper-left at x,y (top left is 0, 0) with the color col. If font is 1, 2, 3, 4 or 5, a built-in font is used (with higher numbers corresponding to larger fonts).

See also imageloadfont().

后退 | 起点 | 前进
imagearc | 上一级 | imagecharup


imagecharup

(PHP 3, PHP 4 )

imagecharup -- Draw a character vertically

Description

int imagecharup ( resource image, int font, int x, int y, string c, int col)

imagecharup() draws the character c vertically in the image identified by image at coordinates x, y (top left is 0, 0) with the color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.

See also imageloadfont().

后退 | 起点 | 前进
imagechar | 上一级 | imagecolorallocate


imagecolorallocate

(PHP 3, PHP 4 )

imagecolorallocate -- Allocate a color for an image

Description

int imagecolorallocate ( resource image, int red, int green, int blue)

imagecolorallocate() returns a color identifier representing the color composed of the given RGB components. The im argument is the return from the imagecreate() function. red, green and blue are the values of the red, green and blue component of the requested color respectively. These parameters are integers between 0 and 255. imagecolorallocate() must be called to create each color that is to be used in the image represented by image.

$white = imagecolorallocate ($im, 255, 255, 255);
$black = imagecolorallocate ($im, 0, 0, 0);

Returns -1 if the allocation failed.

后退 | 起点 | 前进
imagecharup | 上一级 | imagecolorat


imagecolorat

(PHP 3, PHP 4 )

imagecolorat -- Get the index of the color of a pixel

Description

int imagecolorat ( resource image, int x, int y)

Returns the index of the color of the pixel at the specified location in the image specified by image.

See also imagecolorset() and imagecolorsforindex().

后退 | 起点 | 前进
imagecolorallocate | 上一级 | imagecolorclosest


imagecolorclosest

(PHP 3, PHP 4 )

imagecolorclosest -- Get the index of the closest color to the specified color

Description

int imagecolorclosest ( resource image, int red, int green, int blue)

Returns the index of the color in the palette of the image which is "closest" to the specified RGB value.

The "distance" between the desired color and each color in the palette is calculated as if the RGB values represented points in three-dimensional space.

See also imagecolorexact().

后退 | 起点 | 前进
imagecolorat | 上一级 | imagecolorclosestalpha


imagecolorclosestalpha

(PHP 4 >= 4.0.6)

imagecolorclosestalpha -- Get the index of the closest color to the specified color + alpha

Description

int imagecolorclosestalpha ( resource image, int red, int green, int blue, int alpha)

Returns the index of the color in the palette of the image which is "closest" to the specified RGB value and alpha level.

See also imagecolorexactalpha().

注: This function was added in PHP 4.0.6 and requires GD 2.0.1

后退 | 起点 | 前进
imagecolorclosest | 上一级 | imagecolorclosesthwb


imagecolorclosesthwb

(PHP 4 >= 4.0.1)

imagecolorclosesthwb -- Get the index of the color which has the hue, white and blackness nearest to the given color

Description

int imagecolorclosesthwb ( resource image, int red, int green, int blue)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
imagecolorclosestalpha | 上一级 | imagecolordeallocate


imagecolordeallocate

(PHP 3>= 3.0.6, PHP 4 )

imagecolordeallocate -- De-allocate a color for an image

Description

int imagecolordeallocate ( resource image, int color)

The imagecolordeallocate() function de-allocates a color previously allocated with the imagecolorallocate() function.

$white = imagecolorallocate ($im, 255, 255, 255);
imagecolordeallocate ($im, $white);

后退 | 起点 | 前进
imagecolorclosesthwb | 上一级 | imagecolorexact


imagecolorexact

(PHP 3, PHP 4 )

imagecolorexact -- Get the index of the specified color

Description

int imagecolorexact ( resource image, int red, int green, int blue)

Returns the index of the specified color in the palette of the image.

If the color does not exist in the image's palette, -1 is returned.

See also imagecolorclosest().

后退 | 起点 | 前进
imagecolordeallocate | 上一级 | imagecolorexactalpha


imagecolorexactalpha

(PHP 4 >= 4.0.6)

imagecolorexactalpha -- Get the index of the specified color + alpha

Description

int imagecolorexactalpha ( resource image, int red, int green, int blue, int alpha)

Returns the index of the specified color+alpha in the palette of the image.

If the color does not exist in the image's palette, -1 is returned.

See also imagecolorclosestalpha().

注: This function was added in PHP 4.0.6 and requires GD 2.0.1 or later

后退 | 起点 | 前进
imagecolorexact | 上一级 | imagecolorresolve


imagecolorresolve

(PHP 3>= 3.0.2, PHP 4 )

imagecolorresolve -- Get the index of the specified color or its closest possible alternative

Description

int imagecolorresolve ( resource image, int red, int green, int blue)

This function is guaranteed to return a color index for a requested color, either the exact color or the closest possible alternative.

See also imagecolorclosest().

后退 | 起点 | 前进
imagecolorexactalpha | 上一级 | imagecolorresolvealpha


imagecolorresolvealpha

(PHP 4 >= 4.0.6)

imagecolorresolvealpha -- Get the index of the specified color + alpha or its closest possible alternative

Description

int imagecolorresolvealpha ( resource image, int red, int green, int blue, int alpha)

This function is guaranteed to return a color index for a requested color, either the exact color or the closest possible alternative.

See also imagecolorclosestalpha().

注: This function was added in PHP 4.0.6 and requires GD 2.0.1

后退 | 起点 | 前进
imagecolorresolve | 上一级 | imagecolorset


imagecolorset

(PHP 3, PHP 4 )

imagecolorset -- Set the color for the specified palette index

Description

bool imagecolorset ( resource image, int index, int red, int green, int blue)

This sets the specified index in the palette to the specified color. This is useful for creating flood-fill-like effects in paletted images without the overhead of performing the actual flood-fill.

See also imagecolorat().

后退 | 起点 | 前进
imagecolorresolvealpha | 上一级 | imagecolorsforindex


imagecolorsforindex

(PHP 3, PHP 4 )

imagecolorsforindex -- Get the colors for an index

Description

array imagecolorsforindex ( resource image, int index)

This returns an associative array with red, green, and blue keys that contain the appropriate values for the specified color index.

See also imagecolorat() and imagecolorexact().

后退 | 起点 | 前进
imagecolorset | 上一级 | imagecolorstotal


imagecolorstotal

(PHP 3, PHP 4 )

imagecolorstotal -- Find out the number of colors in an image's palette

Description

int imagecolorstotal ( resource image)

This returns the number of colors in the specified image's palette.

See also imagecolorat() and imagecolorsforindex().

后退 | 起点 | 前进
imagecolorsforindex | 上一级 | imagecolortransparent


imagecolortransparent

(PHP 3, PHP 4 )

imagecolortransparent -- Define a color as transparent

Description

int imagecolortransparent ( resource image [, int color])

imagecolortransparent() sets the transparent color in the image image to color. image is the image identifier returned by imagecreate() and color is a color identifier returned by imagecolorallocate().

注: The transparent color is a property of the image, transparency is not a property of the color. Once you have a set a color to be the transparent color, any regions of the image in that color that were drawn previously will be transparent.

The identifier of the new (or current, if none is specified) transparent color is returned.

后退 | 起点 | 前进
imagecolorstotal | 上一级 | imagecopy


imagecopy

(PHP 3>= 3.0.6, PHP 4 )

imagecopy -- Copy part of an image

Description

int imagecopy ( resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h)

Copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y.

后退 | 起点 | 前进
imagecolortransparent | 上一级 | imagecopymerge


imagecopymerge

(PHP 4 >= 4.0.1)

imagecopymerge -- Copy and merge part of an image

Description

int imagecopymerge ( resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h, int pct)

Copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y. The two images will be merged according to pct which can range from 0 to 100. When pct = 0, no action is taken, when 100 this function behaves identically to imagecopy().

注: This function was added in PHP 4.0.6

后退 | 起点 | 前进
imagecopy | 上一级 | imagecopymergegray


imagecopymergegray

(PHP 4 >= 4.0.6)

imagecopymergegray -- Copy and merge part of an image with gray scale

Description

int imagecopymergegray ( resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h, int pct)

imagecopymergegray() copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y. The two images will be merged according to pct which can range from 0 to 100. When pct = 0, no action is taken, when 100 this function behaves identically to imagecopy().

This function is identical to imagecopymerge() except that when merging it preservese the hue of the source by converting the destination pixels to gray scale before the copy operation.

注: This function was added in PHP 4.0.6

后退 | 起点 | 前进
imagecopymerge | 上一级 | imagecopyresampled


imagecopyresampled

(PHP 4 >= 4.0.6)

imagecopyresampled -- Copy and resize part of an image with resampling

Description

int imagecopyresampled ( resource dst_im, resource src_im, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH)

imagecopyresampled() copies a rectangular portion of one image to another image, smoothly interpolating pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity. Dst_im is the destination image, src_im is the source image identifier. If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if dst_im is the same as src_im) but if the regions overlap the results will be unpredictable.

See also imagecopyresized().

注: This function was added in PHP 4.0.6 and requires GD 2.0.1 or later

后退 | 起点 | 前进
imagecopymergegray | 上一级 | imagecopyresized


imagecopyresized

(PHP 3, PHP 4 )

imagecopyresized -- Copy and resize part of an image

Description

int imagecopyresized ( resource dst_im, resource src_im, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH)

imagecopyresized() copies a rectangular portion of one image to another image. Dst_im is the destination image, src_im is the source image identifier. If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if dst_im is the same as src_im) but if the regions overlap the results will be unpredictable.

See also imagecopyresampled().

后退 | 起点 | 前进
imagecopyresampled | 上一级 | imagecreate


imagecreate

(PHP 3, PHP 4 )

imagecreate -- Create a new palette based image

Description

resource imagecreate ( int x_size, int y_size)

imagecreate() returns an image identifier representing a blank image of size x_size by y_size.

例子 1. Creating a new GD image stream and outputting an image.

<?php
header ("Content-type: image/png");
$im = @imagecreate (50, 100)
    or die ("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate ($im, 255, 255, 255);
$text_color = imagecolorallocate ($im, 233, 14, 91);
imagestring ($im, 1, 5, 5,  "A Simple Text String", $text_color);
imagepng ($im);
?>

后退 | 起点 | 前进
imagecopyresized | 上一级 | imagecreatefromgd2


imagecreatefromgd2

(PHP 4 >= 4.1.0)

imagecreatefromgd2 -- Create a new image from GD2 file or URL

Description

resource imagecreatefromgd2 ( string filename)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
imagecreate | 上一级 | imagecreatefromgd2part


imagecreatefromgd2part

(PHP 4 >= 4.1.0)

imagecreatefromgd2part -- Create a new image from a given part of GD2 file or URL

Description

resource imagecreatefromgd2part ( string filename, int srcX, int srcY, int width, int height)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
imagecreatefromgd2 | 上一级 | imagecreatefromgd


imagecreatefromgd

(PHP 4 >= 4.1.0)

imagecreatefromgd -- Create a new image from GD file or URL

Description

resource imagecreatefromgd ( string filename)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
imagecreatefromgd2part | 上一级 | imagecreatefromgif


imagecreatefromgif

(PHP 3, PHP 4 )

imagecreatefromgif -- Create a new image from file or URL

Description

resource imagecreatefromgif ( string filename)

imagecreatefromgif() returns an image identifier representing the image obtained from the given filename.

imagecreatefromgif() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error GIF:

例子 1. Example to handle an error during creation (courtesy vic@zymsys.com)

function LoadGif ($imgname) {
    $im = @imagecreatefromgif ($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im = imagecreate (150, 30); /* Create a blank image */
        $bgc = imagecolorallocate ($im, 255, 255, 255);
        $tc = imagecolorallocate ($im, 0, 0, 0);
        imagefilledrectangle ($im, 0, 0, 150, 30, $bgc);
        /* Output an errmsg */
        imagestring ($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}

注: Since all GIF support was removed from the GD library in version 1.6, this function is not available if you are using that version of the GD library.

后退 | 起点 | 前进
imagecreatefromgd | 上一级 | imagecreatefromjpeg


imagecreatefromjpeg

(PHP 3>= 3.0.16, PHP 4 )

imagecreatefromjpeg -- Create a new image from file or URL

Description

resource imagecreatefromjpeg ( string filename)

imagecreatefromjpeg() returns an image identifier representing the image obtained from the given filename.

imagecreatefromjpeg() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error JPEG:

例子 1. Example to handle an error during creation (courtesy vic@zymsys.com )

function LoadJpeg ($imgname) {
    $im = @imagecreatefromjpeg ($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im  = imagecreate (150, 30); /* Create a blank image */
        $bgc = imagecolorallocate ($im, 255, 255, 255);
        $tc  = imagecolorallocate ($im, 0, 0, 0);
        imagefilledrectangle ($im, 0, 0, 150, 30, $bgc);
        /* Output an errmsg */
        imagestring ($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}

后退 | 起点 | 前进
imagecreatefromgif | 上一级 | imagecreatefrompng


imagecreatefrompng

(PHP 3>= 3.0.13, PHP 4 )

imagecreatefrompng -- Create a new image from file or URL

Description

resource imagecreatefrompng ( string filename)

imagecreatefrompng() returns an image identifier representing the image obtained from the given filename.

imagecreatefrompng() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error PNG:

例子 1. Example to handle an error during creation (courtesy vic@zymsys.com)

function LoadPNG ($imgname) {
    $im = @imagecreatefrompng ($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im  = imagecreate (150, 30); /* Create a blank image */
        $bgc = imagecolorallocate ($im, 255, 255, 255);
        $tc  = imagecolorallocate ($im, 0, 0, 0);
        imagefilledrectangle ($im, 0, 0, 150, 30, $bgc);
        /* Output an errmsg */
        imagestring ($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}

后退 | 起点 | 前进
imagecreatefromjpeg | 上一级 | imagecreatefromstring


imagecreatefromstring

(PHP 4 >= 4.0.4)

imagecreatefromstring -- Create a new image from the image stream in the string

Description

resource imagecreatefromstring ( string image)

imagecreatefromstring() returns an image identifier representing the image obtained from the given string.

后退 | 起点 | 前进
imagecreatefrompng | 上一级 | imagecreatefromwbmp


imagecreatefromwbmp

(PHP 4 >= 4.0.1)

imagecreatefromwbmp -- Create a new image from file or URL

Description

resource imagecreatefromwbmp ( string filename)

imagecreatefromwbmp() returns an image identifier representing the image obtained from the given filename.

imagecreatefromwbmp() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error WBMP:

例子 1. Example to handle an error during creation (courtesy vic@zymsys.com)

function LoadWBMP ($imgname) {
    $im = @imagecreatefromwbmp ($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im  = imagecreate (20, 20); /* Create a blank image */
        $bgc = imagecolorallocate ($im, 255, 255, 255);
        $tc  = imagecolorallocate ($im, 0, 0, 0);
        imagefilledrectangle ($im, 0, 0, 10, 10, $bgc);
        /* Output an errmsg */
        imagestring ($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}

注: WBMP support is only available if PHP was compiled against GD-1.8 or later.

后退 | 起点 | 前进
imagecreatefromstring | 上一级 | imagecreatefromxbm


imagecreatefromxbm

(PHP 4 >= 4.0.1)

imagecreatefromxbm -- Create a new image from file or URL

Description

resource imagecreatefromxbm ( string filename)

imagecreatefromxbm() returns an image identifier representing the image obtained from the given filename.

后退 | 起点 | 前进
imagecreatefromwbmp | 上一级 | imagecreatefromxpm


imagecreatefromxpm

(PHP 4 >= 4.0.1)

imagecreatefromxpm -- Create a new image from file or URL

Description

resource imagecreatefromxpm ( string filename)

imagecreatefromxpm() returns an image identifier representing the image obtained from the given filename.

后退 | 起点 | 前进
imagecreatefromxbm | 上一级 | imagecreatetruecolor


imagecreatetruecolor

(PHP 4 >= 4.0.6)

imagecreatetruecolor -- Create a new true color image

Description

resource imagecreatetruecolor ( int x_size, int y_size)

imagecreatetruecolor() returns an image identifier representing a black image of size x_size by y_size.

注: This function was added in PHP 4.0.6 and requires GD 2.0.1 or later

注: This function will not work with GIF file formats.

后退 | 起点 | 前进
imagecreatefromxpm | 上一级 | imagedashedline


imagedashedline

(PHP 3, PHP 4 )

imagedashedline -- Draw a dashed line

Description

int imagedashedline ( resource image, int x1, int y1, int x2, int y2, int col)

This function is deprecated. Use combination of imagesetstyle() and imageline() instead.

后退 | 起点 | 前进
imagecreatetruecolor | 上一级 | imagedestroy


imagedestroy

(PHP 3, PHP 4 )

imagedestroy -- Destroy an image

Description

int imagedestroy ( resource image)

imagedestroy() frees any memory associated with image image. image is the image identifier returned by the imagecreate() function.

后退 | 起点 | 前进
imagedashedline | 上一级 | imageellipse


imageellipse

(PHP 4 >= 4.0.6)

imageellipse -- Draw an ellipse

Description

int imageellipse ( resource image, int cx, int cy, int w, int h, int col)

imageellipse() draws an ellipse centered at cx, cy (top left is 0, 0) in the image represented by image. W and h specifies the ellipse's width and height respectively. The color of the ellipse is specified by color.

注: This function was added in PHP 4.0.6 and requires GD 2.0.2 or later

See also imagearc().

后退 | 起点 | 前进
imagedestroy | 上一级 | imagefill


imagefill

(PHP 3, PHP 4 )

imagefill -- Flood fill

Description

int imagefill ( resource image, int x, int y, int col)

imagefill() performs a flood fill starting at coordinate x, y (top left is 0, 0) with color col in the image image.

后退 | 起点 | 前进
imageellipse | 上一级 | imagefilledarc


imagefilledarc

(PHP 4 >= 4.0.6)

imagefilledarc -- Draw a partial ellipse and fill it

Description

int imagefilledarc ( resource image, int cx, int cy, int w, int h, int s, int e, int col, int style)

imagefilledarc() draws a partial ellipse centered at cx, cy (top left is 0, 0) in the image represented by image. W and h specifies the ellipse's width and height respectively while the start and end points are specified in degrees indicated by the s and e arguments. style is a bitwise OR of the following possibilities:

  1. IMG_ARC_PIE

  2. IMG_ARC_CHORD

  3. IMG_ARC_NOFILL

  4. IMG_ARC_EDGED

IMG_ARC_PIE and IMG_ARC_CHORD are mutually exclusive; IMG_ARC_CHORD just connects the starting and ending angles with a straight line, while IMG_ARC_PIE produces a rounded edge. IMG_ARC_NOFILL indicates that the arc or chord should be outlined, not filled. IMG_ARC_EDGED, used together with IMG_ARC_NOFILL, indicates that the beginning and ending angles should be connected to the center - this is a good way to outline (rather than fill) a 'pie slice'.

注: This function was added in PHP 4.0.6 and requires GD 2.0.1

后退 | 起点 | 前进
imagefill | 上一级 | imagefilledellipse


imagefilledellipse

(PHP 4 >= 4.0.6)

imagefilledellipse -- Draw a filled ellipse

Description

int imagefilledellipse ( resource image, int cx, int cy, int w, int h, int col)

imagefilledellipse() draws an ellipse centered at cx, cy (top left is 0, 0) in the image represented by image. W and h specifies the ellipse's width and height respectively. The ellipse is filled using color

注: This function was added in PHP 4.0.6 and requires GD 2.0.1 or later

See also imagefilledarc().

后退 | 起点 | 前进
imagefilledarc | 上一级 | imagefilledpolygon


imagefilledpolygon

(PHP 3, PHP 4 )

imagefilledpolygon -- Draw a filled polygon

Description

int imagefilledpolygon ( resource image, array points, int num_points, int col)

imagefilledpolygon() creates a filled polygon in image image. points is a PHP array containing the polygon's vertices, ie. points[0] = x0, points[1] = y0, points[2] = x1, points[3] = y1, etc. num_points is the total number of vertices.

后退 | 起点 | 前进
imagefilledellipse | 上一级 | imagefilledrectangle


imagefilledrectangle

(PHP 3, PHP 4 )

imagefilledrectangle -- Draw a filled rectangle

Description

int imagefilledrectangle ( resource image, int x1, int y1, int x2, int y2, int col)

imagefilledrectangle() creates a filled rectangle of color col in image image starting at upper left coordinates x1, y1 and ending at bottom right coordinates x2, y2. 0, 0 is the top left corner of the image.

后退 | 起点 | 前进
imagefilledpolygon | 上一级 | imagefilltoborder


imagefilltoborder

(PHP 3, PHP 4 )

imagefilltoborder -- Flood fill to specific color

Description

int imagefilltoborder ( resource image, int x, int y, int border, int col)

imagefilltoborder() performs a flood fill whose border color is defined by border. The starting point for the fill is x, y (top left is 0, 0) and the region is filled with color col.

后退 | 起点 | 前进
imagefilledrectangle | 上一级 | imagefontheight


imagefontheight

(PHP 3, PHP 4 )

imagefontheight -- Get font height

Description

int imagefontheight ( int font)

Returns the pixel height of a character in the specified font.

See also imagefontwidth() and imageloadfont().

后退 | 起点 | 前进
imagefilltoborder | 上一级 | imagefontwidth


imagefontwidth

(PHP 3, PHP 4 )

imagefontwidth -- Get font width

Description

int imagefontwidth ( int font)

Returns the pixel width of a character in font.

See also imagefontheight() and imageloadfont().

后退 | 起点 | 前进
imagefontheight | 上一级 | imageftbbox


imageftbbox

(PHP 4 >= 4.1.0)

imageftbbox -- Give the bounding box of a text using fonts via freetype2

Description

array imageftbbox ( int size, int angle, string font_file, string text [, array extrainfo])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
imagefontwidth | 上一级 | imagefttext


imagefttext

(PHP 4 >= 4.1.0)

imagefttext -- Write text to the image using fonts using FreeType 2

Description

array imagefttext ( resource image, int size, int angle, int x, int y, int col, string font_file, string text [, array extrainfo])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
imageftbbox | 上一级 | imagegammacorrect


imagegammacorrect

(PHP 3>= 3.0.13, PHP 4 )

imagegammacorrect -- Apply a gamma correction to a GD image

Description

int imagegammacorrect ( resource image, float inputgamma, float outputgamma)

The imagegammacorrect() function applies gamma correction to a gd image stream (image) given an input gamma, the parameter inputgamma and an output gamma, the parameter outputgamma.

后退 | 起点 | 前进
imagefttext | 上一级 | imagegd2


imagegd2

(PHP 4 >= 4.1.0)

imagegd2 -- Output GD2 image to browser or file

Description

int imagegd2 ( resource image [, string filename])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
imagegammacorrect | 上一级 | imagegd


imagegd

(PHP 4 >= 4.1.0)

imagegd -- Output GD image to browser or file

Description

int imagegd ( resource image [, string filename])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
imagegd2 | 上一级 | imagegif


imagegif

(PHP 3, PHP 4 )

imagegif -- Output image to browser or file

Description

int imagegif ( resource image [, string filename])

imagegif() creates the GIF file in filename from the image image. The image argument is the return from the imagecreate() function.

The image format will be GIF87a unless the image has been made transparent with imagecolortransparent(), in which case the image format will be GIF89a.

The filename argument is optional, and if left off, the raw image stream will be output directly. By sending an image/gif content-type using header(), you can create a PHP script that outputs GIF images directly.

注: Since all GIF support was removed from the GD library in version 1.6, this function is not available if you are using that version of the GD library.

The following code snippet allows you to write more portable PHP applications by auto-detecting the type of GD support which is available. Replace the sequence header ("Content-type: image/gif"); imagegif ($im); by the more flexible sequence:

<?php
if (function_exists("imagegif")) {
    header ("Content-type: image/gif");
    imagegif ($im);
}
elseif (function_exists("imagejpeg")) {
    header ("Content-type: image/jpeg");
    imagejpeg ($im, "", 0.5);
}
elseif (function_exists("imagepng")) {
    header ("Content-type: image/png");
    imagepng ($im);
}
elseif (function_exists("imagewbmp")) {
    header ("Content-type: image/vnd.wap.wbmp");
    imagewbmp ($im);
}
else
    die("No image support in this PHP server");
?>

注: As of version 3.0.18 and 4.0.2 you can use the function imagetypes() in place of function_exists() for checking the presence of the various supported image formats:

if (imagetypes() & IMG_GIF) {
    header ("Content-type: image/gif");
    imagegif ($im);
}
elseif (imagetypes() & IMG_JPG) {
        ... etc.

See also imagepng(), imagewbmp(), imagejpeg(), imagetypes().

后退 | 起点 | 前进
imagegd | 上一级 | imageinterlace


imageinterlace

(PHP 3, PHP 4 )

imageinterlace -- Enable or disable interlace

Description

int imageinterlace ( resource image [, int interlace])

imageinterlace() turns the interlace bit on or off. If interlace is 1 the image will be interlaced, and if interlace is 0 the interlace bit is turned off.

If the interlace bit is set and the image is used as a JPEG image, the image is created as a progressive JPEG.

This function returns whether the interlace bit is set for the image.

后退 | 起点 | 前进
imagegif | 上一级 | imagejpeg


imagejpeg

(PHP 3>= 3.0.16, PHP 4 )

imagejpeg -- Output image to browser or file

Description

int imagejpeg ( resource image [, string filename [, int quality]])

imagejpeg() creates the JPEG file in filename from the image image. The image argument is the return from the imagecreate() function.

The filename argument is optional, and if left off, the raw image stream will be output directly. To skip the filename argument in order to provide a quality argument just use an empty string (''). By sending an image/jpeg content-type using header(), you can create a PHP script that outputs JPEG images directly.

注: JPEG support is only available if PHP was compiled against GD-1.8 or later.

quality is optional, and ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default is the default IJG quality value (about 75).

If you want to output Progressive JPEGs, you need to set interlacing on with imageinterlace().

See also
imagepng(),
imagegif(),
imagewbmp(),
imageinterlace() and
imagetypes().

后退 | 起点 | 前进
imageinterlace | 上一级 | imageline


imageline

(PHP 3, PHP 4 )

imageline -- Draw a line

Description

int imageline ( resource image, int x1, int y1, int x2, int y2, int col)

imageline() draws a line from x1, y1 to x2, y2 (top left is 0, 0) in image im of color col.

See also imagecreate() and imagecolorallocate().

后退 | 起点 | 前进
imagejpeg | 上一级 | imageloadfont


imageloadfont

(PHP 3, PHP 4 )

imageloadfont -- Load a new font

Description

int imageloadfont ( string file)

imageloadfont() loads a user-defined bitmap font and returns an identifier for the font (that is always greater than 5, so it will not conflict with the built-in fonts).

The font file format is currently binary and architecture dependent. This means you should generate the font files on the same type of CPU as the machine you are running PHP on.

表格 1. Font file format

byte position | C data type | description
byte 0-3 | int | number of characters in the font
byte 4-7 | int | value of first character in the font (often 32 for space)
byte 8-11 | int | pixel width of each character
byte 12-15 | int | pixel height of each character
byte 16- | char | array with character data, one byte per pixel in each character, for a total of (nchars*width*height) bytes.

See also imagefontwidth() and imagefontheight().

后退 | 起点 | 前进
imageline | 上一级 | imagepalettecopy


imagepalettecopy

(PHP 4 >= 4.0.1)

imagepalettecopy -- Copy the palette from one image to another

Description

int imagepalettecopy ( resource destination, resource source)

imagepalettecopy() copies the palette from the source image to the destination image.

后退 | 起点 | 前进
imageloadfont | 上一级 | imagepng


imagepng

(PHP 3>= 3.0.13, PHP 4 )

imagepng -- Output a PNG image to either the browser or a file

Description

int imagepng ( resource image [, string filename])

The imagepng() outputs a GD image stream (image) in PNG format to standard output (usually the browser) or, if a filename is given by the filename it outputs the image to the file.

<?php
$im = imagecreatefrompng ("test.png");
imagepng ($im);
?>

See also imagegif(), imagewbmp(), imagejpeg(), imagetypes().

后退 | 起点 | 前进
imagepalettecopy | 上一级 | imagepolygon


imagepolygon

(PHP 3, PHP 4 )

imagepolygon -- Draw a polygon

Description

int imagepolygon ( resource image, array points, int num_points, int col)

imagepolygon() creates a polygon in image id. points is a PHP array containing the polygon's vertices, ie. points[0] = x0, points[1] = y0, points[2] = x1, points[3] = y1, etc. num_points is the total number of vertices.

See also imagecreate().

后退 | 起点 | 前进
imagepng | 上一级 | imagepsbbox


imagepsbbox

(PHP 3>= 3.0.9, PHP 4 )

imagepsbbox -- Give the bounding box of a text rectangle using PostScript Type1 fonts

Description

array imagepsbbox ( string text, int font, int size [, int space [, int tightness [, float angle]]])

Size is expressed in pixels.

Space allows you to change the default value of a space in a font. This amount is added to the normal value and can also be negative.

Tightness allows you to control the amount of white space between characters. This amount is added to the normal character width and can also be negative.

Angle is in degrees.

Parameters space and tightness are expressed in character space units, where 1 unit is 1/1000th of an em-square.

Parameters space, tightness, and angle are optional.

The bounding box is calculated using information available from character metrics, and unfortunately tends to differ slightly from the results achieved by actually rasterizing the text. If the angle is 0 degrees, you can expect the text to need 1 pixel more to every direction.

This function returns an array containing the following elements:

0 | lower left x-coordinate
1 | lower left y-coordinate
2 | upper right x-coordinate
3 | upper right y-coordinate

See also imagepstext().

后退 | 起点 | 前进
imagepolygon | 上一级 | imagepscopyfont


imagepscopyfont

(PHP 3>= 3.0.9, PHP 4 )

imagepscopyfont -- Make a copy of an already loaded font for further modification

Description

int imagepscopyfont ( int fontindex)

Use this function if you need make further modifications to the font, for example extending/condensing, slanting it or changing it's character encoding vector, but need to keep the original along as well. Note that the font you want to copy must be one obtained using imagepsloadfont(), not a font that is itself a copied one. You can although make modifications to it before copying.

If you use this function, you must free the fonts obtained this way yourself and in reverse order. Otherwise your script will hang.

In the case everything went right, a valid font index will be returned and can be used for further purposes. Otherwise the function returns FALSE and prints a message describing what went wrong.

See also imagepsloadfont().

后退 | 起点 | 前进
imagepsbbox | 上一级 | imagepsencodefont


imagepsencodefont

(PHP 3>= 3.0.9, PHP 4 )

imagepsencodefont -- Change the character encoding vector of a font

Description

int imagepsencodefont ( int font_index, string encodingfile)

Loads a character encoding vector from from a file and changes the fonts encoding vector to it. As a PostScript fonts default vector lacks most of the character positions above 127, you'll definitely want to change this if you use an other language than english. The exact format of this file is described in T1libs documentation. T1lib comes with two ready-to-use files, IsoLatin1.enc and IsoLatin2.enc.

If you find yourself using this function all the time, a much better way to define the encoding is to set ps.default_encoding in the configuration file to point to the right encoding file and all fonts you load will automatically have the right encoding.

后退 | 起点 | 前进
imagepscopyfont | 上一级 | imagepsextendfont


imagepsextendfont

(PHP 3>= 3.0.9, PHP 4 )

imagepsextendfont -- Extend or condense a font

Description

bool imagepsextendfont ( int font_index, float extend)

Extend or condense a font (font_index), if the value of the extend parameter is less than one you will be condensing the font.

后退 | 起点 | 前进
imagepsencodefont | 上一级 | imagepsfreefont


imagepsfreefont

(PHP 3>= 3.0.9, PHP 4 )

imagepsfreefont -- Free memory used by a PostScript Type 1 font

Description

void imagepsfreefont ( int fontindex)

See also imagepsloadfont().

后退 | 起点 | 前进
imagepsextendfont | 上一级 | imagepsloadfont


imagepsloadfont

(PHP 3>= 3.0.9, PHP 4 )

imagepsloadfont -- Load a PostScript Type 1 font from file

Description

int imagepsloadfont ( string filename)

In the case everything went right, a valid font index will be returned and can be used for further purposes. Otherwise the function returns FALSE and prints a message describing what went wrong, which you cannot read directly, while the output type is image.

<?php
header ("Content-type: image/jpeg");
$im = imagecreate (350, 45);
$black = imagecolorallocate ($im, 0, 0, 0);
$white = imagecolorallocate ($im, 255, 255, 255);
$font = imagepsloadfont ("bchbi.pfb"); // or locate your .pfb files on your machine
imagepstext ($im, "Testing... It worked!", $font, 32, $white, $black, 32, 32);
imagepsfreefont ($font);
imagejpeg ($im, "", 100); //for best quality...your mileage may vary
imagedestroy ($im);
?>

See also imagepsfreefont().

后退 | 起点 | 前进
imagepsfreefont | 上一级 | imagepsslantfont


imagepsslantfont

(PHP 3>= 3.0.9, PHP 4 )

imagepsslantfont -- Slant a font

Description

bool imagepsslantfont ( int font_index, float slant)

Slant a font given by the font_index parameter with a slant of the value of the slant parameter.

后退 | 起点 | 前进
imagepsloadfont | 上一级 | imagepstext


imagepstext

(PHP 3>= 3.0.9, PHP 4 )

imagepstext -- To draw a text string over an image using PostScript Type1 fonts

Description

array imagepstext ( resource image, string text, int font, int size, int foreground, int background, int x, int y [, int space [, int tightness [, float angle [, int antialias_steps]]]])

Size is expressed in pixels.

Foreground is the color in which the text will be painted. Background is the color to which the text will try to fade in with antialiasing. No pixels with the color background are actually painted, so the background image does not need to be of solid color.

The coordinates given by x, y will define the origin (or reference point) of the first character (roughly the lower-left corner of the character). This is different from the imagestring(), where x, y define the upper-right corner of the first character. Refer to PostScipt documentation about fonts and their measuring system if you have trouble understanding how this works.

Space allows you to change the default value of a space in a font. This amount is added to the normal value and can also be negative.

Tightness allows you to control the amount of white space between characters. This amount is added to the normal character width and can also be negative.

Angle is in degrees.

Antialias_steps allows you to control the number of colours used for antialiasing text. Allowed values are 4 and 16. The higher value is recommended for text sizes lower than 20, where the effect in text quality is quite visible. With bigger sizes, use 4. It's less computationally intensive.

Parameters space and tightness are expressed in character space units, where 1 unit is 1/1000th of an em-square.

Parameters space, tightness, angle and antialias are optional.

This function returns an array containing the following elements:

0 | lower left x-coordinate
1 | lower left y-coordinate
2 | upper right x-coordinate
3 | upper right y-coordinate

See also imagepsbbox().

后退 | 起点 | 前进
imagepsslantfont | 上一级 | imagerectangle


imagerectangle

(PHP 3, PHP 4 )

imagerectangle -- Draw a rectangle

Description

int imagerectangle ( resource image, int x1, int y1, int x2, int y2, int col)

imagerectangle() creates a rectangle of color col in image image starting at upper left coordinate x1, y1 and ending at bottom right coordinate x2, y2. 0, 0 is the top left corner of the image.

后退 | 起点 | 前进
imagepstext | 上一级 | imagesetbrush


imagesetbrush

(PHP 4 >= 4.0.6)

imagesetbrush -- Set the brush image for line drawing

Description

int imagesetbrush ( resource image, resource brush)

imagesetbrush() sets the brush image to be used by all line drawing functions (such as imageline() and imagepolygon()) when drawing with the special colors IMG_COLOR_BRUSHED or IMG_COLOR_STYLEDBRUSHED.

注: You need not take special action when you are finished with a brush, but if you destroy the brush image, you must not use the IMG_COLOR_BRUSHED or IMG_COLOR_STYLEDBRUSHED colors until you have set a new brush image!

注: This function was added in PHP 4.0.6

后退 | 起点 | 前进
imagerectangle | 上一级 | imagesetpixel


imagesetpixel

(PHP 3, PHP 4 )

imagesetpixel -- Set a single pixel

Description

int imagesetpixel ( resource image, int x, int y, int col)

imagesetpixel() draws a pixel at x, y (top left is 0, 0) in image image of color col.

See also imagecreate() and imagecolorallocate().

后退 | 起点 | 前进
imagesetbrush | 上一级 | imagesetstyle


imagesetstyle

(PHP 4 >= 4.0.6)

imagesetstyle -- Set the style for line drawing

Description

int imagesetstyle ( resource image, array style)

imagesetstyle() sets the style to be used by all line drawing functions (such as imageline() and imagepolygon()) when drawing with the special color IMG_COLOR_STYLED or lines of images with color IMG_COLOR_STYLEDBRUSHED.

The style parameter is an array of pixels. Following example script draws a dashed line from upper left to lower right corner of the canvas:

例子 1. imagesetstyle

<?php
header ("Content-type: image/png");
$im  = imagecreate (100, 100);
$w   = imagecolorallocate ($im, 255, 255, 255);
$red = imagecolorallocate ($im, 255, 0, 0);

/* Draw a dashed line, 5 red pixels, 5 white pixels */
$style = array ($red,$red,$red,$red,$red,$w,$w,$w,$w,$w);
imagesetstyle ($im, $style);
imageline ($im, 0, 0, 100, 100, IMG_COLOR_STYLED);

/* Draw a line of happy faces using imagesetbrush() with imagesetstyle */
$style = array ($w,$w,$w,$w,$w,$w,$w,$w,$w,$w,$w,$w,$red);
imagesetstyle ($im, $style);

$brush = imagecreatefrompng ("http://www.libpng.org/pub/png/images/smile.happy.png");
imagecolortransparent ($brush, $w);
imagesetbrush ($im, $brush);
imageline ($im, 100, 0, 0, 100, IMG_COLOR_STYLEDBRUSHED);

imagepng ($im);
imagedestroy ($im);
?>

See also imagesetbrush(), imageline().

注: This function was added in PHP 4.0.6

后退 | 起点 | 前进
imagesetpixel | 上一级 | imagesetthickness


imagesetthickness

(PHP 4 >= 4.0.6)

imagesetthickness -- Set the thickness for line drawing

Description

void imagesetthickness ( resource image, int thickness)

imagesetthickness() sets the thickness of the lines drawn when drawing rectangles, polygons, ellipses etc. etc. to thickness pixels.

注: This function was added in PHP 4.0.6 and requires GD 2.0.1 or later

后退 | 起点 | 前进
imagesetstyle | 上一级 | imagesettile


imagesettile

(PHP 4 >= 4.0.6)

imagesettile -- Set the tile image for filling

Description

int imagesettile ( resource image, resource tile)

imagesettile() sets the tile image to be used by all region filling functions (such as imagefill() and imagefilledpolygon()) when filling with the special color IMG_COLOR_TILED.

A tile is an image used to fill an area with a repeated pattern. Any GD image can be used as a tile, and by setting the transparent color index of the tile image with imagecolortransparent(), a tile allows certain parts of the underlying area to shine through can be created.

注: You need not take special action when you are finished with a tile, but if you destroy the tile image, you must not use the IMG_COLOR_TILED color until you have set a new tile image!

注: This function was added in PHP 4.0.6

后退 | 起点 | 前进
imagesetthickness | 上一级 | imagestring


imagestring

(PHP 3, PHP 4 )

imagestring -- Draw a string horizontally

Description

int imagestring ( resource image, int font, int x, int y, string s, int col)

imagestring() draws the string s in the image identified by image at coordinates x, y (top left is 0, 0) in color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.

See also imageloadfont().

后退 | 起点 | 前进
imagesettile | 上一级 | imagestringup


imagestringup

(PHP 3, PHP 4 )

imagestringup -- Draw a string vertically

Description

int imagestringup ( resource image, int font, int x, int y, string s, int col)

imagestringup() draws the string s vertically in the image identified by image at coordinates x, y (top left is 0, 0) in color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.

See also imageloadfont().

后退 | 起点 | 前进
imagestring | 上一级 | imagesx


imagesx

(PHP 3, PHP 4 )

imagesx -- Get image width

Description

int imagesx ( resource image)

imagesx() returns the width of the image identified by image.

See also imagecreate() and imagesy().

后退 | 起点 | 前进
imagestringup | 上一级 | imagesy


imagesy

(PHP 3, PHP 4 )

imagesy -- Get image height

Description

int imagesy ( resource image)

imagesy() returns the height of the image identified by image.

See also imagecreate() and imagesx().

后退 | 起点 | 前进
imagesx | 上一级 | imagetruecolortopalette


imagetruecolortopalette

(PHP 4 >= 4.0.6)

imagetruecolortopalette -- Convert a true color image to a palette image

Description

void imagetruecolortopalette ( resource image, bool dither, int ncolors)

imagetruecolortopalette() converts a truecolor image to a palette image. The code for this function was originally drawn from the Independent JPEG Group library code, which is excellent. The code has been modified to preserve as much alpha channel information as possible in the resulting palette, in addition to preserving colors as well as possible. This does not work as well as might be hoped. It is usually best to simply produce a truecolor output image instead, which guarantees the highest output quality.

dither indicates if the image should be dithered - if it is TRUE then dithering will be used which will result in a more speckled image but with better color approximation.

ncolors sets the maximum number of colors that should be retained in the palette.

注: This function was added in PHP 4.0.6 and requires GD 2.0.1 or later

后退 | 起点 | 前进
imagesy | 上一级 | imagettfbbox


imagettfbbox

(PHP 3>= 3.0.1, PHP 4 )

imagettfbbox -- Give the bounding box of a text using TrueType fonts

Description

array imagettfbbox ( int size, int angle, string fontfile, string text)

This function calculates and returns the bounding box in pixels for a TrueType text.

text

The string to be measured.

size

The font size in pixels.

fontfile

The name of the TrueType font file. (Can also be an URL.) Depending on which version of the GD library that PHP is using, it may attempt to search for files that do not begin with a leading '/' by appending '.ttf' to the filename and searching along a library-defined font path.

angle

Angle in degrees in which text will be measured.

imagettfbbox() returns an array with 8 elements representing four points making the bounding box of the text:

0 | lower left corner, X position
1 | lower left corner, Y position
2 | lower right corner, X position
3 | lower right corner, Y position
4 | upper right corner, X position
5 | upper right corner, Y position
6 | upper left corner, X position
7 | upper left corner, Y position

The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner seeing the text horizontallty.

This function requires both the GD library and the FreeType library.

See also imagettftext().

后退 | 起点 | 前进
imagetruecolortopalette | 上一级 | imagettftext


imagettftext

(PHP 3, PHP 4 )

imagettftext -- Write text to the image using TrueType fonts

Description

array imagettftext ( resource image, int size, int angle, int x, int y, int col, string fontfile, string text)

imagettftext() draws the string text in the image identified by image, starting at coordinates x, y (top left is 0, 0), at an angle of angle in color col, using the TrueType font file identified by fontfile. Depending on which version of the GD library that PHP is using, when fontfile does not begin with a leading '/', '.ttf' will be appended to the filename and the the library will attempt to search for that filename along a library-defined font path.

The coordinates given by x, y will define the basepoint of the first character (roughly the lower-left corner of the character). This is different from the imagestring(), where x, y define the upper-right corner of the first character.

Angle is in degrees, with 0 degrees being left-to-right reading text (3 o'clock direction), and higher values representing a counter-clockwise rotation. (i.e., a value of 90 would result in bottom-to-top reading text).

Fontfile is the path to the TrueType font you wish to use.

Text is the text string which may include UTF-8 character sequences (of the form: &#123;) to access characters in a font beyond the first 255.

Col is the color index. Using the negative of a color index has the effect of turning off antialiasing.

imagettftext() returns an array with 8 elements representing four points making the bounding box of the text. The order of the points is lower left, lower right, upper right, upper left. The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner when you see the text horizontallty.

This example script will produce a black GIF 400x30 pixels, with the words "Testing..." in white in the font Arial.

例子 1. imagettftext

<?php
header ("Content-type: image/gif");
$im = imagecreate (400, 30);
$black = imagecolorallocate ($im, 0, 0, 0);
$white = imagecolorallocate ($im, 255, 255, 255);
imagettftext ($im, 20, 0, 10, 20, $white, "/path/arial.ttf", "Testing...Omega: &#937;");
imagegif ($im);
imagedestroy ($im);
?>

This function requires both the GD library and the FreeType library.

See also imagettfbbox().

后退 | 起点 | 前进
imagettfbbox | 上一级 | imagetypes


imagetypes

(PHP 3 CVS only, PHP 4 >= 4.0.2)

imagetypes -- Return the image types supported by this PHP build

Description

int imagetypes ( void)

This function returns a bit-field corresponding to the image formats supported by the version of GD linked into PHP. The following bits are returned, IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP. To check for PNG support, for example, do this:

例子 1. imagetypes

<?php
if (imagetypes() & IMG_PNG) {
    echo "PNG Support is enabled";
}
?>

后退 | 起点 | 前进
imagettftext | 上一级 | imagewbmp


imagewbmp

(PHP 3>= 3.0.15, PHP 4 >= 4.0.1)

imagewbmp -- Output image to browser or file

Description

int imagewbmp ( resource image [, string filename [, int foreground]])

imagewbmp() creates the WBMP file in filename from the image image. The image argument is the return from the imagecreate() function.

The filename argument is optional, and if left off, the raw image stream will be output directly. By sending an image/vnd.wap.wbmp content-type using header(), you can create a PHP script that outputs WBMP images directly.

注: WBMP support is only available if PHP was compiled against GD-1.8 or later.

Using the optional foreground parameter, you can set the foreground color. Use an identifier obtained from imagecolorallocate(). The default foreground color is black.

See also image2wbmp(), imagepng(),
imagegif(), imagejpeg(),
imagetypes().

后退 | 起点 | 前进
imagetypes | 上一级 | iptcembed


iptcembed

(PHP 3>= 3.0.7, PHP 4 )

iptcembed -- Embed binary IPTC data into a JPEG image

Description

array iptcembed ( string iptcdata, string jpeg_file_name [, int spool])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
imagewbmp | 上一级 | iptcparse


iptcparse

(PHP 3>= 3.0.6, PHP 4 )

iptcparse -- Parse a binary IPTC http://www.iptc.org/ block into single tags.

Description

array iptcparse ( string iptcblock)

This function parses a binary IPTC block into its single tags. It returns an array using the tagmarker as an index and the value as the value. It returns FALSE on error or if no IPTC data was found. See getimagesize() for a sample.

后退 | 起点 | 前进
iptcembed | 上一级 | jpeg2wbmp


jpeg2wbmp

(PHP 4 >= 4.0.5)

jpeg2wbmp -- Convert JPEG image file to WBMP image file

Description

int jpeg2wbmp ( string jpegname, string wbmpname, int d_height, int d_width, int threshold)

Converts the jpegname JPEG file to WBMP format, and saves it as wbmpname. With the d_height and d_width you specify the height and width of the destination image.

注: WBMP support is only available if PHP was compiled against GD-1.8 or later.

See also png2wbmp().

后退 | 起点 | 前进
iptcparse | 上一级 | png2wbmp


png2wbmp

(PHP 4 >= 4.0.5)

png2wbmp -- Convert PNG image file to WBMP image file

Description

int png2wbmp ( string pngname, string wbmpname, int d_height, int d_width, int threshold)

Converts the pngname PNG file to WBMP format, and saves it as wbmpname. With the d_height and d_width you specify the height and width of the destination image.

注: WBMP support is only available if PHP was compiled against GD-1.8 or later.

See also jpeg2wbmp().

后退 | 起点 | 前进
jpeg2wbmp | 上一级 | read_exif_data


read_exif_data

(PHP 4 >= 4.0.1)

read_exif_data -- Reads header information stored in TIFF and JPEG images

Description

array exif_read_data ( string filename, string sections, bool arrays, bool thumbnail)

注: The read_exif_data() function is an alias for exif_read_data().

See also exif_thumbnail().

后退 | 起点 | 前进
png2wbmp | 上一级 | IMAP, POP3 and NNTP functions


IMAP, POP3 and NNTP functions

PHP 手册
后退 前进

XLII. IMAP, POP3 and NNTP functions

介绍

These functions are not limited to the IMAP protocol, despite their name. The underlying c-client library also supports NNTP, POP3 and local mailbox access methods.

需求

This extension requires the c-client library to be installed. Grab the latest version from ftp://ftp.cac.washington.edu/imap/ and compile it.

安装

To get these functions to work, you have to compile PHP with --with-imap.

Then copy c-client/c-client.a to /usr/local/lib/libc-client.a or some other directory on your link path and copy c-client/c-client.h, c-client/imap4r1.h, c-client/rfc-882.h, c-client/mail.h and c-client/linkage.h to /usr/local/include or some other directory in your include path.

注: Depending how the c-client was configured, you might also need to add --with-imap-ssl=/path/to/openssl/ and/or --with-kerberos into the PHP configure line.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

NIL (integer)

OP_DEBUG (integer)

OP_READONLY (integer)

OP_ANONYMOUS (integer)

OP_SHORTCACHE (integer)

OP_SILENT (integer)

OP_PROTOTYPE (integer)

OP_HALFOPEN (integer)

OP_EXPUNGE (integer)

OP_SECURE (integer)

CL_EXPUNGE (integer)

FT_UID (integer)

FT_PEEK (integer)

FT_NOT (integer)

FT_INTERNAL (integer)

FT_PREFETCHTEXT (integer)

ST_UID (integer)

ST_SILENT (integer)

ST_SET (integer)

CP_UID (integer)

CP_MOVE (integer)

SE_UID (integer)

SE_FREE (integer)

SE_NOPREFETCH (integer)

SO_FREE (integer)

SO_NOSERVER (integer)

SA_MESSAGES (integer)

SA_RECENT (integer)

SA_UNSEEN (integer)

SA_UIDNEXT (integer)

SA_UIDVALIDITY (integer)

SA_ALL (integer)

LATT_NOINFERIORS (integer)

LATT_NOSELECT (integer)

LATT_MARKED (integer)

LATT_UNMARKED (integer)

SORTDATE (integer)

SORTARRIVAL (integer)

SORTFROM (integer)

SORTSUBJECT (integer)

SORTTO (integer)

SORTCC (integer)

SORTSIZE (integer)

TYPETEXT (integer)

TYPEMULTIPART (integer)

TYPEMESSAGE (integer)

TYPEAPPLICATION (integer)

TYPEAUDIO (integer)

TYPEIMAGE (integer)

TYPEVIDEO (integer)

TYPEOTHER (integer)

ENC7BIT (integer)

ENC8BIT (integer)

ENCBINARY (integer)

ENCBASE64 (integer)

ENCQUOTEDPRINTABLE (integer)

ENCOTHER (integer)

相关参考

This document can't go into detail on all the topics touched by the provided functions. Further information is provided by the documentation of the c-client library source (docs/internal.txt). and the following RFC documents:

  • RFC2821: Simple Mail Transfer Protocol (SMTP).

  • RFC2822: Standard for ARPA internet text messages.

  • RFC2060: Internet Message Access Protocol (IMAP) Version 4rev1.

  • RFC1939: Post Office Protocol Version 3 (POP3).

  • RFC977: Network News Transfer Protocol (NNTP).

  • RFC2076: Common Internet Message Headers.

  • RFC2045 , RFC2046 , RFC2047 , RFC2048 & RFC2049: Multipurpose Internet Mail Extensions (MIME).

A detailed overview is also available in the books Programming Internet Email by David Wood and Managing IMAP by Dianna Mullet & Kevin Mullet.

警告

Crashes and startup problems of PHP may be encountered when loading this extension in conjunction with the recode extension. See the recode extension for more information.

目录
imap_8bit — Convert an 8bit string to a quoted-printable string
imap_alerts — This function returns all IMAP alert messages (if any) that have occurred during this page request or since the alert stack was reset
imap_append — Append a string message to a specified mailbox
imap_base64 — Decode BASE64 encoded text
imap_binary — Convert an 8bit string to a base64 string
imap_body — Read the message body
imap_bodystruct — Read the structure of a specified body section of a specific message
imap_check — Check current mailbox
imap_clearflag_full — Clears flags on messages
imap_close — Close an IMAP stream
imap_createmailbox — Create a new mailbox
imap_delete — Mark a messge for deletion from current mailbox
imap_deletemailbox — Delete a mailbox
imap_errors — This function returns all of the IMAP errors (if any) that have occurred during this page request or since the error stack was reset.
imap_expunge — Delete all messages marked for deletion
imap_fetch_overview — Read an overview of the information in the headers of the given message
imap_fetchbody — Fetch a particular section of the body of the message
imap_fetchheader — Returns header for a message
imap_fetchstructure — Read the structure of a particular message
imap_get_quota — Retrieve the quota level settings, and usage statics per mailbox
imap_get_quotaroot — Retrieve the quota settings per user
imap_getmailboxes — Read the list of mailboxes, returning detailed information on each one
imap_getsubscribed — List all the subscribed mailboxes
imap_header — Read the header of the message
imap_headerinfo — Read the header of the message
imap_headers — Returns headers for all messages in a mailbox
imap_last_error — This function returns the last IMAP error (if any) that occurred during this page request
imap_listmailbox — Read the list of mailboxes
imap_listsubscribed — List all the subscribed mailboxes
imap_mail_compose — Create a MIME message based on given envelope and body sections
imap_mail_copy — Copy specified messages to a mailbox
imap_mail_move — Move specified messages to a mailbox
imap_mail — Send an email message
imap_mailboxmsginfo — Get information about the current mailbox
imap_mime_header_decode — Decode MIME header elements
imap_msgno — This function returns the message sequence number for the given UID
imap_num_msg — Gives the number of messages in the current mailbox
imap_num_recent — Gives the number of recent messages in current mailbox
imap_open — Open an IMAP stream to a mailbox
imap_ping — Check if the IMAP stream is still active
imap_qprint — Convert a quoted-printable string to an 8 bit string
imap_renamemailbox — Rename an old mailbox to new mailbox
imap_reopen — Reopen IMAP stream to new mailbox
imap_rfc822_parse_adrlist — Parses an address string
imap_rfc822_parse_headers — Parse mail headers from a string
imap_rfc822_write_address — Returns a properly formatted email address given the mailbox, host, and personal info.
imap_scanmailbox — Read the list of mailboxes, takes a string to search for in the text of the mailbox
imap_search — This function returns an array of messages matching the given search criteria
imap_set_quota — Sets a quota for a given mailbox
imap_setacl — Sets the ACL for a giving mailbox
imap_setflag_full — Sets flags on messages
imap_sort — Sort an array of message headers
imap_status — This function returns status information on a mailbox other than the current one
imap_subscribe — Subscribe to a mailbox
imap_thread — Return threaded by REFERENCES tree
imap_uid — This function returns the UID for the given message sequence number
imap_undelete — Unmark the message which is marked deleted
imap_unsubscribe — Unsubscribe from a mailbox
imap_utf7_decode — Decodes a modified UTF-7 encoded string.
imap_utf7_encode — Converts 8bit data to modified UTF-7 text.
imap_utf8 — Converts text to UTF8

后退 | 起点 | 前进
read_exif_data | 上一级 | imap_8bit


imap_8bit

(PHP 3, PHP 4 )

imap_8bit -- Convert an 8bit string to a quoted-printable string

Description

string imap_8bit ( string string)

Convert an 8bit string to a quoted-printable string (according to RFC2045, section 6.7).

Returns a quoted-printable string.

See also imap_qprint().

后退 | 起点 | 前进
IMAP, POP3 and NNTP functions | 上一级 | imap_alerts


imap_alerts

(PHP 3>= 3.0.12, PHP 4 )

imap_alerts -- This function returns all IMAP alert messages (if any) that have occurred during this page request or since the alert stack was reset

Description

array imap_alerts ( void)

This function returns an array of all of the IMAP alert messages generated since the last imap_alerts() call, or the beginning of the page. When imap_alerts() is called, the alert stack is subsequently cleared. The IMAP specification requires that these messages be passed to the user.

后退 | 起点 | 前进
imap_8bit | 上一级 | imap_append


imap_append

(PHP 3, PHP 4 )

imap_append -- Append a string message to a specified mailbox

Description

int imap_append ( int imap_stream, string mbox, string message [, string flags])

Returns TRUE on sucess, FALSE on error.

imap_append() appends a string message to the specified mailbox mbox. If the optional flags is specified, writes the flags to that mailbox also.

When talking to the Cyrus IMAP server, you must use "\r\n" as your end-of-line terminator instead of "\n" or the operation will fail.

例子 1. imap_append() example

$stream = imap_open("{your.imap.host}INBOX.Drafts","username", "password");

$check = imap_check($stream);
print "Msg Count before append: ". $check->Nmsgs."\n";

imap_append($stream,"{your.imap.host}INBOX.Drafts"
                   ,"From: me@my.host\r\n"
                   ."To: you@your.host\r\n"
                   ."Subject: test\r\n"
                   ."\r\n"
                   ."this is a test message, please ignore\r\n"
                   );

$check = imap_check($stream);
print "Msg Count after append : ". $check->Nmsgs."\n";

imap_close($stream);

后退 | 起点 | 前进
imap_alerts | 上一级 | imap_base64


imap_base64

(PHP 3, PHP 4 )

imap_base64 -- Decode BASE64 encoded text

Description

string imap_base64 ( string text)

imap_base64() function decodes BASE-64 encoded text (see RFC2045, Section 6.8). The decoded message is returned as a string.

See also imap_binary().

后退 | 起点 | 前进
imap_append | 上一级 | imap_binary


imap_binary

(PHP 3>= 3.0.2, PHP 4 )

imap_binary -- Convert an 8bit string to a base64 string

Description

string imap_binary ( string string)

Convert an 8bit string to a base64 string (according to RFC2045, Section 6.8).

Returns a base64 string.

See also imap_base64().

后退 | 起点 | 前进
imap_base64 | 上一级 | imap_body


imap_body

(PHP 3, PHP 4 )

imap_body -- Read the message body

Description

string imap_body ( int imap_stream, int msg_number [, int flags])

imap_body() returns the body of the message, numbered msg_number in the current mailbox. The optional flags are a bit mask with one or more of the following:

  • FT_UID - The msgno is a UID

  • FT_PEEK - Do not set the \Seen flag if not already set

  • FT_INTERNAL - The return string is in internal format, will not canonicalize to CRLF.

imap_body() will only return a verbatim copy of the message body. To extract single parts of a multipart MIME-encoded message you have to use imap_fetchstructure() to analyze its structure and imap_fetchbody() to extract a copy of a single body component.

后退 | 起点 | 前进
imap_binary | 上一级 | imap_bodystruct


imap_bodystruct

(PHP 3>= 3.0.4, PHP 4 )

imap_bodystruct -- Read the structure of a specified body section of a specific message

Description

object imap_bodystruct ( int stream_id, int msg_no, int section)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
imap_body | 上一级 | imap_check


imap_check

(PHP 3, PHP 4 )

imap_check -- Check current mailbox

Description

object imap_check ( int imap_stream)

Returns information about the current mailbox. Returns FALSE on failure.

The imap_check() function checks the current mailbox status on the server and returns the information in an object with following properties:

  • Date - last change of mailbox contents

  • Driver - protocol used to access this mailbox: POP3, IMAP, NNTP

  • Mailbox - the mailbox name

  • Nmsgs - number of messages in the mailbox

  • Recent - number of recent messages in the mailbox

后退 | 起点 | 前进
imap_bodystruct | 上一级 | imap_clearflag_full


imap_clearflag_full

(PHP 3>= 3.0.3, PHP 4 )

imap_clearflag_full -- Clears flags on messages

Description

string imap_clearflag_full ( int stream, string sequence, string flag, string options)

This function causes a store to delete the specified flag to the flags set for the messages in the specified sequence. The flags which you can unset are "\\Seen", "\\Answered", "\\Flagged", "\\Deleted", and "\\Draft" (as defined by RFC2060).

The options are a bit mask with one or more of the following:

ST_UID The sequence argument contains UIDs instead of
sequence numbers

后退 | 起点 | 前进
imap_check | 上一级 | imap_close


imap_close

(PHP 3, PHP 4 )

imap_close -- Close an IMAP stream

Description

int imap_close ( int imap_stream [, int flags])

Close the imap stream. Takes an optional flag CL_EXPUNGE, which will silently expunge the mailbox before closing, removing all messages marked for deletion.

后退 | 起点 | 前进
imap_clearflag_full | 上一级 | imap_createmailbox


imap_createmailbox

(PHP 3, PHP 4 )

imap_createmailbox -- Create a new mailbox

Description

int imap_createmailbox ( int imap_stream, string mbox)

imap_createmailbox() creates a new mailbox specified by mbox. Names containing international characters should be encoded by imap_utf7_encode()

Returns TRUE on success and FALSE on error.

See also imap_renamemailbox(),
imap_deletemailbox() and
imap_open() for the format
of mbox names.

例子 1. imap_createmailbox() example

$mbox = imap_open("{your.imap.host}","username","password",OP_HALFOPEN)
     or die("can't connect: ".imap_last_error());

$name1 = "phpnewbox";
$name2 = imap_utf7_encode("phpnewb&ouml;x");

$newname = $name1;

echo "Newname will be '$name1'<br>\n";

# we will now create a new mailbox "phptestbox" in your inbox folder,
# check its status after creation and finaly remove it to restore
# your inbox to its initial state
if(@imap_createmailbox($mbox,imap_utf7_encode("{your.imap.host}INBOX.$newname"))) {
  $status = @imap_status($mbox,"{your.imap.host}INBOX.$newname",SA_ALL);
  if($status) {
    print("your new mailbox '$name1' has the following status:<br>\n");
    print("Messages:   ". $status->messages   )."<br>\n";
    print("Recent:     ". $status->recent     )."<br>\n";
    print("Unseen:     ". $status->unseen     )."<br>\n";
    print("UIDnext:    ". $status->uidnext    )."<br>\n";
    print("UIDvalidity:". $status->uidvalidity)."<br>\n";

    if(imap_renamemailbox($mbox,"{your.imap.host}INBOX.$newname","{your.imap.host}INBOX.$name2")) {
      echo "renamed new mailbox from '$name1' to '$name2'<br>\n";
      $newname=$name2;
    } else {
      print "imap_renamemailbox on new mailbox failed: ".imap_last_error()."<br>\n";
    }
  } else {
    print  "imap_status on new mailbox failed: ".imap_last_error()."<br>\n";
  }
  if(@imap_deletemailbox($mbox,"{your.imap.host}INBOX.$newname")) {
    print "new mailbox removed to restore initial state<br>\n";
  } else {
    print  "imap_deletemailbox on new mailbox failed: ".implode("<br>\n",imap_errors())."<br>\n";
  }

} else {
  print  "could not create new mailbox: ".implode("<br>\n",imap_errors())."<br>\n";
}

imap_close($mbox);

后退 | 起点 | 前进
imap_close | 上一级 | imap_delete


imap_delete

(PHP 3, PHP 4 )

imap_delete -- Mark a messge for deletion from current mailbox

Description

int imap_delete ( int imap_stream, int msg_number [, int flags])

Returns TRUE.

imap_delete() marks messages listed in msg_number for deletion. The optional flags parameter only has a single option, FT_UID, which tells the function to treat the msg_number argument as a UID. Messages marked for deletion will stay in the mailbox until either imap_expunge() is called or imap_close() is called with the optional parameter CL_EXPUNGE.

注: POP3 mailboxes do not have their message flags saved between connections, so imap_expunge() must be called during the same connection in order for messages marked for deletion to actually be purged.

例子 1. imap_delete() Beispiel

$mbox = imap_open ("{your.imap.host}INBOX", "username", "password")
    or die ("can't connect: " . imap_last_error());

$check = imap_mailboxmsginfo ($mbox);
print "Messages before delete: " . $check->Nmsgs . "<br>\n" ;
imap_delete ($mbox, 1);
$check = imap_mailboxmsginfo ($mbox);
print "Messages after  delete: " . $check->Nmsgs . "<br>\n" ;
imap_expunge ($mbox);
$check = imap_mailboxmsginfo ($mbox);
print "Messages after expunge: " . $check->Nmsgs . "<br>\n" ;
imap_close ($mbox);

后退 | 起点 | 前进
imap_createmailbox | 上一级 | imap_deletemailbox


imap_deletemailbox

(PHP 3, PHP 4 )

imap_deletemailbox -- Delete a mailbox

Description

int imap_deletemailbox ( int imap_stream, string mbox)

imap_deletemailbox() deletes the specified mailbox (see imap_open() for the format of mbox names).

Returns TRUE on success and FALSE on error.

See also imap_createmailbox(),
imap_renamemailbox(), and
imap_open() for the format of
mbox.

后退 | 起点 | 前进
imap_delete | 上一级 | imap_errors


imap_errors

(PHP 3>= 3.0.12, PHP 4 )

imap_errors -- This function returns all of the IMAP errors (if any) that have occurred during this page request or since the error stack was reset.

Description

array imap_errors ( void)

This function returns an array of all of the IMAP error messages generated since the last imap_errors() call, or the beginning of the page. When imap_errors() is called, the error stack is subsequently cleared.

后退 | 起点 | 前进
imap_deletemailbox | 上一级 | imap_expunge


imap_expunge

(PHP 3, PHP 4 )

imap_expunge -- Delete all messages marked for deletion

Description

int imap_expunge ( int imap_stream)

imap_expunge() deletes all the messages marked
for deletion by imap_delete(),
imap_mail_move(), or
imap_setflag_full().

Returns TRUE.

后退 | 起点 | 前进
imap_errors | 上一级 | imap_fetch_overview


imap_fetch_overview

(PHP 3>= 3.0.4, PHP 4 )

imap_fetch_overview -- Read an overview of the information in the headers of the given message

Description

array imap_fetch_overview ( int imap_stream, string sequence [, int flags])

This function fetches mail headers for the given sequence and returns an overview of their contents. sequence will contain a sequence of message indices or UIDs, if flags contains FT_UID. The returned value is an array of objects describing one message header each:

  • subject - the messages subject

  • from - who sent it

  • date - when was it sent

  • message_id - Message-ID

  • references - is a reference to this message id

  • size - size in bytes

  • uid - UID the message has in the mailbox

  • msgno - message sequence number in the maibox

  • recent - this message is flagged as recent

  • flagged - this message is flagged

  • answered - this message is flagged as answered

  • deleted - this message is flagged for deletion

  • seen - this message is flagged as already read

  • draft - this message is flagged as being a draft

例子 1. imap_fetch_overview() example

$mbox = imap_open("{your.imap.host:143}","username","password")
     or die("can't connect: ".imap_last_error());

$overview = imap_fetch_overview($mbox,"2,4:6",0);

if(is_array($overview)) {
        reset($overview);
        while( list($key,$val) = each($overview)) {
                print     $val->msgno
                . " - " . $val->date
                . " - " . $val->subject
                . "\n";
        }
}

imap_close($mbox);

后退 | 起点 | 前进
imap_expunge | 上一级 | imap_fetchbody


imap_fetchbody

(PHP 3, PHP 4 )

imap_fetchbody -- Fetch a particular section of the body of the message

Description

string imap_fetchbody ( int imap_stream, int msg_number, string part_number [, flags flags])

This function causes a fetch of a particular section of the body of the specified messages as a text string and returns that text string. The section specification is a string of integers delimited by period which index into a body part list as per the IMAP4 specification. Body parts are not decoded by this function.

The options for imap_fetchbody() is a bitmask with one or more of the following:

  • FT_UID - The msg_number is a UID

  • FT_PEEK - Do not set the \Seen flag if not already set

  • FT_INTERNAL - The return string is in "internal" format, without any attempt to canonicalize CRLF.

See also: imap_fetchstructure().

后退 | 起点 | 前进
imap_fetch_overview | 上一级 | imap_fetchheader


imap_fetchheader

(PHP 3>= 3.0.3, PHP 4 )

imap_fetchheader -- Returns header for a message

Description

string imap_fetchheader ( int imap_stream, int msgno, int flags)

This function causes a fetch of the complete, unfiltered RFC2822 format header of the specified message as a text string and returns that text string.

The options are:

FT_UID The msgno argument is a UID
FT_INTERNAL The return string is in "internal" format,
without any attempt to canonicalize to CRLF
newlines
FT_PREFETCHTEXT The RFC822.TEXT should be pre-fetched at the
same time. This avoids an extra RTT on an
IMAP connection if a full message text is
desired (e.g. in a "save to local file"
operation)

后退 | 起点 | 前进
imap_fetchbody | 上一级 | imap_fetchstructure


imap_fetchstructure

(PHP 3, PHP 4 )

imap_fetchstructure -- Read the structure of a particular message

Description

object imap_fetchstructure ( int imap_stream, int msg_number [, int flags])

This function fetches all the structured information for a given message. The optional flags parameter only has a single option, FT_UID, which tells the function to treat the msg_number argument as a UID. The returned object includes the envelope, internal date, size, flags and body structure along with a similar object for each mime attachement. The structure of the returned objects is as follows:

表格 1. Returned Objects for imap_fetchstructure()

type | Primary body type
encoding | Body transfer encoding
ifsubtype | TRUE if there is a subtype string
subtype | MIME subtype
ifdescription | TRUE if there is a description string
description | Content description string
ifid | TRUE if there is an identification string
id | Identification string
lines | Number of lines
bytes | Number of bytes
ifdisposition | TRUE if there is a disposition string
disposition | Disposition string
ifdparameters | TRUE if the dparameters array exists
dparameters | An array of objects where each object has an "attribute" and a "value" property corresponding to the parameters on the Content-disposition MIMEheader.
ifparameters | TRUE if the parameters array exists
parameters | An array of objects where each object has an "attribute" and a "value" property.
parts | An array of objects identical in structure to the top-level object, each of which corresponds to a MIME body part.

表格 2. Primary body type

0 | text
1 | multipart
2 | message
3 | application
4 | audio
5 | image
6 | video
7 | other

表格 3. Transfer encodings

0 | 7BIT
1 | 8BIT
2 | BINARY
3 | BASE64
4 | QUOTED-PRINTABLE
5 | OTHER

See also: imap_fetchbody().

后退 | 起点 | 前进
imap_fetchheader | 上一级 | imap_get_quota


imap_get_quota

(PHP 4 >= 4.0.5)

imap_get_quota -- Retrieve the quota level settings, and usage statics per mailbox

Description

array imap_get_quota ( int imap_stream, string quota_root)

Returns an array with integer values limit and usage for the given mailbox. The value of limit represents the total amount of space allowed for this mailbox. The usage value represents the mailboxes current level of capacity. Will return FALSE in the case of failure.

This function is currently only available to users of the c-client2000 or greater library.

NOTE: For this function to work, the mail stream is required to be opened as the mail-admin user. For a non-admin user version of this function, please see the imap_get_quotaroot() function of PHP.

imap_stream should be the value returned from an imap_open() call. NOTE: This stream is required to be opened as the mail admin user for the get_quota function to work. quota_root should normally be in the form of user.name where name is the mailbox you wish to retrieve information about.

例子 1. imap_get_quota() example

$mbox = imap_open("{your.imap.host}","mailadmin","password",OP_HALFOPEN)
      or die("can't connect: ".imap_last_error());

$quota_value = imap_get_quota($mbox, "user.kalowsky");
if(is_array($quota_value)) {
    print "Usage level is: " . $quota_value['usage'];
    print "Limit level is: " . $quota_value['limit'];
}

imap_close($mbox);

As of PHP version 4.3, the function more properly reflects the functionality as dictated by the RFC 2087. The array return value has changed to support an unlimited number of returned resources (i.e. messages, or sub-folders) with each named resource receiving an individual array key. Each key value then contains an another array with the usage and limit values within it. The example below shows the updated returned output.

For backwards compatibility reasons, the originial access methods are still available for use, although it is suggested to update.

例子 2. imap_get_quota() 4.3 or greater example

$mbox = imap_open("{your.imap.host}","mailadmin","password",OP_HALFOPEN)
      or die("can't connect: ".imap_last_error());

$quota_values = imap_get_quota($mbox, "user.kalowsky");
if(is_array($quota_values)) {
   $storage = $quota_values['STORAGE'];
   print "STORAGE usage level is: " .  $storage['usage'];
   print "STORAGE limit level is: " .  $storage['limit'];

   $message = $quota_values['MESSAGE'];
   print "MESSAGE usage level is: " .  $message['usage'];
   print "MESSAGE usage level is: " .  $message['limit'];

   /* ...  */
}

imap_close($mbox);

See also imap_open(), imap_set_quota(), imap_get_quotaroot().

后退 | 起点 | 前进
imap_fetchstructure | 上一级 | imap_get_quotaroot


imap_get_quotaroot

(PHP 4 CVS only)

imap_get_quotaroot -- Retrieve the quota settings per user

Description

array imap_get_quotaroot ( int imap_stream, string quota_root)

Returns an array of integer values pertaining to the specified user mailbox. All values contain a key based upon the resource name, and a corresponding array with the usage and limit values within.

The limit value represents the total amount of space allowed for this user's total mailbox usage. The usage value represents the user's current total mailbox capacity. This function will return FALSE in the case of call failure, and an array of information about the connection upon an un-parsable response from the server.

This function is currently only available to users of the c-client2000 or greater library.

imap_stream should be the value returned from an imap_open() call. This stream should be opened as the user whose mailbox you wish to check. quota_root should normally be in the form of which mailbox (i.e. INBOX).

例子 1. imap_get_quotaroot() example

$mbox = imap_open("{your.imap.host}","kalowsky","password",OP_HALFOPEN)
      or die("can't connect: ".imap_last_error());

$quota = imap_get_quotaroot($mbox, "INBOX");
if(is_array($quota)) {
   $storage = $quota_values['STORAGE'];
   print "STORAGE usage level is: " .  $storage['usage'];
   print "STORAGE limit level is: " .  $storage['limit'];

   $message = $quota_values['MESSAGE'];
   print "MESSAGE usage level is: " .  $message['usage'];
   print "MESSAGE usage level is: " .  $message['limit'];

   /* ...  */

}

imap_close($mbox);

See also imap_open(), imap_set_quota(), imap_get_quota().

后退 | 起点 | 前进
imap_get_quota | 上一级 | imap_getmailboxes


imap_getmailboxes

(PHP 3>= 3.0.12, PHP 4 )

imap_getmailboxes -- Read the list of mailboxes, returning detailed information on each one

Description

array imap_getmailboxes ( int imap_stream, string ref, string pattern)

Returns an array of objects containing mailbox information. Each object has the attributes name, specifying the full name of the mailbox; delimiter, which is the hierarchy delimiter for the part of the hierarchy this mailbox is in; and attributes. Attributes is a bitmask that can be tested against:

  • LATT_NOINFERIORS - This mailbox has no "children" (there are no mailboxes below this one).

  • LATT_NOSELECT - This is only a container, not a mailbox - you cannot open it.

  • LATT_MARKED - This mailbox is marked. Only used by UW-IMAPD.

  • LATT_UNMARKED - This mailbox is not marked. Only used by UW-IMAPD.

Mailbox names containing international Characters outside the printable ASCII range will be encoded and may be decoded by imap_utf7_decode().

ref should normally be just the server specification as described in imap_open(), and pattern specifies where in the mailbox hierarchy to start searching. If you want all mailboxes, pass '*' for pattern.

There are two special characters you can pass as part of the pattern: '*' and '%'. '*' means to return all mailboxes. If you pass pattern as '*', you will get a list of the entire mailbox hierarchy. '%' means to return the current level only. '%' as the pattern parameter will return only the top level mailboxes; '~/mail/%' on UW_IMAPD will return every mailbox in the ~/mail directory, but none in subfolders of that directory.

例子 1. imap_getmailboxes() example

$mbox = imap_open("{your.imap.host}","username","password",OP_HALFOPEN)
      or die("can't connect: ".imap_last_error());

$list = imap_getmailboxes($mbox,"{your.imap.host}","*");
if(is_array($list)) {
  reset($list);
  while (list($key, $val) = each($list))
  {
    print "($key) ";
    print imap_utf7_decode($val->name).",";
    print "'".$val->delimiter."',";
    print $val->attributes."<br>\n";
  }
} else
  print "imap_getmailboxes failed: ".imap_last_error()."\n";

imap_close($mbox);

See also imap_getsubscribed().

后退 | 起点 | 前进
imap_get_quotaroot | 上一级 | imap_getsubscribed


imap_getsubscribed

(PHP 3>= 3.0.12, PHP 4 )

imap_getsubscribed -- List all the subscribed mailboxes

Description

array imap_getsubscribed ( int imap_stream, string ref, string pattern)

This function is identical to imap_getmailboxes(), except that it only returns mailboxes that the user is subscribed to.

后退 | 起点 | 前进
imap_getmailboxes | 上一级 | imap_header


imap_header

(PHP 3, PHP 4 )

imap_header -- Read the header of the message

Description

object imap_header ( int imap_stream, int msg_number [, int fromlength [, int subjectlength [, string defaulthost]]])

This is an alias to imap_headerinfo() and is identical to this in any way.

后退 | 起点 | 前进
imap_getsubscribed | 上一级 | imap_headerinfo


imap_headerinfo

(PHP 3, PHP 4 )

imap_headerinfo -- Read the header of the message

Description

object imap_headerinfo ( int imap_stream, int msg_number [, int fromlength [, int subjectlength [, string defaulthost]]])

This function returns an object of various header elements.

remail, date, Date, subject, Subject, in_reply_to, message_id,
newsgroups, followup_to, references

message flags:
Recent - 'R' if recent and seen,
'N' if recent and not seen,
' ' if not recent
Unseen - 'U' if not seen AND not recent,
' ' if seen OR not seen and recent
Answered -'A' if answered,
' ' if unanswered
Deleted - 'D' if deleted,
' ' if not deleted
Draft - 'X' if draft,
' ' if not draft
Flagged - 'F' if flagged,
' ' if not flagged

NOTE that the Recent/Unseen behavior is a little odd. If you want to
know if a message is Unseen, you must check for

Unseen == 'U' || Recent == 'N'

toaddress (full to: line, up to 1024 characters)

to[] (returns an array of objects from the To line, containing):
personal
adl
mailbox
host

fromaddress (full from: line, up to 1024 characters)

from[] (returns an array of objects from the From line, containing):
personal
adl
mailbox
host

ccaddress (full cc: line, up to 1024 characters)
cc[] (returns an array of objects from the Cc line, containing):
personal
adl
mailbox
host

bccaddress (full bcc line, up to 1024 characters)
bcc[] (returns an array of objects from the Bcc line, containing):
personal
adl
mailbox
host

reply_toaddress (full reply_to: line, up to 1024 characters)
reply_to[] (returns an array of objects from the Reply_to line,
containing):
personal
adl
mailbox
host

senderaddress (full sender: line, up to 1024 characters)
sender[] (returns an array of objects from the sender line, containing):
personal
adl
mailbox
host

return_path (full return-path: line, up to 1024 characters)
return_path[] (returns an array of objects from the return_path line,
containing):
personal
adl
mailbox
host

udate (mail message date in unix time)

fetchfrom (from line formatted to fit fromlength
characters)

fetchsubject (subject line formatted to fit subjectlength characters)

后退 | 起点 | 前进
imap_header | 上一级 | imap_headers


imap_headers

(PHP 3, PHP 4 )

imap_headers -- Returns headers for all messages in a mailbox

Description

array imap_headers ( int imap_stream)

Returns an array of string formatted with header info. One element per mail message.

后退 | 起点 | 前进
imap_headerinfo | 上一级 | imap_last_error


imap_last_error

(PHP 3>= 3.0.12, PHP 4 )

imap_last_error -- This function returns the last IMAP error (if any) that occurred during this page request

Description

string imap_last_error ( void)

This function returns the full text of the last IMAP error message that occurred on the current page. The error stack is untouched; calling imap_last_error() subsequently, with no intervening errors, will return the same error.

后退 | 起点 | 前进
imap_headers | 上一级 | imap_listmailbox


imap_listmailbox

(PHP 3, PHP 4 )

imap_listmailbox -- Read the list of mailboxes

Description

array imap_listmailbox ( int imap_stream, string ref, string pattern)

Returns an array containing the names of the mailboxes. See imap_getmailboxes() for a description of ref and pattern.

例子 1. imap_listmailbox() example

$mbox = imap_open("{your.imap.host}","username","password",OP_HALFOPEN)
      or die("can't connect: ".imap_last_error());

$list = imap_listmailbox($mbox,"{your.imap.host}","*");
if(is_array($list)) {
  reset($list);
  while (list($key, $val) = each($list))
    print imap_utf7_decode($val)."<br>\n";
} else
  print "imap_listmailbox failed: ".imap_last_error()."\n";

imap_close($mbox);

后退 | 起点 | 前进
imap_last_error | 上一级 | imap_listsubscribed


imap_listsubscribed

(PHP 3, PHP 4 )

imap_listsubscribed -- List all the subscribed mailboxes

Description

array imap_listsubscribed ( int imap_stream, string ref, string pattern)

Returns an array of all the mailboxes that you have subscribed. This is almost identical to imap_listmailbox(), but will only return mailboxes the user you logged in as has subscribed.

后退 | 起点 | 前进
imap_listmailbox | 上一级 | imap_mail_compose


imap_mail_compose

(PHP 3>= 3.0.5, PHP 4 )

imap_mail_compose -- Create a MIME message based on given envelope and body sections

Description

string imap_mail_compose ( array envelope, array body)

例子 1. imap_mail_compose() example

<?php

$envelope["from"]="musone@afterfive.com";
$envelope["to"]="musone@darkstar";
$envelope["cc"]="musone@edgeglobal.com";

$part1["type"]=TYPEMULTIPART;
$part1["subtype"]="mixed";

$filename="/tmp/imap.c.gz";
$fp=fopen($filename,"r");
$contents=fread($fp,filesize($filename));
fclose($fp);

$part2["type"]=TYPEAPPLICATION;
$part2["encoding"]=ENCBINARY;
$part2["subtype"]="octet-stream";
$part2["description"]=basename($filename);
$part2["contents.data"]=$contents;

$part3["type"]=TYPETEXT;
$part3["subtype"]="plain";
$part3["description"]="description3";
$part3["contents.data"]="contents.data3\n\n\n\t";

$body[1]=$part1;
$body[2]=$part2;
$body[3]=$part3;

echo nl2br(imap_mail_compose($envelope,$body));

?>

后退 | 起点 | 前进
imap_listsubscribed | 上一级 | imap_mail_copy


imap_mail_copy

(PHP 3, PHP 4 )

imap_mail_copy -- Copy specified messages to a mailbox

Description

int imap_mail_copy ( int imap_stream, string msglist, string mbox [, int flags])

Returns TRUE on success and FALSE on error.

Copies mail messages specified by msglist to specified mailbox. msglist is a range not just message numbers (as described in RFC2060).

Flags is a bitmask of one or more of

  • CP_UID - the sequence numbers contain UIDS

  • CP_MOVE - Delete the messages from the current mailbox after copying

后退 | 起点 | 前进
imap_mail_compose | 上一级 | imap_mail_move


imap_mail_move

(PHP 3, PHP 4 )

imap_mail_move -- Move specified messages to a mailbox

Description

int imap_mail_move ( int imap_stream, string msglist, string mbox [, int flags])

Moves mail messages specified by msglist to specified mailbox. msglist is a range not just message numbers (as described in RFC2060).

Flags is a bitmask and may contain the single option

  • CP_UID - the sequence numbers contain UIDS

Returns TRUE on success and FALSE on error.

后退 | 起点 | 前进
imap_mail_copy | 上一级 | imap_mail


imap_mail

(PHP 3>= 3.0.14, PHP 4 )

imap_mail -- Send an email message

Description

string imap_mail ( string to, string subject, string message [, string additional_headers [, string cc [, string bcc [, string rpath]]]])

This function allows sending of emails with correct handling of Cc and Bcc receivers. The parameters to, cc and bcc are all strings and are all parsed as rfc822 address lists. The receivers specified in bcc will get the mail, but are excluded from the headers. Use the rpath parameter to specify return path. This is useful when using php as a mail client for multiple users.

后退 | 起点 | 前进
imap_mail_move | 上一级 | imap_mailboxmsginfo


imap_mailboxmsginfo

(PHP 3>= 3.0.2, PHP 4 )

imap_mailboxmsginfo -- Get information about the current mailbox

Description

object imap_mailboxmsginfo ( int imap_stream)

Returns information about the current mailbox. Returns FALSE on failure.

The imap_mailboxmsginfo() function checks the current mailbox status on the server. It is similar to imap_status(), but will additionally sum up the size of all messages in the mailbox, which will take some additional time to execute. It returns the information in an object with following properties.

表格 1. Mailbox properties

Date | date of last change
Driver | driver
Mailbox | name of the mailbox
Nmsgs | number of messages
Recent | number of recent messages
Unread | number of unread messages
Deleted | number of deleted messages
Size | mailbox size

例子 1. imap_mailboxmsginfo() example

<?php

$mbox = imap_open("{your.imap.host}INBOX","username", "password")
      or die("can't connect: ".imap_last_error());

$check = imap_mailboxmsginfo($mbox);

if($check) {
    print "Date: "    . $check->Date    ."<br>\n" ;
    print "Driver: "  . $check->Driver  ."<br>\n" ;
    print "Mailbox: " . $check->Mailbox ."<br>\n" ;
    print "Messages: ". $check->Nmsgs   ."<br>\n" ;
    print "Recent: "  . $check->Recent  ."<br>\n" ;
    print "Unread: "  . $check->Unread  ."<br>\n" ;
    print "Deleted: " . $check->Deleted ."<br>\n" ;
    print "Size: "    . $check->Size    ."<br>\n" ;
} else {
    print "imap_check() failed: ".imap_last_error(). "<br>\n";
}

imap_close($mbox);

?>

后退 | 起点 | 前进
imap_mail | 上一级 | imap_mime_header_decode


imap_mime_header_decode

(PHP 3>= 3.0.17, PHP 4 )

imap_mime_header_decode -- Decode MIME header elements

Description

array imap_mime_header_decode ( string text)

imap_mime_header_decode() function decodes MIME message header extensions that are non ASCII text (see RFC2047) The decoded elements are returned in an array of objects, where each object has two properties, "charset" & "text". If the element hasn't been encoded, and in other words is in plain US-ASCII,the "charset" property of that element is set to "default".

例子 1. imap_mime_header_decode() example

$text="=?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <keld@dkuug.dk>";

$elements=imap_mime_header_decode($text);
for($i=0;$i<count($elements);$i++) {
    echo "Charset: {$elements[$i]->charset}\n";
    echo "Text: {$elements[$i]->text}\n\n";
}

In the above example we would have two elements, whereas the first element had previously been encoded with ISO-8859-1, and the second element would be plain US-ASCII.

后退 | 起点 | 前进
imap_mailboxmsginfo | 上一级 | imap_msgno


imap_msgno

(PHP 3>= 3.0.3, PHP 4 )

imap_msgno -- This function returns the message sequence number for the given UID

Description

int imap_msgno ( int imap_stream, int uid)

This function returns the message sequence number for the given UID. It is the inverse of imap_uid().

后退 | 起点 | 前进
imap_mime_header_decode | 上一级 | imap_num_msg


imap_num_msg

(PHP 3, PHP 4 )

imap_num_msg -- Gives the number of messages in the current mailbox

Description

int imap_num_msg ( int imap_stream)

Return the number of messages in the current mailbox.

See also: imap_num_recent() and imap_status().

后退 | 起点 | 前进
imap_msgno | 上一级 | imap_num_recent


imap_num_recent

(PHP 3, PHP 4 )

imap_num_recent -- Gives the number of recent messages in current mailbox

Description

int imap_num_recent ( int imap_stream)

Returns the number of recent messages in the current mailbox.

See also: imap_num_msg() and imap_status().

后退 | 起点 | 前进
imap_num_msg | 上一级 | imap_open


imap_open

(PHP 3, PHP 4 )

imap_open -- Open an IMAP stream to a mailbox

Description

int imap_open ( string mailbox, string username, string password [, int flags])

Returns an IMAP stream on success and FALSE on error. This function can also be used to open streams to POP3 and NNTP servers, but some functions and features are only available on IMAP servers.

A mailbox name consists of a server part and a mailbox path on this server. The special name INBOX stands for the current users personal mailbox. The server part, which is enclosed in '{' and '}', consists of the servers name or ip address, an optional port (prefixed by ':'), and an optional protocol specification (prefixed by '/'). The server part is mandatory in all mailbox parameters. Mailbox names that contain international characters besides those in the printable ASCII space have to be encoded with imap_utf7_encode().

The options are a bit mask with one or more of the following:

  • OP_READONLY - Open mailbox read-only

  • OP_ANONYMOUS - Dont use or update a .newsrc for news (NNTP only)

  • OP_HALFOPEN - For IMAP and NNTP names, open a connection but dont open a mailbox

  • CL_EXPUNGE - Expunge mailbox automatically upon mailbox close

To connect to an IMAP server running on port 143 on the local machine, do the following:

$mbox = imap_open ("{localhost:143}INBOX", "user_id", "password");

To connect to a POP3 server on port 110 on the local server, use:

$mbox = imap_open ("{localhost:110/pop3}INBOX", "user_id", "password");

To connect to an SSL IMAP or POP3 server, add /ssl after the protocol specification:

$mbox = imap_open ("{localhost:993/imap/ssl}INBOX", "user_id", "password");

To connect to an SSL IMAP or POP3 server with a self-signed certificate, add /ssl/novalidate-cert after the protocol specification:

$mbox = imap_open ("{localhost:995/pop3/ssl/novalidate-cert}", "user_id", "password");

To connect to an NNTP server on port 119 on the local server, use:

$nntp = imap_open ("{localhost:119/nntp}comp.test", "", "");

To connect to a remote server replace "localhost" with the name or the IP address of the server you want to connect to.

例子 1. imap_open() example

$mbox = imap_open ("{your.imap.host:143}", "username", "password");

echo "<p><h1>Mailboxes</h1>\n";
$folders = imap_listmailbox ($mbox, "{your.imap.host:143}", "*");

if ($folders == false) {
    echo "Call failed<br>\n";
} else {
    while (list ($key, $val) = each ($folders)) {
        echo $val."<br>\n";
    }
}

echo "<p><h1>Headers in INBOX</h1>\n";
$headers = imap_headers ($mbox);

if ($headers == false) {
    echo "Call failed<br>\n";
} else {
    while (list ($key,$val) = each ($headers)) {
        echo $val."<br>\n";
    }
}

imap_close($mbox);

后退 | 起点 | 前进
imap_num_recent | 上一级 | imap_ping


imap_ping

(PHP 3, PHP 4 )

imap_ping -- Check if the IMAP stream is still active

Description

int imap_ping ( int imap_stream)

Returns TRUE if the stream is still alive, FALSE otherwise.

imap_ping() function pings the stream to see it is still active. It may discover new mail; this is the preferred method for a periodic "new mail check" as well as a "keep alive" for servers which have inactivity timeout. (As PHP scripts do not tend to run that long, i can hardly imagine that this function will be usefull to anyone.)

后退 | 起点 | 前进
imap_open | 上一级 | imap_qprint


imap_qprint

(PHP 3, PHP 4 )

imap_qprint -- Convert a quoted-printable string to an 8 bit string

Description

string imap_qprint ( string string)

Convert a quoted-printable string to an 8 bit string (according to RFC2045, section 6.7).

Returns an 8 bit (binary) string.

See also imap_8bit().

后退 | 起点 | 前进
imap_ping | 上一级 | imap_renamemailbox


imap_renamemailbox

(PHP 3, PHP 4 )

imap_renamemailbox -- Rename an old mailbox to new mailbox

Description

int imap_renamemailbox ( int imap_stream, string old_mbox, string new_mbox)

This function renames on old mailbox to new mailbox (see imap_open() for the format of mbox names).

Returns TRUE on success and FALSE on error.

See also imap_createmailbox(),
imap_deletemailbox(), and
imap_open() for the format of
mbox.

后退 | 起点 | 前进
imap_qprint | 上一级 | imap_reopen


imap_reopen

(PHP 3, PHP 4 )

imap_reopen -- Reopen IMAP stream to new mailbox

Description

int imap_reopen ( int imap_stream, string mailbox [, string flags])

This function reopens the specified stream to a new mailbox on an IMAP or NNTP server.

The options are a bit mask with one or more of the following:

  • OP_READONLY - Open mailbox read-only

  • OP_ANONYMOUS - Dont use or update a .newsrc for news (NNTP only)

  • OP_HALFOPEN - For IMAP and NNTP names, open a connection but dont open a mailbox.

  • CL_EXPUNGE - Expunge mailbox automatically upon mailbox close (see also imap_delete() and imap_expunge())

Returns TRUE on success and FALSE on error.

后退 | 起点 | 前进
imap_renamemailbox | 上一级 | imap_rfc822_parse_adrlist


imap_rfc822_parse_adrlist

(PHP 3>= 3.0.2, PHP 4 )

imap_rfc822_parse_adrlist -- Parses an address string

Description

array imap_rfc822_parse_adrlist ( string address, string default_host)

This function parses the address string as defined in RFC2822 and for each address, returns an array of objects. The objects properties are:

  • mailbox - the mailbox name (username)

  • host - the host name

  • personal - the personal name

  • adl - at domain source route

例子 1. imap_rfc822_parse_adrlist() example

$address_string = "Hartmut Holzgraefe <hartmut@cvs.php.net>, postmaster@somedomain.net, root";
$address_array  = imap_rfc822_parse_adrlist($address_string,"somedomain.net");
if(! is_array($address_array)) die("somethings wrong\n");

reset($address_array);
while(list($key,$val)=each($address_array)){
  print "mailbox : ".$val->mailbox."<br>\n";
  print "host    : ".$val->host."<br>\n";
  print "personal: ".$val->personal."<br>\n";
  print "adl     : ".$val->adl."<p>\n";
}

后退 | 起点 | 前进
imap_reopen | 上一级 | imap_rfc822_parse_headers


imap_rfc822_parse_headers

(PHP 4 )

imap_rfc822_parse_headers -- Parse mail headers from a string

Description

object imap_rfc822_parse_headers ( string headers [, string defaulthost])

This function returns an object of various header elements, similar to imap_header(), except without the flags and other elements that come from the IMAP server.

后退 | 起点 | 前进
imap_rfc822_parse_adrlist | 上一级 | imap_rfc822_write_address


imap_rfc822_write_address

(PHP 3>= 3.0.2, PHP 4 )

imap_rfc822_write_address -- Returns a properly formatted email address given the mailbox, host, and personal info.

Description

string imap_rfc822_write_address ( string mailbox, string host, string personal)

Returns a properly formatted email address as defined in RFC2822 given the mailbox, host, and personal info.

例子 1. imap_rfc822_write_address() example

print imap_rfc822_write_address("hartmut","cvs.php.net","Hartmut Holzgraefe")."\n";

后退 | 起点 | 前进
imap_rfc822_parse_headers | 上一级 | imap_scanmailbox


imap_scanmailbox

(PHP 3, PHP 4 )

imap_scanmailbox -- Read the list of mailboxes, takes a string to search for in the text of the mailbox

Description

array imap_scanmailbox ( int imap_stream, string ref, string pattern, string content)

Returns an array containing the names of the mailboxes that have content in the text of the mailbox. This function is similar to imap_listmailbox(), but it will additionally check for the presence of the string content inside the mailbox data. See imap_getmailboxes() for a description of ref and pattern.

后退 | 起点 | 前进
imap_rfc822_write_address | 上一级 | imap_search


imap_search

(PHP 3>= 3.0.12, PHP 4 )

imap_search -- This function returns an array of messages matching the given search criteria

Description

array imap_search ( int imap_stream, string criteria, int flags)

This function performs a search on the mailbox currently opened in the given imap stream. criteria is a string, delimited by spaces, in which the following keywords are allowed. Any multi-word arguments (eg. FROM "joey smith") must be quoted.

  • ALL - return all messages matching the rest of the criteria

  • ANSWERED - match messages with the \\ANSWERED flag set

  • BCC "string" - match messages with "string" in the Bcc: field

  • BEFORE "date" - match messages with Date: before "date"

  • BODY "string" - match messages with "string" in the body of the message

  • CC "string" - match messages with "string" in the Cc: field

  • DELETED - match deleted messages

  • FLAGGED - match messages with the \\FLAGGED (sometimes referred to as Important or Urgent) flag set

  • FROM "string" - match messages with "string" in the From: field

  • KEYWORD "string" - match messages with "string" as a keyword

  • NEW - match new messages

  • OLD - match old messages

  • ON "date" - match messages with Date: matching "date"

  • RECENT - match messages with the \\RECENT flag set

  • SEEN - match messages that have been read (the \\SEEN flag is set)

  • SINCE "date" - match messages with Date: after "date"

  • SUBJECT "string" - match messages with "string" in the Subject:

  • TEXT "string" - match messages with text "string"

  • TO "string" - match messages with "string" in the To:

  • UNANSWERED - match messages that have not been answered

  • UNDELETED - match messages that are not deleted

  • UNFLAGGED - match messages that are not flagged

  • UNKEYWORD "string" - match messages that do not have the keyword "string"

  • UNSEEN - match messages which have not been read yet

For example, to match all unanswered messages sent by Mom, you'd use: "UNANSWERED FROM mom". Searches appear to be case insensitive. This list of criteria is from a reading of the UW c-client source code and may be uncomplete or inaccurate (see also RFC2060, section 6.4.4).

Valid values for flags are SE_UID, which causes the returned array to contain UIDs instead of messages sequence numbers.

后退 | 起点 | 前进
imap_scanmailbox | 上一级 | imap_set_quota


imap_set_quota

(PHP 4 >= 4.0.5)

imap_set_quota -- Sets a quota for a given mailbox

Description

int imap_set_quota ( int imap_stream, string quota_root, int quota_limit)

Sets an upper limit quota on a per mailbox basis. This function requires the imap_stream to have been opened as the mail administrator account. It will not work if opened as any other user.

This function is currently only available to users of the c-client2000 or greater library.

imap_stream is the stream pointer returned from a imap_open() call. This stream must be opened as the mail administrator, other wise this function will fail. quota_root is the mailbox to have a quota set. This should follow the IMAP standard format for a mailbox, 'user.name'. quota_limit is the maximum size (in KB) for the quota_root.

Returns TRUE on success and FALSE on error.

例子 1. imap_set_quota() example

$mbox = imap_open ("{your.imap.host:143}", "mailadmin", "password");

if(!imap_set_quota($mbox, "user.kalowsky", 3000)) {
    print "Error in setting quota\n";
    return;
}

imap_close($mbox);

See also imap_open(), imap_set_quota().

后退 | 起点 | 前进
imap_search | 上一级 | imap_setacl


imap_setacl

(PHP 4 >= 4.1.0)

imap_setacl -- Sets the ACL for a giving mailbox

Description

int imap_setacl ( int stream_id, string mailbox, string id, string rights)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
imap_set_quota | 上一级 | imap_setflag_full


imap_setflag_full

(PHP 3>= 3.0.3, PHP 4 )

imap_setflag_full -- Sets flags on messages

Description

string imap_setflag_full ( int stream, string sequence, string flag, string options)

This function causes a store to add the specified flag to the flags set for the messages in the specified sequence.

The flags which you can set are "\\Seen", "\\Answered", "\\Flagged", "\\Deleted", and "\\Draft" (as defined by RFC2060).

The options are a bit mask with one or more of the following:

ST_UID The sequence argument contains UIDs instead of
sequence numbers

例子 1. imap_setflag_full() example

$mbox = imap_open("{your.imap.host:143}","username","password")
     or die("can't connect: ".imap_last_error());

$status = imap_setflag_full($mbox,"2,5","\\Seen \\Flagged");

print gettype($status)."\n";
print $status."\n";

imap_close($mbox);

后退 | 起点 | 前进
imap_setacl | 上一级 | imap_sort


imap_sort

(PHP 3>= 3.0.3, PHP 4 )

imap_sort -- Sort an array of message headers

Description

array imap_sort ( int stream, int criteria, int reverse, int options)

Returns an array of message numbers sorted by the given parameters.

Reverse is 1 for reverse-sorting.

Criteria can be one (and only one) of the following:

SORTDATE message Date
SORTARRIVAL arrival date
SORTFROM mailbox in first From address
SORTSUBJECT message Subject
SORTTO mailbox in first To address
SORTCC mailbox in first cc address
SORTSIZE size of message in octets

The flags are a bitmask of one or more of the following:

SE_UID Return UIDs instead of sequence numbers
SE_NOPREFETCH Don't prefetch searched messages.

后退 | 起点 | 前进
imap_setflag_full | 上一级 | imap_status


imap_status

(PHP 3>= 3.0.4, PHP 4 )

imap_status -- This function returns status information on a mailbox other than the current one

Description

object imap_status ( int imap_stream, string mailbox, int options)

This function returns an object containing status information. Valid flags are:

  • SA_MESSAGES - set status->messages to the number of messages in the mailbox

  • SA_RECENT - set status->recent to the number of recent messages in the mailbox

  • SA_UNSEEN - set status->unseen to the number of unseen (new) messages in the mailbox

  • SA_UIDNEXT - set status->uidnext to the next uid to be used in the mailbox

  • SA_UIDVALIDITY - set status->uidvalidity to a constant that changes when uids for the mailbox may no longer be valid

  • SA_ALL - set all of the above

status->flags is also set, which contains a bitmask which can be checked against any of the above constants.

例子 1. imap_status() example

$mbox = imap_open("{your.imap.host}","username","password",OP_HALFOPEN)
      or die("can't connect: ".imap_last_error());

$status = imap_status($mbox,"{your.imap.host}INBOX",SA_ALL);
if($status) {
  print("Messages:   ". $status->messages   )."<br>\n";
  print("Recent:     ". $status->recent     )."<br>\n";
  print("Unseen:     ". $status->unseen     )."<br>\n";
  print("UIDnext:    ". $status->uidnext    )."<br>\n";
  print("UIDvalidity:". $status->uidvalidity)."<br>\n";
} else
  print "imap_status failed: ".imap_last_error()."\n";

imap_close($mbox);

后退 | 起点 | 前进
imap_sort | 上一级 | imap_subscribe


imap_subscribe

(PHP 3, PHP 4 )

imap_subscribe -- Subscribe to a mailbox

Description

int imap_subscribe ( int imap_stream, string mbox)

Subscribe to a new mailbox.

Returns TRUE on success and FALSE on error.

后退 | 起点 | 前进
imap_status | 上一级 | imap_thread


imap_thread

(PHP 4 >= 4.1.0)

imap_thread -- Return threaded by REFERENCES tree

Description

int imap_thread ( int stream_id [, int flags])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
imap_subscribe | 上一级 | imap_uid


imap_uid

(PHP 3>= 3.0.3, PHP 4 )

imap_uid -- This function returns the UID for the given message sequence number

Description

int imap_uid ( int imap_stream, int msgno)

This function returns the UID for the given message sequence number. An UID is an unique identifier that will not change over time while a message sequence number may change whenever the content of the mailbox changes. This function is the inverse of imap_msgno().

注: This is not supported by POP3 mailboxes.

后退 | 起点 | 前进
imap_thread | 上一级 | imap_undelete


imap_undelete

(PHP 3, PHP 4 )

imap_undelete -- Unmark the message which is marked deleted

Description

int imap_undelete ( int imap_stream, int msg_number)

This function removes the deletion flag for a specified message, which is set by imap_delete() or imap_mail_move().

Returns TRUE on success and FALSE on error.

后退 | 起点 | 前进
imap_uid | 上一级 | imap_unsubscribe


imap_unsubscribe

(PHP 3, PHP 4 )

imap_unsubscribe -- Unsubscribe from a mailbox

Description

int imap_unsubscribe ( int imap_stream, string mbox)

Unsubscribe from a specified mailbox.

Returns TRUE on success and FALSE on error.

后退 | 起点 | 前进
imap_undelete | 上一级 | imap_utf7_decode


imap_utf7_decode

(PHP 3>= 3.0.15, PHP 4 )

imap_utf7_decode -- Decodes a modified UTF-7 encoded string.

Description

string imap_utf7_decode ( string text)

Decodes modified UTF-7 text into 8bit data.

Returns the decoded 8bit data, or FALSE if the input string was not valid modified UTF-7. This function is needed to decode mailbox names that contain international characters outside of the printable ASCII range. The modified UTF-7 encoding is defined in RFC 2060, section 5.1.3 (original UTF-7 was defned in RFC1642).

后退 | 起点 | 前进
imap_unsubscribe | 上一级 | imap_utf7_encode


imap_utf7_encode

(PHP 3>= 3.0.15, PHP 4 )

imap_utf7_encode -- Converts 8bit data to modified UTF-7 text.

Description

string imap_utf7_encode ( string data)

Converts 8bit data to modified UTF-7 text. This is needed to encode mailbox names that contain international characters outside of the printable ASCII range. The modified UTF-7 encoding is defined in RFC 2060, section 5.1.3 (original UTF-7 was defned in RFC1642).

Returns the modified UTF-7 text.

后退 | 起点 | 前进
imap_utf7_decode | 上一级 | imap_utf8


imap_utf8

(PHP 3>= 3.0.13, PHP 4 )

imap_utf8 -- Converts text to UTF8

Description

string imap_utf8 ( string text)

Converts the given text to UTF8 (as defined in RFC2044).

后退 | 起点 | 前进
imap_utf7_encode | 上一级 | Informix functions


Informix functions

PHP 手册
后退 前进

XLIII. Informix functions

介绍

The Informix driver for Informix (IDS) 7.x, SE 7.x, Universal Server (IUS) 9.x and IDS 2000 is implemented in "ifx.ec" and "php3_ifx.h" in the informix extension directory. IDS 7.x support is fairly complete, with full support for BYTE and TEXT columns. IUS 9.x support is partly finished: the new data types are there, but SLOB and CLOB support is still under construction.

需求

Configuration notes: You need a version of ESQL/C to compile the PHP Informix driver. ESQL/C versions from 7.2x on should be OK. ESQL/C is now part of the Informix Client SDK.

Make sure that the "INFORMIXDIR" variable has been set, and that $INFORMIXDIR/bin is in your PATH before you run the "configure" script.

安装

注: The configure script will autodetect the libraries and include directories, if you run configure --with_informix=yes. You can override this detection by specifying "IFX_LIBDIR", "IFX_LIBS" and "IFX_INCDIR" in the environment. The configure script will also try to detect your Informix server version. It will set the "HAVE_IFX_IUS" conditional compilation variable if your Informix version >= 9.00.

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

注: Make sure that the Informix environment variables INFORMIXDIR and INFORMIXSERVER are available to the PHP ifx driver, and that the INFORMIX bin directory is in the PATH. Check this by running a script that contains a call to phpinfo() before you start testing. The phpinfo() output should list these environment variables. This is TRUE for both CGI php and Apache mod_php. You may have to set these environment variables in your Apache startup script.

The Informix shared libraries should also be available to the loader (check LD_LINBRARY_PATH or ld.so.conf/ldconfig).

Some notes on the use of BLOBs (TEXT and BYTE columns): BLOBs are normally addressed by BLOB identifiers. Select queries return a "blob id" for every BYTE and TEXT column. You can get at the contents with "string_var = ifx_get_blob($blob_id);" if you choose to get the BLOBs in memory (with : "ifx_blobinfile(0);"). If you prefer to receive the content of BLOB columns in a file, use "ifx_blobinfile(1);", and "ifx_get_blob($blob_id);" will get you the filename. Use normal file I/O to get at the blob contents.

For insert/update queries you must create these "blob id's" yourself with "ifx_create_blob();". You then plug the blob id's into an array, and replace the blob columns with a question mark (?) in the query string. For updates/inserts, you are responsible for setting the blob contents with ifx_update_blob().

The behaviour of BLOB columns can be altered by configuration variables that also can be set at runtime :

configuration variable : ifx.textasvarchar

configuration variable : ifx.byteasvarchar

runtime functions :

ifx_textasvarchar(0) : use blob id's for select queries with TEXT columns

ifx_byteasvarchar(0) : use blob id's for select queries with BYTE columns

ifx_textasvarchar(1) : return TEXT columns as if they were VARCHAR columns, so that you don't need to use blob id's for select queries.

ifx_byteasvarchar(1) : return BYTE columns as if they were VARCHAR columns, so that you don't need to use blob id's for select queries.

configuration variable : ifx.blobinfile

runtime function :

ifx_blobinfile_mode(0) : return BYTE columns in memory, the blob id lets you get at the contents.

ifx_blobinfile_mode(1) : return BYTE columns in a file, the blob id lets you get at the file name.

If you set ifx_text/byteasvarchar to 1, you can use TEXT and BYTE columns in select queries just like normal (but rather long) VARCHAR fields. Since all strings are "counted" in PHP, this remains "binary safe". It is up to you to handle this correctly. The returned data can contain anything, you are responsible for the contents.

If you set ifx_blobinfile to 1, use the file name returned by ifx_get_blob(..) to get at the blob contents. Note that in this case YOU ARE RESPONSIBLE FOR DELETING THE TEMPORARY FILES CREATED BY INFORMIX when fetching the row. Every new row fetched will create new temporary files for every BYTE column.

The location of the temporary files can be influenced by the environment variable "blobdir", default is "." (the current directory). Something like : putenv(blobdir=tmpblob"); will ease the cleaning up of temp files accidentally left behind (their names all start with "blb").

Automatically trimming "char" (SQLCHAR and SQLNCHAR) data: This can be set with the configuration variable

ifx.charasvarchar : if set to 1 trailing spaces will be automatically trimmed, to save you some "chopping".

NULL values: The configuration variable ifx.nullformat (and the runtime function ifx_nullformat()) when set to TRUE will return NULL columns as the string "NULL", when set to FALSE they return the empty string. This allows you to discriminate between NULL columns and empty columns.

表格 1. Informix configuration options

Name | Default | Changeable
ifx.allow_persistent | "1" | PHP_INI_SYSTEM
ifx.max_persistent | "-1" | PHP_INI_SYSTEM
ifx.max_links | "-1" | PHP_INI_SYSTEM
ifx.default_host | NULL | PHP_INI_SYSTEM
ifx.default_user | NULL | PHP_INI_SYSTEM
ifx.default_password | NULL | PHP_INI_SYSTEM
ifx.blobinfile | "1" | PHP_INI_ALL
ifx.textasvarchar | "0" | PHP_INI_ALL
ifx.byteasvarchar | "0" | PHP_INI_ALL
ifx.charasvarchar | "0" | PHP_INI_ALL
ifx.nullformat | "0" | PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

Here is a short explanation of the configuration directives.

ifx.allow_persistent boolean

Whether to allow persistent Informix connections.

ifx.max_persistent integer

The maximum number of persistent Informix connections per process.

ifx.max_links integer

The maximum number of Informix connections per process, including persistent connections.

ifx.default_host string

The default host to connect to when no host is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.

ifx.default_user string

The default user id to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.

ifx.default_password string

The default password to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.

ifx.blobinfile boolean

Set to TRUE if you want to return blob columns in a file, FALSE if you want them in memory. You can override the setting at runtime with ifx_blobinfile_mode().

ifx.textasvarchar boolean

Set to TRUE if you want to return TEXT columns as normal strings in select statements, FALSE if you want to use blob id parameters. You can override the setting at runtime with ifx_textasvarchar().

ifx.byteasvarchar boolean

Set to TRUE if you want to return BYTE columns as normal strings in select queries, FALSE if you want to use blob id parameters. You can override the setting at runtime with ifx_textasvarchar().

ifx.charasvarchar boolean

Set to TRUE if you want to trim trailing spaces from CHAR columns when fetching them.

ifx.nullformat boolean

Set to TRUE if you want to return NULL columns as the literal string "NULL", FALSE if you want them returned as the empty string "". You can override this setting at runtime with ifx_nullformat().

资源类型

预定义常量

该扩展模块未定义任何常量。

目录
ifx_affected_rows — Get number of rows affected by a query
ifx_blobinfile_mode — Set the default blob mode for all select queries
ifx_byteasvarchar — Set the default byte mode
ifx_close — Close Informix connection
ifx_connect — Open Informix server connection
ifx_copy_blob — Duplicates the given blob object
ifx_create_blob — Creates an blob object
ifx_create_char — Creates an char object
ifx_do — Execute a previously prepared SQL-statement
ifx_error — Returns error code of last Informix call
ifx_errormsg — Returns error message of last Informix call
ifx_fetch_row — Get row as enumerated array
ifx_fieldproperties — List of SQL fieldproperties
ifx_fieldtypes — List of Informix SQL fields
ifx_free_blob — Deletes the blob object
ifx_free_char — Deletes the char object
ifx_free_result — Releases resources for the query
ifx_get_blob — Return the content of a blob object
ifx_get_char — Return the content of the char object
ifx_getsqlca — Get the contents of sqlca.sqlerrd[0..5] after a query
ifx_htmltbl_result — Formats all rows of a query into a HTML table
ifx_nullformat — Sets the default return value on a fetch row
ifx_num_fields — Returns the number of columns in the query
ifx_num_rows — Count the rows already fetched from a query
ifx_pconnect — Open persistent Informix connection
ifx_prepare — Prepare an SQL-statement for execution
ifx_query — Send Informix query
ifx_textasvarchar — Set the default text mode
ifx_update_blob — Updates the content of the blob object
ifx_update_char — Updates the content of the char object
ifxus_close_slob — Deletes the slob object
ifxus_create_slob — Creates an slob object and opens it
ifxus_free_slob — Deletes the slob object
ifxus_open_slob — Opens an slob object
ifxus_read_slob — Reads nbytes of the slob object
ifxus_seek_slob — Sets the current file or seek position
ifxus_tell_slob — Returns the current file or seek position
ifxus_write_slob — Writes a string into the slob object

后退 | 起点 | 前进
imap_utf8 | 上一级 | ifx_affected_rows


ifx_affected_rows

(PHP 3>= 3.0.3, PHP 4 )

ifx_affected_rows -- Get number of rows affected by a query

Description

int ifx_affected_rows ( int result_id)

result_id is a valid result id returned by ifx_query() or ifx_prepare().

Returns the number of rows affected by a query associated with result_id.

For inserts, updates and deletes the number is the real number (sqlerrd[2]) of affected rows. For selects it is an estimate (sqlerrd[0]). Don't rely on it. The database server can never return the actual number of rows that will be returned by a SELECT because it has not even begun fetching them at this stage (just after the "PREPARE" when the optimizer has determined the query plan).

Useful after ifx_prepare() to limit queries to reasonable result sets.

See also: ifx_num_rows()

例子 1. Informix affected rows

$rid = ifx_prepare ("select * from emp
                     where name like " . $name, $connid);
if (! $rid) {
    ... error ...
}
$rowcount = ifx_affected_rows ($rid);
if ($rowcount > 1000) {
    printf ("Too many rows in result set (%d)\n<br>", $rowcount);
    die ("Please restrict your query<br>\n");
}

后退 | 起点 | 前进
Informix functions | 上一级 | ifx_blobinfile_mode


ifx_blobinfile_mode

(PHP 3>= 3.0.4, PHP 4 )

ifx_blobinfile_mode -- Set the default blob mode for all select queries

Description

void ifx_blobinfile_mode ( int mode)

Set the default blob mode for all select queries. Mode "0" means save Byte-Blobs in memory, and mode "1" means save Byte-Blobs in a file.

后退 | 起点 | 前进
ifx_affected_rows | 上一级 | ifx_byteasvarchar


ifx_byteasvarchar

(PHP 3>= 3.0.4, PHP 4 )

ifx_byteasvarchar -- Set the default byte mode

Description

void ifx_byteasvarchar ( int mode)

Sets the default byte mode for all select-queries. Mode "0" will return a blob id, and mode "1" will return a varchar with text content.

后退 | 起点 | 前进
ifx_blobinfile_mode | 上一级 | ifx_close


ifx_close

(PHP 3>= 3.0.3, PHP 4 )

ifx_close -- Close Informix connection

Description

int ifx_close ( [int link_identifier])

Returns: always TRUE.

ifx_close() closes the link to an Informix database that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.

Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

ifx_close() will not close persistent links generated by ifx_pconnect().

See also: ifx_connect(), and ifx_pconnect().

例子 1. Closing a Informix connection

$conn_id = ifx_connect ("mydb@ol_srv", "itsme", "mypassword");
... some queries and stuff ...
ifx_close($conn_id);

后退 | 起点 | 前进
ifx_byteasvarchar | 上一级 | ifx_connect


ifx_connect

(PHP 3>= 3.0.3, PHP 4 )

ifx_connect -- Open Informix server connection

Description

int ifx_connect ( [string database [, string userid [, string password]]])

Returns a connection identifier on success, or FALSE on error.

ifx_connect() establishes a connection to an Informix server. All of the arguments are optional, and if they're missing, defaults are taken from values supplied in configuration file (ifx.default_host for the host (Informix libraries will use INFORMIXSERVER environment value if not defined), ifx.default_user for user, ifx.default_password for the password (none if not defined).

In case a second call is made to ifx_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 ifx_close().

See also ifx_pconnect(), and ifx_close().

例子 1. Connect to a Informix database

$conn_id = ifx_connect ("mydb@ol_srv1", "imyself", "mypassword");

后退 | 起点 | 前进
ifx_close | 上一级 | ifx_copy_blob


ifx_copy_blob

(PHP 3>= 3.0.4, PHP 4 )

ifx_copy_blob -- Duplicates the given blob object

Description

int ifx_copy_blob ( int bid)

Duplicates the given blob object. bid is the ID of the blob object.

Returns FALSE on error otherwise the new blob object-id.

后退 | 起点 | 前进
ifx_connect | 上一级 | ifx_create_blob


ifx_create_blob

(PHP 3>= 3.0.4, PHP 4 )

ifx_create_blob -- Creates an blob object

Description

int ifx_create_blob ( int type, int mode, string param)

Creates an blob object.

type: 1 = TEXT, 0 = BYTE

mode: 0 = blob-object holds the content in memory, 1 = blob-object holds the content in file.

param: if mode = 0: pointer to the content, if mode = 1: pointer to the filestring.

Return FALSE on error, otherwise the new blob object-id.

后退 | 起点 | 前进
ifx_copy_blob | 上一级 | ifx_create_char


ifx_create_char

(PHP 3>= 3.0.6, PHP 4 )

ifx_create_char -- Creates an char object

Description

int ifx_create_char ( string param)

Creates an char object. param should be the char content.

后退 | 起点 | 前进
ifx_create_blob | 上一级 | ifx_do


ifx_do

(PHP 3>= 3.0.4, PHP 4 )

ifx_do -- Execute a previously prepared SQL-statement

Description

int ifx_do ( int result_id)

Returns TRUE on success, FALSE on error.

Executes a previously prepared query or opens a cursor for it.

Does NOT free result_id on error.

Also sets the real number of ifx_affected_rows() for non-select statements for retrieval by ifx_affected_rows()

See also: ifx_prepare(). There is a example.

后退 | 起点 | 前进
ifx_create_char | 上一级 | ifx_error


ifx_error

(PHP 3>= 3.0.3, PHP 4 )

ifx_error -- Returns error code of last Informix call

Description

string ifx_error ( void)

The Informix error codes (SQLSTATE & SQLCODE) formatted as follows :

x [SQLSTATE = aa bbb SQLCODE=cccc]

where x = space : no error

E : error

N : no more data

W : warning

? : undefined

If the "x" character is anything other than space, SQLSTATE and SQLCODE describe the error in more detail.

See the Informix manual for the description of SQLSTATE and SQLCODE

Returns in a string one character describing the general results of a statement and both SQLSTATE and SQLCODE associated with the most recent SQL statement executed. The format of the string is "(char) [SQLSTATE=(two digits) (three digits) SQLCODE=(one digit)]". The first character can be ' ' (space) (success), 'W' (the statement caused some warning), 'E' (an error happened when executing the statement) or 'N' (the statement didn't return any data).

See also: ifx_errormsg()

后退 | 起点 | 前进
ifx_do | 上一级 | ifx_errormsg


ifx_errormsg

(PHP 3>= 3.0.4, PHP 4 )

ifx_errormsg -- Returns error message of last Informix call

Description

string ifx_errormsg ( [int errorcode])

Returns the Informix error message associated with the most recent Informix error, or, when the optional "errorcode" param is present, the error message corresponding to "errorcode".

See also: ifx_error()

printf("%s\n&lt;br>", ifx_errormsg(-201));

后退 | 起点 | 前进
ifx_error | 上一级 | ifx_fetch_row


ifx_fetch_row

(PHP 3>= 3.0.3, PHP 4 )

ifx_fetch_row -- Get row as enumerated array

Description

array ifx_fetch_row ( int result_id [, mixed position])

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.

Blob columns are returned as integer blob id values for use in ifx_get_blob() unless you have used ifx_textasvarchar(1) or ifx_byteasvarchar(1), in which case blobs are returned as string values. Returns FALSE on error

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

position is an optional parameter for a "fetch" operation on "scroll" cursors: "NEXT", "PREVIOUS", "CURRENT", "FIRST", "LAST" or a number. If you specify a number, an "absolute" row fetch is executed. This parameter is optional, and only valid for SCROLL cursors.

ifx_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, with the column name as key.

Subsequent calls to ifx_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

例子 1. Informix fetch rows

$rid = ifx_prepare ("select * from emp where name like " . $name,
                     $connid, IFX_SCROLL);
if (! $rid) {
    ... error ...
}
$rowcount = ifx_affected_rows($rid);
if ($rowcount > 1000) {
    printf ("Too many rows in result set (%d)\n<br>", $rowcount);
    die ("Please restrict your query<br>\n");
}
if (! ifx_do ($rid)) {
   ... error ...
}
$row = ifx_fetch_row ($rid, "NEXT");
while (is_array($row)) {
    for(reset($row); $fieldname=key($row); next($row)) {
        $fieldvalue = $row[$fieldname];
        printf ("%s = %s,", $fieldname, $fieldvalue);
    }
    printf("\n<br>");
    $row = ifx_fetch_row ($rid, "NEXT");
}
ifx_free_result ($rid);

后退 | 起点 | 前进
ifx_errormsg | 上一级 | ifx_fieldproperties


ifx_fieldproperties

(PHP 3>= 3.0.3, PHP 4 )

ifx_fieldproperties -- List of SQL fieldproperties

Description

array ifx_fieldproperties ( int result_id)

Returns an associative array with fieldnames as key and the SQL fieldproperties as data for a query with result_id. Returns FALSE on error.

Returns the Informix SQL fieldproperties of every field in the query as an associative array. Properties are encoded as: "SQLTYPE;length;precision;scale;ISNULLABLE" where SQLTYPE = the Informix type like "SQLVCHAR" etc. and ISNULLABLE = "Y" or "N".

例子 1. Informix SQL fieldproperties

$properties = ifx_fieldproperties ($resultid);
if (! isset($properties)) {
  ... error ...
}
for ($i = 0; $i < count($properties); $i++) {
    $fname = key ($properties);
    printf ("%s:\t type =  %s\n", $fname, $properties[$fname]);
    next ($properties);
}

后退 | 起点 | 前进
ifx_fetch_row | 上一级 | ifx_fieldtypes


ifx_fieldtypes

(PHP 3>= 3.0.3, PHP 4 )

ifx_fieldtypes -- List of Informix SQL fields

Description

array ifx_fieldtypes ( int result_id)

Returns an associative array with fieldnames as key and the SQL fieldtypes as data for query with result_id. Returns FALSE on error.

例子 1. Fieldnames and SQL fieldtypes

$types = ifx_fieldtypes ($resultid);
if (! isset ($types)) {
  ... error ...
}
for ($i = 0; $i < count($types); $i++) {
    $fname = key($types);
    printf("%s :\t type =  %s\n", $fname, $types[$fname]);
    next($types);
}

后退 | 起点 | 前进
ifx_fieldproperties | 上一级 | ifx_free_blob


ifx_free_blob

(PHP 3>= 3.0.4, PHP 4 )

ifx_free_blob -- Deletes the blob object

Description

int ifx_free_blob ( int bid)

Deletes the blobobject for the given blob object-id bid. Returns FALSE on error otherwise TRUE.

后退 | 起点 | 前进
ifx_fieldtypes | 上一级 | ifx_free_char


ifx_free_char

(PHP 3>= 3.0.6, PHP 4 )

ifx_free_char -- Deletes the char object

Description

int ifx_free_char ( int bid)

Deletes the charobject for the given char object-id bid. Returns FALSE on error otherwise TRUE.

后退 | 起点 | 前进
ifx_free_blob | 上一级 | ifx_free_result


ifx_free_result

(PHP 3>= 3.0.3, PHP 4 )

ifx_free_result -- Releases resources for the query

Description

int ifx_free_result ( int result_id)

Releases resources for the query associated with result_id. Returns FALSE on error.

后退 | 起点 | 前进
ifx_free_char | 上一级 | ifx_get_blob


ifx_get_blob

(PHP 3>= 3.0.4, PHP 4 )

ifx_get_blob -- Return the content of a blob object

Description

int ifx_get_blob ( int bid)

Returns the content of the blob object for the given blob object-id bid.

后退 | 起点 | 前进
ifx_free_result | 上一级 | ifx_get_char


ifx_get_char

(PHP 3>= 3.0.6, PHP 4 )

ifx_get_char -- Return the content of the char object

Description

int ifx_get_char ( int bid)

Returns the content of the char object for the given char object-id bid.

后退 | 起点 | 前进
ifx_get_blob | 上一级 | ifx_getsqlca


ifx_getsqlca

(PHP 3>= 3.0.8, PHP 4 )

ifx_getsqlca -- Get the contents of sqlca.sqlerrd[0..5] after a query

Description

array ifx_getsqlca ( int result_id)

result_id is a valid result id returned by ifx_query() or ifx_prepare().

Returns a pseudo-row (associative array) with sqlca.sqlerrd[0] ... sqlca.sqlerrd[5] after the query associated with result_id.

For inserts, updates and deletes the values returned are those as set by the server after executing the query. This gives access to the number of affected rows and the serial insert value. For SELECTs the values are those saved after the PREPARE statement. This gives access to the *estimated* number of affected rows. The use of this function saves the overhead of executing a "select dbinfo('sqlca.sqlerrdx')" query, as it retrieves the values that were saved by the ifx driver at the appropriate moment.

例子 1. Retrieve Informix sqlca.sqlerrd[x] values

/* assume the first column of 'sometable' is a serial */
$qid = ifx_query("insert into sometable
                  values (0, '2nd column', 'another column') ", $connid);
if (! $qid) {
    ... error ...
}
$sqlca = ifx_getsqlca ($qid);
$serial_value = $sqlca["sqlerrd1"];
echo "The serial value of the inserted row is : " . $serial_value<br>\n";

后退 | 起点 | 前进
ifx_get_char | 上一级 | ifx_htmltbl_result


ifx_htmltbl_result

(PHP 3>= 3.0.3, PHP 4 )

ifx_htmltbl_result -- Formats all rows of a query into a HTML table

Description

int ifx_htmltbl_result ( int result_id [, string html_table_options])

Returns the number of rows fetched or FALSE on error.

Formats all rows of the result_id query into a html table. The optional second argument is a string of <table> tag options

例子 1. Informix results as HTML table

$rid = ifx_prepare ("select * from emp where name like " . $name,
                     $connid, IFX_SCROLL);
if (! $rid) {
   ... error ...
}
$rowcount = ifx_affected_rows ($rid);
if ($rowcount > 1000) {
    printf ("Too many rows in result set (%d)\n<br>", $rowcount);
    die ("Please restrict your query<br>\n");
}
if (! ifx_do($rid) {
  ... error ...
}

ifx_htmltbl_result ($rid, "border=\"2\"");

ifx_free_result($rid);

后退 | 起点 | 前进
ifx_getsqlca | 上一级 | ifx_nullformat


ifx_nullformat

(PHP 3>= 3.0.4, PHP 4 )

ifx_nullformat -- Sets the default return value on a fetch row

Description

void ifx_nullformat ( int mode)

Sets the default return value of a NULL-value on a fetch row. Mode "0" returns "", and mode "1" returns "NULL".

后退 | 起点 | 前进
ifx_htmltbl_result | 上一级 | ifx_num_fields


ifx_num_fields

(PHP 3>= 3.0.3, PHP 4 )

ifx_num_fields -- Returns the number of columns in the query

Description

int ifx_num_fields ( int result_id)

Returns the number of columns in query for result_id or FALSE on error

After preparing or executing a query, this call gives you the number of columns in the query.

后退 | 起点 | 前进
ifx_nullformat | 上一级 | ifx_num_rows


ifx_num_rows

(PHP 3>= 3.0.3, PHP 4 )

ifx_num_rows -- Count the rows already fetched from a query

Description

int ifx_num_rows ( int result_id)

Gives the number of rows fetched so far for a query with result_id after a ifx_query() or ifx_do() query.

后退 | 起点 | 前进
ifx_num_fields | 上一级 | ifx_pconnect


ifx_pconnect

(PHP 3>= 3.0.3, PHP 4 )

ifx_pconnect -- Open persistent Informix connection

Description

int ifx_pconnect ( [string database [, string userid [, string password]]])

Returns: A positive Informix persistent link identifier on success, or FALSE on error

ifx_pconnect() acts very much like ifx_connect() with two major differences.

This function behaves exactly like ifx_connect() when PHP is not running as an Apache module. First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ifx_close() will not close links established by ifx_pconnect()).

This type of links is therefore called 'persistent'.

See also: ifx_connect().

后退 | 起点 | 前进
ifx_num_rows | 上一级 | ifx_prepare


ifx_prepare

(PHP 3>= 3.0.4, PHP 4 )

ifx_prepare -- Prepare an SQL-statement for execution

Description

int ifx_prepare ( string query, int conn_id [, int cursor_def, mixed blobidarray])

Returns a integer result_id for use by ifx_do(). Sets affected_rows for retrieval by the ifx_affected_rows() function.

Prepares query on connection conn_id. For "select-type" queries a cursor is declared and opened. The optional cursor_type parameter allows you to make this a "scroll" and/or "hold" cursor. It's a bitmask and can be either IFX_SCROLL, IFX_HOLD, or both or'ed together.

For either query type the estimated number of affected rows is saved for retrieval by ifx_affected_rows().

If you have BLOB (BYTE or TEXT) columns in the query, you can add a blobidarray parameter containing the corresponding "blob ids", and you should replace those columns with a "?" in the query text.

If the contents of the TEXT (or BYTE) column allow it, you can also use "ifx_textasvarchar(1)" and "ifx_byteasvarchar(1)". This allows you to treat TEXT (or BYTE) columns just as if they were ordinary (but long) VARCHAR columns for select queries, and you don't need to bother with blob id's.

With ifx_textasvarchar(0) or ifx_byteasvarchar(0) (the default situation), select queries will return BLOB columns as blob id's (integer value). You can get the value of the blob as a string or file with the blob functions (see below).

See also: ifx_do().

后退 | 起点 | 前进
ifx_pconnect | 上一级 | ifx_query


ifx_query

(PHP 3>= 3.0.3, PHP 4 )

ifx_query -- Send Informix query

Description

int ifx_query ( string query, int link_identifier [, int cursor_type [, mixed blobidarray]])

Returns: A positive Informix result identifier on success, or FALSE on error.

A "result_id" resource used by other functions to retrieve the query results. Sets "affected_rows" for retrieval by the ifx_affected_rows() function.

ifx_query() sends a query to the currently active database on the server that's associated with the specified link identifier.

Executes query on connection conn_id. For "select-type" queries a cursor is declared and opened. The optional cursor_type parameter allows you to make this a "scroll" and/or "hold" cursor. It's a bitmask and can be either IFX_SCROLL, IFX_HOLD, or both or'ed together. Non-select queries are "execute immediate". IFX_SCROLL and IFX_HOLD are symbolic constants and as such shouldn't be between quotes. I you omit this parameter the cursor is a normal sequential cursor.

For either query type the number of (estimated or real) affected rows is saved for retrieval by ifx_affected_rows().

If you have BLOB (BYTE or TEXT) columns in an update query, you can add a blobidarray parameter containing the corresponding "blob ids", and you should replace those columns with a "?" in the query text.

If the contents of the TEXT (or BYTE) column allow it, you can also use "ifx_textasvarchar(1)" and "ifx_byteasvarchar(1)". This allows you to treat TEXT (or BYTE) columns just as if they were ordinary (but long) VARCHAR columns for select queries, and you don't need to bother with blob id's.

With ifx_textasvarchar(0) or ifx_byteasvarchar(0) (the default situation), select queries will return BLOB columns as blob id's (integer value). You can get the value of the blob as a string or file with the blob functions (see below).

See also: ifx_connect().

例子 1. Show all rows of the "orders" table as a html table

ifx_textasvarchar(1);      // use "text mode" for blobs
$res_id = ifx_query("select * from orders", $conn_id);
if (! $res_id) {
    printf("Can't select orders : %s\n<br>%s<br>\n", ifx_error());
    ifx_errormsg();
    die;
}
ifx_htmltbl_result($res_id, "border=\"1\"");
ifx_free_result($res_id);

例子 2. Insert some values into the "catalog" table

// create blob id's for a byte and text column
$textid = ifx_create_blob(0, 0, "Text column in memory");
$byteid = ifx_create_blob(1, 0, "Byte column in memory");
                      // store blob id's in a blobid array
$blobidarray[] = $textid;
$blobidarray[] = $byteid;
                      // launch query
$query = "insert into catalog (stock_num, manu_code, " .
         "cat_descr,cat_picture) values(1,'HRO',?,?)";
$res_id = ifx_query($query, $conn_id, $blobidarray);
if (! $res_id) {
  ... error ...
}
                     // free result id
ifx_free_result($res_id);

后退 | 起点 | 前进
ifx_prepare | 上一级 | ifx_textasvarchar


ifx_textasvarchar

(PHP 3>= 3.0.4, PHP 4 )

ifx_textasvarchar -- Set the default text mode

Description

void ifx_textasvarchar ( int mode)

Sets the default text mode for all select-queries. Mode "0" will return a blob id, and mode "1" will return a varchar with text content.

后退 | 起点 | 前进
ifx_query | 上一级 | ifx_update_blob


ifx_update_blob

(PHP 3>= 3.0.4, PHP 4 )

ifx_update_blob -- Updates the content of the blob object

Description

ifx_update_blob ( int bid, string content)

Updates the content of the blob object for the given blob object bid. content is a string with new data. Returns FALSE on error otherwise TRUE.

后退 | 起点 | 前进
ifx_textasvarchar | 上一级 | ifx_update_char


ifx_update_char

(PHP 3>= 3.0.6, PHP 4 )

ifx_update_char -- Updates the content of the char object

Description

int ifx_update_char ( int bid, string content)

Updates the content of the char object for the given char object bid. content is a string with new data. Returns FALSE on error otherwise TRUE.

后退 | 起点 | 前进
ifx_update_blob | 上一级 | ifxus_close_slob


ifxus_close_slob

(PHP 3>= 3.0.4, PHP 4 )

ifxus_close_slob -- Deletes the slob object

Description

int ifxus_close_slob ( int bid)

Deletes the slob object on the given slob object-id bid. Return FALSE on error otherwise TRUE.

后退 | 起点 | 前进
ifx_update_char | 上一级 | ifxus_create_slob


ifxus_create_slob

(PHP 3>= 3.0.4, PHP 4 )

ifxus_create_slob -- Creates an slob object and opens it

Description

int ifxus_create_slob ( int mode)

Creates an slob object and opens it. Modes: 1 = LO_RDONLY, 2 = LO_WRONLY, 4 = LO_APPEND, 8 = LO_RDWR, 16 = LO_BUFFER, 32 = LO_NOBUFFER -> or-mask. You can also use constants named IFX_LO_RDONLY, IFX_LO_WRONLY etc. Return FALSE on error otherwise the new slob object-id.

后退 | 起点 | 前进
ifxus_close_slob | 上一级 | ifxus_free_slob


ifxus_free_slob

(PHP 3>= 3.0.4, PHP 4 )

ifxus_free_slob -- Deletes the slob object

Description

int ifxus_free_slob ( int bid)

Deletes the slob object. bid is the Id of the slob object. Returns FALSE on error otherwise TRUE.

后退 | 起点 | 前进
ifxus_create_slob | 上一级 | ifxus_open_slob


ifxus_open_slob

(PHP 3>= 3.0.4, PHP 4 )

ifxus_open_slob -- Opens an slob object

Description

int ifxus_open_slob ( long bid, int mode)

Opens an slob object. bid should be an existing slob id. Modes: 1 = LO_RDONLY, 2 = LO_WRONLY, 4 = LO_APPEND, 8 = LO_RDWR, 16 = LO_BUFFER, 32 = LO_NOBUFFER -> or-mask. Returns FALSE on error otherwise the new slob object-id.

后退 | 起点 | 前进
ifxus_free_slob | 上一级 | ifxus_read_slob


ifxus_read_slob

(PHP 3>= 3.0.4, PHP 4 )

ifxus_read_slob -- Reads nbytes of the slob object

Description

int ifxus_read_slob ( long bid, long nbytes)

Reads nbytes of the slob object. bid is a existing slob id and nbytes is the number of bytes read. Return FALSE on error otherwise the string.

后退 | 起点 | 前进
ifxus_open_slob | 上一级 | ifxus_seek_slob


ifxus_seek_slob

(PHP 3>= 3.0.4, PHP 4 )

ifxus_seek_slob -- Sets the current file or seek position

Description

int ifxus_seek_slob ( long bid, int mode, long offset)

Sets the current file or seek position of an open slob object. bid should be an existing slob id. Modes: 0 = LO_SEEK_SET, 1 = LO_SEEK_CUR, 2 = LO_SEEK_END and offset is an byte offset. Return FALSE on error otherwise the seek position.

后退 | 起点 | 前进
ifxus_read_slob | 上一级 | ifxus_tell_slob


ifxus_tell_slob

(PHP 3>= 3.0.4, PHP 4 )

ifxus_tell_slob -- Returns the current file or seek position

Description

int ifxus_tell_slob ( long bid)

Returns the current file or seek position of an open slob object bid should be an existing slob id. Return FALSE on error otherwise the seek position.

后退 | 起点 | 前进
ifxus_seek_slob | 上一级 | ifxus_write_slob


ifxus_write_slob

(PHP 3>= 3.0.4, PHP 4 )

ifxus_write_slob -- Writes a string into the slob object

Description

int ifxus_write_slob ( long bid, string content)

Writes a string into the slob object. bid is a existing slob id and content the content to write. Return FALSE on error otherwise bytes written.

后退 | 起点 | 前进
ifxus_tell_slob | 上一级 | InterBase functions


InterBase functions

PHP 手册
后退 前进

XLIV. InterBase functions

介绍

InterBase is a popular database put out by Borland/Inprise. More information about InterBase is available at http://www.interbase.com/. Oh, by the way, InterBase just joined the open source movement!

注: Full support for InterBase 6 was added in PHP 4.0.

This database uses a single quote (') character for escaping, a behavior similar to the Sybase database, add to your php.ini the following directive:

magic_quotes_sybase = On

需求

安装

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. InterBase configuration options

Name | Default | Changeable
ibase.allow_persistent | "1" | PHP_INI_SYSTEM
ibase.max_persistent | "-1" | PHP_INI_SYSTEM
ibase.max_links | "-1" | PHP_INI_SYSTEM
ibase.default_user | NULL | PHP_INI_ALL
ibase.default_password | NULL | PHP_INI_ALL
ibase.timestampformat | "%m/%d/%Y%H:%M:%S" | PHP_INI_ALL
ibase.dateformat | "%m/%d/%Y" | PHP_INI_ALL
ibase.timeformat | "%H:%M:%S" | PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

资源类型

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

IBASE_DEFAULT (integer)

IBASE_TEXT (integer)

IBASE_UNIXTIME (integer)

IBASE_READ (integer)

IBASE_COMMITTED (integer)

IBASE_CONSISTENCY (integer)

IBASE_NOWAIT (integer)

IBASE_TIMESTAMP (integer)

IBASE_DATE (integer)

IBASE_TIME (integer)

目录
ibase_blob_add — Add data into created blob
ibase_blob_cancel — Cancel creating blob
ibase_blob_close — Close blob
ibase_blob_create — Create blob for adding data
ibase_blob_echo — Output blob contents to browser
ibase_blob_get — Get len bytes data from open blob
ibase_blob_import — Create blob, copy file in it, and close it
ibase_blob_info — Return blob length and other useful info
ibase_blob_open — Open blob for retrieving data parts
ibase_close — Close a connection to an InterBase database
ibase_commit — Commit a transaction
ibase_connect — Open a connection to an InterBase database
ibase_errmsg — Returns error messages
ibase_execute — Execute a previously prepared query
ibase_fetch_object — Get an object from a InterBase database
ibase_fetch_row — Fetch a row from an InterBase database
ibase_field_info — Get information about a field
ibase_free_query — Free memory allocated by a prepared query
ibase_free_result — Free a result set
ibase_num_fields — Get the number of fields in a result set
ibase_pconnect — Creates an persistent connection to an InterBase database
ibase_prepare — Prepare a query for later binding of parameter placeholders and execution
ibase_query — Execute a query on an InterBase database
ibase_rollback — Rolls back a transaction
ibase_timefmt — Sets the format of timestamp, date and time type columns returned from queries
ibase_trans — Begin a transaction

后退 | 起点 | 前进
ifxus_write_slob | 上一级 | ibase_blob_add


ibase_blob_add

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_add -- Add data into created blob

Description

int ibase_blob_add ( int blob_id, string data)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
InterBase functions | 上一级 | ibase_blob_cancel


ibase_blob_cancel

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_cancel -- Cancel creating blob

Description

int ibase_blob_cancel ( int blob_id)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ibase_blob_add | 上一级 | ibase_blob_close


ibase_blob_close

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_close -- Close blob

Description

int ibase_blob_close ( int blob_id)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ibase_blob_cancel | 上一级 | ibase_blob_create


ibase_blob_create

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_create -- Create blob for adding data

Description

int ibase_blob_create ( [int link_identifier])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ibase_blob_close | 上一级 | ibase_blob_echo


ibase_blob_echo

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_echo -- Output blob contents to browser

Description

int ibase_blob_echo ( string blob_id_str)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ibase_blob_create | 上一级 | ibase_blob_get


ibase_blob_get

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_get -- Get len bytes data from open blob

Description

string ibase_blob_get ( int blob_id, int len)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ibase_blob_echo | 上一级 | ibase_blob_import


ibase_blob_import

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_import -- Create blob, copy file in it, and close it

Description

string ibase_blob_import ( [int link_identifier, int file_id])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ibase_blob_get | 上一级 | ibase_blob_info


ibase_blob_info

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_info -- Return blob length and other useful info

Description

object ibase_blob_info ( string blob_id_str)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ibase_blob_import | 上一级 | ibase_blob_open


ibase_blob_open

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_open -- Open blob for retrieving data parts

Description

int ibase_blob_open ( string blob_id)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ibase_blob_info | 上一级 | ibase_close


ibase_close

(PHP 3>= 3.0.6, PHP 4 )

ibase_close -- Close a connection to an InterBase database

Description

int ibase_close ( [int connection_id])

Closes the link to an InterBase database that's associated with a connection id returned from ibase_connect(). If the connection id is omitted, the last opened link is assumed. Default transaction on link is committed, other transactions are rolled back.

后退 | 起点 | 前进
ibase_blob_open | 上一级 | ibase_commit


ibase_commit

(PHP 3>= 3.0.7, PHP 4 )

ibase_commit -- Commit a transaction

Description

int ibase_commit ( [int link_identifier, int trans_number])

Commits transaction trans_number which was created with ibase_trans().

后退 | 起点 | 前进
ibase_close | 上一级 | ibase_connect


ibase_connect

(PHP 3>= 3.0.6, PHP 4 )

ibase_connect -- Open a connection to an InterBase database

Description

int ibase_connect ( string database [, string username [, string password [, string charset [, int buffers [, int dialect [, string role]]]]]])

Establishes a connection to an InterBase server. The database argument has to be a valid path to database file on the server it resides on. If the server is not local, it must be prefixed with either 'hostname:' (TCP/IP), '//hostname/' (NetBEUI) or 'hostname@' (IPX/SPX), depending on the connection protocol used. username and password can also be specified with PHP configuration directives ibase.default_user and ibase.default_password. charset is the default character set for a database. buffers is the number of database buffers to allocate for the server-side cache. If 0 or omitted, server chooses its own default. dialect selects the default SQL dialect for any statement executed within a connection, and it defaults to the highest one supported by client libraries.

In case a second call is made to ibase_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling ibase_close().

例子 1. ibase_connect() example

<?php
    $dbh = ibase_connect($host, $username, $password);
    $stmt = 'SELECT * FROM tblname';
    $sth = ibase_query($dbh, $stmt);
    while ($row = ibase_fetch_object($sth)) {
        echo $row->email, "\n";
    }
    ibase_free_result($sth);
    ibase_close($dbh);
?>

注: buffers was added in PHP 4.0RC2.

注: dialect was added in PHP 4.0RC2. It is functional only with InterBase 6 and versions higher than that.

注: role was added in PHP 4.0RC2. It is functional only with InterBase 5 and versions higher than that.

See also ibase_pconnect().

后退 | 起点 | 前进
ibase_commit | 上一级 | ibase_errmsg


ibase_errmsg

(PHP 3>= 3.0.7, PHP 4 )

ibase_errmsg -- Returns error messages

Description

string ibase_errmsg ( void)

Returns a string containing an error message.

后退 | 起点 | 前进
ibase_connect | 上一级 | ibase_execute


ibase_execute

(PHP 3>= 3.0.6, PHP 4 )

ibase_execute -- Execute a previously prepared query

Description

int ibase_execute ( int query [, int bind_args])

Execute a query prepared by ibase_prepare(). 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.

<?php
    $updates = array(
        1 => 'Eric',
        5 => 'Filip',
        7 => 'Larry'
    );

    $query = ibase_prepare("UPDATE FOO SET BAR = ? WHERE BAZ = ?");

    while (list($baz, $bar) = each($updates)) {
        ibase_execute($query, $bar, $baz);
    }
?>

后退 | 起点 | 前进
ibase_errmsg | 上一级 | ibase_fetch_object


ibase_fetch_object

(PHP 3>= 3.0.7, PHP 4 )

ibase_fetch_object -- Get an object from a InterBase database

Description

object ibase_fetch_object ( int result_id)

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)) {
        print $row->email . "\n";
    }
    ibase_close ($dbh);
?>

Subsequent call to ibase_fetch_object() would return the next row in the result set, or FALSE if there are no more rows.

See also ibase_fetch_row().

后退 | 起点 | 前进
ibase_execute | 上一级 | ibase_fetch_row


ibase_fetch_row

(PHP 3>= 3.0.6, PHP 4 )

ibase_fetch_row -- Fetch a row from an InterBase database

Description

array ibase_fetch_row ( int result_identifier)

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 call to ibase_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

后退 | 起点 | 前进
ibase_fetch_object | 上一级 | ibase_field_info


ibase_field_info

(PHP 3>= 3.0.7, PHP 4 )

ibase_field_info -- Get information about a field

Description

array ibase_field_info ( int result, int field number)

Returns an array with information about a field after a select query has been run. The array is in the form of name, alias, relation, length, type.

$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";
    }

后退 | 起点 | 前进
ibase_fetch_row | 上一级 | ibase_free_query


ibase_free_query

(PHP 3>= 3.0.6, PHP 4 )

ibase_free_query -- Free memory allocated by a prepared query

Description

int ibase_free_query ( int query)

Free a query prepared by ibase_prepare().

后退 | 起点 | 前进
ibase_field_info | 上一级 | ibase_free_result


ibase_free_result

(PHP 3>= 3.0.6, PHP 4 )

ibase_free_result -- Free a result set

Description

int ibase_free_result ( int result_identifier)

Free's a result set the has been created by ibase_query().

后退 | 起点 | 前进
ibase_free_query | 上一级 | ibase_num_fields


ibase_num_fields

(PHP 3>= 3.0.7, PHP 4 )

ibase_num_fields -- Get the number of fields in a result set

Description

int ibase_num_fields ( int result_id)

Returns an integer containing the number of fields in a result set.

<?php
       $dbh = ibase_connect ($host, $username, $password);
       $stmt = 'SELECT * FROM tblname';
       $sth = ibase_query ($dbh, $stmt);

       if (ibase_num_fields($sth) > 0) {
       while ($row = ibase_fetch_object ($sth)) {
       print $row->email . "\n";
       }
       } else {
       die ("No Results were found for your query");
       }

       ibase_close ($dbh);
       ?>

See also: ibase_field_info().

后退 | 起点 | 前进
ibase_free_result | 上一级 | ibase_pconnect


ibase_pconnect

(PHP 3>= 3.0.6, PHP 4 )

ibase_pconnect -- Creates an persistent connection to an InterBase database

Description

int ibase_pconnect ( string database [, string username [, string password [, string charset [, int buffers [, int dialect [, string role]]]]]])

ibase_pconnect() acts very much like ibase_connect() with two major differences. First, when connecting, the function will first try to find a (persistent) link that's already opened with the same parameters. If one is found, an identifier for it will be returned instead of opening a new connection. Second, the connection to the InterBase server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ibase_close() will not close links established by ibase_pconnect()). This type of link is therefore called 'persistent'.

注: buffers was added in PHP4-RC2.

注: dialect was added in PHP4-RC2. It is functional only with InterBase 6 and versions higher than that.

注: role was added in PHP4-RC2. It is functional only with InterBase 5 and versions higher than that.

See also ibase_connect() for the meaning of parameters passed to this function. They are exactly the same.

后退 | 起点 | 前进
ibase_num_fields | 上一级 | ibase_prepare


ibase_prepare

(PHP 3>= 3.0.6, PHP 4 )

ibase_prepare -- Prepare a query for later binding of parameter placeholders and execution

Description

int ibase_prepare ( [int link_identifier, string query])

Prepare a query for later binding of parameter placeholders and execution (via ibase_execute()).

后退 | 起点 | 前进
ibase_pconnect | 上一级 | ibase_query


ibase_query

(PHP 3>= 3.0.6, PHP 4 )

ibase_query -- Execute a query on an InterBase database

Description

int ibase_query ( [int link_identifier, string query [, int bind_args]])

Performs a query on an InterBase database. If the query is not successful, returns FALSE. If it is successful and there are resulting rows (such as with a SELECT query), returns a result identifier. If the query was successful and there were no results, returns TRUE. Returns FALSE if the query fails.

See also ibase_errmsg(),
ibase_fetch_row(),
ibase_fetch_object(), and
ibase_free_result().

后退 | 起点 | 前进
ibase_prepare | 上一级 | ibase_rollback


ibase_rollback

(PHP 3>= 3.0.7, PHP 4 )

ibase_rollback -- Rolls back a transaction

Description

int ibase_rollback ( [int link_identifier, int trans_number])

Rolls back transaction trans_number which was created with ibase_trans().

后退 | 起点 | 前进
ibase_query | 上一级 | ibase_timefmt


ibase_timefmt

(PHP 3>= 3.0.6, PHP 4 )

ibase_timefmt -- Sets the format of timestamp, date and time type columns returned from queries

Description

int ibase_timefmt ( string format [, int columntype])

Sets the format of timestamp, date or time type columns returned from queries. Internally, the columns are formatted by c-function strftime(), so refer to it's 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 also set defaults for these formats with PHP configuration directives ibase.timestampformat, ibase.dateformat and ibase.timeformat.

注: columntype was added in PHP 4.0. It has any meaning only with InterBase version 6 and higher.

注: A backwards incompatible change happened in PHP 4.0 when PHP configuration directive ibase.timeformat was renamed to ibase.timestampformat and directives ibase.dateformat and ibase.timeformat were added, so that the names would match better their functionality.

后退 | 起点 | 前进
ibase_rollback | 上一级 | ibase_trans


ibase_trans

(PHP 3>= 3.0.7, PHP 4 )

ibase_trans -- Begin a transaction

Description

int ibase_trans ( [int trans_args [, int link_identifier]])

Begins a transaction.

后退 | 起点 | 前进
ibase_timefmt | 上一级 | Ingres II functions


Ingres II functions

PHP 手册
后退 前进

XLV. Ingres II functions

介绍

These functions allow you to access Ingres II database servers.

注: If you already used PHP extensions to access other database servers, note that Ingres doesn't allow concurrent queries and/or transaction over one connection, thus you won't find any result or transaction handle in this extension. The result of a query must be treated before sending another query, and a transaction must be commited or rolled back before opening another transaction (which is automaticaly done when sending the first query).

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

需求

To compile PHP with Ingres support, you need the Open API library and header files included with Ingres II.

安装

In order to have these functions available, you must compile php with Ingres support by using the --with-ingres option. If the II_SYSTEM environment variable isn't correctly set you may have to use --with-ingres=DIR to specify your Ingres installation directory.

When using this extension with Apache, if Apache does not start and complains with "PHP Fatal error: Unable to start ingres_ii module in Unknown on line 0" then make sure the environement variable II_SYSTEM is correctly set. Adding "export II_SYSTEM="/home/ingres/II" in the script that starts Apache, just before launching httpd, should be fine.

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. Ingres II configuration options

Name | Default | Changeable
ingres.allow_persistent | "1" | PHP_INI_SYSTEM
ingres.max_persistent | "-1" | PHP_INI_SYSTEM
ingres.max_links | "-1" | PHP_INI_SYSTEM
ingres.default_database | NULL | PHP_INI_ALL
ingres.default_user | NULL | PHP_INI_ALL
ingres.default_password | NULL | PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

资源类型

该扩展模块未定义任何资源类型。

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

INGRES_ASSOC (integer)

INGRES_NUM (integer)

INGRES_BOTH (integer)

目录
ingres_autocommit — Switch autocommit on or off
ingres_close — Close an Ingres II database connection
ingres_commit — Commit a transaction
ingres_connect — Open a connection to an Ingres II database
ingres_fetch_array — Fetch a row of result into an array
ingres_fetch_object — Fetch a row of result into an object.
ingres_fetch_row — Fetch a row of result into an enumerated array
ingres_field_length — Get the length of a field
ingres_field_name — Get the name of a field in a query result.
ingres_field_nullable — Test if a field is nullable
ingres_field_precision — Get the precision of a field
ingres_field_scale — Get the scale of a field
ingres_field_type — Get the type of a field in a query result
ingres_num_fields — Get the number of fields returned by the last query
ingres_num_rows — Get the number of rows affected or returned by the last query
ingres_pconnect — Open a persistent connection to an Ingres II database
ingres_query — Send a SQL query to Ingres II
ingres_rollback — Roll back a transaction

后退 | 起点 | 前进
ibase_trans | 上一级 | ingres_autocommit


ingres_autocommit

(PHP 4 >= 4.0.2)

ingres_autocommit -- Switch autocommit on or off

Description

bool ingres_autocommit ( [resource link])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ingres_autocommit() is called before opening a transaction (before the first call to ingres_query() or just after a call to ingres_rollback() or ingres_commit()) to switch the "autocommit" mode of the server on or off (when the script begins the autocommit mode is off).

When the autocommit mode is on, every query is automaticaly commited by the server, as if ingres_commit() was called after every call to ingres_query().

See also
ingres_query(),
ingres_rollback(), and
ingres_commit().

后退 | 起点 | 前进
Ingres II functions | 上一级 | ingres_close


ingres_close

(PHP 4 >= 4.0.2)

ingres_close -- Close an Ingres II database connection

Description

bool ingres_close ( [resource link])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Returns TRUE on success, or FALSE on failure.

ingres_close() closes the connection to the Ingres server that's associated with the specified link. If the link parameter isn't specified, the last opened link is used.

ingres_close() isn't usually necessary, as it won't close persistent connections and all non-persistent connections are automatically closed at the end of the script.

See also ingres_connect() and ingres_pconnect().

后退 | 起点 | 前进
ingres_autocommit | 上一级 | ingres_commit


ingres_commit

(PHP 4 >= 4.0.2)

ingres_commit -- Commit a transaction

Description

bool ingres_commit ( [resource link])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ingres_commit() commits the currently open transaction, making all changes made to the database permanent.

This closes the transaction. A new one can be open by sending a query with ingres_query().

You can also have the server commit automaticaly after every query by calling ingres_autocommit() before opening the transaction.

See also
ingres_query(),
ingres_rollback(), and
ingres_autocommit().

后退 | 起点 | 前进
ingres_close | 上一级 | ingres_connect


ingres_connect

(PHP 4 >= 4.0.2)

ingres_connect -- Open a connection to an Ingres II database

Description

resource ingres_connect ( [string database [, string username [, string password]]])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Returns a Ingres II link resource on success, or FALSE on failure.

ingres_connect() opens a connection with the Ingres database designated by database, which follows the syntax [node_id::]dbname[/svr_class].

If some parameters are missing, ingres_connect() uses the values in php.ini for ingres.default_database, ingres.default_user, and ingres.default_password.

The connection is closed when the script ends or when ingres_close() is called on this link.

All the other ingres functions use the last opened link as a default, so you need to store the returned value only if you use more than one link at a time.

例子 1. ingres_connect() example

<?php
    $link = ingres_connect ("mydb", "user", "pass")
        or die ("Could not connect");
    print ("Connected successfully");
    ingres_close ($link);
?>

例子 2. ingres_connect() example using default link

<?php
    ingres_connect ("mydb", "user", "pass")
        or die ("Could not connect");
    print ("Connected successfully");
    ingres_close ();
?>

See also ingres_pconnect() and ingres_close().

后退 | 起点 | 前进
ingres_commit | 上一级 | ingres_fetch_array


ingres_fetch_array

(PHP 4 >= 4.0.2)

ingres_fetch_array -- Fetch a row of result into an array

Description

array ingres_fetch_array ( [int result_type [, resource link]])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ingres_fetch_array() Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

This function is an extended version of ingres_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

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 must use the numeric index of the column or make an alias for the column.

ingres_query(select t1.f1 as foo t2.f1 as bar from t1, t2);
$result = ingres_fetch_array();
$foo = $result["foo"];
$bar = $result["bar"];

result_type can be INGRES_NUM for enumerated array, INGRES_ASSOC for associative array, or INGRES_BOTH (default).

Speed-wise, the function is identical to ingres_fetch_object(), and almost as quick as ingres_fetch_row() (the difference is insignificant).

例子 1. ingres_fetch_array() example

<?php
ingres_connect ($database, $user, $password);

ingres_query ("select * from table");
while ($row = ingres_fetch_array()) {
    echo $row["user_id"];  # using associative array
    echo $row["fullname"];
    echo $row[1];          # using enumerated array
    echo $row[2];
}
?>

See also
ingres_query(),
ingres_num_fields(),
ingres_field_name(),
ingres_fetch_object(), and
ingres_fetch_row().

后退 | 起点 | 前进
ingres_connect | 上一级 | ingres_fetch_object


ingres_fetch_object

(PHP 4 >= 4.0.2)

ingres_fetch_object -- Fetch a row of result into an object.

Description

object ingres_fetch_object ( [int result_type [, resource link]])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ingres_fetch_object() Returns an object that corresponds to the fetched row, or FALSE if there are no more rows.

This function is similar to ingres_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

The optional argument result_type is a constant and can take the following values: INGRES_ASSOC, INGRES_NUM, and INGRES_BOTH.

Speed-wise, the function is identical to ingres_fetch_array(), and almost as quick as ingres_fetch_row() (the difference is insignificant).

例子 1. ingres_fetch_object() example

<?php
ingres_connect ($database, $user, $password);
ingres_query ("select * from table");
while ($row = ingres_fetch_object()) {
    echo $row->user_id;
    echo $row->fullname;
}
?>

See also
ingres_query(),
ingres_num_fields(),
ingres_field_name(),
ingres_fetch_array(), and
ingres_fetch_row().

后退 | 起点 | 前进
ingres_fetch_array | 上一级 | ingres_fetch_row


ingres_fetch_row

(PHP 4 >= 4.0.2)

ingres_fetch_row -- Fetch a row of result into an enumerated array

Description

array ingres_fetch_row ( [resource link])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ingres_fetch_row() returns an array that corresponds to the fetched row, or FALSE if there are no more rows. Each result column is stored in an array offset, starting at offset 1.

Subsequent call to ingres_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

例子 1. ingres_fetch_row() example

<?php
ingres_connect ($database, $user, $password);

ingres_query ("select * from table");
while ($row = ingres_fetch_row()) {
    echo $row[1];
    echo $row[2];
}
?>

See also
ingres_num_fields(),
ingres_query(),
ingres_fetch_array(), and
ingres_fetch_object().

后退 | 起点 | 前进
ingres_fetch_object | 上一级 | ingres_field_length


ingres_field_length

(PHP 4 >= 4.0.2)

ingres_field_length -- Get the length of a field

Description

int ingres_field_length ( int index [, resource link])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ingres_field_length() returns the length of a field. This is the number of bytes used by the server to store the field. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also
ingres_query(),
ingres_fetch_array(),
ingres_fetch_object(), and
ingres_fetch_row().

后退 | 起点 | 前进
ingres_fetch_row | 上一级 | ingres_field_name


ingres_field_name

(PHP 4 >= 4.0.2)

ingres_field_name -- Get the name of a field in a query result.

Description

string ingres_field_name ( int index [, resource link])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ingres_field_name() returns the name of a field in a query result, or FALSE on failure.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also
ingres_query(),
ingres_fetch_array(),
ingres_fetch_object() and
ingres_fetch_row().

后退 | 起点 | 前进
ingres_field_length | 上一级 | ingres_field_nullable


ingres_field_nullable

(PHP 4 >= 4.0.2)

ingres_field_nullable -- Test if a field is nullable

Description

bool ingres_field_nullable ( int index [, resource link])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ingres_field_nullable() returns TRUE if the field can be set to the NULL value and FALSE if it can't.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also
ingres_query(),
ingres_fetch_array(),
ingres_fetch_object(), and
ingres_fetch_row().

后退 | 起点 | 前进
ingres_field_name | 上一级 | ingres_field_precision


ingres_field_precision

(PHP 4 >= 4.0.2)

ingres_field_precision -- Get the precision of a field

Description

int ingres_field_precision ( int index [, resource link])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ingres_field_precision() returns the precision of a field. This value is used only for decimal, float and money SQL data types. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also
ingres_query(),
ingres_fetch_array(),
ingres_fetch_object(), and
ingres_fetch_row().

后退 | 起点 | 前进
ingres_field_nullable | 上一级 | ingres_field_scale


ingres_field_scale

(PHP 4 >= 4.0.2)

ingres_field_scale -- Get the scale of a field

Description

int ingres_field_scale ( int index [, resource link])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ingres_field_scale() returns the scale of a field. This value is used only for the decimal SQL data type. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also
ingres_query(),
ingres_fetch_array(),
ingres_fetch_object(), and
ingres_fetch_row().

后退 | 起点 | 前进
ingres_field_precision | 上一级 | ingres_field_type


ingres_field_type

(PHP 4 >= 4.0.2)

ingres_field_type -- Get the type of a field in a query result

Description

string ingres_field_type ( int index [, resource link])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ingres_field_type() returns the type of a field in a query result, or FALSE on failure. Examples of types returned are "IIAPI_BYTE_TYPE", "IIAPI_CHA_TYPE", "IIAPI_DTE_TYPE", "IIAPI_FLT_TYPE", "IIAPI_INT_TYPE", "IIAPI_VCH_TYPE". Some of these types can map to more than one SQL type depending on the length of the field (see ingres_field_length()). For example "IIAPI_FLT_TYPE" can be a float4 or a float8. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also
ingres_query(),
ingres_fetch_array(),
ingres_fetch_object(), and
ingres_fetch_row().

后退 | 起点 | 前进
ingres_field_scale | 上一级 | ingres_num_fields


ingres_num_fields

(PHP 4 >= 4.0.2)

ingres_num_fields -- Get the number of fields returned by the last query

Description

int ingres_num_fields ( [resource link])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ingres_num_fields() returns the number of fields in the results returned by the Ingres server after a call to ingres_query()

See also
ingres_query(),
ingres_fetch_array(),
ingres_fetch_object(), and
ingres_fetch_row().

后退 | 起点 | 前进
ingres_field_type | 上一级 | ingres_num_rows


ingres_num_rows

(PHP 4 >= 4.0.2)

ingres_num_rows -- Get the number of rows affected or returned by the last query

Description

int ingres_num_rows ( [resource link])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

For delete, insert or update queries, ingres_num_rows() returns the number of rows affected by the query. For other queries, ingres_num_rows() returns the number of rows in the query's result.

注: This function is mainly meant to get the number of rows modified in the database. If this function is called before using ingres_fetch_array(), ingres_fetch_object() or ingres_fetch_row() the server will delete the result's data and the script won't be able to get them.

You should instead retrieve the result's data using one of these fetch functions in a loop until it returns FALSE, indicating that no more results are available.

See also
ingres_query(),
ingres_fetch_array(),
ingres_fetch_object(), and
ingres_fetch_row().

后退 | 起点 | 前进
ingres_num_fields | 上一级 | ingres_pconnect


ingres_pconnect

(PHP 4 >= 4.0.2)

ingres_pconnect -- Open a persistent connection to an Ingres II database

Description

resource ingres_pconnect ( [string database [, string username [, string password]]])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Returns a Ingres II link resource on success, or FALSE on failure.

See ingres_connect() for parameters details and examples. There are only 2 differences between ingres_pconnect() and ingres_connect() : 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 Ingres server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ingres_close() will not close links established by ingres_pconnect()). This type of link is therefore called 'persistent'.

See also ingres_connect() and ingres_close().

后退 | 起点 | 前进
ingres_num_rows | 上一级 | ingres_query


ingres_query

(PHP 4 >= 4.0.2)

ingres_query -- Send a SQL query to Ingres II

Description

bool ingres_query ( string query [, resource link])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Returns TRUE on success, or FALSE on failure.

ingres_query() sends the given query to the Ingres server. This query must be a valid SQL query (see the Ingres SQL reference guide)

The query becomes part of the currently open transaction. If there is no open transaction, ingres_query() opens a new transaction. To close the transaction, you can either call ingres_commit() to commit the changes made to the database or ingres_rollback() to cancel these changes. When the script ends, any open transaction is rolled back (by calling ingres_rollback()). You can also use ingres_autocommit() before opening a new transaction to have every SQL query immediatly commited.

Some types of SQL queries can't be sent with this function:

  • close (see ingres_close())

  • commit (see ingres_commit())

  • connect (see ingres_connect())

  • disconnect (see ingres_close())

  • get dbevent

  • prepare to commit

  • rollback (see ingres_rollback())

  • savepoint

  • set autocommit (see ingres_autocommit())

  • all cursor related queries are unsupported

例子 1. ingres_query() example

<?php
ingres_connect ($database, $user, $password);

ingres_query ("select * from table");
while ($row = ingres_fetch_row()) {
    echo $row[1];
    echo $row[2];
}
?>

See also
ingres_fetch_array(),
ingres_fetch_object(),
ingres_fetch_row(),
ingres_commit(),
ingres_rollback(), and
ingres_autocommit().

后退 | 起点 | 前进
ingres_pconnect | 上一级 | ingres_rollback


ingres_rollback

(PHP 4 >= 4.0.2)

ingres_rollback -- Roll back a transaction

Description

bool ingres_rollback ( [resource link])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ingres_rollback() rolls back the currently open transaction, actually canceling all changes made to the database during the transaction.

This closes the transaction. A new one can be open by sending a query with ingres_query().

See also
ingres_query(),
ingres_commit(), and
ingres_autocommit().

后退 | 起点 | 前进
ingres_query | 上一级 | IRC Gateway Functions


IRC Gateway Functions

PHP 手册
后退 前进

XLVI. IRC Gateway Functions

介绍

With ircg you can build powerful, fast and scalable webchat solutions in conjunction with dedicated or public IRC servers.

IRCG runs under tis platforms:

  • AIX

  • FreeBSD

  • HP-UX

  • Irix

  • Linux

  • Solaris

  • Tru64

需求

To install and use IRCG you need the following software:

  1. IRCG-Library from Sascha Schumann.

  2. SGI Static Threads Library

  3. thttpd webserver

安装

A detailed installation instruction can be found here.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

预定义常量

该扩展模块未定义任何常量。

目录
ircg_channel_mode — Set channel mode flags for user
ircg_disconnect — Close connection to server
ircg_fetch_error_msg — Returns the error from previous ircg operation
ircg_get_username — Get username for connection
ircg_html_encode — Encodes HTML preserving output
ircg_ignore_add — Add a user to your ignore list on a server
ircg_ignore_del — Remove a user from your ignore list on a server
ircg_is_conn_alive — Check connection status
ircg_join — Join a channel on a connected server
ircg_kick — Kick a user out of a channel on server
ircg_lookup_format_messages — Select a set of format strings for display of IRC messages
ircg_msg — Send message to channel or user on server
ircg_nick — Change nickname on server
ircg_nickname_escape — Encode special characters in nickname to be IRC-compliant
ircg_nickname_unescape — Decodes encoded nickname
ircg_notice — Send a notice to a user on server
ircg_part — Leave a channel on server
ircg_pconnect — Connect to an IRC server
ircg_register_format_messages — Register a set of format strings for display of IRC messages
ircg_set_current — Set current connection for output
ircg_set_file — Set logfile for connection
ircg_set_on_die — Set hostaction to be execute when connection dies
ircg_topic — Set topic for channel on server
ircg_whois — Query user information for nick on server

后退 | 起点 | 前进
ingres_rollback | 上一级 | ircg_channel_mode


ircg_channel_mode

(PHP 4 >= 4.0.5)

ircg_channel_mode -- Set channel mode flags for user

Description

boolean ircg_channel_mode ( resource connection, string channel, string mode_spec, string nick)

Set channel mode flags for channel on server connected to by connection. Mode flags are passed in mode_spec and are applied to the user specified by nick.

Mode flags are set or cleared by specifind a mode character and prepending it with a plus or minus character respectively. E.g. operator mode is granted by '+o' and revoked by '-o' passed as mode_spec.

后退 | 起点 | 前进
IRC Gateway Functions | 上一级 | ircg_disconnect


ircg_disconnect

(PHP 4 >= 4.0.4)

ircg_disconnect -- Close connection to server

Description

boolean ircg_disconnect ( resource connection, string reason)

ircg_disconnect() will close a connection to a server previously established with ircg-pconnect().

See also: ircg_pconnect().

后退 | 起点 | 前进
ircg_channel_mode | 上一级 | ircg_fetch_error_msg


ircg_fetch_error_msg

(PHP 4 >= 4.1.0)

ircg_fetch_error_msg -- Returns the error from previous ircg operation

Description

array ircg_fetch_error_msg ( resource connection)

ircg_fetch_error_msg() returns the error from the last called ircg function.

注: Errorcode is stored in first array element, errortext in second.

例子 1. ircg_fetch_error_msg() example

if (!ircg_join ($id, "#php")) {
    $error = ircg_fetch_error_msg($id);
    print ("Can't join channel #php. Errorcode:
            $error[0] Description: $error[1]");
}

后退 | 起点 | 前进
ircg_disconnect | 上一级 | ircg_get_username


ircg_get_username

(PHP 4 >= 4.1.0)

ircg_get_username -- Get username for connection

Description

string ircg_get_username ( resource connection)

Function ircg_get_username() returns the username for specified connection connection. Returns FALSE if connection died or is not valid.

后退 | 起点 | 前进
ircg_fetch_error_msg | 上一级 | ircg_html_encode


ircg_html_encode

(PHP 4 >= 4.0.5)

ircg_html_encode -- Encodes HTML preserving output

Description

boolean ircg_html_encode ( string html_string)

Encodes a HTML string html_string for output. This feature could be usable, e.g. if someone wants to discuss about an html problem.

后退 | 起点 | 前进
ircg_get_username | 上一级 | ircg_ignore_add


ircg_ignore_add

(PHP 4 >= 4.0.5)

ircg_ignore_add -- Add a user to your ignore list on a server

Description

boolean ircg_ignore_add ( resource connection, string nick)

This function will add user nick to your ignore list on the server connected to by connection. By doing so you will suppress all messages from this user from being send to you.

See also: ircg_ignore_del().

后退 | 起点 | 前进
ircg_html_encode | 上一级 | ircg_ignore_del


ircg_ignore_del

(PHP 4 >= 4.0.5)

ircg_ignore_del -- Remove a user from your ignore list on a server

Description

boolean ircg_ignore_del ( resource connection, string nick)

This function remove user nick from your ignore list on the server connected to by connection.

See also: ircg_ignore_add().

后退 | 起点 | 前进
ircg_ignore_add | 上一级 | ircg_is_conn_alive


ircg_is_conn_alive

(PHP 4 >= 4.0.5)

ircg_is_conn_alive -- Check connection status

Description

boolean ircg_is_conn_alive ( resource connection)

ircg_is_conn_alive() returns TRUE if connection is still alive and working or FALSE if the server no longer talks to us.

后退 | 起点 | 前进
ircg_ignore_del | 上一级 | ircg_join


ircg_join

(PHP 4 >= 4.0.4)

ircg_join -- Join a channel on a connected server

Description

boolean ircg_join ( resource connection, string channel)

Join the channel channel on the server connected to by connection.

后退 | 起点 | 前进
ircg_is_conn_alive | 上一级 | ircg_kick


ircg_kick

(PHP 4 >= 4.0.5)

ircg_kick -- Kick a user out of a channel on server

Description

boolean ircg_kick ( resource connection, string channel, string nick, string reason)

Kick user nick from channel on server connected to by connection. reason should give a short message describing why this action was performed.

后退 | 起点 | 前进
ircg_join | 上一级 | ircg_lookup_format_messages


ircg_lookup_format_messages

(PHP 4 >= 4.0.5)

ircg_lookup_format_messages -- Select a set of format strings for display of IRC messages

Description

boolean ircg_lookup_format_messages ( string name)

Select the set of format strings to use for display of IRC messages and events. Sets may be registered with ircg_register_format_messages(), a default set named ircg is always available.

See also: ircg_register_format_messages()

后退 | 起点 | 前进
ircg_kick | 上一级 | ircg_msg


ircg_msg

(PHP 4 >= 4.0.4)

ircg_msg -- Send message to channel or user on server

Description

boolean ircg_msg ( resource connection, string recipient, string message [, boolean suppress])

ircg_msg() will send the message to a channel or user on the server connected to by connection. A recipient starting with # or & will send the message to a channel, anything else will be interpreted as a username.

Setting the optional parameter suppress to a TRUE value will suppress output of your message to your own connection.

后退 | 起点 | 前进
ircg_lookup_format_messages | 上一级 | ircg_nick


ircg_nick

(PHP 4 >= 4.0.5)

ircg_nick -- Change nickname on server

Description

boolean ircg_nick ( resource connection, string nick)

Change your nickname on the given connection to the one given in nick if possible.

Will return TRUE on success and FALSE on failure.

后退 | 起点 | 前进
ircg_msg | 上一级 | ircg_nickname_escape


ircg_nickname_escape

(PHP 4 >= 4.0.6)

ircg_nickname_escape -- Encode special characters in nickname to be IRC-compliant

Description

string ircg_nickname_escape ( string nick)

Function ircg_nickname_escape() returns a decoded nickname specified by nick wich is IRC-compliant.

See also: ircg_nickname_unescape()

后退 | 起点 | 前进
ircg_nick | 上一级 | ircg_nickname_unescape


ircg_nickname_unescape

(PHP 4 >= 4.0.6)

ircg_nickname_unescape -- Decodes encoded nickname

Description

string ircg_nickname_unescape ( string nick)

Function ircg_nickname_unescape() returns a decoded nickname, which is specified in nick.

See also: ircg_nickname_escape()

后退 | 起点 | 前进
ircg_nickname_escape | 上一级 | ircg_notice


ircg_notice

(PHP 4 >= 4.0.5)

ircg_notice -- Send a notice to a user on server

Description

boolean ircg_notice ( resource connection, string , string message)

This function will send the message text to the user nick on the server connected to by connection. Query your IRC documentation of choice for the exact difference between a MSG and a NOTICE.

后退 | 起点 | 前进
ircg_nickname_unescape | 上一级 | ircg_part


ircg_part

(PHP 4 >= 4.0.4)

ircg_part -- Leave a channel on server

Description

boolean ircg_part ( resource connection, string channel)

Leave the channel channel on the server connected to by connection.

后退 | 起点 | 前进
ircg_notice | 上一级 | ircg_pconnect


ircg_pconnect

(PHP 4 >= 4.0.4)

ircg_pconnect -- Connect to an IRC server

Description

resource ircg_pconnect ( string username [, string server_ip [, int server_port [, string msg_format [, array ctcp_messages [, array user_settings]]]]])

ircg_pconnect() will try to establish a connection to an IRC server and return a connection resource handle for further use.

The only mandatory parameter is username, this will set your initial nickname on the server. server_ip and server_port are optional and default to 127.0.0.1 and 6667.

注: For now parameter server_ip will not do any hostname lookups and will only accept IP addresses in numerical form.

Currently ircg_pconnect() always returns a valid handle, even if the connection failed.

You can customize the output of IRC messages and events by selection a format string set previously created with ircg_register_format_messages() by specifing the sets name in msg_format.

ctcp_messages

user_settings

See also: ircg_disconnect(),
ircg_is_conn_alive(),
ircg_register_format_messages().

后退 | 起点 | 前进
ircg_part | 上一级 | ircg_register_format_messages


ircg_register_format_messages

(PHP 4 >= 4.0.5)

ircg_register_format_messages -- Register a set of format strings for display of IRC messages

Description

boolean ircg_register_format_messages ( string name, array messages)

With ircg_register_format_messages() you can customize the way your IRC output looks like. You can even register different format string sets and switch between them on the fly with ircg_lookup_format_messages().

  • Plain channel message

  • Private message received

  • Private message sent

  • Some user leaves channel

  • Some user enters channel

  • Some user was kicked from the channel

  • Topic has been changed

  • Error

  • Fatal error

  • Join list end(?)

  • Self part(?)

  • Some user changes his nick

  • Some user quits his connection

  • Mass join begin

  • Mass join element

  • Mass join end

  • Whois user

  • Whois server

  • Whois idle

  • Whois channel

  • Whois end

  • Voice status change on user

  • Operator status change on user

  • Banlist

  • Banlist end

  • %f - from

  • %t - to

  • %c - channel

  • %r - plain message

  • %m - encoded message

  • %j - js encoded message

  • 1 - mod encode

  • 2 - nickname decode

See also: ircg_lookup_format_messages().

后退 | 起点 | 前进
ircg_pconnect | 上一级 | ircg_set_current


ircg_set_current

(PHP 4 >= 4.0.4)

ircg_set_current -- Set current connection for output

Description

boolean ircg_set_current ( resource connection)

Select the current connection for output in this execution context. Every output sent from the server connected to by connection will be copied to standard output while using default formatting or a format string set specified by ircg_register_format_messages() and selected by ircg_lookup_format_messages().

See also: ircg_register_format_messages() and ircg_lookup_format_messages().

后退 | 起点 | 前进
ircg_register_format_messages | 上一级 | ircg_set_file


ircg_set_file

(PHP 4 >= 4.2.0)

ircg_set_file -- Set logfile for connection

Description

bool ircg_set_file ( resource connection, string path)

Function ircg_set_file() specifies a logfile path in which all output from connection connection will be logged. Returns TRUE on success, otherwise FALSE.

后退 | 起点 | 前进
ircg_set_current | 上一级 | ircg_set_on_die


ircg_set_on_die

(PHP 4 >= 4.2.0)

ircg_set_on_die -- Set hostaction to be execute when connection dies

Description

bool ircg_set_on_die ( resource connection, string host, int port, string data)

In case of the termination of connection connection IRCG will connect to host at port (Note: host must be an IPv4 address, IRCG does not resolve host-names due to blocking issues), send data to the new host connection and will wait until the remote part closes connection. This can be used to trigger a php script for example.

后退 | 起点 | 前进
ircg_set_file | 上一级 | ircg_topic


ircg_topic

(PHP 4 >= 4.0.5)

ircg_topic -- Set topic for channel on server

Description

boolean ircg_topic ( resource connection, string channel, string new_topic)

Change the topic for channel channel on the server connected to by connection to new_topic.

后退 | 起点 | 前进
ircg_set_on_die | 上一级 | ircg_whois


ircg_whois

(PHP 4 >= 4.0.5)

ircg_whois -- Query user information for nick on server

Description

boolean ircg_whois ( resource connection, string nick)

Sends a query to the connected server connection to send information for the specified user nick.

后退 | 起点 | 前进
ircg_topic | 上一级 | PHP / Java Integration


PHP / Java Integration

PHP 手册
后退 前进

XLVII. PHP / Java Integration

介绍

There are two possible ways to bridge PHP and Java: you can either integrate PHP into a Java Servlet environment, which is the more stable and efficient solution, or integrate Java support into PHP. The former is provided by a SAPI module that interfaces with the Servlet server, the latter by this Java extension.

The Java extension provides a simple and effective means for creating and invoking methods on Java objects from PHP. The JVM is created using JNI, and everything runs in-process.

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

需求

You need a Java VM installed on your machine to use this extension.

安装

Build instructions for this extension can be found in php4/ext/java/README.

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. Java configuration options

Name | Default | Changeable
java.class.path | NULL | PHP_INI_ALL
java.home | NULL | PHP_INI_ALL
java.library.path | NULL | PHP_INI_ALL
java.library | JAVALIB | PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

范例

例子 1. Java Example

<?php
  // get instance of Java class java.lang.System in PHP
  $system = new Java('java.lang.System');

  // demonstrate property access
  print 'Java version='.$system->getProperty('java.version').' <br>';
  print 'Java vendor=' .$system->getProperty('java.vendor').' <br>';
  print 'OS='.$system->getProperty('os.name').' '.
              $system->getProperty('os.version').' on '.
              $system->getProperty('os.arch').' <br>';

  // java.util.Date example
  $formatter = new Java('java.text.SimpleDateFormat',
                        "EEEE, MMMM dd, yyyy 'at' h:mm:ss a zzzz");

  print $formatter->format(new Java('java.util.Date'));
?>

例子 2. AWT Example

<?php
  // This example is only intented to be run as a CGI.

  $frame  = new Java('java.awt.Frame', 'PHP');
  $button = new Java('java.awt.Button', 'Hello Java World!');

  $frame->add('North', $button);
  $frame->validate();
  $frame->pack();
  $frame->visible = True;

  $thread = new Java('java.lang.Thread');
  $thread->sleep(10000);

  $frame->dispose();
?>
Notes:

  • new Java() will create an instance of a class if a suitable constructor is available. If no parameters are passed and the default constructor is useful as it provides access to classes like java.lang.System which expose most of their functionallity through static methods.

  • Accessing a member of an instance will first look for bean properties then public fields. In other words, print $date.time will first attempt to be resolved as $date.getTime(), then as $date.time.

  • Both static and instance members can be accessed on an object with the same syntax. Furthermore, if the java object is of type java.lang.Class, then static members of the class (fields and methods) can be accessed.

  • Exceptions raised result in PHP warnings, and NULL results. The warnings may be eliminated by prefixing the method call with an "@" sign. The following APIs may be used to retrieve and reset the last error:

    • java_last_exception_get()

    • java_last_exception_clear()

  • Overload resolution is in general a hard problem given the differences in types between the two languages. The PHP Java extension employs a simple, but fairly effective, metric for determining which overload is the best match.

    Additionally, method names in PHP are not case sensitive, potentially increasing the number of overloads to select from.

    Once a method is selected, the parameters are cooerced if necessary, possibly with a loss of data (example: double precision floating point numbers will be converted to boolean).

  • In the tradition of PHP, arrays and hashtables may pretty much be used interchangably. Note that hashtables in PHP may only be indexed by integers or strings; and that arrays of primitive types in Java can not be sparse. Also note that these constructs are passed by value, so may be expensive in terms of memory and time.

Java Servlet SAPI

The Java Servlet SAPI builds upon the mechanism defined by the Java extension to enable the entire PHP processor to be run as a servlet. The primary advanatage of this from a PHP perspective is that web servers which support servlets typically take great care in pooling and reusing JVMs. Build instructions for the Servlet SAPI module can be found in php4/sapi/README. Notes:

  • While this code is intended to be able to run on any servlet engine, it has only been tested on Apache's Jakarta/tomcat to date. Bug reports, success stories and/or patches required to get this code to run on other engines would be appreciated.

  • PHP has a habit of changing the working directory. sapi/servlet will eventually change it back, but while PHP is running the servlet engine may not be able to load any classes from the CLASSPATH which are specified using a relative directory syntax, or find the work directory used for administration and JSP compilation tasks.

目录
java_last_exception_clear — Clear last Java exception
java_last_exception_get — Get last Java exception

后退 | 起点 | 前进
ircg_whois | 上一级 | java_last_exception_clear


java_last_exception_clear

(PHP 4 >= 4.0.2)

java_last_exception_clear -- Clear last Java exception

Description

void java_last_exception_clear ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

See java_last_exception_get() for an example.

后退 | 起点 | 前进
PHP / Java Integration | 上一级 | java_last_exception_get


java_last_exception_get

(PHP 4 >= 4.0.2)

java_last_exception_get -- Get last Java exception

Description

exception java_last_exception_get ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

The following example demonstrates the usage of Java's exception handler from within PHP:

例子 1. Java exception handler

<?php
  $stack = new Java('java.util.Stack');
  $stack->push(1);

  // This should succeed
  $result = $stack->pop();
  $ex = java_last_exception_get();
  if (!$ex) print "$result\n";

  // This should fail (error suppressed by @)
  $result = @$stack->pop();
  $ex = java_last_exception_get();
  if ($ex) print $ex->toString();

  // Clear last exception
  java_last_exception_clear();
?>

后退 | 起点 | 前进
java_last_exception_clear | 上一级 | LDAP functions


LDAP functions

PHP 手册
后退 前进

XLVIII. LDAP functions

介绍

LDAP is the Lightweight Directory Access Protocol, and is a protocol used to access "Directory Servers". The Directory is a special kind of database that holds information in a tree structure.

The concept is similar to your hard disk directory structure, except that in this context, the root directory is "The world" and the first level subdirectories are "countries". Lower levels of the directory structure contain entries for companies, organisations or places, while yet lower still we find directory entries for people, and perhaps equipment or documents.

To refer to a file in a subdirectory on your hard disk, you might use something like:

/usr/local/myapp/docs

The forwards slash marks each division in the reference, and the sequence is read from left to right.

The equivalent to the fully qualified file reference in LDAP is the "distinguished name", referred to simply as "dn". An example dn might be:

cn=John Smith,ou=Accounts,o=My Company,c=US

The comma marks each division in the reference, and the sequence is read from right to left. You would read this dn as:

country = US
organization = My Company
organizationalUnit = Accounts
commonName = John Smith

In the same way as there are no hard rules about how you organise the directory structure of a hard disk, a directory server manager can set up any structure that is meaningful for the purpose. However, there are some conventions that are used. The message is that you can not write code to access a directory server unless you know something about its structure, any more than you can use a database without some knowledge of what is available.

Lots of information about LDAP can be found at

  • Netscape

  • University of Michigan

  • OpenLDAP Project

  • LDAP World

The Netscape SDK contains a helpful Programmer's Guide in HTML format.

需求

You will need to get and compile LDAP client libraries from either the University of Michigan ldap-3.3 package or the Netscape Directory SDK 3.0 to compile PHP with LDAP support.

安装

LDAP support in PHP is not enabled by default. You will need to use the --with-ldap configuration option when compiling PHP to enable LDAP support.

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. LDAP configuration options

Name | Default | Changeable
ldap.max_links | "-1" | PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().

资源类型

该扩展模块未定义任何资源类型。

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

LDAP_DEREF_NEVER (integer)

LDAP_DEREF_SEARCHING (integer)

LDAP_DEREF_FINDING (integer)

LDAP_DEREF_ALWAYS (integer)

LDAP_OPT_DEREF (integer)

LDAP_OPT_SIZELIMIT (integer)

LDAP_OPT_TIMELIMIT (integer)

LDAP_OPT_PROTOCOL_VERSION (integer)

LDAP_OPT_ERROR_NUMBER (integer)

LDAP_OPT_REFERRALS (integer)

LDAP_OPT_RESTART (integer)

LDAP_OPT_HOST_NAME (integer)

LDAP_OPT_ERROR_STRING (integer)

LDAP_OPT_MATCHED_DN (integer)

LDAP_OPT_SERVER_CONTROLS (integer)

LDAP_OPT_CLIENT_CONTROLS (integer)

LDAP_OPT_DEBUG_LEVEL (integer)

GSLC_SSL_NO_AUTH (integer)

GSLC_SSL_ONEWAY_AUTH (integer)

GSLC_SSL_TWOWAY_AUTH (integer)

范例

Retrieve information for all entries where the surname starts with "S" from a directory server, displaying an extract with name and email address.

例子 1. LDAP search example

<?php
// basic sequence with LDAP is connect, bind, search, interpret search
// result, close connection

echo "<h3>LDAP query test</h3>";
echo "Connecting ...";
$ds=ldap_connect("localhost");  // must be a valid LDAP server!
echo "connect result is ".$ds."<p>";

if ($ds) {
    echo "Binding ...";
    $r=ldap_bind($ds);     // this is an "anonymous" bind, typically
                           // read-only access
    echo "Bind result is ".$r."<p>";

    echo "Searching for (sn=S*) ...";
    // Search surname entry
    $sr=ldap_search($ds,"o=My Company, c=US", "sn=S*");
    echo "Search result is ".$sr."<p>";

    echo "Number of entires returned is ".ldap_count_entries($ds,$sr)."<p>";

    echo "Getting entries ...<p>";
    $info = ldap_get_entries($ds, $sr);
    echo "Data for ".$info["count"]." items returned:<p>";

    for ($i=0; $i<$info["count"]; $i++) {
        echo "dn is: ". $info[$i]["dn"] ."<br>";
        echo "first cn entry is: ". $info[$i]["cn"][0] ."<br>";
        echo "first email entry is: ". $info[$i]["mail"][0] ."<p>";
    }

    echo "Closing connection";
    ldap_close($ds);

} else {
    echo "<h4>Unable to connect to LDAP server</h4>";
}
?>

Using the PHP LDAP calls

Before you can use the LDAP calls you will need to know ..

  • The name or address of the directory server you will use

  • The "base dn" of the server (the part of the world directory that is held on this server, which could be "o=My Company,c=US")

  • Whether you need a password to access the server (many servers will provide read access for an "anonymous bind" but require a password for anything else)

The typical sequence of LDAP calls you will make in an application will follow this pattern:

ldap_connect() // establish connection to server
|
ldap_bind() // anonymous or authenticated "login"
|
do something like search or update the directory
and display the results
|
ldap_close() // "logout"

目录
ldap_8859_to_t61 — Translate 8859 characters to t61 characters
ldap_add — Add entries to LDAP directory
ldap_bind — Bind to LDAP directory
ldap_close — Close link to LDAP server
ldap_compare — Compare value of attribute found in entry specified with DN
ldap_connect — Connect to an LDAP server
ldap_count_entries — Count the number of entries in a search
ldap_delete — Delete an entry from a directory
ldap_dn2ufn — Convert DN to User Friendly Naming format
ldap_err2str — Convert LDAP error number into string error message
ldap_errno — Return the LDAP error number of the last LDAP command
ldap_error — Return the LDAP error message of the last LDAP command
ldap_explode_dn — Splits DN into its component parts
ldap_first_attribute — Return first attribute
ldap_first_entry — Return first result id
ldap_first_reference — Return first reference
ldap_free_result — Free result memory
ldap_get_attributes — Get attributes from a search result entry
ldap_get_dn — Get the DN of a result entry
ldap_get_entries — Get all result entries
ldap_get_option — Get the current value for given option
ldap_get_values_len — Get all binary values from a result entry
ldap_get_values — Get all values from a result entry
ldap_list — Single-level search
ldap_mod_add — Add attribute values to current attributes
ldap_mod_del — Delete attribute values from current attributes
ldap_mod_replace — Replace attribute values with new ones
ldap_modify — Modify an LDAP entry
ldap_next_attribute — Get the next attribute in result
ldap_next_entry — Get next result entry
ldap_next_reference — Get next reference
ldap_parse_reference — Extract information from reference entry
ldap_parse_result — Extract information from result
ldap_read — Read an entry
ldap_rename — Modify the name of an entry
ldap_search — Search LDAP tree
ldap_set_option — Set the value of the given option
ldap_set_rebind_proc — Set a callback function to do re-binds on referral chasing.
ldap_sort — Sort LDAP result entries
ldap_start_tls — Start TLS
ldap_t61_to_8859 — Translate t61 characters to 8859 characters
ldap_unbind — Unbind from LDAP directory

后退 | 起点 | 前进
java_last_exception_get | 上一级 | ldap_8859_to_t61


ldap_8859_to_t61

(PHP 4 >= 4.0.2)

ldap_8859_to_t61 -- Translate 8859 characters to t61 characters

Description

string ldap_8859_to_t61 ( string value)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
LDAP functions | 上一级 | ldap_add


ldap_add

(PHP 3, PHP 4 )

ldap_add -- Add entries to LDAP directory

Description

bool ldap_add ( resource link_identifier, string dn, array entry)

如果成功则返回 TRUE，失败则返回 FALSE。

The ldap_add() function is used to add entries in the LDAP directory. The DN of the entry to be added is specified by dn. Array entry specifies the information about the entry. The values in the entries are indexed by individual attributes. In case of multiple values for an attribute, they are indexed using integers starting with 0.

entry["attribute1"] = value
entry["attribute2"][0] = value1
entry["attribute2"][1] = value2

例子 1. Complete example with authenticated bind

<?php
$ds=ldap_connect("localhost");  // assuming the LDAP server is on this host

if ($ds) {
    // bind with appropriate dn to give update access
    $r=ldap_bind($ds,"cn=root, o=My Company, c=US", "secret");

    // prepare data
    $info["cn"]="John Jones";
    $info["sn"]="Jones";
    $info["mail"]="jonj@here.and.now";
    $info["objectclass"]="person";

    // add data to directory
    $r=ldap_add($ds, "cn=John Jones, o=My Company, c=US", $info);

    ldap_close($ds);
} else {
    echo "Unable to connect to LDAP server";
}
?>

后退 | 起点 | 前进
ldap_8859_to_t61 | 上一级 | ldap_bind


ldap_bind

(PHP 3, PHP 4 )

ldap_bind -- Bind to LDAP directory

Description

bool ldap_bind ( resource link_identifier [, string bind_rdn [, string bind_password]])

Binds to the LDAP directory with specified RDN and password. 如果成功则返回 TRUE，失败则返回 FALSE。

ldap_bind() does a bind operation on the directory. bind_rdn and bind_password are optional. If not specified, anonymous bind is attempted.

后退 | 起点 | 前进
ldap_add | 上一级 | ldap_close


ldap_close

(PHP 3, PHP 4 )

ldap_close -- Close link to LDAP server

Description

bool ldap_close ( resource link_identifier)

如果成功则返回 TRUE，失败则返回 FALSE。

ldap_close() closes the link to the LDAP server that's associated with the specified link_identifier.

This call is internally identical to ldap_unbind(). The LDAP API uses the call ldap_unbind(), so perhaps you should use this in preference to ldap_close().

注: This function is an alias of ldap_unbind().

后退 | 起点 | 前进
ldap_bind | 上一级 | ldap_compare


ldap_compare

(PHP 4 >= 4.0.2)

ldap_compare -- Compare value of attribute found in entry specified with DN

Description

bool ldap_compare ( resource link_identifier, string dn, string attribute, string value)

Returns TRUE if value matches otherwise returns FALSE. Returns -1 on error.

ldap_compare() is used to compare value of attribute to value of same attribute in LDAP directory entry specified with dn.

The following example demonstrates how to check whether or not given password matches the one defined in DN specified entry.

例子 1. Complete example of password check

<?php

$ds=ldap_connect("localhost");  // assuming the LDAP server is on this host

if ($ds) {

    // bind
    if(ldap_bind($ds)) {

        // prepare data
        $dn = "cn=Matti Meikku, ou=My Unit, o=My Company, c=FI";
        $value = "secretpassword";
        $attr = "password";

        // compare value
        $r=ldap_compare($ds, $dn, $attr, $value);

        if ($r === -1) {
            echo "Error: ".ldap_error($ds);
        } elseif ($r === TRUE) {
            echo "Password correct.";
        } elseif ($r === FALSE) {
            echo "Wrong guess! Password incorrect.";
        }

    } else {
        echo "Unable to bind to LDAP server.";
    }

    ldap_close($ds);

} else {
    echo "Unable to connect to LDAP server.";
}
?>

警告

ldap_compare() can NOT be used to compare BINARY values!

注: This function was added in 4.0.2.

后退 | 起点 | 前进
ldap_close | 上一级 | ldap_connect


ldap_connect

(PHP 3, PHP 4 )

ldap_connect -- Connect to an LDAP server

Description

resource ldap_connect ( [string hostname [, int port]])

Returns a positive LDAP link identifier on success, or FALSE on error.

ldap_connect() establishes a connection to a LDAP server on a specified hostname and port. Both the arguments are optional. If no arguments are specified then the link identifier of the already opened link will be returned. If only hostname is specified, then the port defaults to 389.

If you are using OpenLDAP 2.x.x you can specify a URL instead of the hostname. To use LDAP with SSL, compile OpenLDAP 2.x.x with SSL support, configure PHP with SSL, and use ldaps://hostname/ as host parameter. The port parameter is not used when using URLs.

注: URL and SSL support were added in 4.0.4.

后退 | 起点 | 前进
ldap_compare | 上一级 | ldap_count_entries


ldap_count_entries

(PHP 3, PHP 4 )

ldap_count_entries -- Count the number of entries in a search

Description

int ldap_count_entries ( resource link_identifier, resource result_identifier)

Returns number of entries in the result or FALSE on error.

ldap_count_entries() returns the number of entries stored in the result of previous search operations. result_identifier identifies the internal ldap result.

后退 | 起点 | 前进
ldap_connect | 上一级 | ldap_delete


ldap_delete

(PHP 3, PHP 4 )

ldap_delete -- Delete an entry from a directory

Description

bool ldap_delete ( resource link_identifier, string dn)

如果成功则返回 TRUE，失败则返回 FALSE。

ldap_delete() function delete a particular entry in LDAP directory specified by dn.

后退 | 起点 | 前进
ldap_count_entries | 上一级 | ldap_dn2ufn


ldap_dn2ufn

(PHP 3, PHP 4 )

ldap_dn2ufn -- Convert DN to User Friendly Naming format

Description

string ldap_dn2ufn ( string dn)

ldap_dn2ufn() function is used to turn a DN, specified by dn, into a more user-friendly form, stripping off type names.

后退 | 起点 | 前进
ldap_delete | 上一级 | ldap_err2str


ldap_err2str

(PHP 3>= 3.0.13, PHP 4 )

ldap_err2str -- Convert LDAP error number into string error message

Description

string ldap_err2str ( int errno)

Returns string error message.

This function returns the string error message explaining the error number errno. While LDAP errno numbers are standardized, different libraries return different or even localized textual error messages. Never check for a specific error message text, but always use an error number to check.

See also ldap_errno() and ldap_error().

例子 1. Enumerating all LDAP error messages

<?php
  for($i=0; $i<100; $i++) {
    printf("Error $i: %s<br>\n", ldap_err2str($i));
  }
?>

后退 | 起点 | 前进
ldap_dn2ufn | 上一级 | ldap_errno


ldap_errno

(PHP 3>= 3.0.12, PHP 4 )

ldap_errno -- Return the LDAP error number of the last LDAP command

Description

int ldap_errno ( resource link_identifier)

Return the LDAP error number of the last LDAP command for this link.

This function returns the standardized error number returned by the last LDAP command for the given link_identifier. This number can be converted into a textual error message using ldap_err2str().

Unless you lower your warning level in your php.ini sufficiently or prefix your LDAP commands with @ (at) characters to suppress warning output, the errors generated will also show up in your HTML output.

例子 1. Generating and catching an error

<?php
// This example contains an error, which we will catch.
$ld = ldap_connect("localhost");
$bind = ldap_bind($ld);
// syntax error in filter expression (errno 87),
// must be "objectclass=*" to work.
$res =  @ldap_search($ld, "o=Myorg, c=DE", "objectclass");
if (!$res) {
    printf("LDAP-Errno: %s<br>\n", ldap_errno($ld));
    printf("LDAP-Error: %s<br>\n", ldap_error($ld));
    die("Argh!<br>\n");
}
$info = ldap_get_entries($ld, $res);
printf("%d matching entries.<br>\n", $info["count"]);
?>

See also ldap_err2str() and ldap_error().

后退 | 起点 | 前进
ldap_err2str | 上一级 | ldap_error


ldap_error

(PHP 3>= 3.0.12, PHP 4 )

ldap_error -- Return the LDAP error message of the last LDAP command

Description

string ldap_error ( resource link_identifier)

Returns string error message.

This function returns the string error message explaining the error generated by the last LDAP command for the given link_identifier While LDAP errno numbers are standardized, different libraries return different or even localized textual error messages. Never check for a specific error message text, but always use an error number to check.

Unless you lower your warning level in your php.ini sufficiently or prefix your LDAP commands with @ (at) characters to suppress warning output, the errors generated will also show up in your HTML output.

See also ldap_err2str() and ldap_errno().

后退 | 起点 | 前进
ldap_errno | 上一级 | ldap_explode_dn


ldap_explode_dn

(PHP 3, PHP 4 )

ldap_explode_dn -- Splits DN into its component parts

Description

array ldap_explode_dn ( string dn, int with_attrib)

ldap_explode_dn() function is used to split the DN returned by ldap_get_dn() and breaks it up into its component parts. Each part is known as Relative Distinguished Name, or RDN. ldap_explode_dn() returns an array of all those components. with_attrib is used to request if the RDNs are returned with only values or their attributes as well. To get RDNs with the attributes (i.e. in attribute=value format) set with_attrib to 0 and to get only values set it to 1.

后退 | 起点 | 前进
ldap_error | 上一级 | ldap_first_attribute


ldap_first_attribute

(PHP 3, PHP 4 )

ldap_first_attribute -- Return first attribute

Description

string ldap_first_attribute ( resource link_identifier, resource result_entry_identifier, int ber_identifier)

Returns the first attribute in the entry on success and FALSE on error.

Similar to reading entries, attributes are also read one by one from a particular entry. ldap_first_attribute() returns the first attribute in the entry pointed by the result_entry_identifier. Remaining attributes are retrieved by calling ldap_next_attribute() successively. ber_identifier is the identifier to internal memory location pointer. It is passed by reference. The same ber_identifier is passed to the ldap_next_attribute() function, which modifies that pointer.

See also ldap_get_attributes()

后退 | 起点 | 前进
ldap_explode_dn | 上一级 | ldap_first_entry


ldap_first_entry

(PHP 3, PHP 4 )

ldap_first_entry -- Return first result id

Description

resource ldap_first_entry ( resource link_identifier, resource result_identifier)

Returns the result entry identifier for the first entry on success and FALSE on error.

Entries in the LDAP result are read sequentially using the ldap_first_entry() and ldap_next_entry() functions. ldap_first_entry() returns the entry identifier for first entry in the result. This entry identifier is then supplied to lap_next_entry() routine to get successive entries from the result.

See also ldap_get_entries().

后退 | 起点 | 前进
ldap_first_attribute | 上一级 | ldap_first_reference


ldap_first_reference

(PHP 4 >= 4.0.5)

ldap_first_reference -- Return first reference

Description

resource ldap_first_reference ( resource link, resource result)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ldap_first_entry | 上一级 | ldap_free_result


ldap_free_result

(PHP 3, PHP 4 )

ldap_free_result -- Free result memory

Description

bool ldap_free_result ( resource result_identifier)

如果成功则返回 TRUE，失败则返回 FALSE。

ldap_free_result() frees up the memory allocated internally to store the result and pointed by the result_identifier. All result memory will be automatically freed when the script terminates.

Typically all the memory allocated for the ldap result gets freed at the end of the script. In case the script is making successive searches which return large result sets, ldap_free_result() could be called to keep the runtime memory usage by the script low.

后退 | 起点 | 前进
ldap_first_reference | 上一级 | ldap_get_attributes


ldap_get_attributes

(PHP 3, PHP 4 )

ldap_get_attributes -- Get attributes from a search result entry

Description

array ldap_get_attributes ( resource link_identifier, resource result_entry_identifier)

Returns a complete entry information in a multi-dimensional array on success and FALSE on error.

ldap_get_attributes() function is used to simplify reading the attributes and values from an entry in the search result. The return value is a multi-dimensional array of attributes and values.

Having located a specific entry in the directory, you can find out what information is held for that entry by using this call. You would use this call for an application which "browses" directory entries and/or where you do not know the structure of the directory entries. In many applications you will be searching for a specific attribute such as an email address or a surname, and won't care what other data is held.

return_value["count"] = number of attributes in the entry
return_value[0] = first attribute
return_value[n] = nth attribute

return_value["attribute"]["count"] = number of values for attribute
return_value["attribute"][0] = first value of the attribute
return_value["attribute"][i] = (i+1)th value of the attribute

例子 1. Show the list of attributes held for a particular directory entry

// $ds is the link identifier for the directory

// $sr is a valid search result from a prior call to
// one of the ldap directory search calls

$entry = ldap_first_entry($ds, $sr);

$attrs = ldap_get_attributes($ds, $entry);

echo $attrs["count"]." attributes held for this entry:<p>";

for ($i=0; $i<$attrs["count"]; $i++)
    echo $attrs[$i]."<br>";

See also ldap_first_attribute() and ldap_next_attribute()

后退 | 起点 | 前进
ldap_free_result | 上一级 | ldap_get_dn


ldap_get_dn

(PHP 3, PHP 4 )

ldap_get_dn -- Get the DN of a result entry

Description

string ldap_get_dn ( resource link_identifier, resource result_entry_identifier)

Returns the DN of the result entry and FALSE on error.

ldap_get_dn() function is used to find out the DN of an entry in the result.

后退 | 起点 | 前进
ldap_get_attributes | 上一级 | ldap_get_entries


ldap_get_entries

(PHP 3, PHP 4 )

ldap_get_entries -- Get all result entries

Description

array ldap_get_entries ( resource link_identifier, resource result_identifier)

Returns a complete result information in a multi-dimenasional array on success and FALSE on error.

ldap_get_entries() function is used to simplify reading multiple entries from the result, specified with result_identifier, and then reading the attributes and multiple values. The entire information is returned by one function call in a multi-dimensional array. The structure of the array is as follows.

The attribute index is converted to lowercase. (Attributes are case-insensitive for directory servers, but not when used as array indices.)

return_value["count"] = number of entries in the result
return_value[0] : refers to the details of first entry

return_value[i]["dn"] = DN of the ith entry in the result

return_value[i]["count"] = number of attributes in ith entry
return_value[i][j] = jth attribute in the ith entry in the result

return_value[i]["attribute"]["count"] = number of values for
attribute in ith entry
return_value[i]["attribute"][j] = jth value of attribute in ith entry

See also ldap_first_entry() and ldap_next_entry()

后退 | 起点 | 前进
ldap_get_dn | 上一级 | ldap_get_option


ldap_get_option

(PHP 4 >= 4.0.4)

ldap_get_option -- Get the current value for given option

Description

bool ldap_get_option ( resource link_identifier, int option, mixed retval)

Sets retval to the value of the specified option. 如果成功则返回 TRUE，失败则返回 FALSE。

The parameter option can be one of: LDAP_OPT_DEREF, LDAP_OPT_SIZELIMIT, LDAP_OPT_TIMELIMIT, LDAP_OPT_PROTOCOL_VERSION, LDAP_OPT_ERROR_NUMBER, LDAP_OPT_REFERRALS, LDAP_OPT_RESTART, LDAP_OPT_HOST_NAME, LDAP_OPT_ERROR_STRING, LDAP_OPT_MATCHED_DN. These are described in draft-ietf-ldapext-ldap-c-api-xx.txt

注: This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x, and was added in PHP 4.0.4

例子 1. Check protocol version

// $ds is a valid link identifier for a directory server
if (ldap_get_option($ds, LDAP_OPT_PROTOCOL_VERSION, $version))
    echo "Using protocol version $version";
else
    echo "Unable to determine protocol version";

See also ldap_set_option().

后退 | 起点 | 前进
ldap_get_entries | 上一级 | ldap_get_values_len


ldap_get_values_len

(PHP 3>= 3.0.13, PHP 4 )

ldap_get_values_len -- Get all binary values from a result entry

Description

array ldap_get_values_len ( resource link_identifier, resource result_entry_identifier, string attribute)

Returns an array of values for the attribute on success and FALSE on error.

ldap_get_values_len() function is used to read all the values of the attribute in the entry in the result. entry is specified by the result_entry_identifier. The number of values can be found by indexing "count" in the resultant array. Individual values are accessed by integer index in the array. The first index is 0.

This function is used exactly like ldap_get_values() except that it handles binary data and not string data.

注: This function was added in 4.0.

后退 | 起点 | 前进
ldap_get_option | 上一级 | ldap_get_values


ldap_get_values

(PHP 3, PHP 4 )

ldap_get_values -- Get all values from a result entry

Description

array ldap_get_values ( resource link_identifier, resource result_entry_identifier, string attribute)

Returns an array of values for the attribute on success and FALSE on error.

ldap_get_values() function is used to read all the values of the attribute in the entry in the result. entry is specified by the result_entry_identifier. The number of values can be found by indexing "count" in the resultant array. Individual values are accessed by integer index in the array. The first index is 0.

This call needs a result_entry_identifier, so needs to be preceded by one of the ldap search calls and one of the calls to get an individual entry.

You application will either be hard coded to look for certain attributes (such as "surname" or "mail") or you will have to use the ldap_get_attributes() call to work out what attributes exist for a given entry.

LDAP allows more than one entry for an attribute, so it can, for example, store a number of email addresses for one person's directory entry all labeled with the attribute "mail"

return_value["count"] = number of values for attribute
return_value[0] = first value of attribute
return_value[i] = ith value of attribute

例子 1. List all values of the "mail" attribute for a directory entry

// $ds is a valid link identifier for a directory server

// $sr is a valid search result from a prior call to
//     one of the ldap directory search calls

// $entry is a valid entry identifier from a prior call to
//        one of the calls that returns a directory entry

$values = ldap_get_values($ds, $entry,"mail");

echo $values["count"]." email addresses for this entry.<p>";

for ($i=0; $i < $values["count"]; $i++)
    echo $values[$i]."<br>";

后退 | 起点 | 前进
ldap_get_values_len | 上一级 | ldap_list


ldap_list

(PHP 3, PHP 4 )

ldap_list -- Single-level search

Description

resource ldap_list ( resource link_identifier, string base_dn, string filter [, array attributes [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]])

Returns a search result identifier or FALSE on error.

ldap_list() performs the search for a specified filter on the directory with the scope LDAP_SCOPE_ONELEVEL.

LDAP_SCOPE_ONELEVEL means that the search should only return information that is at the level immediately below the base_dn given in the call. (Equivalent to typing "ls" and getting a list of files and folders in the current working directory.)

This call takes 5 optional parameters. See ldap_search() notes.

注: These optional parameters were added in 4.0.2: attrsonly, sizelimit, timelimit, deref.

例子 1. Produce a list of all organizational units of an organization

// $ds is a valid link identifier for a directory server

$basedn = "o=My Company, c=US";
$justthese = array("ou");

$sr=ldap_list($ds, $basedn, "ou=*", $justthese);

$info = ldap_get_entries($ds, $sr);

for ($i=0; $i<$info["count"]; $i++)
    echo $info[$i]["ou"][0] ;

注: From 4.0.5 on it's also possible to do parallel searches. See ldap_search() for details.

后退 | 起点 | 前进
ldap_get_values | 上一级 | ldap_mod_add


ldap_mod_add

(PHP 3>= 3.0.8, PHP 4 )

ldap_mod_add -- Add attribute values to current attributes

Description

bool ldap_mod_add ( resource link_identifier, string dn, array entry)

如果成功则返回 TRUE，失败则返回 FALSE。

This function adds attribute(s) to the specified dn. It performs the modification at the attribute level as opposed to the object level. Object-level additions are done by the ldap_add() function.

后退 | 起点 | 前进
ldap_list | 上一级 | ldap_mod_del


ldap_mod_del

(PHP 3>= 3.0.8, PHP 4 )

ldap_mod_del -- Delete attribute values from current attributes

Description

bool ldap_mod_del ( resource link_identifier, string dn, array entry)

如果成功则返回 TRUE，失败则返回 FALSE。

This function removes attribute(s) from the specified dn. It performs the modification at the attribute level as opposed to the object level. Object-level deletions are done by the ldap_delete() function.

后退 | 起点 | 前进
ldap_mod_add | 上一级 | ldap_mod_replace


ldap_mod_replace

(PHP 3>= 3.0.8, PHP 4 )

ldap_mod_replace -- Replace attribute values with new ones

Description

bool ldap_mod_replace ( resoure link_identifier, string dn, array entry)

如果成功则返回 TRUE，失败则返回 FALSE。

This function replaces attribute(s) from the specified dn. It performs the modification at the attribute level as opposed to the object level. Object-level modifications are done by the ldap_modify() function.

后退 | 起点 | 前进
ldap_mod_del | 上一级 | ldap_modify


ldap_modify

(PHP 3, PHP 4 )

ldap_modify -- Modify an LDAP entry

Description

bool ldap_modify ( resource link_identifier, string dn, array entry)

如果成功则返回 TRUE，失败则返回 FALSE。

ldap_modify() function is used to modify the existing entries in the LDAP directory. The structure of the entry is same as in ldap_add().

后退 | 起点 | 前进
ldap_mod_replace | 上一级 | ldap_next_attribute


ldap_next_attribute

(PHP 3, PHP 4 )

ldap_next_attribute -- Get the next attribute in result

Description

string ldap_next_attribute ( resource link_identifier, resource result_entry_identifier, resource ber_identifier)

Returns the next attribute in an entry on success and FALSE on error.

ldap_next_attribute() is called to retrieve the attributes in an entry. The internal state of the pointer is maintained by the ber_identifier. It is passed by reference to the function. The first call to ldap_next_attribute() is made with the result_entry_identifier returned from ldap_first_attribute().

See also ldap_get_attributes()

后退 | 起点 | 前进
ldap_modify | 上一级 | ldap_next_entry


ldap_next_entry

(PHP 3, PHP 4 )

ldap_next_entry -- Get next result entry

Description

resource ldap_next_entry ( resource link_identifier, resource result_entry_identifier)

Returns entry identifier for the next entry in the result whose entries are being read starting with ldap_first_entry(). If there are no more entries in the result then it returns FALSE.

ldap_next_entry() function is used to retrieve the entries stored in the result. Successive calls to the ldap_next_entry() return entries one by one till there are no more entries. The first call to ldap_next_entry() is made after the call to ldap_first_entry() with the result_entry_identifier as returned from the ldap_first_entry().

See also ldap_get_entries()

后退 | 起点 | 前进
ldap_next_attribute | 上一级 | ldap_next_reference


ldap_next_reference

(PHP 4 >= 4.0.5)

ldap_next_reference -- Get next reference

Description

resource ldap_next_reference ( resource link, resource entry)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ldap_next_entry | 上一级 | ldap_parse_reference


ldap_parse_reference

(PHP 4 >= 4.0.5)

ldap_parse_reference -- Extract information from reference entry

Description

bool ldap_parse_reference ( resource link, resource entry, array referrals)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ldap_next_reference | 上一级 | ldap_parse_result


ldap_parse_result

(PHP 4 >= 4.0.5)

ldap_parse_result -- Extract information from result

Description

bool ldap_parse_result ( resource link, resource result, int errcode, string matcheddn, string errmsg, array referrals)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ldap_parse_reference | 上一级 | ldap_read


ldap_read

(PHP 3, PHP 4 )

ldap_read -- Read an entry

Description

resource ldap_read ( resource link_identifier, string base_dn, string filter [, array attributes [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]])

Returns a search result identifier or FALSE on error.

ldap_read() performs the search for a specified filter on the directory with the scope LDAP_SCOPE_BASE. So it is equivalent to reading an entry from the directory.

An empty filter is not allowed. If you want to retrieve absolutely all information for this entry, use a filter of "objectClass=*". If you know which entry types are used on the directory server, you might use an appropriate filter such as "objectClass=inetOrgPerson".

This call takes 5 optional parameters. See ldap_search() notes.

注: These optional parameters were added in 4.0.2: attrsonly, sizelimit, timelimit, deref.

From 4.0.5 on it's also possible to do parallel searches. See ldap_search() for details.

后退 | 起点 | 前进
ldap_parse_result | 上一级 | ldap_rename


ldap_rename

(PHP 4 >= 4.0.5)

ldap_rename -- Modify the name of an entry

Description

bool ldap_rename ( resource link_identifier, string dn, string newrdn, string newparent, bool deleteoldrdn)

The entry specified by dn is renamed/moved. The new RDN is specified by newrdn and the new parent/superior entry is specified by newparent. If the parameter deleteoldrdn is TRUE the old RDN value(s) is removed, else the old RDN value(s) is retained as non-distinguished values of the entry. 如果成功则返回 TRUE，失败则返回 FALSE。

注: This function currently only works with LDAPv3. You may have to use ldap_set_option() prior to binding to use LDAPv3. This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x, and was added in PHP 4.0.5.

后退 | 起点 | 前进
ldap_read | 上一级 | ldap_search


ldap_search

(PHP 3, PHP 4 )

ldap_search -- Search LDAP tree

Description

resource ldap_search ( resource link_identifier, string base_dn, string filter [, array attributes [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]])

Returns a search result identifier or FALSE on error.

ldap_search() performs the search for a specified filter on the directory with the scope of LDAP_SCOPE_SUBTREE. This is equivalent to searching the entire directory. base_dn specifies the base DN for the directory.

There is a optional fourth parameter, that can be added to restrict the attributes and values returned by the server to just those required. This is much more efficient than the default action (which is to return all attributes and their associated values). The use of the fourth parameter should therefore be considered good practice.

The fourth parameter is a standard PHP string array of the required attributes, eg array("mail","sn","cn") Note that the "dn" is always returned irrespective of which attributes types are requested.

Note too that some directory server hosts will be configured to return no more than a preset number of entries. If this occurs, the server will indicate that it has only returned a partial results set. This occurs also if the sixth parameter sizelimit has been used to limit the count of fetched entries.

The fifth parameter attrsonly should be set to 1 if only attribute types are wanted. If set to 0 both attributes types and attribute values are fetched which is the default behaviour.

With the sixth parameter sizelimit it is possible to limit the count of entries fetched. Setting this to 0 means no limit. NOTE: This parameter can NOT override server-side preset sizelimit. You can set it lower though.

The seventh parameter timelimit sets the number of seconds how long is spend on the search. Setting this to 0 means no limit. NOTE: This parameter can NOT override server-side preset timelimit. You can set it lower though.

The eigth parameter deref specifies how aliases should be handled during the search. It can be one of the following:

  • LDAP_DEREF_NEVER - (default) aliases are never dereferenced.

  • LDAP_DEREF_SEARCHING - aliases should be dereferenced during the search but not when locating the base object of the search.

  • LDAP_DEREF_FINDING - aliases should be dereferenced when locating the base object but not during the search.

  • LDAP_DEREF_ALWAYS - aliases should be dereferenced always.

注: These optional parameters were added in 4.0.2: attrsonly, sizelimit, timelimit, deref.

The search filter can be simple or advanced, using boolean operators in the format described in the LDAP doumentation (see the Netscape Directory SDK for full information on filters).

The example below retrieves the organizational unit, surname, given name and email address for all people in "My Company" where the surname or given name contains the substring $person. This example uses a boolean filter to tell the server to look for information in more than one attribute.

例子 1. LDAP search

// $ds is a valid link identifier for a directory server

// $person is all or part of a person's name, eg "Jo"

$dn = "o=My Company, c=US";
$filter="(|(sn=$person*)(givenname=$person*))";
$justthese = array( "ou", "sn", "givenname", "mail");

$sr=ldap_search($ds, $dn, $filter, $justthese);

$info = ldap_get_entries($ds, $sr);

print $info["count"]." entries returned<p>";

From 4.0.5 on it's also possible to do parallel searches. To do this you use an array of link identifiers, rather than a single identifier, as the first argument. If you don't want the same base DN and the same filter for all the searches, you can also use an array of base DNs and/or an array of filters. Those arrays must be of the same size as the link identifier array since the first entries of the arrays are used for one search, the second entries are used for another, and so on. When doing parallel searches an array of search result identifiers is returned, except in case of error, then the entry corresponding to the search will be FALSE. This is very much like the value normally returned, except that a result identifier is always returned when a search was made. There are some rare cases where the normal search returns FALSE while the parallel search returns an identifier.

后退 | 起点 | 前进
ldap_rename | 上一级 | ldap_set_option


ldap_set_option

(PHP 4 >= 4.0.4)

ldap_set_option -- Set the value of the given option

Description

bool ldap_set_option ( resource link_identifier, int option, mixed newval)

Sets the value of the specified option to be newval. 如果成功则返回 TRUE，失败则返回 FALSE。 on error.

The parameter option can be one of: LDAP_OPT_DEREF, LDAP_OPT_SIZELIMIT, LDAP_OPT_TIMELIMIT, LDAP_OPT_PROTOCOL_VERSION, LDAP_OPT_ERROR_NUMBER, LDAP_OPT_REFERRALS, LDAP_OPT_RESTART, LDAP_OPT_HOST_NAME, LDAP_OPT_ERROR_STRING, LDAP_OPT_MATCHED_DN, LDAP_OPT_SERVER_CONTROLS, LDAP_OPT_CLIENT_CONTROLS. Here's a brief description, see draft-ietf-ldapext-ldap-c-api-xx.txt for details.

The options LDAP_OPT_DEREF, LDAP_OPT_SIZELIMIT, LDAP_OPT_TIMELIMIT, LDAP_OPT_PROTOCOL_VERSION and LDAP_OPT_ERROR_NUMBER have integer value, LDAP_OPT_REFERRALS and LDAP_OPT_RESTART have boolean value, and the options LDAP_OPT_HOST_NAME, LDAP_OPT_ERROR_STRING and LDAP_OPT_MATCHED_DN have string value. The first example illustrates their use. The options LDAP_OPT_SERVER_CONTROLS and LDAP_OPT_CLIENT_CONTROLS require a list of controls, this means that the value must be an array of controls. A control consists of an oid identifying the control, an optional value, and an optional flag for criticality. In PHP a control is given by an array containing an element with the key oid and string value, and two optional elements. The optional elements are key value with string value and key iscritical with boolean value. iscritical defaults to FALSE if not supplied. See also the second example below.

注: This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x, and was added in PHP 4.0.4.

例子 1. Set protocol version

// $ds is a valid link identifier for a directory server
if (ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3))
    echo "Using LDAPv3";
else
    echo "Failed to set protocol version to 3";

例子 2. Set server controls

// $ds is a valid link identifier for a directory server
// control with no value
$ctrl1 = array("oid" => "1.2.752.58.10.1", "iscritical" => TRUE);
// iscritical defaults to FALSE
$ctrl2 = array("oid" => "1.2.752.58.1.10", "value" => "magic");
// try to set both controls
if (!ldap_set_option($ds, LDAP_OPT_SERVER_CONTROLS, array($ctrl1, $ctrl2)))
    echo "Failed to set server controls";

See also ldap_get_option().

后退 | 起点 | 前进
ldap_search | 上一级 | ldap_set_rebind_proc


ldap_set_rebind_proc

(PHP 4 >= 4.2.0)

ldap_set_rebind_proc -- Set a callback function to do re-binds on referral chasing.

Description

bool ldap_set_rebind_proc ( resource link, string callback)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ldap_set_option | 上一级 | ldap_sort


ldap_sort

(PHP 4 >= 4.2.0)

ldap_sort -- Sort LDAP result entries

Description

bool ldap_sort ( resource link, resource result, string sortfilter)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ldap_set_rebind_proc | 上一级 | ldap_start_tls


ldap_start_tls

(PHP 4 >= 4.2.0)

ldap_start_tls -- Start TLS

Description

bool ldap_start_tls ( resource link)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ldap_sort | 上一级 | ldap_t61_to_8859


ldap_t61_to_8859

(PHP 4 >= 4.0.2)

ldap_t61_to_8859 -- Translate t61 characters to 8859 characters

Description

string ldap_t61_to_8859 ( string value)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ldap_start_tls | 上一级 | ldap_unbind


ldap_unbind

(PHP 3, PHP 4 )

ldap_unbind -- Unbind from LDAP directory

Description

bool ldap_unbind ( resource link_identifier)

如果成功则返回 TRUE，失败则返回 FALSE。

ldap_unbind() function unbinds from the LDAP directory.

后退 | 起点 | 前进
ldap_t61_to_8859 | 上一级 | Mail functions


Mail functions

PHP 手册
后退 前进

XLIX. Mail functions

介绍

The mail() function allows you to send mail

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

这些函数作为 PHP 核心的一部分，无需被安装即可使用。

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. Mail configuration options

Name | Default | Changeable
SMTP | "localhost" | PHP_INI_ALL
smtp_port | "25" | PHP_INI_ALL
sendmail_from | NULL | PHP_INI_ALL
sendmail_path | DEFAULT_SENDMAIL_PATH | PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().

Here is a short explanation of the configuration directives.

SMTP string

Used under Windws only: DNS name or IP address of the SMTP server PHP should use for mail sent with the mail() function.

SMTP int

Used under Windws only: Number of the port to connect to the server specified with the SMTP setting when sending mail with mail(); defaults to 25. Only available since PHP 4.3.0.

sendmail_from string

Which "From:" mail address should be used in mail sent from PHP under Windows.

sendmail_path string

Where the sendmail program can be found, usually /usr/sbin/sendmail or /usr/lib/sendmail. configure does an honest attempt of locating this one for you and set a default, but if it fails, you can set it here.

Systems not using sendmail should set this directive to the sendmail wrapper/replacement their mail system offers, if any. For example, Qmail users can normally set it to /var/qmail/bin/sendmail or /var/qmail/bin/qmail-inject.

qmail-inject does not require any option to process mail correctly.

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

目录
ezmlm_hash — Calculate the hash value needed by EZMLM
mail — send mail

后退 | 起点 | 前进
ldap_unbind | 上一级 | ezmlm_hash


ezmlm_hash

(PHP 3>= 3.0.17, PHP 4 >= 4.0.2)

ezmlm_hash -- Calculate the hash value needed by EZMLM

Description

int ezmlm_hash ( string addr)

ezmlm_hash() calculates the hash value needed when keeping EZMLM mailing lists in a MySQL database.

例子 1. Calculating the hash and subscribing a user

$user = "joecool@example.com";
$hash = ezmlm_hash ($user);
$query = sprintf ("INSERT INTO sample VALUES (%s, '%s')", $hash, $user);
$db->query($query); // using PHPLIB db interface

后退 | 起点 | 前进
Mail functions | 上一级 | mail


mail

(PHP 3, PHP 4 )

mail -- send mail

Description

bool mail ( string to, string subject, string message [, string additional_headers [, string additional_parameters]])

mail() automatically mails the message specified in message to the receiver specified in to. Multiple recipients can be specified by putting a comma between each address in to. Email with attachments and special types of content can be sent using this function. This is accomplished via MIME-encoding - for more information, see this Zend article or the PEAR Mime Classes.

The following RFC's may also be useful: RFC 1896, RFC 2045, RFC 2046, RFC 2047, RFC 2048, and RFC 2049.

mail() returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.

警告

The Windows implementation of mail() differs in many ways from the Unix implementation. First, it doesn't use a local binary for composing messages but only operates on direct sockets which means a MTA is needed listening on a network socket (which can either on the localhost or a remote machine). Second, the custom headers like From:, Cc:, Bcc: and Date: are not interpreted by the MTA in the first place, but are parsed by PHP. PHP < 4.3 only supported the Cc: header element (and was case-sensitive). PHP >= 4.3 supports all the mentioned header elements and is no longer case-sensitive.

例子 1. Sending mail.

mail("joecool@example.com", "My Subject", "Line 1\nLine 2\nLine 3");

If a fourth string argument is passed, this string is inserted at the end of the header. This is typically used to add extra headers. Multiple extra headers are separated with a carriage return and newline.

注: You must use \r\n to seperate headers, although some Unix mail transfer agents may work with just a single newline (\n).

例子 2. Sending mail with extra headers.

mail("nobody@example.com", "the subject", $message,
     "From: webmaster@$SERVER_NAME\r\n"
    ."Reply-To: webmaster@$SERVER_NAME\r\n"
    ."X-Mailer: PHP/" . phpversion());

The additional_parameters parameter can be used to pass an additional parameter to the program configured to use when sending mail using the sendmail_path configuration setting. For example, this can be used to set the envelope sender address when using sendmail. You may need to add the user that your web server runs as to your sendmail configuration to prevent a 'X-Warning' header from being added to the message when you set the envelope sender using this method.

例子 3. Sending mail with extra headers and setting an additional command line parameter.

mail("nobody@example.com", "the subject", $message,
     "From: webmaster@$SERVER_NAME", "-fwebmaster@$SERVER_NAME");

注: This fifth parameter was added in PHP 4.0.5. Since PHP 4.2.3 this parameter is disabled in safe_mode and the mail() function will expose a warning message and return FALSE if you're trying to use it.

You can also use simple string building techniques to build complex email messages.

例子 4. Sending complex email.

/* recipients */
$to  = "Mary <mary@example.com>" . ", " ; // note the comma
$to .= "Kelly <kelly@example.com>";

/* subject */
$subject = "Birthday Reminders for August";

/* message */
$message = '
<html>
<head>
 <title>Birthday Reminders for August</title>
</head>
<body>
<p>Here are the birthdays upcoming in August!</p>
<table>
 <tr>
  <th>Person</th><th>Day</th><th>Month</th><th>Year</th>
 </tr>
 <tr>
  <td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
 </tr>
 <tr>
  <td>Sally</td><td>17th</td><td>August</td><td>1973</td>
 </tr>
</table>
</body>
</html>
';

/* To send HTML mail, you can set the Content-type header. */
$headers  = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";

/* additional headers */
$headers .= "From: Birthday Reminder <birthday@example.com>\r\n";

$headers .= "Cc: birthdayarchive@example.com\r\n";
$headers .= "Bcc: birthdaycheck@example.com\r\n";

/* and now mail it */
mail($to, $subject, $message, $headers);

注: Make sure you do not have any newline characters in the to or subject, or the mail may not be sent properly.

注: The to parameter cannot be an address in the form of "Something <someone@somewhere.com>". The mail command will not parse this properly while talking with the MTA.

See also imap_mail().

后退 | 起点 | 前进
ezmlm_hash | 上一级 | mailparse functions


mailparse functions

PHP 手册
后退 前进

L. mailparse functions

介绍

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

目录
mailparse_determine_best_xfer_encoding — Figures out the best way of encoding the content read from the file pointer fp, which must be seek-able
mailparse_msg_create — Returns a handle that can be used to parse a message
mailparse_msg_extract_part_file — Extracts/decodes a message section, decoding the transfer encoding
mailparse_msg_extract_part — Extracts/decodes a message section. If callbackfunc is not specified, the contents will be sent to "stdout"
mailparse_msg_free — Frees a handle allocated by mailparse_msg_crea
mailparse_msg_get_part_data — Returns an associative array of info about the message
mailparse_msg_get_part — Returns a handle on a given section in a mimemessage
mailparse_msg_get_structure — Returns an array of mime section names in the supplied message
mailparse_msg_parse_file — Parse file and return a resource representing the structure
mailparse_msg_parse — Incrementally parse data into buffer
mailparse_rfc822_parse_addresses — Parse addresses and returns a hash containing that data
mailparse_stream_encode — Streams data from source file pointer, apply encoding and write to destfp
mailparse_uudecode_all — Scans the data from fp and extract each embedded uuencoded file. Returns an array listing filename information

后退 | 起点 | 前进
mail | 上一级 | mailparse_determine_best_xfer_encoding


mailparse_determine_best_xfer_encoding

(4.1.0 - 4.1.2 only)

mailparse_determine_best_xfer_encoding -- Figures out the best way of encoding the content read from the file pointer fp, which must be seek-able

Description

int mailparse_determine_best_xfer_encoding ( resource fp)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
mailparse functions | 上一级 | mailparse_msg_create


mailparse_msg_create

(4.1.0 - 4.1.2 only)

mailparse_msg_create -- Returns a handle that can be used to parse a message

Description

int mailparse_msg_create ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
mailparse_determine_best_xfer_encoding | 上一级 | mailparse_msg_extract_part_file


mailparse_msg_extract_part_file

(4.1.0 - 4.1.2 only)

mailparse_msg_extract_part_file -- Extracts/decodes a message section, decoding the transfer encoding

Description

string mailparse_msg_extract_part_file ( resource rfc2045, string filename [, string callbackfunc])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
mailparse_msg_create | 上一级 | mailparse_msg_extract_part


mailparse_msg_extract_part

(4.1.0 - 4.1.2 only)

mailparse_msg_extract_part -- Extracts/decodes a message section. If callbackfunc is not specified, the contents will be sent to "stdout"

Description

void mailparse_msg_extract_part ( resource rfc2045, string msgbody [, string callbackfunc])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
mailparse_msg_extract_part_file | 上一级 | mailparse_msg_free


mailparse_msg_free

(4.1.0 - 4.1.2 only)

mailparse_msg_free -- Frees a handle allocated by mailparse_msg_crea

Description

void mailparse_msg_free ( resource rfc2045buf)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
mailparse_msg_extract_part | 上一级 | mailparse_msg_get_part_data


mailparse_msg_get_part_data

(4.1.0 - 4.1.2 only)

mailparse_msg_get_part_data -- Returns an associative array of info about the message

Description

array mailparse_msg_get_part_data ( resource rfc2045)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
mailparse_msg_free | 上一级 | mailparse_msg_get_part


mailparse_msg_get_part

(4.1.0 - 4.1.2 only)

mailparse_msg_get_part -- Returns a handle on a given section in a mimemessage

Description

int mailparse_msg_get_part ( resource rfc2045, string mimesection)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
mailparse_msg_get_part_data | 上一级 | mailparse_msg_get_structure


mailparse_msg_get_structure

(4.1.0 - 4.1.2 only)

mailparse_msg_get_structure -- Returns an array of mime section names in the supplied message

Description

array mailparse_msg_get_structure ( resource rfc2045)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
mailparse_msg_get_part | 上一级 | mailparse_msg_parse_file


mailparse_msg_parse_file

(4.1.0 - 4.1.2 only)

mailparse_msg_parse_file -- Parse file and return a resource representing the structure

Description

resource mailparse_msg_parse_file ( string filename)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
mailparse_msg_get_structure | 上一级 | mailparse_msg_parse


mailparse_msg_parse

(4.1.0 - 4.1.2 only)

mailparse_msg_parse -- Incrementally parse data into buffer

Description

void mailparse_msg_parse ( resource rfc2045buf, string data)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
mailparse_msg_parse_file | 上一级 | mailparse_rfc822_parse_addresses


mailparse_rfc822_parse_addresses

(4.1.0 - 4.1.2 only)

mailparse_rfc822_parse_addresses -- Parse addresses and returns a hash containing that data

Description

array mailparse_rfc822_parse_addresses ( string addresses)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
mailparse_msg_parse | 上一级 | mailparse_stream_encode


mailparse_stream_encode

(4.1.0 - 4.1.2 only)

mailparse_stream_encode -- Streams data from source file pointer, apply encoding and write to destfp

Description

bool mailparse_stream_encode ( resource sourcefp, resource destfp, string encoding)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
mailparse_rfc822_parse_addresses | 上一级 | mailparse_uudecode_all


mailparse_uudecode_all

(no version information, might be only in CVS)

mailparse_uudecode_all -- Scans the data from fp and extract each embedded uuencoded file. Returns an array listing filename information

Description

array mailparse_uudecode_all ( resource fp)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
mailparse_stream_encode | 上一级 | Mathematical Functions


Mathematical Functions

PHP 手册
后退 前进

LI. Mathematical Functions

介绍

These math functions will only handle values within the range of the integer and float types on your computer (this corresponds currently to the C types long resp. double). If you need to handle bigger numbers, take a look at the arbitrary precision math functions.

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

这些函数作为 PHP 核心的一部分，无需被安装即可使用。

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

这里列出的所有常量将作为 PHP 核心的一部分一直有效。

表格 1. 数学常量

常量名 | 常量值 | 描述
M_PI | 3.14159265358979323846 | Pi
M_E | 2.7182818284590452354 | e
M_LOG2E | 1.4426950408889634074 | log_2 e
M_LOG10E | 0.43429448190325182765 | log_10 e
M_LN2 | 0.69314718055994530942 | log_e 2
M_LN10 | 2.30258509299404568402 | log_e 10
M_PI_2 | 1.57079632679489661923 | pi/2
M_PI_4 | 0.78539816339744830962 | pi/4
M_1_PI | 0.31830988618379067154 | 1/pi
M_2_PI | 0.63661977236758134308 | 2/pi
M_SQRTPI | 1.77245385090551602729 | sqrt(pi) [4.0.2]
M_2_SQRTPI | 1.12837916709551257390 | 2/sqrt(pi)
M_SQRT2 | 1.41421356237309504880 | sqrt(2)
M_SQRT3 | 1.73205080756887729352 | sqrt(3) [4.0.2]
M_SQRT1_2 | 0.70710678118654752440 | 1/sqrt(2)
M_LNPI | 1.14472988584940017414 | log_e(pi) [4.0.2]
M_EULER | 0.57721566490153286061 | Euler constant [4.0.2]
只有常量 M_PI 在 PHP 4.0.0 之前就存在，其它所有常量从 PHP 4.0.0 起开始存在。用 [4.0.2] 标记的常量是在 PHP 4.0.2 中增加的。

目录
abs — Absolute value
acos — Arc cosine
acosh — Inverse hyperbolic cosine
asin — Arc sine
asinh — Inverse hyperbolic sine
atan2 — arc tangent of two variables
atan — Arc tangent
atanh — Inverse hyperbolic tangent
base_convert — Convert a number between arbitrary bases
bindec — Binary to decimal
ceil — Round fractions up
cos — 余弦
cosh — Hyperbolic cosine
decbin — Decimal to binary
dechex — Decimal to hexadecimal
decoct — Decimal to octal
deg2rad — Converts the number in degrees to the radian equivalent
exp — e to the power of ...
expm1 — Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero
floor — Round fractions down
getrandmax — Show largest possible random value
hexdec — Hexadecimal to decimal
hypot — Returns sqrt( num1*num1 + num2*num2)
is_finite —
is_infinite —
is_nan —
lcg_value — Combined linear congruential generator
log10 — 以10为底的对数
log1p — Returns log(1 + number), computed in a way that accurate even when the val ue of number is close to zero
log — 自然对数
max — Find highest value
min — Find lowest value
mt_getrandmax — Show largest possible random value
mt_rand — Generate a better random value
mt_srand — Seed the better random number generator
number_format — Format a number with grouped thousands
octdec — Octal to decimal
pi — 得到圆周率值
pow — Exponential expression
rad2deg — Converts the radian number to the equivalent number in degrees
rand — Generate a random value
round — Rounds a float
sin — 正弦
sinh — Hyperbolic sine
sqrt — Square root
srand — Seed the random number generator
tan — 正切
tanh — Hyperbolic tangent

后退 | 起点 | 前进
mailparse_uudecode_all | 上一级 | abs


abs

(PHP 3, PHP 4 )

abs -- Absolute value

Description

mixed abs ( mixed number)

Returns the absolute value of number. If the argument number is of type float, the return type is also float, otherwise it is integer (as float usually has a bigger value range than integer).

例子 1. abs() example

$abs = abs(-4.2); // $abs = 4.2; (double/float)
$abs2 = abs(5);   // $abs2 = 5; (integer)
$abs3 = abs(-5);  // $abs3 = 5; (integer)

后退 | 起点 | 前进
Mathematical Functions | 上一级 | acos


acos

(PHP 3, PHP 4 )

acos -- Arc cosine

Description

float acos ( float arg)

Returns the arc cosine of arg in radians. acos() is the complementary function of cos(), which means that a==cos(acos(a)) for every value of a that is within acos()' range.

See also acosh(), asin() and atan().

后退 | 起点 | 前进
abs | 上一级 | acosh


acosh

(PHP 4 >= 4.1.0)

acosh -- Inverse hyperbolic cosine

Description

float acosh ( float arg)

Returns the inverse hyperbolic cosine of arg, i.e. the value whose hyperbolic cosine is arg.

注: 该函数不适用于 Windows 平台！

See also acos(), asinh() and atanh().

后退 | 起点 | 前进
acos | 上一级 | asin


asin

(PHP 3, PHP 4 )

asin -- Arc sine

Description

float asin ( float arg)

Returns the arc sine of arg in radians. asin() is the complementary function of sin(), which means that a==sin(asin(a)) for every value of a that is within asin()'s range.

See also asinh(), acos() and atan().

后退 | 起点 | 前进
acosh | 上一级 | asinh


asinh

(PHP 4 >= 4.1.0)

asinh -- Inverse hyperbolic sine

Description

float asinh ( float arg)

Returns the inverse hyperbolic sine of arg, i.e. the value whose hyperbolic sine is arg.

注: 该函数不适用于 Windows 平台！

See also asin(), acosh() and atanh().

后退 | 起点 | 前进
asin | 上一级 | atan2


atan2

(PHP 3>= 3.0.5, PHP 4 )

atan2 -- arc tangent of two variables

Description

float atan2 ( float y, float x)

This function calculates the arc tangent of the two variables x and y. It is similar to calculating the arc tangent of y / x, except that the signs of both arguments are used to determine the quadrant of the result.

The function returns the result in radians, which is between -PI and PI (inclusive).

See also acos() and atan().

后退 | 起点 | 前进
asinh | 上一级 | atan


atan

(PHP 3, PHP 4 )

atan -- Arc tangent

Description

float atan ( float arg)

Returns the arc tangent of arg in radians. atan() is the complementary function of tan(), which means that a==tan(atan(a)) for every value of a that is within atan()'s range.

See also atanh(), asin() and acos().

后退 | 起点 | 前进
atan2 | 上一级 | atanh


atanh

(PHP 4 >= 4.1.0)

atanh -- Inverse hyperbolic tangent

Description

float atanh ( float arg)

Returns the inverse hyperbolic tangent of arg, i.e. the value whose hyperbolic tangent is arg.

注: 该函数不适用于 Windows 平台！

See also atan(), asinh() and acosh().

后退 | 起点 | 前进
atan | 上一级 | base_convert


base_convert

(PHP 3>= 3.0.6, PHP 4 )

base_convert -- Convert a number between arbitrary bases

Description

string base_convert ( string number, int frombase, int tobase)

Returns a string containing number represented in base tobase. The base in which number is given is specified in frombase. Both frombase and tobase have to be between 2 and 36, inclusive. Digits in numbers with a base higher than 10 will be represented with the letters a-z, with a meaning 10, b meaning 11 and z meaning 35.

例子 1. base_convert()

$binary = base_convert ($hexadecimal, 16, 2);

后退 | 起点 | 前进
atanh | 上一级 | bindec


bindec

(PHP 3, PHP 4 )

bindec -- Binary to decimal

Description

int bindec ( string binary_string)

Returns the decimal equivalent of the binary number represented by the binary_string argument.

bindec() converts a binary number to an integer. The largest number that can be converted is 31 bits of 1's or 2147483647 in decimal.

See also: decbin().

后退 | 起点 | 前进
base_convert | 上一级 | ceil


ceil

(PHP 3, PHP 4 )

ceil -- Round fractions up

Description

float ceil ( float value)

Returns the next highest integer value by rounding up value if necessary. The return value of ceil() is still of type float as the value range of float is usually bigger than that of integer.

例子 1. ceil() example

echo ceil(4.3);    // 5
echo ceil(9.999);  // 10

See also floor() and round().

后退 | 起点 | 前进
bindec | 上一级 | cos


cos

(PHP 3, PHP 4 )

cos -- 余弦

描述

float cos ( float arg)

cos() 返回参数 arg 的余弦值。参数 arg 的单位为弧度。

参见 acos(), sin() tan() 和 deg2rad().

后退 | 起点 | 前进
ceil | 上一级 | cosh


cosh

(PHP 4 >= 4.1.0)

cosh -- Hyperbolic cosine

Description

float cosh ( float arg)

Returns the hyperbolic cosine of arg, defined as (exp(arg) + exp(-arg))/2.

See also cos(), acosh(), sin() and tan().

后退 | 起点 | 前进
cos | 上一级 | decbin


decbin

(PHP 3, PHP 4 )

decbin -- Decimal to binary

Description

string decbin ( int number)

Returns a string containing a binary representation of the given number argument. The largest number that can be converted is 4294967295 in decimal resulting to a string of 32 1's.

See also: bindec().

后退 | 起点 | 前进
cosh | 上一级 | dechex


dechex

(PHP 3, PHP 4 )

dechex -- Decimal to hexadecimal

Description

string dechex ( int number)

Returns a string containing a hexadecimal representation of the given number argument. The largest number that can be converted is 2147483647 in decimal resulting to "7fffffff".

See also hexdec().

后退 | 起点 | 前进
decbin | 上一级 | decoct


decoct

(PHP 3, PHP 4 )

decoct -- Decimal to octal

Description

string decoct ( int number)

Returns a string containing an octal representation of the given number argument. The largest number that can be converted is 2147483647 in decimal resulting to "17777777777".

See also octdec().

后退 | 起点 | 前进
dechex | 上一级 | deg2rad


deg2rad

(PHP 3>= 3.0.4, PHP 4 )

deg2rad -- Converts the number in degrees to the radian equivalent

Description

float deg2rad ( float number)

This function converts number from degrees to the radian equivalent.

See also rad2deg().

后退 | 起点 | 前进
decoct | 上一级 | exp


exp

(PHP 3, PHP 4 )

exp -- e to the power of ...

Description

float exp ( float arg)

Returns e raised to the power of arg.

See also pow().

后退 | 起点 | 前进
deg2rad | 上一级 | expm1


expm1

(PHP 4 >= 4.1.0)

expm1 -- Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero

Description

float expm1 ( float number)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
exp | 上一级 | floor


floor

(PHP 3, PHP 4 )

floor -- Round fractions down

Description

float floor ( float value)

Returns the next lowest integer value by rounding down value if necessary. The return value of floor() is still of type float because the value range of float is usually bigger than that of integer.

例子 1. floor() example

echo floor(4.3);   // 4
echo floor(9.999); // 9

See also ceil() and round().

后退 | 起点 | 前进
expm1 | 上一级 | getrandmax


getrandmax

(PHP 3, PHP 4 )

getrandmax -- Show largest possible random value

Description

int getrandmax ( void)

Returns the maximum value that can be returned by a call to rand().

See also rand(), srand() and mt_getrandmax().

后退 | 起点 | 前进
floor | 上一级 | hexdec


hexdec

(PHP 3, PHP 4 )

hexdec -- Hexadecimal to decimal

Description

int hexdec ( string hex_string)

Returns the decimal equivalent of the hexadecimal number represented by the hex_string argument. hexdec() converts a hexadecimal string to a decimal number. The largest number that can be converted is 7fffffff or 2147483647 in decimal.

hexdec() will replace of any non-hexadecimal characters it encounters by 0. This way, all left zeros are ignored, but right zeros will be valued.

例子 1. hexdec() example

var_dump(hexdec("See"));
var_dump(hexdec("ee"));
// both prints "int(238)"

var_dump(hexdec("that"));
var_dump(hexdec("a0"));
// both prints int(160)

See also dechex().

后退 | 起点 | 前进
getrandmax | 上一级 | hypot


hypot

(PHP 4 >= 4.1.0)

hypot -- Returns sqrt( num1*num1 + num2*num2)

Description

float hypot ( float num1, float num2)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
hexdec | 上一级 | is_finite


is_finite

(PHP 4 >= 4.2.0)

is_finite --

Description

bool is_finite ( float val)

Returns TRUE if val is a legal finite number within the allowed range for a PHP float on this platform.

后退 | 起点 | 前进
hypot | 上一级 | is_infinite


is_infinite

(PHP 4 >= 4.2.0)

is_infinite --

Description

bool is_infinite ( float val)

Returns TRUE if val is infinite (positive or negative), like the result of log(0) or any value too big to fit into a float on this platform.

后退 | 起点 | 前进
is_finite | 上一级 | is_nan


is_nan

(PHP 4 >= 4.2.0)

is_nan --

Description

bool is_nan ( float val)

Returns TRUE if val is 'not a number', like the result of acos(1.01).

后退 | 起点 | 前进
is_infinite | 上一级 | lcg_value


lcg_value

(PHP 4 )

lcg_value -- Combined linear congruential generator

Description

float lcg_value ( void)

lcg_value() returns a pseudo random number in the range of (0, 1). The function combines two CGs with periods of 2^31 - 85 and 2^31 - 249. The period of this function is equal to the product of both primes.

后退 | 起点 | 前进
is_nan | 上一级 | log10


log10

(PHP 3, PHP 4 )

log10 -- 以10为底的对数

描述

float log10 ( float arg)

返回参数 arg 以10为底的对数。

后退 | 起点 | 前进
lcg_value | 上一级 | log1p


log1p

(PHP 4 >= 4.1.0)

log1p -- Returns log(1 + number), computed in a way that accurate even when the val ue of number is close to zero

Description

float log1p ( float number)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
log10 | 上一级 | log


log

(PHP 3, PHP 4 )

log -- 自然对数

描述

float log ( float arg)

返回参数 arg 的自然对数。

后退 | 起点 | 前进
log1p | 上一级 | max


max

(PHP 3, PHP 4 )

max -- Find highest value

Description

mixed max ( mixed arg1, mixed arg2, mixed argn)

max() returns the numerically highest of the parameter values.

If the first parameter is an array, max() returns the highest value in that array. If the first parameter is an integer, string or float, you need at least two parameters and max() returns the biggest of these values. You can compare an unlimited number of values.

If one or more of the values is a float, all the values will be treated as floats, and a float is returned. If none of the values is a float, all of them will be treated as integers, and an integer is returned.

后退 | 起点 | 前进
log | 上一级 | min


min

(PHP 3, PHP 4 )

min -- Find lowest value

Description

number min ( number arg1, number arg2 [, ...])

number min ( array numbers)

min() returns the numerically lowest of the parameter values.

In the first variant, you need at least two parameters and min() returns the lowest of these values. You can compare an unlimited number of values. If one of the variables is undefined, min() will fail.

In the second variant, min() returns the lowest value in numbers.

If one or more of the values is a float, all the values will be treated as floats, and a float is returned. If none of the values is a float, all of them will be treated as integers, and an integer is returned. Upon failure, min() returns NULL and an error of level E_WARNING is generated.

<?php
$a = 4;
$b = 9;
$c = 3;
$arr = array(99, 34, 11);

// You may want to implement your own error checking in
// case of failure (a variable may not be set)
if (!$min_value = @min($a, $b, $c)) {
    echo "Could not get min value, please try again.";
} else {
    echo "min value is $min_value";
}

print min($arr);  // 11

?>

See also max().

后退 | 起点 | 前进
max | 上一级 | mt_getrandmax


mt_getrandmax

(PHP 3>= 3.0.6, PHP 4 )

mt_getrandmax -- Show largest possible random value

Description

int mt_getrandmax ( void)

Returns the maximum value that can be returned by a call to mt_rand().

See also mt_rand(), mt_srand() and getrandmax().

后退 | 起点 | 前进
min | 上一级 | mt_rand


mt_rand

(PHP 3>= 3.0.6, PHP 4 )

mt_rand -- Generate a better random value

Description

int mt_rand ( [int min, int max])

Many random number generators of older libcs have dubious or unknown characteristics and are slow. By default, PHP uses the libc random number generator with the rand() function. mt_rand() function is a drop-in replacement for this. It uses a random number generator with known characteristics, the Mersenne Twister, which will produce random numbers that should be suitable for seeding some kinds of cryptography (see the home pages for details) and is four times faster than what the average libc provides. The Homepage of the Mersenne Twister can be found at http://www.math.keio.ac.jp/~matumoto/emt.html, and an optimized version of the MT source is available from http://www.scp.syr.edu/~marc/hawk/twister.html .

If called without the optional min, max arguments mt_rand() returns a pseudo-random value between 0 and RAND_MAX. If you want a random number between 5 and 15 (inclusive), for example, use mt_rand (5, 15).

In older versions of PHP, you had to seed the random number generator before use with mt_srand(). Since 4.2.0 this is no longer necessary.

注: In versions before 3.0.7 the meaning of max was range. To get the same results in these versions the short example should be mt_rand (5, 11) to get a random number between 5 and 15.

See also mt_srand(),
mt_getrandmax() and
rand().

后退 | 起点 | 前进
mt_getrandmax | 上一级 | mt_srand


mt_srand

(PHP 3>= 3.0.6, PHP 4 )

mt_srand -- Seed the better random number generator

Description

void mt_srand ( int seed)

Seeds the random number generator with seed.

// seed with microseconds
function make_seed() {
    list($usec, $sec) = explode(' ', microtime());
    return (float) $sec + ((float) $usec * 100000);
}
mt_srand(make_seed());
$randval = mt_rand();

注: Since PHP 4.2.0 it's no longer necessary to seed the random number generator before using it.

See also mt_rand(), mt_getrandmax() and srand().

后退 | 起点 | 前进
mt_rand | 上一级 | number_format


number_format

(PHP 3, PHP 4 )

number_format -- Format a number with grouped thousands

Description

string number_format ( float number [, int decimals [, string dec_point [, string thousands_sep]]])

number_format() returns a formatted version of number. This function accepts either one, two or four parameters (not three):

If only one parameter is given, number will be formatted without decimals, but with a comma (",") between every group of thousands.

If two parameters are given, number will be formatted with decimals decimals with a dot (".") in front, and a comma (",") between every group of thousands.

If all four parameters are given, number will be formatted with decimals decimals, dec_point instead of a dot (".") before the decimals and thousands_sep instead of a comma (",") between every group of thousands.

注: Only the first character of thousands_sep is used. For example, if you use foo as thousands_sep on the number 1000, number_format() will return 1f000.

例子 1. number_format() Example

For instance, French notation usually use two decimals, comma (',') as decimal separator, and space (' ') as thousand separator. This is achieved with this line :

<?php

    $number = 1234.56;

    // english notation (default)
    $english_format_number = number_format($number);
    // 1,234.56

    // French notation
    $nombre_format_francais = number_format($number, 2, ',', ' ');
    // 1 234,56

    $number = 1234.5678;

    // english notation without thousands seperator
    $english_format_number = number_format($number, 2, '.', '');
    // 1234.57

?>

See also: sprintf(), printf() and sscanf().

后退 | 起点 | 前进
mt_srand | 上一级 | octdec


octdec

(PHP 3, PHP 4 )

octdec -- Octal to decimal

Description

int octdec ( string octal_string)

Returns the decimal equivalent of the octal number represented by the octal_string argument. The largest number that can be converted is 17777777777 or 2147483647 in decimal.

See also decoct().

后退 | 起点 | 前进
number_format | 上一级 | pi


pi

(PHP 3, PHP 4 )

pi -- 得到圆周率值

描述

float pi ( void)

返回圆周率的近似值。返回值的 浮点数 的精度是由 php.ini 中的 precision 指示确定。默认值是 14。你也可以使用 M_PI 常量，该常量产生与 pi() 完全相同的结果。

echo pi(); // 3.1415926535898
echo M_PI; // 3.1415926535898

后退 | 起点 | 前进
octdec | 上一级 | pow


pow

(PHP 3, PHP 4 )

pow -- Exponential expression

Description

number pow ( number base, number exp)

Returns base raised to the power of exp. If possible, this function will return an integer.

If the power cannot be computed, a warning will be issued, and pow() will return FALSE.

例子 1. Some examples of pow()

<?php

var_dump( pow(2,8) ); // int(256)
echo pow(-1,20); // 1
echo pow(0, 0); // 1

echo pow(-1, 5.5); // error

?>

警告

In PHP 4.0.6 and earlier pow() always returned a float, and did not issue warnings.

See also exp() and sqrt().

后退 | 起点 | 前进
pi | 上一级 | rad2deg


rad2deg

(PHP 3>= 3.0.4, PHP 4 )

rad2deg -- Converts the radian number to the equivalent number in degrees

Description

float rad2deg ( float number)

This function converts number from radian to degrees.

See also deg2rad().

后退 | 起点 | 前进
pow | 上一级 | rand


rand

(PHP 3, PHP 4 )

rand -- Generate a random value

Description

int rand ( [int min, int max])

If called without the optional min, max arguments rand() returns a pseudo-random value between 0 and RAND_MAX. If you want a random number between 5 and 15 (inclusive), for example, use rand (5, 15).

In older versions of PHP, you had to seed the random number generator before use with srand(). Since 4.2.0 this is no longer necessary.

注: In versions before 3.0.7 the meaning of max was range. To get the same results in these versions the short example should be rand (5, 11) to get a random number between 5 and 15.

See also srand(),
getrandmax(),  and
mt_rand().

后退 | 起点 | 前进
rad2deg | 上一级 | round


round

(PHP 3, PHP 4 )

round -- Rounds a float

Description

float round ( float val [, int precision])

Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).

注意

PHP doesn't handle strings like "12,300.2" correctly by default. See converting from strings.

echo round(3.4);         // 3
echo round(3.5);         // 4
echo round(3.6);         // 4
echo round(3.6, 0);      // 4
echo round(1.95583, 2);  // 1.96
echo round(1241757, -3); // 1242000

注: The precision parameter is only available in PHP 4.

See also ceil() and floor().

后退 | 起点 | 前进
rand | 上一级 | sin


sin

(PHP 3, PHP 4 )

sin -- 正弦

描述

float sin ( float arg)

sin() 返回参数 arg 的正弦值。参数 arg 的单位为弧度。

<?php

// 返回值的精度由 &php.ini; 中的 precision 指示确定
print sin(deg2rad(60));  //  0.866025403 ...
print sin(60);           // -0.304810621 ...

?>

参见 asin(), cos(), tan() 和 deg2rad().

后退 | 起点 | 前进
round | 上一级 | sinh


sinh

(PHP 4 >= 4.1.0)

sinh -- Hyperbolic sine

Description

float sinh ( float arg)

Returns the hyperbolic sine of arg, defined as (exp(arg) - exp(-arg))/2.

See also sin(), asinh(), cos() and tan().

后退 | 起点 | 前进
sin | 上一级 | sqrt


sqrt

(PHP 3, PHP 4 )

sqrt -- Square root

Description

float sqrt ( float arg)

Returns the square root of arg.

<?php
// Precision depends on your precision directive
echo sqrt(9); // 3
echo sqrt(10); // 3.16227766 ...
?>

See also pow().

后退 | 起点 | 前进
sinh | 上一级 | srand


srand

(PHP 3, PHP 4 )

srand -- Seed the random number generator

Description

void srand ( int seed)

Seeds the random number generator with seed.

// seed with microseconds
function make_seed() {
    list($usec, $sec) = explode(' ', microtime());
    return (float) $sec + ((float) $usec * 100000);
}
srand(make_seed());
$randval = rand();

注: Since PHP 4.2.0 it's no longer necessary to seed the random number generator before using it.

See also rand(),
getrandmax() and
mt_srand().

后退 | 起点 | 前进
sqrt | 上一级 | tan


tan

(PHP 3, PHP 4 )

tan -- 正切

描述

float tan ( float arg)

tan() 返回参数 arg 的正切值。参数 arg 的单位为弧度。

参见 atan(), sin(), cos() 和 deg2rad().

后退 | 起点 | 前进
srand | 上一级 | tanh


tanh

(PHP 4 >= 4.1.0)

tanh -- Hyperbolic tangent

Description

float tanh ( float arg)

Returns the hyperbolic tangent of arg, defined as sinh(arg)/cosh(arg).

See also tan(), atanh(), sin() and cos().

后退 | 起点 | 前进
tan | 上一级 | Multi-Byte String Functions


Multi-Byte String Functions

PHP 手册
后退 前进

LII. Multi-Byte String Functions

介绍

There are many languages in which all characters can be expressed by single byte. Multi-byte character codes are used to express many characters for many languages. mbstring is developed to handle Japanese characters. However, many mbstring functions are able to handle character encoding other than Japanese.

A multi-byte character encoding represents single character with consecutive bytes. Some character encoding has shift(escape) sequences to start/end multi-byte character strings. Therefore, a multi-byte character string may be destroyed when it is divided and/or counted unless multi-byte character encoding safe method is used. This module provides multi-byte character safe string functions and other utility functions such as conversion functions.

Since PHP is basically designed for ISO-8859-1, some multi-byte character encoding does not work well with PHP. Therefore, it is important to set mbstring.internal_encoding to a character encoding that works with PHP.

PHP4 Character Encoding Requirements

  • Per byte encoding

  • Single byte characters in range of 00h-7fh which is compatible with ASCII

  • Multi-byte characters without 00h-7fh

These are examples of internal character encoding that works with PHP and does NOT work with PHP.

Character encodings work with PHP:
ISO-8859-*, EUC-JP, UTF-8

Character encodings do NOT work with PHP:
JIS, SJIS

Character encoding, that does not work with PHP, may be converted with mbstring's HTTP input/output conversion feature/function.

注: SJIS should not be used for internal encoding unless the reader is familiar with parser/compiler, character encoding and character encoding issues.

注: If you use databases with PHP, it is recommended that you use the same character encoding for both database and internal encoding for ease of use and better performance.

If you are using PostgreSQL, it supports character encoding that is different from backend character encoding. See the PostgreSQL manual for details.

安装

mbstring is an extended module. You must enable the module with the configure script. Refer to the Install section for details.

The following configure options are related to the mbstring module.

  • --enable-mbstring : Enable mbstring functions. This option is required to use mbstring functions.

    注: As of PHP 4.3.0, the option --enable-mbstring will be enabled by default and replaced with --with-mbstring[=LANG] to support Chinese, Korean and Russian language support. Japanese character encoding is supported by default. If --with-mbstring=cn is used, simplified chinese encoding will be supported. If --with-mbstring=tw is used, traditional chinese encoding will be supported. If --with-mbstring=kr is used, korean encoding will be supported. If --with-mbstring=ru is used, russian encoding will be supported. If --with-mbstring=all is added, all supported character encoding in mbstring will be enabled, but the binary size of PHP will be maximized because of huge Unicode character maps. Note that Chinese, Korean and Russian encoding is experimentally supported in PHP 4.3.0.

  • --enable-mbstr-enc-trans : Enable HTTP input character encoding conversion using mbstring conversion engine. If this feature is enabled, HTTP input character encoding may be converted to mbstring.internal_encoding automatically.

    注: As of PHP 4.3.0, the option --enable-mbstr-enc-trans will be eliminated and replaced with mbstring.encoding_translation. HTTP input character encoding conversion is enabled when this is set to On (the default is Off).

  • --enable-mbregex : Enable regular expression functions with multibyte character support.

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. Multi-Byte String configuration options

Name | Default | Changeable
mbstring.language | NULL | PHP_INI_ALL
mbstring.detect_order | NULL | PHP_INI_ALL
mbstring.http_input | NULL | PHP_INI_ALL
mbstring.http_output | NULL | PHP_INI_ALL
mbstring.internal_encoding | NULL | PHP_INI_ALL
mbstring.script_encoding | NULL | PHP_INI_ALL
mbstring.substitute_character | NULL | PHP_INI_ALL
mbstring.func_overload | "0" | PHP_INI_SYSTEM
mbstring.encoding_translation | "0" | PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

Here is a short explanation of the configuration directives.

  • mbstring.language defines default language used in mbstring. Note that this option defines mbstring.interanl_encoding and mbstring.interanl_encoding should be placed after mbstring.language in php.ini

  • mbstring.encoding_translation enables HTTP input character encoding detection and translation into internal chatacter encoding.

  • mbstring.internal_encoding defines default internal character encoding.

  • mbstring.http_input defines default HTTP input character encoding.

  • mbstring.http_output defines default HTTP output character encoding.

  • mbstring.detect_order defines default character code detection order. See also mb_detect_order().

  • mbstring.substitute_character defines character to substitute for invalid character encoding.

  • mbstring.func_overloadoverload(replace) single byte functions by mbstring functions. mail(), ereg(), etc. are overloaded by mb_send_mail(), mb_ereg(), etc. Possible values are 0, 1, 2, 4 or a combination of them. For example, 7 for overload everything. 0: No overload, 1: Overload mail() function, 2: Overload str*() functions, 4: Overload ereg*() functions.

Web Browsers are supposed to use the same character encoding when submitting form. However, browsers may not use the same character encoding. See mb_http_input() to detect character encoding used by browsers.

If enctype is set to multipart/form-data in HTML forms, mbstring does not convert character encoding in POST data. The user must convert them in the script, if conversion is needed.

Although, browsers are smart enough to detect character encoding in HTML. charset is better to be set in HTTP header. Change default_charset according to character encoding.

例子 1. php.ini setting example

; Set default language
mbstring.language        = English; Set default language to English (default)
mbstring.language        = Japanese; Set default language to Japanese

;; Set default internal encoding
;; Note: Make sure to use character encoding works with PHP
mbstring.internal_encoding    = UTF-8  ; Set internal encoding to UTF-8

;; HTTP input encoding translation is enabled.
mbstring.encoding_translation = On

;; Set default HTTP input character encoding
;; Note: Script cannot change http_input setting.
mbstring.http_input           = pass    ; No conversion.
mbstring.http_input           = auto    ; Set HTTP input to auto
                                ; "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS"
mbstring.http_input           = SJIS    ; Set HTTP2 input to  SJIS
mbstring.http_input           = UTF-8,SJIS,EUC-JP ; Specify order

;; Set default HTTP output character encoding
mbstring.http_output          = pass    ; No conversion
mbstring.http_output          = UTF-8   ; Set HTTP output encoding to UTF-8

;; Set default character encoding detection order
mbstring.detect_order         = auto    ; Set detect order to auto
mbstring.detect_order         = ASCII,JIS,UTF-8,SJIS,EUC-JP ; Specify order

;; Set default substitute character
mbstring.substitute_character = 12307   ; Specify Unicode value
mbstring.substitute_character = none    ; Do not print character
mbstring.substitute_character = long    ; Long Example: U+3000,JIS+7E7E

例子 2. php.ini setting for EUC-JP users

;; Disable Output Buffering
output_buffering      = Off

;; Set HTTP header charset
default_charset       = EUC-JP

;; Set default language to Japanese
mbstring.language = Japanese

;; HTTP input encoding translation is enabled.
mbstring.encoding_translation = On

;; Set HTTP input encoding conversion to auto
mbstring.http_input   = auto

;; Convert HTTP output to EUC-JP
mbstring.http_output  = EUC-JP

;; Set internal encoding to EUC-JP
mbstring.internal_encoding = EUC-JP

;; Do not print invalid characters
mbstring.substitute_character = none

例子 3. php.ini setting for SJIS users

;; Enable Output Buffering
output_buffering     = On

;; Set mb_output_handler to enable output conversion
output_handler       = mb_output_handler

;; Set HTTP header charset
default_charset      = Shift_JIS

;; Set default language to Japanese
mbstring.language = Japanese

;; Set http input encoding conversion to auto
mbstring.http_input  = auto

;; Convert to SJIS
mbstring.http_output = SJIS

;; Set internal encoding to EUC-JP
mbstring.internal_encoding = EUC-JP

;; Do not print invalid characters
mbstring.substitute_character = none

资源类型

该扩展模块未定义任何资源类型。

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

MB_OVERLOAD_MAIL (integer)

MB_OVERLOAD_STRING (integer)

MB_OVERLOAD_REGEX (integer)

HTTP Input and Output

HTTP input/output character encoding conversion may convert binary data also. Users are supposed to control character encoding conversion if binary data is used for HTTP input/output.

If enctype for HTML form is set to multipart/form-data, mbstring does not convert character encoding in POST data. If it is the case, strings are needed to be converted to internal character encoding.

  • HTTP Input

    There is no way to control HTTP input character conversion from PHP script. To disable HTTP input character conversion, it has to be done in php.ini.

    例子 4. Disable HTTP input conversion in php.ini

    ;; Disable HTTP Input conversion
mbstring.http_input = pass
;; Disable HTTP Input conversion (PHP 4.3.0 or higher)
mbstring.encoding_translation = Off

    When using PHP as an Apache module, it is possible to override PHP ini setting per Virtual Host in httpd.conf or per directory with .htaccess. Refer to the Configuration section and Apache Manual for details.

  • HTTP Output

    There are several ways to enable output character encoding conversion. One is using php.ini, another is using ob_start() with mb_output_handler() as ob_start callback function.

    注: For PHP3-i18n users, mbstring's output conversion differs from PHP3-i18n. Character encoding is converted using output buffer.

例子 5. php.ini setting example

;; Enable output character encoding conversion for all PHP pages

;; Enable Output Buffering
output_buffering    = On

;; Set mb_output_handler to enable output conversion
output_handler      = mb_output_handler

例子 6. Script example

<?php

// Enable output character encoding conversion only for this page

// Set HTTP output character encoding to SJIS
mb_http_output('SJIS');

// Start buffering and specify "mb_output_handler" as
// callback function
ob_start('mb_output_handler');

?>

Supported Character Encodings

Currently, the following character encoding is supported by the mbstring module. Character encoding may be specified for mbstring functions' encoding parameter.

The following character encoding is supported in this PHP extension:

UCS-4, UCS-4BE, UCS-4LE, UCS-2, UCS-2BE, UCS-2LE, UTF-32, UTF-32BE, UTF-32LE, UCS-2LE, UTF-16, UTF-16BE, UTF-16LE, UTF-8, UTF-7, ASCII, EUC-JP, SJIS, eucJP-win, SJIS-win, ISO-2022-JP, JIS, ISO-8859-1, ISO-8859-2, ISO-8859-3, ISO-8859-4, ISO-8859-5, ISO-8859-6, ISO-8859-7, ISO-8859-8, ISO-8859-9, ISO-8859-10, ISO-8859-13, ISO-8859-14, ISO-8859-15, byte2be, byte2le, byte4be, byte4le, BASE64, 7bit, 8bit and UTF7-IMAP.

As of PHP 4.3.0, the following character encoding support will be added experimentaly : EUC-CN, CP936, HZ, EUC-TW, CP950, BIG-5, EUC-KR, UHC (CP949), ISO-2022-KR, Windows-1251 (CP1251), Windows-1252 (CP1252), CP866, KOI8-R.

php.ini entry, which accepts encoding name, accepts "auto" and "pass" also. mbstring functions, which accepts encoding name, and accepts "auto".

If "pass" is set, no character encoding conversion is performed.

If "auto" is set, it is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS".

See also mb_detect_order()

注: "Supported character encoding" does not mean that it works as internal character code.

Overloading PHP string functions with multi byte string functions

Because almost PHP application written for language using single-byte character encoding, there are some difficulties for multibyte string handling including japanese. Almost PHP string functions such as substr() do not support multibyte string.

Multibyte extension (mbstring) has some PHP string functions with multibyte support (ex. substr() supports mb_substr()).

Multibyte extension (mbstring) also supports 'function overloading' to add multibyte string functionality without code modification. Using function overloading, some PHP string functions will be oveloaded multibyte string functions. For example, mb_substr() is called instead of substr() if function overloading is enabled. Function overload makes easy to port application supporting only single-byte encoding for multibyte application.

mbstring.func_overload in php.ini should be set some positive value to use function overloading. The value should specify the category of overloading functions, sbould be set 1 to enable mail function overloading. 2 to enable string functions, 4 to regular expression functions. For example, if is set for 7, mail, strings, regex functions should be overloaded. The list of overloaded functions are shown in below.

表格 2. Functions to be overloaded

value of mbstring.func_overload | original function | overloaded function
1 | mail() | mb_send_mail()
2 | strlen() | mb_strlen()
2 | strpos() | mb_strpos()
2 | strrpos() | mb_strrpos()
2 | substr() | mb_substr()
4 | ereg() | mb_ereg()
4 | eregi() | mb_eregi()
4 | ereg_replace() | mb_ereg_replace()
4 | eregi_replace() | mb_eregi_replace()
4 | split() | mb_split()

Basics of Japanese multi-byte characters

Most Japanese characters need more than 1 byte per character. In addition, several character encoding schemas are used under a Japanese environment. There are EUC-JP, Shift_JIS(SJIS) and ISO-2022-JP(JIS) character encoding. As Unicode becomes popular, UTF-8 is used also. To develop Web applications for a Japanese environment, it is important to use the character set for the task in hand, whether HTTP input/output, RDBMS and E-mail.

  • Storage for a character can be up to six bytes

  • A multi-byte character is usually twice of the width compared to single-byte characters. Wider characters are called "zen-kaku" - meaning full width, narrower characters are called "han-kaku" - meaning half width. "zen-kaku" characters are usually fixed width.

  • Some character encoding defines shift(escape) sequence for entering/exiting multi-byte character strings.

  • ISO-2022-JP must be used for SMTP/NNTP.

  • "i-mode" web site is supposed to use SJIS.

References

Multi-byte character encoding and its related issues are very complex. It is impossible to cover in sufficient detail here. Please refer to the following URLs and other resources for further readings.

  • Unicode/UTF/UCS/etc

    http://www.unicode.org/

  • Japanese/Korean/Chinese character information

    ftp://ftp.ora.com/pub/examples/nutshell/ujip/doc/cjk.inf

目录
mb_convert_encoding — Convert character encoding
mb_convert_kana — Convert "kana" one from another ("zen-kaku" ,"han-kaku" and more)
mb_convert_variables — Convert character code in variable(s)
mb_decode_mimeheader — Decode string in MIME header field
mb_decode_numericentity — Decode HTML numeric string reference to character
mb_detect_encoding — Detect character encoding
mb_detect_order — Set/Get character encoding detection order
mb_encode_mimeheader — Encode string for MIME header
mb_encode_numericentity — Encode character to HTML numeric string reference
mb_ereg_match — Regular expression match for multibyte string
mb_ereg_replace — Replace regular expression with multibyte support
mb_ereg_search_getpos — Returns start point for next regular expression match
mb_ereg_search_getregs — Retrive the result from the last multibyte regular expression match
mb_ereg_search_init — Setup string and regular expression for multibyte regular expression match
mb_ereg_search_pos — Return position and length of matched part of multibyte regular expression for predefined multibyte string
mb_ereg_search_regs — Returns the matched part of multibyte regular expression
mb_ereg_search_setpos — Set start point of next regular expression match
mb_ereg_search — Multibyte regular expression match for predefined multibyte string
mb_ereg — Regular expression match with multibyte support
mb_eregi_replace — Replace regular expression with multibyte support ignoring case
mb_eregi — Regular expression match ignoring case with multibyte support
mb_get_info — Get internal settings of mbstring
mb_http_input — Detect HTTP input character encoding
mb_http_output — Set/Get HTTP output character encoding
mb_internal_encoding — Set/Get internal character encoding
mb_language — Set/Get current language
mb_output_handler — Callback function converts character encoding in output buffer
mb_parse_str — Parse GET/POST/COOKIE data and set global variable
mb_preferred_mime_name — Get MIME charset string
mb_regex_encoding — Returns current encoding for multibyte regex as string
mb_send_mail — Send encoded mail.
mb_split — Split multibyte string using regular expression
mb_strcut — Get part of string
mb_strimwidth — Get truncated string with specified width
mb_strlen — Get string length
mb_strpos — Find position of first occurrence of string in a string
mb_strrpos — Find position of last occurrence of a string in a string
mb_strwidth — Return width of string
mb_substitute_character — Set/Get substitution character
mb_substr — Get part of string

后退 | 起点 | 前进
tanh | 上一级 | mb_convert_encoding


mb_convert_encoding

(PHP 4 >= 4.0.6)

mb_convert_encoding -- Convert character encoding

Description

string mb_convert_encoding ( string str, string to-encoding [, mixed from-encoding])

mb_convert_encoding() converts character encoding of string str from from-encoding to to-encoding.

str : String to be converted.

from-encoding is specified by character code name before conversion. it can be array or string - comma separated enumerated list. If it is not specified, the internal encoding will be used.

例子 1. mb_convert_encoding() example

/* Convert internal character encoding to SJIS */
$str = mb_convert_encoding($str, "SJIS");

/* Convert EUC-JP to UTF-7 */
$str = mb_convert_encoding($str, "UTF-7", "EUC-JP");

/* Auto detect encoding from JIS, eucjp-win, sjis-win, then convert str to UCS-2LE */
$str = mb_convert_encoding($str, "UCS-2LE", "JIS, eucjp-win, sjis-win");

/* "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS" */
$str = mb_convert_encoding($str, "EUC-JP", "auto");

See also: mb_detect_order().

后退 | 起点 | 前进
Multi-Byte String Functions | 上一级 | mb_convert_kana


mb_convert_kana

(PHP 4 >= 4.0.6)

mb_convert_kana -- Convert "kana" one from another ("zen-kaku" ,"han-kaku" and more)

Description

string mb_convert_kana ( string str, string option [, mixed encoding])

mb_convert_kana() performs "han-kaku" - "zen-kaku" conversion for string str. It returns converted string. This function is only useful for Japanese.

option is conversion option. Default value is "KV".

encoding is character encoding. If it is omitted, internal character encoding is used.

Applicable Conversion Options

       option : Specify with conversion of following options. Default "KV"
       "r" :  Convert "zen-kaku" alphabets to "han-kaku"
       "R" :  Convert "han-kaku" alphabets to "zen-kaku"
       "n" :  Convert "zen-kaku" numbers to "han-kaku"
       "N" :  Convert "han-kaku" numbers to "zen-kaku"
       "a" :  Convert "zen-kaku" alphabets and numbers to "han-kaku"
       "A" :  Convert "zen-kaku" alphabets and numbers to "han-kaku"
       (Characters included in "a", "A" options are
       U+0021 - U+007E excluding U+0022, U+0027, U+005C, U+007E)
       "s" :  Convert "zen-kaku" space to "han-kaku" (U+3000 -> U+0020)
       "S" :  Convert "han-kaku" space to "zen-kaku" (U+0020 -> U+3000)
       "k" :  Convert "zen-kaku kata-kana" to "han-kaku kata-kana"
       "K" :  Convert "han-kaku kata-kana" to "zen-kaku kata-kana"
       "h" :  Convert "zen-kaku hira-gana" to "han-kaku kata-kana"
       "H" :  Convert "han-kaku kata-kana" to "zen-kaku hira-gana"
       "c" :  Convert "zen-kaku kata-kana" to "zen-kaku hira-gana"
       "C" :  Convert "zen-kaku hira-gana" to "zen-kaku kata-kana"
       "V" :  Collapse voiced sound notation and convert them into a character. Use with "K","H"

例子 1. mb_convert_kana() example

/* Convert all "kana" to "zen-kaku" "kata-kana" */
$str = mb_convert_kana($str, "KVC");

/* Convert "han-kaku" "kata-kana" to "zen-kaku" "kata-kana"
   and "zen-kaku" alpha-numeric to "han-kaku" */
$str = mb_convert_kana($str, "KVa");

后退 | 起点 | 前进
mb_convert_encoding | 上一级 | mb_convert_variables


mb_convert_variables

(PHP 4 >= 4.0.6)

mb_convert_variables -- Convert character code in variable(s)

Description

string mb_convert_variables ( string to-encoding, mixed from-encoding, mixed vars)

mb_convert_variables() convert character encoding of variables vars in encoding from-encoding to encoding to-encoding. It returns character encoding before conversion for success, FALSE for failure.

mb_convert_variables() join strings in Array or Object to detect encoding, since encoding detection tends to fail for short strings. Therefore, it is impossible to mix encoding in single array or object.

It from-encoding is specified by array or comma separated string, it tries to detect encoding from from-coding. When encoding is omitted, detect_order is used.

vars (3rd and larger) is reference to variable to be converted. String, Array and Object are accepted. mb_convert_variables() assumes all parameters have the same encoding.

例子 1. mb_convert_variables() example

/* Convert variables $post1, $post2 to internal encoding */
$interenc = mb_internal_encoding();
$inputenc = mb_convert_variables($interenc, "ASCII,UTF-8,SJIS-win", $post1, $post2);

后退 | 起点 | 前进
mb_convert_kana | 上一级 | mb_decode_mimeheader


mb_decode_mimeheader

(PHP 4 >= 4.0.6)

mb_decode_mimeheader -- Decode string in MIME header field

Description

string mb_decode_mimeheader ( string str)

mb_decode_mimeheader() decodes encoded-word string str in MIME header.

It returns decoded string in internal character encoding.

See also mb_encode_mimeheader().

后退 | 起点 | 前进
mb_convert_variables | 上一级 | mb_decode_numericentity


mb_decode_numericentity

(PHP 4 >= 4.0.6)

mb_decode_numericentity -- Decode HTML numeric string reference to character

Description

string mb_decode_numericentity ( string str, array convmap [, string encoding])

Convert numeric string reference of string str in specified block to character. It returns converted string.

array is array to specifies code area to convert.

encoding is character encoding. If it is omitted, internal character encoding is used.

例子 1. convmap example

$convmap = array (
   int start_code1, int end_code1, int offset1, int mask1,
   int start_code2, int end_code2, int offset2, int mask2,
   ........
   int start_codeN, int end_codeN, int offsetN, int maskN );
// Specify Unicode value for start_codeN and end_codeN
// Add offsetN to value and take bit-wise 'AND' with maskN,
// then convert value to numeric string reference.

See also: mb_encode_numericentity().

后退 | 起点 | 前进
mb_decode_mimeheader | 上一级 | mb_detect_encoding


mb_detect_encoding

(PHP 4 >= 4.0.6)

mb_detect_encoding -- Detect character encoding

Description

string mb_detect_encoding ( string str [, mixed encoding-list])

mb_detect_encoding() detects character encoding in string str. It returns detected character encoding.

encoding-list is list of character encoding. Encoding order may be specified by array or comma separated list string.

If encoding_list is omitted, detect_order is used.

例子 1. mb_detect_encoding() example

/* Detect character encoding with current detect_order */
echo mb_detect_encoding($str);

/* "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS" */
echo mb_detect_encoding($str, "auto");

/* Specify encoding_list character encoding by comma separated list */
echo mb_detect_encoding($str, "JIS, eucjp-win, sjis-win");

/* Use array to specify encoding_list  */
$ary[] = "ASCII";
$ary[] = "JIS";
$ary[] = "EUC-JP";
echo mb_detect_encoding($str, $ary);

See also: mb_detect_order().

后退 | 起点 | 前进
mb_decode_numericentity | 上一级 | mb_detect_order


mb_detect_order

(PHP 4 >= 4.0.6)

mb_detect_order -- Set/Get character encoding detection order

Description

array mb_detect_order ( [mixed encoding-list])

mb_detect_order() sets automatic character encoding detection order to encoding-list. It returns TRUE for success, FALSE for failure.

encoding-list is array or comma separated list of character encoding. ("auto" is expanded to "ASCII, JIS, UTF-8, EUC-JP, SJIS")

If encoding-list is omitted, it returns current character encoding detection order as array.

This setting affects mb_detect_encoding() and mb_send_mail().

注: mbstring currently implements following encoding detection filters. If there is a invalid byte sequence for following encoding, encoding detection will fail.

注: UTF-8, UTF-7, ASCII, EUC-JP,SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP

For ISO-8859-*, mbstring always detects as ISO-8859-*.

For UTF-16, UTF-32, UCS2 and UCS4, encoding detection will fail always.

例子 1. Useless detect order example

; Always detect as ISO-8859-1
detect_order = ISO-8859-1, UTF-8

; Always detect as UTF-8, since ASCII/UTF-7 values are
; valid for UTF-8
detect_order = UTF-8, ASCII, UTF-7

例子 2. mb_detect_order() examples

/* Set detection order by enumerated list */
mb_detect_order("eucjp-win,sjis-win,UTF-8");

/* Set detection order by array */
$ary[] = "ASCII";
$ary[] = "JIS";
$ary[] = "EUC-JP";
mb_detect_order($ary);

/* Display current detection order */
echo implode(", ", mb_detect_order());

See also mb_internal_encoding(),
mb_http_input(),
mb_http_output()
mb_send_mail().

后退 | 起点 | 前进
mb_detect_encoding | 上一级 | mb_encode_mimeheader


mb_encode_mimeheader

(PHP 4 >= 4.0.6)

mb_encode_mimeheader -- Encode string for MIME header

Description

string mb_encode_mimeheader ( string str [, string charset [, string transfer-encoding [, string linefeed]]])

mb_encode_mimeheader() converts string str to encoded-word for header field. It returns converted string in ASCII encoding.

charset is character encoding name. Default is ISO-2022-JP.

transfer-encoding is transfer encoding. It should be one of "B" (Base64) or "Q" (Quoted-Printable). Default is "B".

linefeed is end of line marker. Default is "\r\n" (CRLF).

例子 1. mb_convert_kana() example

$name = ""; // kanji
$mbox = "kru";
$doma = "gtinn.mon";
$addr = mb_encode_mimeheader($name, "UTF-7", "Q") . " <" . $mbox . "@" . $doma . ">";
echo $addr;

See also mb_decode_mimeheader().

后退 | 起点 | 前进
mb_detect_order | 上一级 | mb_encode_numericentity


mb_encode_numericentity

(PHP 4 >= 4.0.6)

mb_encode_numericentity -- Encode character to HTML numeric string reference

Description

string mb_encode_numericentity ( string str, array convmap [, string encoding])

mb_encode_numericentity() converts specified character codes in string str from HTML numeric character reference to character code. It returns converted string.

array is array specifies code area to convert.

encoding is character encoding.

例子 1. convmap example

$convmap = array (
 int start_code1, int end_code1, int offset1, int mask1,
 int start_code2, int end_code2, int offset2, int mask2,
 ........
 int start_codeN, int end_codeN, int offsetN, int maskN );
// Specify Unicode value for start_codeN and end_codeN
// Add offsetN to value and take bit-wise 'AND' with maskN, then
// it converts value to numeric string reference.

例子 2. mb_encode_numericentity() example

/* Convert Left side of ISO-8859-1 to HTML numeric character reference */
$convmap = array(0x80, 0xff, 0, 0xff);
$str = mb_encode_numericentity($str, $convmap, "ISO-8859-1");

/* Convert user defined SJIS-win code in block 95-104 to numeric
   string reference */
$convmap = array(
       0xe000, 0xe03e, 0x1040, 0xffff,
       0xe03f, 0xe0bb, 0x1041, 0xffff,
       0xe0bc, 0xe0fa, 0x1084, 0xffff,
       0xe0fb, 0xe177, 0x1085, 0xffff,
       0xe178, 0xe1b6, 0x10c8, 0xffff,
       0xe1b7, 0xe233, 0x10c9, 0xffff,
       0xe234, 0xe272, 0x110c, 0xffff,
       0xe273, 0xe2ef, 0x110d, 0xffff,
       0xe2f0, 0xe32e, 0x1150, 0xffff,
       0xe32f, 0xe3ab, 0x1151, 0xffff );
$str = mb_encode_numericentity($str, $convmap, "sjis-win");

See also: mb_decode_numericentity().

后退 | 起点 | 前进
mb_encode_mimeheader | 上一级 | mb_ereg_match


mb_ereg_match

(PHP 4 >= 4.2.0)

mb_ereg_match -- Regular expression match for multibyte string

Description

bool mb_ereg_match ( string pattern, string string [, string option])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

mb_ereg_match() returns TRUE if string matches regular expression pattern, FALSE if not.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

注: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg().

后退 | 起点 | 前进
mb_encode_numericentity | 上一级 | mb_ereg_replace


mb_ereg_replace

(PHP 4 >= 4.2.0)

mb_ereg_replace -- Replace regular expression with multibyte support

Description

string mb_ereg_replace ( string pattern, string replacement, string string [, array option])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

mb_ereg_replace() scans string for matches to pattern, then replaces the matched text with replacement and returns the result string or FALSE on error. Multibyte character can be used in pattern.

Matching condition can be set by option parameter. If i is specified for this parameter, the case will be ignored. If x is specified, white space will be ignored. If m is specified, match will be executed in multiline mode and line break will be included in '.'. If p is specified, match will be executed in POSIX mode, line break will be considered as normal character. If e is specified, replacement string will be evaluated as PHP expression.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

注: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_eregi_replace().

后退 | 起点 | 前进
mb_ereg_match | 上一级 | mb_ereg_search_getpos


mb_ereg_search_getpos

(PHP 4 >= 4.2.0)

mb_ereg_search_getpos -- Returns start point for next regular expression match

Description

array mb_ereg_search_getpos ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

mb_ereg_search_getpos() returns
the point to start regular expression match for
mb_ereg_search(),
mb_ereg_search_pos(),
mb_ereg_search_regs(). The position is
represented by bytes from the head of string.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

注: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg_search_setpos().

后退 | 起点 | 前进
mb_ereg_replace | 上一级 | mb_ereg_search_getregs


mb_ereg_search_getregs

(PHP 4 >= 4.2.0)

mb_ereg_search_getregs -- Retrive the result from the last multibyte regular expression match

Description

array mb_ereg_search_getregs ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

mb_ereg_search_getregs() returns an array including the sub-string of matched part by last mb_ereg_search(), mb_ereg_search_pos(), mb_ereg_search_regs(). If there are some maches, the first element will have the matched sub-string, the second element will have the first part grouped with brackets, the third element will have the second part grouped with brackets, and so on. It returns FALSE on error;

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

注: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg_search_init().

后退 | 起点 | 前进
mb_ereg_search_getpos | 上一级 | mb_ereg_search_init


mb_ereg_search_init

(PHP 4 >= 4.2.0)

mb_ereg_search_init -- Setup string and regular expression for multibyte regular expression match

Description

array mb_ereg_search_init ( string string [, string pattern [, string option]])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

mb_ereg_search_init() sets string and pattern for multibyte regular expression. These values are used for mb_ereg_search(), mb_ereg_search_pos(), mb_ereg_search_regs(). It returns TRUE for success, FALSE for error.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

注: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg_search_regs().

后退 | 起点 | 前进
mb_ereg_search_getregs | 上一级 | mb_ereg_search_pos


mb_ereg_search_pos

(PHP 4 >= 4.2.0)

mb_ereg_search_pos -- Return position and length of matched part of multibyte regular expression for predefined multibyte string

Description

array mb_ereg_search_pos ( [string pattern [, string option]])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

mb_ereg_search_pos() returns an array including position of matched part for multibyte regular expression. The first element of the array will be the beggining of matched part, the second element will be length (bytes) of matched part. It returns FALSE on error.

The string for match is specified by mb_ereg_search_init(). It it is not specified, the previous one will be used.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

注: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg_search_init().

后退 | 起点 | 前进
mb_ereg_search_init | 上一级 | mb_ereg_search_regs


mb_ereg_search_regs

(PHP 4 >= 4.2.0)

mb_ereg_search_regs -- Returns the matched part of multibyte regular expression

Description

array mb_ereg_search_regs ( [string pattern [, string option]])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

mb_ereg_search_regs() executes the multibyte regular expression match, and if there are some matched part, it returns an array including substring of matched part as first element, the first grouped part with brackets as second element, the second grouped part as third element, and so on. It returns FALSE on error.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

注: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg_search_init().

后退 | 起点 | 前进
mb_ereg_search_pos | 上一级 | mb_ereg_search_setpos


mb_ereg_search_setpos

(PHP 4 >= 4.2.0)

mb_ereg_search_setpos -- Set start point of next regular expression match

Description

array mb_ereg_search_setpos ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

mb_ereg_search_setpos() sets the starting point of match for mb_ereg_search().

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

注: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg_search_init().

后退 | 起点 | 前进
mb_ereg_search_regs | 上一级 | mb_ereg_search


mb_ereg_search

(PHP 4 >= 4.2.0)

mb_ereg_search -- Multibyte regular expression match for predefined multibyte string

Description

bool mb_ereg_search ( [string pattern [, string option]])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

mb_ereg_search() returns TRUE if the multibyte string matches with the regular expression, FALSE for otherwise. The string for matching is set by mb_ereg_search_init(). If pattern is not specified, the previous one is used.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

注: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg_search_init().

后退 | 起点 | 前进
mb_ereg_search_setpos | 上一级 | mb_ereg


mb_ereg

(PHP 4 >= 4.2.0)

mb_ereg -- Regular expression match with multibyte support

Description

int mb_ereg ( string pattern, string string [, array regs])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

mb_ereg() executes the regular expression match with multibyte support, and returns 1 if matches are found. If the optional third parameter was specified, the function returns the byte length of matched part, and therarray regs will contain the substring of matched string. The functions returns 1 if it matches with the empty string. It no matche found or error happend, FALSE will be returned.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

注: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_eregi()

后退 | 起点 | 前进
mb_ereg_search | 上一级 | mb_eregi_replace


mb_eregi_replace

(PHP 4 >= 4.2.0)

mb_eregi_replace -- Replace regular expression with multibyte support ignoring case

Description

string mb_eregi_replace ( string pattern, string replace, string string)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

mb_ereg_replace() scans string for matches to pattern, then replaces the matched text with replacement and returns the result string or FALSE on error. Multibyte character can be used in pattern. The case will be ignored.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

注: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg_replace().

后退 | 起点 | 前进
mb_ereg | 上一级 | mb_eregi


mb_eregi

(PHP 4 >= 4.2.0)

mb_eregi -- Regular expression match ignoring case with multibyte support

Description

int mb_eregi ( string pattern, string string [, array regs])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

mb_eregi() executes the regular expression match with multibyte support, and returns 1 if matches are found. This function ignore case. If the optional third parameter was specified, the function returns the byte length of matched part, and therarray regs will contain the substring of matched string. The functions returns 1 if it matches with the empty string. It no matche found or error happend, FALSE will be returned.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

注: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg().

后退 | 起点 | 前进
mb_eregi_replace | 上一级 | mb_get_info


mb_get_info

(PHP 4 >= 4.2.0)

mb_get_info -- Get internal settings of mbstring

Description

string mb_get_info ( [string type])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

mb_get_info() returns internal setting parameter of mbstring.

If type isn't specified or is specified to "all", an array having the elements "internal_encoding", "http_output", "http_input", "func_overload" will be returned.

If type is specified for "http_output", "http_input", "internal_encoding", "func_overload", the specified setting parameter will be returned.

See also mb_internal_encoding(), mb_http_output().

后退 | 起点 | 前进
mb_eregi | 上一级 | mb_http_input


mb_http_input

(PHP 4 >= 4.0.6)

mb_http_input -- Detect HTTP input character encoding

Description

string mb_http_input ( [string type])

mb_http_input() returns result of HTTP input character encoding detection.

type: Input string specifies input type. "G" for GET, "P" for POST, "C" for COOKIE. If type is omitted, it returns last input type processed.

Return Value: Character encoding name. If mb_http_input() does not process specified HTTP input, it returns FALSE.

See also mb_internal_encoding(),
mb_http_output(),
mb_detect_order().

后退 | 起点 | 前进
mb_get_info | 上一级 | mb_http_output


mb_http_output

(PHP 4 >= 4.0.6)

mb_http_output -- Set/Get HTTP output character encoding

Description

string mb_http_output ( [string encoding])

If encoding is set, mb_http_output() sets HTTP output character encoding to encoding. Output after this function is converted to encoding. mb_http_output() returns TRUE for success and FALSE for failure.

If encoding is omitted, mb_http_output() returns current HTTP output character encoding.

See also mb_internal_encoding(),
mb_http_input(),
mb_detect_order().

后退 | 起点 | 前进
mb_http_input | 上一级 | mb_internal_encoding


mb_internal_encoding

(PHP 4 >= 4.0.6)

mb_internal_encoding -- Set/Get internal character encoding

Description

string mb_internal_encoding ( [string encoding])

mb_internal_encoding() sets internal character encoding to encoding If parameter is omitted, it returns current internal encoding.

encoding is used for HTTP input character encoding conversion, HTTP output character encoding conversion and default character encoding for string functions defined by mbstring module.

encoding: Character encoding name

Return Value: If encoding is set,mb_internal_encoding() returns TRUE for success, otherwise returns FALSE. If encoding is omitted, it returns current character encoding name.

例子 1. mb_internal_encoding() example

/* Set internal character encoding to UTF-8 */
mb_internal_encoding("UTF-8");

/* Display current internal character encoding */
echo mb_internal_encoding();

See also mb_http_input(),
mb_http_output(),
mb_detect_order().

后退 | 起点 | 前进
mb_http_output | 上一级 | mb_language


mb_language

(PHP 4 >= 4.0.6)

mb_language -- Set/Get current language

Description

string mb_language ( [string language])

mb_language() sets language. If language is omitted, it returns current language as string.

language setting is used for encoding e-mail messages. Valid languages are "Japanese", "ja","English","en" and "uni" (UTF-8). mb_send_mail() uses this setting to encode e-mail.

Language and its setting is ISO-2022-JP/Base64 for Japanese, UTF-8/Base64 for uni, ISO-8859-1/quoted printable for English.

Return Value: If language is set and language is valid, it returns TRUE. Otherwise, it returns FALSE. When language is omitted, it returns language name as string. If no language is set previously, it returns FALSE.

See also mb_send_mail().

后退 | 起点 | 前进
mb_internal_encoding | 上一级 | mb_output_handler


mb_output_handler

(PHP 4 >= 4.0.6)

mb_output_handler -- Callback function converts character encoding in output buffer

Description

string mb_output_handler ( string contents, int status)

mb_output_handler() is
ob_start() callback
function. mb_output_handler() converts
characters in output buffer from internal character encoding to
HTTP output character encoding.

4.1.0 or later version, this hanlder adds charset HTTP header when following conditions are met:

  • Does not set Content-Type by header()

  • Default MIME type begins with text/

  • http_output setting is other than pass

contents : Output buffer contents

status : Output buffer status

Return Value: String converted

例子 1. mb_output_handler() example

mb_http_output("UTF-8");
ob_start("mb_output_handler");

注: If you want to output some binary data such as image from PHP script, you must set output encoding to "pass" using mb_http_output().

See also ob_start().

后退 | 起点 | 前进
mb_language | 上一级 | mb_parse_str


mb_parse_str

(PHP 4 >= 4.0.6)

mb_parse_str -- Parse GET/POST/COOKIE data and set global variable

Description

boolean mb_parse_str ( string encoded_string [, array result])

mb_parse_str() parses GET/POST/COOKIE data and sets global variables. Since PHP does not provide raw POST/COOKIE data, it can only used for GET data for now. It preses URL encoded data, detects encoding, converts coding to internal encoding and set values to result array or global variables.

encoded_string: URL encoded data.

result: Array contains decoded and character encoding converted values.

Return Value: It returns TRUE for success or FALSE for failure.

See also mb_detect_order(), mb_internal_encoding().

后退 | 起点 | 前进
mb_output_handler | 上一级 | mb_preferred_mime_name


mb_preferred_mime_name

(PHP 4 >= 4.0.6)

mb_preferred_mime_name -- Get MIME charset string

Description

string mb_preferred_mime_name ( string encoding)

mb_preferred_mime_name() returns MIME charset string for character encoding encoding. It returns charset string.

例子 1. mb_preferred_mime_string() example

$outputenc = "sjis-win";
mb_http_output($outputenc);
ob_start("mb_output_handler");
header("Content-Type: text/html; charset=" . mb_preferred_mime_name($outputenc));

后退 | 起点 | 前进
mb_parse_str | 上一级 | mb_regex_encoding


mb_regex_encoding

(PHP 4 >= 4.2.0)

mb_regex_encoding -- Returns current encoding for multibyte regex as string

Description

string mb_regex_encoding ( [string encoding])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

mb_regex_encoding() returns the character encoding used by multibyte regex functions.

If the optional parameter encoding is specified, it is set to the character encoding for multibyte regex. The default value is the internal character encoding.

注: This function is supported in PHP 4.2.0 or higher.

See also: mb_internal_encoding(), mb_ereg()

后退 | 起点 | 前进
mb_preferred_mime_name | 上一级 | mb_send_mail


mb_send_mail

(PHP 4 >= 4.0.6)

mb_send_mail -- Send encoded mail.

Description

boolean mb_send_mail ( string to, string subject, string message [, string additional_headers [, string additional_parameter]])

mb_send_mail() sends email. Headers and
message are converted and encoded according to
mb_language() setting.
mb_send_mail() is wrapper
function of mail(). See
mail() for details.

to is mail addresses send to. Multiple recipients can be specified by putting a comma between each address in to. This parameter is not automatically encoded.

subject is subject of mail.

message is mail message.

additional_headers is inserted at the end of the header. This is typically used to add extra headers. Multiple extra headers are separated with a newline ("\n").

additional_parameter is a MTA command line parameter. It is useful when setting the correct Return-Path header when using sendmail.

如果成功则返回 TRUE，失败则返回 FALSE。

See also mail(),
mb_encode_mimeheader(), and
mb_language().

后退 | 起点 | 前进
mb_regex_encoding | 上一级 | mb_split


mb_split

(PHP 4 >= 4.2.0)

mb_split -- Split multibyte string using regular expression

Description

array mb_split ( string pattern, string string [, int limit])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

mb_split() split multibyte string using regular expression pattern and returns the result as an array.

If optional parameter limit is specified, it will be split in limit elements as maximum.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

注: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg().

后退 | 起点 | 前进
mb_send_mail | 上一级 | mb_strcut


mb_strcut

(PHP 4 >= 4.0.6)

mb_strcut -- Get part of string

Description

string mb_strcut ( string str, int start [, int length [, string encoding]])

mb_strcut() returns the portion of str specified by the start and length parameters.

mb_strcut() performs equivalent operation as mb_substr() with different method. If start position is multi-byte character's second byte or larger, it starts from first byte of multi-byte character.

It subtracts string from str that is shorter than length AND character that is not part of multi-byte string or not being middle of shift sequence.

encoding is character encoding. If it is not set, internal character encoding is used.

See also mb_substr(), mb_internal_encoding().

后退 | 起点 | 前进
mb_split | 上一级 | mb_strimwidth


mb_strimwidth

(PHP 4 >= 4.0.6)

mb_strimwidth -- Get truncated string with specified width

Description

string mb_strimwidth ( string str, int start, int width, string trimmarker [, string encoding])

mb_strimwidth() truncates string str to specified width. It returns truncated string.

If trimmarker is set, trimmarker is appended to return value.

start is start position offset. Number of characters from the beginning of string. (First character is 0)

trimmarker is string that is added to the end of string when string is truncated.

encoding is character encoding. If it is omitted, internal encoding is used.

例子 1. mb_strimwidth() example

$str = mb_strimwidth($str, 0, 40, "..>");

See also: mb_strwidth(), mb_internal_encoding().

后退 | 起点 | 前进
mb_strcut | 上一级 | mb_strlen


mb_strlen

(PHP 4 >= 4.0.6)

mb_strlen -- Get string length

Description

string mb_strlen ( string str [, string encoding])

mb_strlen() returns number of characters in string str having character encoding encoding. A multi-byte character is counted as 1.

encoding is character encoding for str. If encoding is omitted, internal character encoding is used.

See also mb_internal_encoding(), strlen().

后退 | 起点 | 前进
mb_strimwidth | 上一级 | mb_strpos


mb_strpos

(PHP 4 >= 4.0.6)

mb_strpos -- Find position of first occurrence of string in a string

Description

int mb_strpos ( string haystack, string needle [, int offset [, string encoding]])

mb_strpos() returns the numeric position of the first occurrence of needle in the haystack string. If needle is not found, it returns FALSE.

mb_strpos() performs multi-byte safe strpos() operation based on number of characters. needle position is counted from the beginning of the haystack. First character's position is 0. Second character position is 1, and so on.

If encoding is omitted, internal character encoding is used. mb_strrpos() accepts string for needle where strrpos() accepts only character.

offset is search offset. If it is not specified, 0 is used.

encoding is character encoding name. If it is omitted, internal character encoding is used.

See also mb_strpos(),
mb_internal_encoding(),
strpos()

后退 | 起点 | 前进
mb_strlen | 上一级 | mb_strrpos


mb_strrpos

(PHP 4 >= 4.0.6)

mb_strrpos -- Find position of last occurrence of a string in a string

Description

int mb_strrpos ( string haystack, string needle [, string encoding])

mb_strrpos() returns the numeric position of the last occurrence of needle in the haystack string. If needle is not found, it returns FALSE.

mb_strrpos() performs multi-byte safe strrpos() operation based on number of characters. needle position is counted from the beginning of haystack. First character's position is 0. Second character position is 1.

If encoding is omitted, internal encoding is assumed. mb_strrpos() accepts string for needle where strrpos() accepts only character.

encoding is character encoding. If it is not specified, internal character encoding is used.

See also mb_strpos(),
mb_internal_encoding(),
strrpos().

后退 | 起点 | 前进
mb_strpos | 上一级 | mb_strwidth


mb_strwidth

(PHP 4 >= 4.0.6)

mb_strwidth -- Return width of string

Description

int mb_strwidth ( string str [, string encoding])

mb_strwidth() returns width of string str.

Multi-byte character usually twice of width compare to single byte character.

Character width

       U+0000 - U+0019   0
       U+0020 - U+1FFF   1
       U+2000 - U+FF60   2
       U+FF61 - U+FF9F   1
       U+FFA0 -          2

encoding is character encoding. If it is omitted, internal encoding is used.

See also: mb_strimwidth(), mb_internal_encoding().

后退 | 起点 | 前进
mb_strrpos | 上一级 | mb_substitute_character


mb_substitute_character

(PHP 4 >= 4.0.6)

mb_substitute_character -- Set/Get substitution character

Description

mixed mb_substitute_character ( [mixed substrchar])

mb_substitute_character() specifies substitution character when input character encoding is invalid or character code is not exist in output character encoding. Invalid characters may be substituted NULL(no output), string or integer value (Unicode character code value).

This setting affects mb_detect_encoding() and mb_send_mail().

substchar : Specify Unicode value as integer or specify as string as follows

  • "none" : no output

  • "long" : Output character code value (Example: U+3000,JIS+7E7E)

Return Value: If substchar is set, it returns TRUE for success, otherwise returns FALSE. If substchar is not set, it returns Unicode value or "none"/"long".

例子 1. mb_substitute_character() example

/* Set with Unicode U+3013 (GETA MARK) */
mb_substitute_character(0x3013);

/* Set hex format */
mb_substitute_character("long");

/* Display current setting */
echo mb_substitute_character();

后退 | 起点 | 前进
mb_strwidth | 上一级 | mb_substr


mb_substr

(PHP 4 >= 4.0.6)

mb_substr -- Get part of string

Description

string mb_substr ( string str, int start [, int length [, string encoding]])

mb_substr() returns the portion of str specified by the start and length parameters.

mb_substr() performs multi-byte safe substr() operation based on number of characters. Position is counted from the beginning of str. First character's position is 0. Second character position is 1, and so on.

If encoding is omitted, internal encoding is assumed.

encoding is character encoding. If it is omitted, internal character encoding is used.

See also mb_strcut(), mb_internal_encoding().

后退 | 起点 | 前进
mb_substitute_character | 上一级 | MCAL functions


MCAL functions

PHP 手册
后退 前进

LIII. MCAL functions

介绍

MCAL stands for Modular Calendar Access Library.

Libmcal is a C library for accessing calendars. It's written to be very modular, with pluggable drivers. MCAL is the calendar equivalent of the IMAP module for mailboxes.

With mcal support, a calendar stream can be opened much like the mailbox stream with the IMAP support. Calendars can be local file stores, remote ICAP servers, or other formats that are supported by the mcal library.

Calendar events can be pulled up, queried, and stored. There is also support for calendar triggers (alarms) and recurring events.

With libmcal, central calendar servers can be accessed, removing the need for any specific database or local file programming.

Most of the functions use an internal event structure that is unique for each stream. This alleviates the need to pass around large objects between functions. There are convenience functions for setting, initializing, and retrieving the event structure values.

注: PHP had an ICAP extension previously, but the original library and the PHP extension is not supported anymore. The suggested replacement is MCAL.

需求

This extension requires the mcal library to be installed. Grab the latest version from http://mcal.chek.com/ and compile and install it.

安装

After you installed the mcal library, to get these functions to work, you have to compile PHP with --with-mcal.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

MCAL_SUNDAY (integer)

MCAL_MONDAY (integer)

MCAL_TUESDAY (integer)

MCAL_WEDNESDAY (integer)

MCAL_THURSDAY (integer)

MCAL_FRIDAY (integer)

MCAL_SATURDAY (integer)

MCAL_JANUARY (integer)

MCAL_FEBRUARY (integer)

MCAL_MARCH (integer)

MCAL_APRIL (integer)

MCAL_MAY (integer)

MCAL_JUNE (integer)

MCAL_JULY (integer)

MCAL_AUGUST (integer)

MCAL_SEPTEMBER (integer)

MCAL_OCTOBER (integer)

MCAL_NOVEMBER (integer)

MCAL_DECEMBER (integer)

MCAL_RECUR_NONE (integer)

MCAL_RECUR_DAILY (integer)

MCAL_RECUR_WEEKLY (integer)

MCAL_RECUR_MONTHLY_MDAY (integer)

MCAL_RECUR_MONTHLY_WDAY (integer)

MCAL_RECUR_YEARLY (integer)

MCAL_M_SUNDAY (integer)

MCAL_M_MONDAY (integer)

MCAL_M_TUESDAY (integer)

MCAL_M_WEDNESDAY (integer)

MCAL_M_THURSDAY (integer)

MCAL_M_FRIDAY (integer)

MCAL_M_SATURDAY (integer)

MCAL_M_WEEKDAYS (integer)

MCAL_M_WEEKEND (integer)

MCAL_M_ALLDAYS (integer)

目录
mcal_append_event — Store a new event into an MCAL calendar
mcal_close — Close an MCAL stream
mcal_create_calendar — Create a new MCAL calendar
mcal_date_compare — Compares two dates
mcal_date_valid — Returns TRUE if the given year, month, day is a valid date
mcal_day_of_week — Returns the day of the week of the given date
mcal_day_of_year — Returns the day of the year of the given date
mcal_days_in_month — Returns the number of days in the given month
mcal_delete_calendar — Delete an MCAL calendar
mcal_delete_event — Delete an event from an MCAL calendar
mcal_event_add_attribute — Adds an attribute and a value to the streams global event structure
mcal_event_init — Initializes a streams global event structure
mcal_event_set_alarm — Sets the alarm of the streams global event structure
mcal_event_set_category — Sets the category of the streams global event structure
mcal_event_set_class — Sets the class of the streams global event structure
mcal_event_set_description — Sets the description of the streams global event structure
mcal_event_set_end — Sets the end date and time of the streams global event structure
mcal_event_set_recur_daily — Sets the recurrence of the streams global event structure
mcal_event_set_recur_monthly_mday — Sets the recurrence of the streams global event structure
mcal_event_set_recur_monthly_wday — Sets the recurrence of the streams global event structure
mcal_event_set_recur_none — Sets the recurrence of the streams global event structure
mcal_event_set_recur_weekly — Sets the recurrence of the streams global event structure
mcal_event_set_recur_yearly — Sets the recurrence of the streams global event structure
mcal_event_set_start — Sets the start date and time of the streams global event structure
mcal_event_set_title — Sets the title of the streams global event structure
mcal_expunge — Deletes all events marked for being expunged.
mcal_fetch_current_stream_event — Returns an object containing the current streams event structure
mcal_fetch_event — Fetches an event from the calendar stream
mcal_is_leap_year — Returns if the given year is a leap year or not
mcal_list_alarms — Return a list of events that has an alarm triggered at the given datetime
mcal_list_events — Return a list of IDs for a date or a range of dates.
mcal_next_recurrence — Returns the next recurrence of the event
mcal_open — Opens up an MCAL connection
mcal_popen — Opens up a persistent MCAL connection
mcal_rename_calendar — Rename an MCAL calendar
mcal_reopen — Reopens an MCAL connection
mcal_snooze — Turn off an alarm for an event
mcal_store_event — Modify an existing event in an MCAL calendar
mcal_time_valid — Returns TRUE if the given year, month, day is a valid time
mcal_week_of_year — Returns the week number of the given date

后退 | 起点 | 前进
mb_substr | 上一级 | mcal_append_event


mcal_append_event

(PHP 4 )

mcal_append_event -- Store a new event into an MCAL calendar

Description

int mcal_append_event ( int mcal_stream)

mcal_append_event() Stores the global event into an MCAL calendar for the given stream.

Returns the id of the newly inserted event.

后退 | 起点 | 前进
MCAL functions | 上一级 | mcal_close


mcal_close

(PHP 3>= 3.0.13, PHP 4 )

mcal_close -- Close an MCAL stream

Description

int mcal_close ( int mcal_stream, int flags)

Closes the given mcal stream.

后退 | 起点 | 前进
mcal_append_event | 上一级 | mcal_create_calendar


mcal_create_calendar

(PHP 3>= 3.0.13, PHP 4 )

mcal_create_calendar -- Create a new MCAL calendar

Description

string mcal_create_calendar ( int stream, string calendar)

Creates a new calendar named calendar.

后退 | 起点 | 前进
mcal_close | 上一级 | mcal_date_compare


mcal_date_compare

(PHP 3>= 3.0.13, PHP 4 )

mcal_date_compare -- Compares two dates

Description

int mcal_date_compare ( int a_year, int a_month, int a_day, int b_year, int b_month, int b_day)

mcal_date_compare() Compares the two given dates, returns <0, 0, >0 if a<b, a==b, a>b respectively.

后退 | 起点 | 前进
mcal_create_calendar | 上一级 | mcal_date_valid


mcal_date_valid

(PHP 3>= 3.0.13, PHP 4 )

mcal_date_valid -- Returns TRUE if the given year, month, day is a valid date

Description

int mcal_date_valid ( int year, int month, int day)

mcal_date_valid() Returns TRUE if the given year, month and day is a valid date, FALSE if not.

后退 | 起点 | 前进
mcal_date_compare | 上一级 | mcal_day_of_week


mcal_day_of_week

(PHP 3>= 3.0.13, PHP 4 )

mcal_day_of_week -- Returns the day of the week of the given date

Description

int mcal_day_of_week ( int year, int month, int day)

mcal_day_of_week() returns the day of the week of the given date. Possible return values range from 0 for Sunday through 6 for Saturday.

后退 | 起点 | 前进
mcal_date_valid | 上一级 | mcal_day_of_year


mcal_day_of_year

(PHP 3>= 3.0.13, PHP 4 )

mcal_day_of_year -- Returns the day of the year of the given date

Description

int mcal_ ( int year, int month, int day)

mcal_day_of_year() returns the day of the year of the given date.

后退 | 起点 | 前进
mcal_day_of_week | 上一级 | mcal_days_in_month


mcal_days_in_month

(PHP 3>= 3.0.13, PHP 4 )

mcal_days_in_month -- Returns the number of days in the given month

Description

int mcal_days_in_month ( int month, int leap year)

mcal_days_in_month() Returns the number of days in the given month, taking into account if the given year is a leap year or not.

后退 | 起点 | 前进
mcal_day_of_year | 上一级 | mcal_delete_calendar


mcal_delete_calendar

(PHP 3>= 3.0.13, PHP 4 )

mcal_delete_calendar -- Delete an MCAL calendar

Description

string mcal_delete_calendar ( int stream, string calendar)

Deletes the calendar named calendar.

后退 | 起点 | 前进
mcal_days_in_month | 上一级 | mcal_delete_event


mcal_delete_event

(PHP 3>= 3.0.13, PHP 4 )

mcal_delete_event -- Delete an event from an MCAL calendar

Description

int mcal_delete_event ( int mcal_stream [, int event_id])

mcal_delete_event() deletes the calendar event specified by the event_id.

Returns TRUE.

后退 | 起点 | 前进
mcal_delete_calendar | 上一级 | mcal_event_add_attribute


mcal_event_add_attribute

(PHP 3>= 3.0.15, PHP 4 )

mcal_event_add_attribute -- Adds an attribute and a value to the streams global event structure

Description

void mcal_event_add_attribute ( int stream, string attribute, string value)

mcal_event_add_attribute() adds an attribute to the stream's global event structure with the value given by "value".

后退 | 起点 | 前进
mcal_delete_event | 上一级 | mcal_event_init


mcal_event_init

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_init -- Initializes a streams global event structure

Description

int mcal_event_init ( int stream)

mcal_event_init() initializes a streams global event structure. this effectively sets all elements of the structure to 0, or the default settings.

Returns TRUE.

后退 | 起点 | 前进
mcal_event_add_attribute | 上一级 | mcal_event_set_alarm


mcal_event_set_alarm

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_alarm -- Sets the alarm of the streams global event structure

Description

int mcal_event_set_alarm ( int stream, int alarm)

mcal_event_set_alarm() sets the streams global event structure's alarm to the given minutes before the event.

Returns TRUE.

后退 | 起点 | 前进
mcal_event_init | 上一级 | mcal_event_set_category


mcal_event_set_category

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_category -- Sets the category of the streams global event structure

Description

int mcal_event_set_category ( int stream, string category)

mcal_event_set_category() sets the streams global event structure's category to the given string.

Returns TRUE.

后退 | 起点 | 前进
mcal_event_set_alarm | 上一级 | mcal_event_set_class


mcal_event_set_class

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_class -- Sets the class of the streams global event structure

Description

int mcal_event_set_class ( int stream, int class)

mcal_event_set_class() sets the streams global event structure's class to the given value. The class is either 1 for public, or 0 for private.

Returns TRUE.

后退 | 起点 | 前进
mcal_event_set_category | 上一级 | mcal_event_set_description


mcal_event_set_description

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_description -- Sets the description of the streams global event structure

Description

int mcal_event_set_description ( int stream, string description)

mcal_event_set_description() sets the streams global event structure's description to the given string.

Returns TRUE.

后退 | 起点 | 前进
mcal_event_set_class | 上一级 | mcal_event_set_end


mcal_event_set_end

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_end -- Sets the end date and time of the streams global event structure

Description

int mcal_event_set_end ( int stream, int year, int month [, int day [, int hour [, int min [, int sec]]]])

mcal_event_set_end() sets the streams global event structure's end date and time to the given values.

Returns TRUE.

后退 | 起点 | 前进
mcal_event_set_description | 上一级 | mcal_event_set_recur_daily


mcal_event_set_recur_daily

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_recur_daily -- Sets the recurrence of the streams global event structure

Description

int mcal_event_set_recur_daily ( int stream, int year, int month, int day, int interval)

mcal_event_set_recur_daily() sets the streams global event structure's recurrence to the given value to be reoccuring on a daily basis, ending at the given date.

后退 | 起点 | 前进
mcal_event_set_end | 上一级 | mcal_event_set_recur_monthly_mday


mcal_event_set_recur_monthly_mday

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_recur_monthly_mday -- Sets the recurrence of the streams global event structure

Description

int mcal_event_set_recur_monthly_mday ( int stream, int year, int month, int day, int interval)

mcal_event_set_recur_monthly_mday() sets the streams global event structure's recurrence to the given value to be reoccuring on a monthly by month day basis, ending at the given date.

后退 | 起点 | 前进
mcal_event_set_recur_daily | 上一级 | mcal_event_set_recur_monthly_wday


mcal_event_set_recur_monthly_wday

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_recur_monthly_wday -- Sets the recurrence of the streams global event structure

Description

int mcal_event_set_recur_monthly_wday ( int stream, int year, int month, int day, int interval)

mcal_event_set_recur_monthly_wday() sets the streams global event structure's recurrence to the given value to be reoccuring on a monthly by week basis, ending at the given date.

后退 | 起点 | 前进
mcal_event_set_recur_monthly_mday | 上一级 | mcal_event_set_recur_none


mcal_event_set_recur_none

(PHP 3>= 3.0.15, PHP 4 )

mcal_event_set_recur_none -- Sets the recurrence of the streams global event structure

Description

int mcal_event_set_recur_none ( int stream)

mcal_event_set_recur_none() sets the streams global event structure to not recur (event->recur_type is set to MCAL_RECUR_NONE).

后退 | 起点 | 前进
mcal_event_set_recur_monthly_wday | 上一级 | mcal_event_set_recur_weekly


mcal_event_set_recur_weekly

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_recur_weekly -- Sets the recurrence of the streams global event structure

Description

int mcal_event_set_recur_weekly ( int stream, int year, int month, int day, int interval, int weekdays)

mcal_event_set_recur_weekly() sets the streams global event structure's recurrence to the given value to be reoccuring on a weekly basis, ending at the given date.

后退 | 起点 | 前进
mcal_event_set_recur_none | 上一级 | mcal_event_set_recur_yearly


mcal_event_set_recur_yearly

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_recur_yearly -- Sets the recurrence of the streams global event structure

Description

int mcal_event_set_recur_yearly ( int stream, int year, int month, int day, int interval)

mcal_event_set_recur_yearly() sets the streams global event structure's recurrence to the given value to be reoccuring on a yearly basis,ending at the given date.

后退 | 起点 | 前进
mcal_event_set_recur_weekly | 上一级 | mcal_event_set_start


mcal_event_set_start

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_start -- Sets the start date and time of the streams global event structure

Description

int mcal_event_set_start ( int stream, int year, int month [, int day [, int hour [, int min [, int sec]]]])

mcal_event_set_start() sets the streams global event structure's start date and time to the given values.

Returns TRUE.

后退 | 起点 | 前进
mcal_event_set_recur_yearly | 上一级 | mcal_event_set_title


mcal_event_set_title

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_title -- Sets the title of the streams global event structure

Description

int mcal_event_set_title ( int stream, string title)

mcal_event_set_title() sets the streams global event structure's title to the given string.

Returns TRUE.

后退 | 起点 | 前进
mcal_event_set_start | 上一级 | mcal_expunge


mcal_expunge

(no version information, might be only in CVS)

mcal_expunge -- Deletes all events marked for being expunged.

Description

int mcal_expunge ( int stream)

mcal_expunge() Deletes all events which have been previously marked for deletion.

后退 | 起点 | 前进
mcal_event_set_title | 上一级 | mcal_fetch_current_stream_event


mcal_fetch_current_stream_event

(PHP 3>= 3.0.13, PHP 4 )

mcal_fetch_current_stream_event -- Returns an object containing the current streams event structure

Description

object mcal_fetch_current_stream_event ( int stream)

mcal_fetch_current_stream_event() returns the current stream's event structure as an object containing:

  • int id - ID of that event.

  • int public - TRUE if the event if public, FALSE if it is private.

  • string category - Category string of the event.

  • string title - Title string of the event.

  • string description - Description string of the event.

  • int alarm - number of minutes before the event to send an alarm/reminder.

  • object start - Object containing a datetime entry.

  • object end - Object containing a datetime entry.

  • int recur_type - recurrence type

  • int recur_interval - recurrence interval

  • datetime recur_enddate - recurrence end date

  • int recur_data - recurrence data

All datetime entries consist of an object that contains:

  • int year - year

  • int month - month

  • int mday - day of month

  • int hour - hour

  • int min - minutes

  • int sec - seconds

  • int alarm - minutes before event to send an alarm

后退 | 起点 | 前进
mcal_expunge | 上一级 | mcal_fetch_event


mcal_fetch_event

(PHP 3>= 3.0.13, PHP 4 )

mcal_fetch_event -- Fetches an event from the calendar stream

Description

object mcal_fetch_event ( int mcal_stream, int event_id [, int options])

mcal_fetch_event() fetches an event from the calendar stream specified by id.

Returns an event object consisting of:

  • int id - ID of that event.

  • int public - TRUE if the event if public, FALSE if it is private.

  • string category - Category string of the event.

  • string title - Title string of the event.

  • string description - Description string of the event.

  • int alarm - number of minutes before the event to send an alarm/reminder.

  • object start - Object containing a datetime entry.

  • object end - Object containing a datetime entry.

  • int recur_type - recurrence type

  • int recur_interval - recurrence interval

  • datetime recur_enddate - recurrence end date

  • int recur_data - recurrence data

All datetime entries consist of an object that contains:

  • int year - year

  • int month - month

  • int mday - day of month

  • int hour - hour

  • int min - minutes

  • int sec - seconds

  • int alarm - minutes before event to send an alarm

The possible values for recur_type are:

  • 0 - Indicates that this event does not recur

  • 1 - This event recurs daily

  • 2 - This event recurs on a weekly basis

  • 3 - This event recurs monthly on a specific day of the month (e.g. the 10th of the month)

  • 4 - This event recurs monthly on a sequenced day of the week (e.g. the 3rd Saturday)

  • 5 - This event recurs on an annual basis

后退 | 起点 | 前进
mcal_fetch_current_stream_event | 上一级 | mcal_is_leap_year


mcal_is_leap_year

(PHP 3>= 3.0.13, PHP 4 )

mcal_is_leap_year -- Returns if the given year is a leap year or not

Description

int mcal_is_leap_year ( int year)

mcal_is_leap_year() returns 1 if the given year is a leap year, 0 if not.

后退 | 起点 | 前进
mcal_fetch_event | 上一级 | mcal_list_alarms


mcal_list_alarms

(PHP 3>= 3.0.13, PHP 4 )

mcal_list_alarms -- Return a list of events that has an alarm triggered at the given datetime

Description

array mcal_list_alarms ( int mcal_stream [, int begin_year [, int begin_month [, int begin_day [, int end_year [, int end_month [, int end_day]]]]]])

Returns an array of event ID's that has an alarm going off between the start and end dates, or if just a stream is given, uses the start and end dates in the global event structure.

mcal_list_events() function takes in an optional beginning date and an end date for a calendar stream. An array of event id's that are between the given dates or the internal event dates are returned.

后退 | 起点 | 前进
mcal_is_leap_year | 上一级 | mcal_list_events


mcal_list_events

(PHP 3>= 3.0.13, PHP 4 )

mcal_list_events -- Return a list of IDs for a date or a range of dates.

Description

array mcal_list_events ( int mcal_stream, object begin_date [, object end_date])

Returns an array of ID's that are between the start and end dates, or if just a stream is given, uses the start and end dates in the global event structure.

mcal_list_events() function takes in an beginning date and an optional end date for a calendar stream. An array of event id's that are between the given dates or the internal event dates are returned.

后退 | 起点 | 前进
mcal_list_alarms | 上一级 | mcal_next_recurrence


mcal_next_recurrence

(PHP 3>= 3.0.13, PHP 4 )

mcal_next_recurrence -- Returns the next recurrence of the event

Description

int mcal_next_recurrence ( int stream, int weekstart, array next)

mcal_next_recurrence() returns an object filled with the next date the event occurs, on or after the supplied date. Returns empty date field if event does not occur or something is invalid. Uses weekstart to determine what day is considered the beginning of the week.

后退 | 起点 | 前进
mcal_list_events | 上一级 | mcal_open


mcal_open

(PHP 3>= 3.0.13, PHP 4 )

mcal_open -- Opens up an MCAL connection

Description

int mcal_open ( string calendar, string username, string password [, int options])

Returns an MCAL stream on success, FALSE on error.

mcal_open() opens up an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also. The streams internal event structure is also initialized upon connection.

后退 | 起点 | 前进
mcal_next_recurrence | 上一级 | mcal_popen


mcal_popen

(PHP 3>= 3.0.13, PHP 4 )

mcal_popen -- Opens up a persistent MCAL connection

Description

int mcal_popen ( string calendar, string username, string password [, int options])

Returns an MCAL stream on success, FALSE on error.

mcal_popen() opens up an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also. The streams internal event structure is also initialized upon connection.

后退 | 起点 | 前进
mcal_open | 上一级 | mcal_rename_calendar


mcal_rename_calendar

(PHP 3>= 3.0.13, PHP 4 )

mcal_rename_calendar -- Rename an MCAL calendar

Description

string mcal_rename_calendar ( int stream, string old_name, string new_name)

Renames the calendar old_name to new_name.

后退 | 起点 | 前进
mcal_popen | 上一级 | mcal_reopen


mcal_reopen

(PHP 3>= 3.0.13, PHP 4 )

mcal_reopen -- Reopens an MCAL connection

Description

int mcal_reopen ( string calendar [, int options])

Reopens an MCAL stream to a new calendar.

mcal_reopen() reopens an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also.

后退 | 起点 | 前进
mcal_rename_calendar | 上一级 | mcal_snooze


mcal_snooze

(PHP 3>= 3.0.13, PHP 4 )

mcal_snooze -- Turn off an alarm for an event

Description

int mcal_snooze ( int id)

mcal_snooze() turns off an alarm for a calendar event specified by the id.

Returns TRUE.

后退 | 起点 | 前进
mcal_reopen | 上一级 | mcal_store_event


mcal_store_event

(PHP 3>= 3.0.13, PHP 4 )

mcal_store_event -- Modify an existing event in an MCAL calendar

Description

int mcal_store_event ( int mcal_stream)

mcal_store_event() Stores the modifications to the current global event for the given stream.

Returns the event id of the modified event on success and FALSE on error.

后退 | 起点 | 前进
mcal_snooze | 上一级 | mcal_time_valid


mcal_time_valid

(PHP 3>= 3.0.13, PHP 4 )

mcal_time_valid -- Returns TRUE if the given year, month, day is a valid time

Description

int mcal_time_valid ( int hour, int minutes, int seconds)

mcal_time_valid() Returns TRUE if the given hour, minutes and seconds is a valid time, FALSE if not.

后退 | 起点 | 前进
mcal_store_event | 上一级 | mcal_week_of_year


mcal_week_of_year

(PHP 4 )

mcal_week_of_year -- Returns the week number of the given date

Description

int mcal_week_of_year ( int day, int month, int year)

后退 | 起点 | 前进
mcal_time_valid | 上一级 | Mcrypt Encryption Functions


Mcrypt Encryption Functions

PHP 手册
后退 前进

LIV. Mcrypt Encryption Functions

介绍

This is an interface to the mcrypt library, which supports a wide variety of block algorithms such as DES, TripleDES, Blowfish (default), 3-WAY, SAFER-SK64, SAFER-SK128, TWOFISH, TEA, RC2 and GOST in CBC, OFB, CFB and ECB cipher modes. Additionally, it supports RC6 and IDEA which are considered "non-free".

需求

These functions work using mcrypt.

If you linked against libmcrypt 2.4.x or higher, the following additional block algorithms are supported: CAST, LOKI97, RIJNDAEL, SAFERPLUS, SERPENT and the following stream ciphers: ENIGMA (crypt), PANAMA, RC4 and WAKE. With libmcrypt 2.4.x or higher another cipher mode is also available; nOFB.

安装

To use it, download libmcrypt-x.x.tar.gz from here and follow the included installation instructions. You need to compile PHP with the --with-mcrypt parameter to enable this extension. Make sure you compile libmcrypt with the option --disable-posix-threads.

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. Mcrypt configuration options

Name | Default | Changeable
mcrypt.algorithms_dir | NULL | PHP_INI_ALL
mcrypt.modes_dir | NULL | PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

资源类型

该扩展模块未定义任何资源类型。

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

Mcrypt can operate in four block cipher modes (CBC, OFB, CFB, and ECB). If linked against libmcrypt-2.4.x or higher the functions can also operate in the block cipher mode nOFB and in STREAM mode. Below you find a list with all supported encryption modes together with the constants that are defines for the encryption mode. For a more complete reference and discussion see Applied Cryptography by Schneier (ISBN 0-471-11709-9).

  • MCRYPT_MODE_ECB (electronic codebook) is suitable for random data, such as encrypting other keys. Since data there is short and random, the disadvantages of ECB have a favorable negative effect.

  • MCRYPT_MODE_CBC (cipher block chaining) is especially suitable for encrypting files where the security is increased over ECB significantly.

  • MCRYPT_MODE_CFB (cipher feedback) is the best mode for encrypting byte streams where single bytes must be encrypted.

  • MCRYPT_MODE_OFB (output feedback, in 8bit) is comparable to CFB, but can be used in applications where error propagation cannot be tolerated. It's insecure (because it operates in 8bit mode) so it is not recommended to use it.

  • MCRYPT_MODE_NOFB (output feedback, in nbit) is comparable to OFB, but more secure because it operates on the block size of the algorithm.

  • MCRYPT_MODE_STREAM is an extra mode to include some stream algorithms like WAKE or RC4.

Some other mode and random device constants:

MCRYPT_ENCRYPT (integer)

MCRYPT_DECRYPT (integer)

MCRYPT_DEV_RANDOM (integer)

MCRYPT_DEV_URANDOM (integer)

MCRYPT_RAND (integer)

Mcrypt ciphers

Here is a list of ciphers which are currently supported by the mcrypt extension. For a complete list of supported ciphers, see the defines at the end of mcrypt.h. The general rule with the mcrypt-2.2.x API is that you can access the cipher from PHP with MCRYPT_ciphername. With the libmcrypt-2.4.x and libmcrypt-2.5.x API these constants also work, but it is possible to specify the name of the cipher as a string with a call to mcrypt_module_open().

  • MCRYPT_3DES

  • MCRYPT_ARCFOUR_IV (libmcrypt > 2.4.x only)

  • MCRYPT_ARCFOUR (libmcrypt > 2.4.x only)

  • MCRYPT_BLOWFISH

  • MCRYPT_CAST_128

  • MCRYPT_CAST_256

  • MCRYPT_CRYPT

  • MCRYPT_DES

  • MCRYPT_DES_COMPAT (libmcrypt 2.2.x only)

  • MCRYPT_ENIGMA (libmcrypt > 2.4.x only, alias for MCRYPT_CRYPT)

  • MCRYPT_GOST

  • MCRYPT_IDEA (non-free)

  • MCRYPT_LOKI97 (libmcrypt > 2.4.x only)

  • MCRYPT_MARS (libmcrypt > 2.4.x only, non-free)

  • MCRYPT_PANAMA (libmcrypt > 2.4.x only)

  • MCRYPT_RIJNDAEL_128 (libmcrypt > 2.4.x only)

  • MCRYPT_RIJNDAEL_192 (libmcrypt > 2.4.x only)

  • MCRYPT_RIJNDAEL_256 (libmcrypt > 2.4.x only)

  • MCRYPT_RC2

  • MCRYPT_RC4 (libmcrypt 2.2.x only)

  • MCRYPT_RC6 (libmcrypt > 2.4.x only)

  • MCRYPT_RC6_128 (libmcrypt 2.2.x only)

  • MCRYPT_RC6_192 (libmcrypt 2.2.x only)

  • MCRYPT_RC6_256 (libmcrypt 2.2.x only)

  • MCRYPT_SAFER64

  • MCRYPT_SAFER128

  • MCRYPT_SAFERPLUS (libmcrypt > 2.4.x only)

  • MCRYPT_SERPENT(libmcrypt > 2.4.x only)

  • MCRYPT_SERPENT_128 (libmcrypt 2.2.x only)

  • MCRYPT_SERPENT_192 (libmcrypt 2.2.x only)

  • MCRYPT_SERPENT_256 (libmcrypt 2.2.x only)

  • MCRYPT_SKIPJACK (libmcrypt > 2.4.x only)

  • MCRYPT_TEAN (libmcrypt 2.2.x only)

  • MCRYPT_THREEWAY

  • MCRYPT_TRIPLEDES (libmcrypt > 2.4.x only)

  • MCRYPT_TWOFISH (for older mcrypt 2.x versions, or mcrypt > 2.4.x )

  • MCRYPT_TWOFISH128 (TWOFISHxxx are available in newer 2.x versions, but not in the 2.4.x versions)

  • MCRYPT_TWOFISH192

  • MCRYPT_TWOFISH256

  • MCRYPT_WAKE (libmcrypt > 2.4.x only)

  • MCRYPT_XTEA (libmcrypt > 2.4.x only)

You must (in CFB and OFB mode) or can (in CBC mode) supply an initialization vector (IV) to the respective cipher function. The IV must be unique and must be the same when decrypting/encrypting. With data which is stored encrypted, you can take the output of a function of the index under which the data is stored (e.g. the MD5 key of the filename). Alternatively, you can transmit the IV together with the encrypted data (see chapter 9.3 of Applied Cryptography by Schneier (ISBN 0-471-11709-9) for a discussion of this topic).

范例

Mcrypt can be used to encrypt and decrypt using the above mentioned ciphers. If you linked against libmcrypt-2.2.x, the four important mcrypt commands (mcrypt_cfb(), mcrypt_cbc(), mcrypt_ecb(), and mcrypt_ofb()) can operate in both modes which are named MCRYPT_ENCRYPT and MCRYPT_DECRYPT, respectively.

例子 1. Encrypt an input value with TripleDES under 2.2.x in ECB mode

<?php
$key = "this is a very secret key";
$input = "Let us meet at 9 o'clock at the secret place.";

$encrypted_data = mcrypt_ecb (MCRYPT_3DES, $key, $input, MCRYPT_ENCRYPT);
?>
This example will give you the encrypted data as a string in $encrypted_data.

If you linked against libmcrypt 2.4.x or 2.5.x, these functions are still available, but it is recommended that you use the advanced functions.

例子 2. Encrypt an input value with TripleDES under 2.4.x and higher in ECB mode

<?php
    $key = "this is a very secret key";
    $input = "Let us meet at 9 o'clock at the secret place.";

    $td = mcrypt_module_open ('tripledes', '', 'ecb', '');
    $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size ($td), MCRYPT_RAND);
    mcrypt_generic_init ($td, $key, $iv);
    $encrypted_data = mcrypt_generic ($td, $input);
    mcrypt_generic_end ($td);
?>
This example will give you the encrypted data as a string in $encrypted_data. For a full example see mcrypt_module_open().

目录
mcrypt_cbc — Encrypt/decrypt data in CBC mode
mcrypt_cfb — Encrypt/decrypt data in CFB mode
mcrypt_create_iv — Create an initialization vector (IV) from a random source
mcrypt_decrypt — Decrypts crypttext with given parameters
mcrypt_ecb — Encrypt/decrypt data in ECB mode
mcrypt_enc_get_algorithms_name — Returns the name of the opened algorithm
mcrypt_enc_get_block_size — Returns the blocksize of the opened algorithm
mcrypt_enc_get_iv_size — Returns the size of the IV of the opened algorithm
mcrypt_enc_get_key_size — Returns the maximum supported keysize of the opened mode
mcrypt_enc_get_modes_name — Returns the name of the opened mode
mcrypt_enc_get_supported_key_sizes — Returns an array with the supported keysizes of the opened algorithm
mcrypt_enc_is_block_algorithm_mode — Checks whether the encryption of the opened mode works on blocks
mcrypt_enc_is_block_algorithm — Checks whether the algorithm of the opened mode is a block algorithm
mcrypt_enc_is_block_mode — Checks whether the opened mode outputs blocks
mcrypt_enc_self_test — This function runs a self test on the opened module
mcrypt_encrypt — Encrypts plaintext with given parameters
mcrypt_generic_deinit — This function deinitializes an encryption module
mcrypt_generic_end — This function terminates encryption
mcrypt_generic_init — This function initializes all buffers needed for encryption
mcrypt_generic — This function encrypts data
mcrypt_get_block_size — Get the block size of the specified cipher
mcrypt_get_cipher_name — Get the name of the specified cipher
mcrypt_get_iv_size — Returns the size of the IV belonging to a specific cipher/mode combination
mcrypt_get_key_size — Get the key size of the specified cipher
mcrypt_list_algorithms — Get an array of all supported ciphers
mcrypt_list_modes — Get an array of all supported modes
mcrypt_module_close — Close the mcrypt module
mcrypt_module_get_algo_block_size — Returns the blocksize of the specified algorithm
mcrypt_module_get_algo_key_size — Returns the maximum supported keysize of the opened mode
mcrypt_module_get_supported_key_sizes — Returns an array with the supported keysizes of the opened algorithm
mcrypt_module_is_block_algorithm_mode — This function returns if the the specified module is a block algorithm or not
mcrypt_module_is_block_algorithm — This function checks whether the specified algorithm is a block algorithm
mcrypt_module_is_block_mode — This function returns if the the specified mode outputs blocks or not
mcrypt_module_open — This function opens the module of the algorithm and the mode to be used
mcrypt_module_self_test — This function runs a self test on the specified module
mcrypt_ofb — Encrypt/decrypt data in OFB mode
mdecrypt_generic — This function decrypts data

后退 | 起点 | 前进
mcal_week_of_year | 上一级 | mcrypt_cbc


mcrypt_cbc

(PHP 3>= 3.0.8, PHP 4 )

mcrypt_cbc -- Encrypt/decrypt data in CBC mode

Description

string mcrypt_cbc ( int cipher, string key, string data, int mode [, string iv])

string mcrypt_cbc ( string cipher, string key, string data, int mode [, string iv])

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher.

This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.

后退 | 起点 | 前进
Mcrypt Encryption Functions | 上一级 | mcrypt_cfb


mcrypt_cfb

(PHP 3>= 3.0.8, PHP 4 )

mcrypt_cfb -- Encrypt/decrypt data in CFB mode

Description

string mcrypt_cfb ( int cipher, string key, string data, int mode, string iv)

string mcrypt_cfb ( string cipher, string key, string data, int mode [, string iv])

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher.

This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.

后退 | 起点 | 前进
mcrypt_cbc | 上一级 | mcrypt_create_iv


mcrypt_create_iv

(PHP 3>= 3.0.8, PHP 4 )

mcrypt_create_iv -- Create an initialization vector (IV) from a random source

Description

string mcrypt_create_iv ( int size, int source)

mcrypt_create_iv() is used to create an IV.

mcrypt_create_iv() takes two arguments, size determines the size of the IV, source specifies the source of the IV.

The source can be MCRYPT_RAND (system random number generator), MCRYPT_DEV_RANDOM (read data from /dev/random) and MCRYPT_DEV_URANDOM (read data from /dev/urandom). If you use MCRYPT_RAND, make sure to call srand() before to initialize the random number generator.

例子 1. mcrypt_create_iv() example

<?php
    $size = mcrypt_get_iv_size (MCRYPT_CAST_256, MCRYPT_MODE_CFB);
    $iv = mcrypt_create_iv ($size, MCRYPT_DEV_RANDOM);
?>

The IV is only meant to give an alternative seed to the encryption routines. This IV does not need to be secret at all, though it can be desirable. You even can send it along with your ciphertext without loosing security.

More information can be found at http://www.ciphersbyritter.com/GLOSSARY.HTM#IV, http://fn2.freenet.edmonton.ab.ca/~jsavard/crypto/co0409.htm and in chapter 9.3 of Applied Cryptography by Schneier (ISBN 0-471-11709-9) for a discussion of this topic.

后退 | 起点 | 前进
mcrypt_cfb | 上一级 | mcrypt_decrypt


mcrypt_decrypt

(PHP 4 >= 4.0.2)

mcrypt_decrypt -- Decrypts crypttext with given parameters

Description

string mcrypt_decrypt ( string cipher, string key, string data, string mode [, string iv])

mcrypt_decrypt() decrypts the data and returns the unencrypted data.

Cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.

Key is the key with which the data is encrypted. If it's smaller that the required keysize, it is padded with '\0'.

Data is the data that will be decrypted with the given cipher and mode. If the size of the data is not n * blocksize, the data will be padded with '\0'.

Mode is one of the MCRYPT_MODE_modename constants of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

The IV parameter is used for the initialisation in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all bytes set to '\0'.

后退 | 起点 | 前进
mcrypt_create_iv | 上一级 | mcrypt_ecb


mcrypt_ecb

(PHP 3>= 3.0.8, PHP 4 )

mcrypt_ecb -- Encrypt/decrypt data in ECB mode

Description

string mcrypt_ecb ( int cipher, string key, string data, int mode)

string mcrypt_ecb ( string cipher, string key, string data, int mode [, string iv])

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher.

This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.

后退 | 起点 | 前进
mcrypt_decrypt | 上一级 | mcrypt_enc_get_algorithms_name


mcrypt_enc_get_algorithms_name

(PHP 4 >= 4.0.2)

mcrypt_enc_get_algorithms_name -- Returns the name of the opened algorithm

Description

string mcrypt_enc_get_algorithms_name ( resource td)

This function returns the name of the algorithm.

例子 1. mcrypt_enc_get_algorithms_name() example

<?php
    $td = mcrypt_module_open (MCRYPT_CAST_256, '', MCRYPT_MODE_CFB, '');
    echo mcrypt_enc_get_algorithms_name($td). "\n";

    $td = mcrypt_module_open ('cast-256', '', MCRYPT_MODE_CFB, '');
    echo mcrypt_enc_get_algorithms_name($td). "\n";
?>

Prints:
CAST-256
CAST-256

后退 | 起点 | 前进
mcrypt_ecb | 上一级 | mcrypt_enc_get_block_size


mcrypt_enc_get_block_size

(PHP 4 >= 4.0.2)

mcrypt_enc_get_block_size -- Returns the blocksize of the opened algorithm

Description

int mcrypt_enc_get_block_size ( resource td)

This function returns the block size of the algorithm specified by the encryption descriptor td in bytes.

后退 | 起点 | 前进
mcrypt_enc_get_algorithms_name | 上一级 | mcrypt_enc_get_iv_size


mcrypt_enc_get_iv_size

(PHP 4 >= 4.0.2)

mcrypt_enc_get_iv_size -- Returns the size of the IV of the opened algorithm

Description

int mcrypt_enc_get_iv_size ( resource td)

This function returns the size of the iv of the algorithm specified by the encryption descriptor in bytes. If it returns '0' then the IV is ignored in the algorithm. An IV is used in cbc, cfb and ofb modes, and in some algorithms in stream mode.

后退 | 起点 | 前进
mcrypt_enc_get_block_size | 上一级 | mcrypt_enc_get_key_size


mcrypt_enc_get_key_size

(PHP 4 >= 4.0.2)

mcrypt_enc_get_key_size -- Returns the maximum supported keysize of the opened mode

Description

int mcrypt_enc_get_key_size ( resource td)

This function returns the maximum supported key size of the algorithm specified by the encryption descriptor td in bytes.

后退 | 起点 | 前进
mcrypt_enc_get_iv_size | 上一级 | mcrypt_enc_get_modes_name


mcrypt_enc_get_modes_name

(PHP 4 >= 4.0.2)

mcrypt_enc_get_modes_name -- Returns the name of the opened mode

Description

string mcrypt_enc_get_modes_name ( resource td)

This function returns the name of the mode.

例子 1. mcrypt_enc_get_modes_name() example

<?php
    $td = mcrypt_module_open (MCRYPT_CAST_256, '', MCRYPT_MODE_CFB, '');
    echo mcrypt_enc_get_modes_name($td). "\n";

    $td = mcrypt_module_open ('cast-256', '', 'ecb', '');
    echo mcrypt_enc_get_modes_name($td). "\n";
?>

Prints:
CFB
ECB

后退 | 起点 | 前进
mcrypt_enc_get_key_size | 上一级 | mcrypt_enc_get_supported_key_sizes


mcrypt_enc_get_supported_key_sizes

(PHP 4 >= 4.0.2)

mcrypt_enc_get_supported_key_sizes -- Returns an array with the supported keysizes of the opened algorithm

Description

array mcrypt_enc_get_supported_key_sizes ( resource td)

Returns an array with the key sizes supported by the algorithm specified by the encryption descriptor. If it returns an empty array then all key sizes between 1 and mcrypt_enc_get_key_size() are supported by the algorithm.

例子 1. mcrypt_enc_get_supported_key_sizes() example

<?php
    $td = mcrypt_module_open ('rijndael-256', '', 'ecb', '');
    var_dump (mcrypt_enc_get_supported_key_sizes($td));
?>

This will print:

array(3) {
  [0]=>
  int(16)
  [1]=>
  int(24)
  [2]=>
  int(32)
}
?>

后退 | 起点 | 前进
mcrypt_enc_get_modes_name | 上一级 | mcrypt_enc_is_block_algorithm_mode


mcrypt_enc_is_block_algorithm_mode

(PHP 4 >= 4.0.2)

mcrypt_enc_is_block_algorithm_mode -- Checks whether the encryption of the opened mode works on blocks

Description

bool mcrypt_enc_is_block_algorithm_mode ( resource td)

This function returns TRUE if the mode is for use with block algorithms, otherwise it returns FALSE. (eg. FALSE for stream, and TRUE for cbc, cfb, ofb).

后退 | 起点 | 前进
mcrypt_enc_get_supported_key_sizes | 上一级 | mcrypt_enc_is_block_algorithm


mcrypt_enc_is_block_algorithm

(PHP 4 >= 4.0.2)

mcrypt_enc_is_block_algorithm -- Checks whether the algorithm of the opened mode is a block algorithm

Description

bool mcrypt_enc_is_block_algorithm ( resource td)

This function returns TRUE if the algorithm is a block algorithm, or FALSE if it is a stream algorithm.

后退 | 起点 | 前进
mcrypt_enc_is_block_algorithm_mode | 上一级 | mcrypt_enc_is_block_mode


mcrypt_enc_is_block_mode

(PHP 4 >= 4.0.2)

mcrypt_enc_is_block_mode -- Checks whether the opened mode outputs blocks

Description

bool mcrypt_enc_is_block_mode ( resource td)

This function returns TRUE if the mode outputs blocks of bytes or FALSE if it outputs bytes. (eg. TRUE for cbc and ecb, and FALSE for cfb and stream).

后退 | 起点 | 前进
mcrypt_enc_is_block_algorithm | 上一级 | mcrypt_enc_self_test


mcrypt_enc_self_test

(PHP 4 >= 4.0.2)

mcrypt_enc_self_test -- This function runs a self test on the opened module

Description

bool mcrypt_enc_self_test ( resource td)

This function runs the self test on the algorithm specified by the descriptor td. If the self test succeeds it returns FALSE. In case of an error, it returns TRUE.

后退 | 起点 | 前进
mcrypt_enc_is_block_mode | 上一级 | mcrypt_encrypt


mcrypt_encrypt

(PHP 4 >= 4.0.2)

mcrypt_encrypt -- Encrypts plaintext with given parameters

Description

string mcrypt_encrypt ( string cipher, string key, string data, string mode [, string iv])

mcrypt_encrypt() encrypts the data and returns the encrypted data.

Cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.

Key is the key with which the data will be encrypted. If it's smaller that the required keysize, it is padded with '\0'. It is better not to use ASCII strings for keys. It is recommended to use the mhash functions to create a key from a string.

Data is the data that will be encrypted with the given cipher and mode. If the size of the data is not n * blocksize, the data will be padded with '\0'. The returned crypttext can be larger that the size of the data that is given by data.

Mode is one of the MCRYPT_MODE_modename constants of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

The IV parameter is used for the initialisation in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all bytes set to '\0'.

例子 1. mcrypt_encrypt() Example

<?php
    $iv = mcrypt_create_iv (mcrypt_get_iv_size (MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND);
    $key = "This is a very secret key";
    $text = "Meet me at 11 o'clock behind the monument.";
    echo strlen ($text)."\n";

    $crypttext = mcrypt_encrypt (MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv);
    echo strlen ($crypttext)."\n";
?>

The above example will print out:
42
64

See also mcrypt_module_open() for a more advanced API and an example.

后退 | 起点 | 前进
mcrypt_enc_self_test | 上一级 | mcrypt_generic_deinit


mcrypt_generic_deinit

(PHP 4 >= 4.1.1)

mcrypt_generic_deinit -- This function deinitializes an encryption module

Description

bool mcrypt_generic_deinit ( resource td)

This function terminates encryption specified by the encryption descriptor (td). It clears all buffers, but does not close the module. You need to call mcrypt_module_close() yourself. (But PHP does this for you at the end of the script. Returns FALSE on error, or TRUE on succes.

See for an example mcrypt_module_open() and the entry on mcrypt_generic_init().

后退 | 起点 | 前进
mcrypt_encrypt | 上一级 | mcrypt_generic_end


mcrypt_generic_end

(PHP 4 >= 4.0.2)

mcrypt_generic_end -- This function terminates encryption

Description

bool mcrypt_generic_end ( resource td)

This function is deprecated, use mcrypt_generic_deinit() instead. It can cause crashes when used with mcrypt_module_close() due to multiple buffer frees.

This function terminates encryption specified by the encryption descriptor (td). Actually it clears all buffers, and closes all the modules used. Returns FALSE on error, or TRUE on succes.

后退 | 起点 | 前进
mcrypt_generic_deinit | 上一级 | mcrypt_generic_init


mcrypt_generic_init

(PHP 4 >= 4.0.2)

mcrypt_generic_init -- This function initializes all buffers needed for encryption

Description

int mcrypt_generic_init ( resource td, string key, string iv)

The maximum length of the key should be the one obtained by calling mcrypt_enc_get_key_size() and every value smaller than this is legal. The IV should normally have the size of the algorithms block size, but you must obtain the size by calling mcrypt_enc_get_iv_size(). IV is ignored in ECB. IV MUST exist in CFB, CBC, STREAM, nOFB and OFB modes. It needs to be random and unique (but not secret). The same IV must be used for encryption/decryption. If you do not want to use it you should set it to zeros, but this is not recommended. The function returns a negative value on error.

You need to call this function before every call to mcrypt_generic() or mdecrypt_generic().

See for an example mcrypt_module_open() and the entry on mcrypt_generic_deinit().

后退 | 起点 | 前进
mcrypt_generic_end | 上一级 | mcrypt_generic


mcrypt_generic

(PHP 4 >= 4.0.2)

mcrypt_generic -- This function encrypts data

Description

string mcrypt_generic ( resource td, string data)

This function encrypts data. The data is padded with "\0" to make sure the length of the data is n * blocksize. This function returns the encrypted data. Note that the length of the returned string can in fact be longer then the input, due to the padding of the data.

The encryption handle should alwayws be initialized with mcrypt_generic_init() with a key and an IV before calling this function. Where the encryption is done, you should free the encryption buffers by calling mcrypt_generic_deinit(). See mcrypt_module_open() for an example.

See also mdecrypt_generic(),
mcrypt_generic_init() and
mcrypt_generic_deinit().

后退 | 起点 | 前进
mcrypt_generic_init | 上一级 | mcrypt_get_block_size


mcrypt_get_block_size

(PHP 3>= 3.0.8, PHP 4 )

mcrypt_get_block_size -- Get the block size of the specified cipher

Description

int mcrypt_get_block_size ( int cipher)

int mcrypt_get_block_size ( string cipher, string module)

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 2.5.x.

mcrypt_get_block_size() is used to get the size of a block of the specified cipher (in combination with an encryption mode).

This example shows how to use this function when linked against libmcrypt 2.4.x and 2.5.x.

例子 1. mcrypt_get_block_size() example

<?php
    echo mcrypt_get_block_size ('tripledes', 'ecb');
?>

Prints:
8

See also: mcrypt_get_key_size() and mcrypt_encrypt().

后退 | 起点 | 前进
mcrypt_generic | 上一级 | mcrypt_get_cipher_name


mcrypt_get_cipher_name

(PHP 3>= 3.0.8, PHP 4 )

mcrypt_get_cipher_name -- Get the name of the specified cipher

Description

string mcrypt_get_cipher_name ( int cipher)

string mcrypt_get_cipher_name ( string cipher)

mcrypt_get_cipher_name() is used to get the name of the specified cipher.

mcrypt_get_cipher_name() takes the cipher number as an argument (libmcrypt 2.2.x) or takes the cipher name as an argument (libmcrypt 2.4.x or higher) and returns the name of the cipher or FALSE, if the cipher does not exist.

例子 1. mcrypt_get_cipher_name() Example

<?php
   $cipher = MCRYPT_TripleDES;

   echo mcrypt_get_cipher_name ($cipher);
?>

The above example will produce:
3DES

后退 | 起点 | 前进
mcrypt_get_block_size | 上一级 | mcrypt_get_iv_size


mcrypt_get_iv_size

(PHP 4 >= 4.0.2)

mcrypt_get_iv_size -- Returns the size of the IV belonging to a specific cipher/mode combination

Description

int mcrypt_get_iv_size ( resource td)

int mcrypt_get_iv_size ( string cipher, string mode)

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher.

mcrypt_get_iv_size() returns the size of the Initialisation Vector (IV) in bytes. On error the function returns FALSE. If the IV is ignored in the specified cipher/mode combination zero is returned.

cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.

mode is one of the MCRYPT_MODE_modename constants of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

td is the resource that is returned by mcrypt_module_open().

例子 1. mcrypt_create_iv() example

<?php
    $size = mcrypt_get_iv_size (MCRYPT_CAST_256, MCRYPT_MODE_CFB);

    $size = mcrypt_get_iv_size ('des', 'ecb');
?>

See also: mcrypt_create_iv()

后退 | 起点 | 前进
mcrypt_get_cipher_name | 上一级 | mcrypt_get_key_size


mcrypt_get_key_size

(PHP 3>= 3.0.8, PHP 4 )

mcrypt_get_key_size -- Get the key size of the specified cipher

Description

int mcrypt_get_key_size ( int cipher)

int mcrypt_get_key_size ( string cipher, string module)

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 2.5.x.

mcrypt_get_key_size() is used to get the size of a key of the specified cipher (in combination with an encryption mode).

This example shows how to use this function when linked against libmcrypt 2.4.x and 2.5.x.

例子 1. mcrypt_get_block_size() example

<?php
    echo mcrypt_get_key_size ('tripledes', 'ecb');
?>

Prints:
24

See also: mcrypt_get_block_size() and mcrypt_encrypt().

后退 | 起点 | 前进
mcrypt_get_iv_size | 上一级 | mcrypt_list_algorithms


mcrypt_list_algorithms

(PHP 4 >= 4.0.2)

mcrypt_list_algorithms -- Get an array of all supported ciphers

Description

array mcrypt_list_algorithms ( [string lib_dir])

mcrypt_list_algorithms() is used to get an array of all supported algorithms in the lib_dir parameter.

mcrypt_list_algorithms() takes an optional lib_dir parameter which specifies the directory where all algorithms are located. If not specifies, the value of the mcrypt.algorithms_dir php.ini directive is used.

例子 1. mcrypt_list_algorithms() Example

<?php
    $algorithms = mcrypt_list_algorithms ("/usr/local/lib/libmcrypt");

    foreach ($algorithms as $cipher) {
        echo "$cipher<br />\n";
    }
?>

The above example will produce a list with all supported algorithms in the "/usr/local/lib/libmcrypt" directory.

后退 | 起点 | 前进
mcrypt_get_key_size | 上一级 | mcrypt_list_modes


mcrypt_list_modes

(PHP 4 >= 4.0.2)

mcrypt_list_modes -- Get an array of all supported modes

Description

array mcrypt_list_modes ( [string lib_dir])

mcrypt_list_modes() is used to get an array of all supported modes in the lib_dir.

mcrypt_list_modes() takes as optional parameter a directory which specifies the directory where all modes are located. If not specifies, the value of the mcrypt.modes_dir php.ini directive is used.

例子 1. mcrypt_list_modes() Example

<?php
    $modes = mcrypt_list_modes ();

    foreach ($modes as $mode) {
        echo "$mode <br />\n";
    }
?>

The above example will produce a list with all supported algorithms in the default mode directory. If it is not set with the ini directive mcrypt.modes_dir, the default directory of mcrypt is used (which is /usr/local/lib/libmcrypt).

后退 | 起点 | 前进
mcrypt_list_algorithms | 上一级 | mcrypt_module_close


mcrypt_module_close

(PHP 4 >= 4.0.2)

mcrypt_module_close -- Close the mcrypt module

Description

bool mcrypt_module_close ( resource td)

This function closes the specified encryption handle.

See mcrypt_module_open() for an example.

后退 | 起点 | 前进
mcrypt_list_modes | 上一级 | mcrypt_module_get_algo_block_size


mcrypt_module_get_algo_block_size

(PHP 4 >= 4.0.2)

mcrypt_module_get_algo_block_size -- Returns the blocksize of the specified algorithm

Description

int mcrypt_module_get_algo_block_size ( string algorithm [, string lib_dir])

This function returns the block size of the algorithm specified in bytes. The optional lib_dir parameter can contain the location where the mode module is on the system.

后退 | 起点 | 前进
mcrypt_module_close | 上一级 | mcrypt_module_get_algo_key_size


mcrypt_module_get_algo_key_size

(PHP 4 >= 4.0.2)

mcrypt_module_get_algo_key_size -- Returns the maximum supported keysize of the opened mode

Description

int mcrypt_module_get_algo_key_size ( string algorithm [, string lib_dir])

This function returns the maximum supported key size of the algorithm specified in bytes. The optional lib_dir parameter can contain the location where the mode module is on the system.

后退 | 起点 | 前进
mcrypt_module_get_algo_block_size | 上一级 | mcrypt_module_get_supported_key_sizes


mcrypt_module_get_supported_key_sizes

(PHP 4 >= 4.0.2)

mcrypt_module_get_supported_key_sizes -- Returns an array with the supported keysizes of the opened algorithm

Description

array mcrypt_module_get_supported_key_sizes ( string algorithm [, string lib_dir])

Returns an array with the key sizes supported by the specified algorithm. If it returns an empty array then all key sizes between 1 and mcrypt_module_get_algo_key_size() are supported by the algorithm. The optional lib_dir parameter can contain the location where the mode module is on the system.

See also mcrypt_enc_get_supported_key_sizes() which is used on open encryption modules.

后退 | 起点 | 前进
mcrypt_module_get_algo_key_size | 上一级 | mcrypt_module_is_block_algorithm_mode


mcrypt_module_is_block_algorithm_mode

(PHP 4 >= 4.0.2)

mcrypt_module_is_block_algorithm_mode -- This function returns if the the specified module is a block algorithm or not

Description

bool mcrypt_module_is_block_algorithm_mode ( string mode [, string lib_dir])

This function returns TRUE if the mode is for use with block algorithms, otherwise it returns FALSE. (eg. FALSE for stream, and TRUE for cbc, cfb, ofb). The optional lib_dir parameter can contain the location where the mode module is on the system.

后退 | 起点 | 前进
mcrypt_module_get_supported_key_sizes | 上一级 | mcrypt_module_is_block_algorithm


mcrypt_module_is_block_algorithm

(PHP 4 >= 4.0.2)

mcrypt_module_is_block_algorithm -- This function checks whether the specified algorithm is a block algorithm

Description

bool mcrypt_module_is_block_algorithm ( string algorithm [, string lib_dir])

This function returns TRUE if the specified algorithm is a block algorithm, or FALSE is it is a stream algorithm. The optional lib_dir parameter can contain the location where the algorithm module is on the system.

后退 | 起点 | 前进
mcrypt_module_is_block_algorithm_mode | 上一级 | mcrypt_module_is_block_mode


mcrypt_module_is_block_mode

(PHP 4 >= 4.0.2)

mcrypt_module_is_block_mode -- This function returns if the the specified mode outputs blocks or not

Description

bool mcrypt_module_is_block_mode ( string mode [, string lib_dir])

This function returns TRUE if the mode outputs blocks of bytes or FALSE if it outputs just bytes. (eg. TRUE for cbc and ecb, and FALSE for cfb and stream). The optional lib_dir parameter can contain the location where the mode module is on the system.

后退 | 起点 | 前进
mcrypt_module_is_block_algorithm | 上一级 | mcrypt_module_open


mcrypt_module_open

(PHP 4 >= 4.0.2)

mcrypt_module_open -- This function opens the module of the algorithm and the mode to be used

Description

resource mcrypt_module_open ( string algorithm, string algorithm_directory, string mode, string mode_directory)

This function opens the module of the algorithm and the mode to be used. The name of the algorithm is specified in algorithm, eg. "twofish" or is one of the MCRYPT_ciphername constants. The module is closed by calling mcrypt_module_close(). Normally it returns an encryption descriptor, or FALSE on error.

The algorithm_directory and mode_directory are used to locate the encryption modules. When you supply a directory name, it is used. When you set one of these to the empty string (""), the value set by the mcrypt.algorithms_dir or mcrypt.modes_dir ini-directive is used. When these are not set, the default directories that are used are the ones that were compiled in into libmcrypt (usally /usr/local/lib/libmcrypt).

例子 1. mcrypt_module_open() Example

<?php
    $td = mcrypt_module_open (MCRYPT_DES, '', MCRYPT_MODE_ECB, '/usr/lib/mcrypt-modes');
    $td = mcrypt_module_open ('rijndael-256', '', 'ofb', '');
?>

The first line in the example above will try to open the DES cipher from the default directory and the EBC mode from the directory /usr/lib/mcrypt-modes. The second example uses strings as name for the cipher an dmode, this only works when the extension is linked against libmcrypt 2.4.x or 2.5.x.

例子 2. Using mcrypt_module_open() in encryption

<?php
    /* Open the cipher */
    $td = mcrypt_module_open ('rijndael-256', '', 'ofb', '');

    /* Create the IV and determine the keysize length */
    $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);
    $ks = mcrypt_enc_get_key_size ($td);

    /* Create key */
    $key = substr (md5 ('very secret key'), 0, $ks);

    /* Intialize encryption */
    mcrypt_generic_init ($td, $key, $iv);

    /* Encrypt data */
    $encrypted = mcrypt_generic ($td, 'This is very important data');

    /* Terminate encryption handler */
    mcrypt_generic_deinit ($td);

    /* Initialize encryption module for decryption */
    mcrypt_generic_init ($td, $key, $iv);

    /* Decrypt encrypted string */
    $decrypted = mdecrypt_generic ($td, $encrypted);

    /* Terminate decryption handle and close module */
    mcrypt_generic_deinit ($td);
    mcrypt_module_close ($td);

    /* Show string */
    echo trim ($decrypted)."\n";
?>

The first line in the example above will try to open the DES cipher from the default directory and the EBC mode from the directory /usr/lib/mcrypt-modes. The second example uses strings as name for the cipher an dmode, this only works when the extension is linked against libmcrypt 2.4.x or 2.5.x.

See also mcrypt_module_close(),
mcrypt_generic(),
mdecrypt_generic(),
mcrypt_generic_init() and
mcrypt_generic_deinit().

后退 | 起点 | 前进
mcrypt_module_is_block_mode | 上一级 | mcrypt_module_self_test


mcrypt_module_self_test

(PHP 4 >= 4.0.2)

mcrypt_module_self_test -- This function runs a self test on the specified module

Description

bool mcrypt_module_self_test ( string algorithm [, string lib_dir])

This function runs the self test on the algorithm specified. The optional lib_dir parameter can contain the location of where the algorithm module is on the system.

The function returns TRUE if the self test succeeds, or FALSE when if fails.

后退 | 起点 | 前进
mcrypt_module_open | 上一级 | mcrypt_ofb


mcrypt_ofb

(PHP 3>= 3.0.8, PHP 4 )

mcrypt_ofb -- Encrypt/decrypt data in OFB mode

Description

string mcrypt_ofb ( int cipher, string key, string data, int mode, string iv)

string mcrypt_ofb ( string cipher, string key, string data, int mode [, string iv])

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher.

This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.

后退 | 起点 | 前进
mcrypt_module_self_test | 上一级 | mdecrypt_generic


mdecrypt_generic

(PHP 4 >= 4.0.2)

mdecrypt_generic -- This function decrypts data

Description

string mdecrypt_generic ( resource td, string data)

This function decrypts data. Note that the length of the returned string can in fact be longer then the unencrypted string, due to the padding of the data.

例子 1. mdecrypt_generic() Example

<?php
    /* Data */
    $key = 'this is a very long key, even too long for the cipher';
    $plain_text = 'very important data';

    /* Open module, and create IV */
    $td = mcrypt_module_open ('des', '', 'ecb', '');
    $key = substr ($key, 0, mcrypt_enc_get_key_size ($td));
    $iv_size = mcrypt_enc_get_iv_size ($td);
    $iv = mcrypt_create_iv ($iv_size, MCRYPT_RAND);

    /* Initialize encryption handle */
    if (mcrypt_generic_init ($td, $key, $iv) != -1) {

        /* Encrypt data */
        $c_t = mcrypt_generic ($td, $plain_text);
        mcrypt_generic_deinit ($td);

        /* Reinitialize buffers for decryption */
        mcrypt_generic_init ($td, $key, $iv);
        $p_t = mdecrypt_generic ($td, $c_t);

        /* Clean up */
        mcrypt_generic_deinit ($td);
        mcrypt_module_close ($td);
    }

    if (strncmp ($p_t, $plain_text, strlen($plain_text)) == 0) {
        echo "ok\n";
    } else {
        echo "error\n";
    }
?>

The above example shows how to check if the data before the encryption is the same as the data after the decryption. It is very important to reinitialize the encryption buffer with mcrypt_generic_init() before you try to decrypt the data.

The decryption handle should alwayws be initialized with mcrypt_generic_init() with a key and an IV before calling this function. Where the encryption is done, you should free the encryption buffers by calling mcrypt_generic_deinit(). See mcrypt_module_open() for an example.

See also mcrypt_generic(),
mcrypt_generic_init() and
mcrypt_generic_deinit().

后退 | 起点 | 前进
mcrypt_ofb | 上一级 | Mhash Functions


Mhash Functions

PHP 手册
后退 前进

LV. Mhash Functions

介绍

These functions are intended to work with mhash. Mhash can be used to create checksums, message digests, message authentication codes, and more.

This is an interface to the mhash library. mhash supports a wide variety of hash algorithms such as MD5, SHA1, GOST, and many others. For a complete list of supported hashes, refer to the documentation of mhash. The general rule is that you can access the hash algorithm from PHP with MHASH_HASHNAME. For example, to access TIGER you use the PHP constant MHASH_TIGER.

需求

To use it, download the mhash distribution from its web site and follow the included installation instructions.

安装

You need to compile PHP with the --with-mhash[=DIR] parameter to enable this extension. DIR is the mhash install directory.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

Here is a list of hashes which are currently supported by mhash. If a hash is not listed here, but is listed by mhash as supported, you can safely assume that this documentation is outdated.

  • MHASH_MD5

  • MHASH_SHA1

  • MHASH_HAVAL256

  • MHASH_HAVAL192

  • MHASH_HAVAL160

  • MHASH_HAVAL128

  • MHASH_RIPEMD160

  • MHASH_GOST

  • MHASH_TIGER

  • MHASH_CRC32

  • MHASH_CRC32B

范例

例子 1. Compute the MD5 digest and hmac and print it out as hex

<?php
$input = "what do ya want for nothing?";
$hash = mhash (MHASH_MD5, $input);
print "The hash is ".bin2hex ($hash)."<br />\n";
$hash = mhash (MHASH_MD5, $input, "Jefe");
print "The hmac is ".bin2hex ($hash)."<br />\n";
?>

This will produce:
The hash is d03cb659cbf9192dcd066272249f8412
The hmac is 750c783e6ab0b503eaa86e310a5db738

目录
mhash_count — Get the highest available hash id
mhash_get_block_size — Get the block size of the specified hash
mhash_get_hash_name — Get the name of the specified hash
mhash_keygen_s2k — Generates a key
mhash — Compute hash

后退 | 起点 | 前进
mdecrypt_generic | 上一级 | mhash_count


mhash_count

(PHP 3>= 3.0.9, PHP 4 )

mhash_count -- Get the highest available hash id

Description

int mhash_count ( void)

mhash_count() returns the highest available hash id. Hashes are numbered from 0 to this hash id.

例子 1. Traversing all hashes

<?php

$nr = mhash_count();

for ($i = 0; $i <= $nr; $i++) {
    echo sprintf ("The blocksize of %s is %d\n",
        mhash_get_hash_name ($i),
        mhash_get_block_size ($i));
}
?>

后退 | 起点 | 前进
Mhash Functions | 上一级 | mhash_get_block_size


mhash_get_block_size

(PHP 3>= 3.0.9, PHP 4 )

mhash_get_block_size -- Get the block size of the specified hash

Description

int mhash_get_block_size ( int hash)

mhash_get_block_size() is used to get the size of a block of the specified hash.

mhash_get_block_size() takes one argument, the hash and returns the size in bytes or FALSE, if the hash does not exist.

后退 | 起点 | 前进
mhash_count | 上一级 | mhash_get_hash_name


mhash_get_hash_name

(PHP 3>= 3.0.9, PHP 4 )

mhash_get_hash_name -- Get the name of the specified hash

Description

string mhash_get_hash_name ( int hash)

mhash_get_hash_name() is used to get the name of the specified hash.

mhash_get_hash_name() takes the hash id as an argument and returns the name of the hash or FALSE, if the hash does not exist.

例子 1. mhash_get_hash_name() example

<?php
$hash = MHASH_MD5;

print mhash_get_hash_name ($hash);
?>

The above example will print out:
MD5

后退 | 起点 | 前进
mhash_get_block_size | 上一级 | mhash_keygen_s2k


mhash_keygen_s2k

(PHP 4 >= 4.0.4)

mhash_keygen_s2k -- Generates a key

Description

string mhash_keygen_s2k ( int hash, string password, string salt, int bytes)

mhash_keygen_s2k() generates a key that is bytes long, from a user given password. This is the Salted S2K algorithm as specified in the OpenPGP document (RFC 2440). That algorithm will use the specified hash algorithm to create the key. The salt must be different and random enough for every key you generate in order to create different keys. That salt must be known when you check the keys, thus it is a good idea to append the key to it. Salt has a fixed length of 8 bytes and will be padded with zeros if you supply less bytes.

Keep in mind that user supplied passwords are not really suitable to be used as keys in cryptographic algorithms, since users normally choose keys they can write on keyboard. These passwords use only 6 to 7 bits per character (or less). It is highly recommended to use some kind of tranformation (like this function) to the user supplied key.

后退 | 起点 | 前进
mhash_get_hash_name | 上一级 | mhash


mhash

(PHP 3>= 3.0.9, PHP 4 )

mhash -- Compute hash

Description

string mhash ( int hash, string data [, string key])

mhash() applies a hash function specified by hash to the data and returns the resulting hash (also called digest). If the key is specified it will return the resulting HMAC. HMAC is keyed hashing for message authentication, or simply a message digest that depends on the specified key. Not all algorithms supported in mhash can be used in HMAC mode. In case of an error returns FALSE.

后退 | 起点 | 前进
mhash_keygen_s2k | 上一级 | Mimetype Functions


Mimetype Functions

PHP 手册
后退 前进

LVI. Mimetype Functions

介绍

The functions in this module try to guess the content type and encoding of a file by looking for certain magic byte sequences at specific positions within the file. While this is not a bullet proof approach the heuristics used do a very good job.

This extension is derivated from Apache mod_mime_magic, which is itself based on the file command maintaind by Ian F. Darwin. See the source code for further historic and copyright information.

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

The extension needs a copy of the magic.mime as distributed with the file command. This file also part of most recent Linux distributions and usually stored in the /usr/share/misc directory.

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. Mimetype configuration options

Name | Default | Changeable
mime_magic.magicfile | "/usr/share/misc/magic.mime" | PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

目录
mime_content_type — Detect MIME Content-type for a file

后退 | 起点 | 前进
mhash | 上一级 | mime_content_type


mime_content_type

(PHP 4 CVS only)

mime_content_type -- Detect MIME Content-type for a file

Description

string mime_content_type ( string filename)

Returns the MIME content type for a file as determined by using information from the magic.mime file. Content types are returned in MIME format, like text/plain or application/octet-stream.

后退 | 起点 | 前进
Mimetype Functions | 上一级 | Microsoft SQL Server functions


Microsoft SQL Server functions

PHP 手册
后退 前进

LVII. Microsoft SQL Server functions

介绍

These functions allow you to access MS SQL Server database.

注: The MSSQL extension is available on Win32 systems only. You can use the Sybase extension to connect to MSSQL databases from other platforms.

需求

The extension requires the MS SQL Client Tools to be installed on the system where PHP is installed. The Client Tools can be installed from the MS SQL Server CD or by copying ntwdblib.dll from \winnt\system32 on the server to \winnt\system32 on the PHP box. Copying ntwdblib.dll will only provide access. Configuration of the client will require installation of all the tools.

安装

The MSSQL extension is enabled by adding extension=php_mssql.dll to php.ini.

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. MS SQL Server configuration options

Name | Default | Changeable
mssql.allow_persistent | "1" | PHP_INI_SYSTEM
mssql.max_persistent | "-1" | PHP_INI_SYSTEM
mssql.max_links | "-1" | PHP_INI_SYSTEM
mssql.min_error_severity | "10" | PHP_INI_ALL
mssql.min_message_severity | "10" | PHP_INI_ALL
mssql.compatability_mode | "0" | PHP_INI_ALL
mssql.connect_timeout | "5" | PHP_INI_ALL
mssql.timeout | "60" | PHP_INI_ALL
mssql.textsize | "-1" | PHP_INI_ALL
mssql.textlimit | "-1" | PHP_INI_ALL
mssql.batchsize | "0" | PHP_INI_ALL
mssql.datetimeconvert | "1" | PHP_INI_ALL
mssql.secure_connection | "0" | PHP_INI_SYSTEM
mssql.max_procs | "25" | PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

资源类型

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

MSSQL_ASSOC (integer)

MSSQL_NUM (integer)

MSSQL_BOTH (integer)

SQLTEXT (integer)

SQLVARCHAR (integer)

SQLCHAR (integer)

SQLINT1 (integer)

SQLINT2 (integer)

SQLINT4 (integer)

SQLBIT (integer)

SQLFLT8 (integer)

目录
mssql_bind — Adds a parameter to a stored procedure or a remote stored procedure
mssql_close — Close MS SQL Server connection
mssql_connect — Open MS SQL server connection
mssql_data_seek — Move internal row pointer
mssql_execute — Executes a stored procedure on a MS SQL server database
mssql_fetch_array — Fetch row as array
mssql_fetch_assoc — Returns an associative array of the current row in the result set specified by result_id
mssql_fetch_batch — Returns the next batch of records
mssql_fetch_field — Get field information
mssql_fetch_object — Fetch row as object
mssql_fetch_row — Get row as enumerated array
mssql_field_length — Get the length of a field
mssql_field_name — Get the name of a field
mssql_field_seek — Set field offset
mssql_field_type — Get the type of a field
mssql_free_result — Free result memory
mssql_get_last_message — Returns the last message from server (over min_message_severity?)
mssql_guid_string — Converts a 16 byte binary GUID to a string
mssql_init — Initializes a stored procedure or a remote stored procedure
mssql_min_error_severity — Sets the lower error severity
mssql_min_message_severity — Sets the lower message severity
mssql_next_result — Move the internal result pointer to the next result
mssql_num_fields — Get number of fields in result
mssql_num_rows — Get number of rows in result
mssql_pconnect — Open persistent MS SQL connection
mssql_query — Send MS SQL query
mssql_result — Get result data
mssql_rows_affected — Returns the number of records affected by the query
mssql_select_db — Select MS SQL database

后退 | 起点 | 前进
mime_content_type | 上一级 | mssql_bind


mssql_bind

(PHP 4 >= 4.1.0)

mssql_bind -- Adds a parameter to a stored procedure or a remote stored procedure

Description

int mssql_bind ( int stmt, string param_name, mixed var, int type [, int is_output [, int is_null [, int maxlen]]])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
Microsoft SQL Server functions | 上一级 | mssql_close


mssql_close

(PHP 3, PHP 4 )

mssql_close -- Close MS SQL Server connection

Description

int mssql_close ( [int link_identifier])

Returns: TRUE on success, FALSE on error.

mssql_close() closes the link to a MS SQL Server database that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.

Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

mssql_close() will not close persistent links generated by mssql_pconnect().

See also: mssql_connect(), mssql_pconnect().

后退 | 起点 | 前进
mssql_bind | 上一级 | mssql_connect


mssql_connect

(PHP 3, PHP 4 )

mssql_connect -- Open MS SQL server connection

Description

int mssql_connect ( [string servername [, string username [, string password]]])

Returns: A positive MS SQL link identifier on success, or FALSE on error.

mssql_connect() establishes a connection to a MS SQL server. The servername argument has to be a valid servername that is defined in the 'interfaces' file.

In case a second call is made to mssql_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 mssql_close().

See also mssql_pconnect(), mssql_close().

后退 | 起点 | 前进
mssql_close | 上一级 | mssql_data_seek


mssql_data_seek

(PHP 3, PHP 4 )

mssql_data_seek -- Move internal row pointer

Description

int mssql_data_seek ( int result_identifier, int row_number)

Returns: TRUE on success, FALSE on failure.

mssql_data_seek() moves the internal row pointer of the MS SQL result associated with the specified result identifier to point to the specified row number. The next call to mssql_fetch_row() would return that row.

See also: mssql_data_seek().

后退 | 起点 | 前进
mssql_connect | 上一级 | mssql_execute


mssql_execute

(PHP 4 >= 4.1.0)

mssql_execute -- Executes a stored procedure on a MS SQL server database

Description

int mssql_execute ( int stmt)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
mssql_data_seek | 上一级 | mssql_fetch_array


mssql_fetch_array

(PHP 3, PHP 4 )

mssql_fetch_array -- Fetch row as array

Description

int mssql_fetch_array ( int result)

Returns: An array that corresponds to the fetched row, or FALSE if there are no more rows.

mssql_fetch_array() is an extended version of mssql_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

An important thing to note is that using mssql_fetch_array() is NOT significantly slower than using mssql_fetch_row(), while it provides a significant added value.

For further details, also see mssql_fetch_row().

后退 | 起点 | 前进
mssql_execute | 上一级 | mssql_fetch_assoc


mssql_fetch_assoc

(PHP 4 >= 4.2.0)

mssql_fetch_assoc -- Returns an associative array of the current row in the result set specified by result_id

Description

array mssql_fetch_assoc ( int result_id [, int result_type])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
mssql_fetch_array | 上一级 | mssql_fetch_batch


mssql_fetch_batch

(PHP 4 >= 4.0.4)

mssql_fetch_batch -- Returns the next batch of records

Description

int mssql_fetch_batch ( string result_index)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
mssql_fetch_assoc | 上一级 | mssql_fetch_field


mssql_fetch_field

(PHP 3, PHP 4 )

mssql_fetch_field -- Get field information

Description

object mssql_fetch_field ( int result [, int field_offset])

Returns an object containing field information.

mssql_fetch_field() can be used in order to obtain information about fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by mssql_fetch_field() is retrieved.

The properties of the object are:

  • name - column name. if the column is a result of a function, this property is set to computed#N, where #N is a serial number.

  • column_source - the table from which the column was taken

  • max_length - maximum length of the column

  • numeric - 1 if the column is numeric

See also mssql_field_seek().

后退 | 起点 | 前进
mssql_fetch_batch | 上一级 | mssql_fetch_object


mssql_fetch_object

(PHP 3)

mssql_fetch_object -- Fetch row as object

Description

int mssql_fetch_object ( int result)

Returns: An object with properties that correspond to the fetched row, or FALSE if there are no more rows.

mssql_fetch_object() is similar to mssql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

Speed-wise, the function is identical to mssql_fetch_array(), and almost as quick as mssql_fetch_row() (the difference is insignificant).

See also: mssql_fetch-array() and mssql_fetch-row().

后退 | 起点 | 前进
mssql_fetch_field | 上一级 | mssql_fetch_row


mssql_fetch_row

(PHP 3, PHP 4 )

mssql_fetch_row -- Get row as enumerated array

Description

array mssql_fetch_row ( int result)

Returns: An array that corresponds to the fetched row, or FALSE if there are no more rows.

mssql_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 call to mssql_fetch_rows() would return the next row in the result set, or FALSE if there are no more rows.

See also: mssql_fetch_array(),
mssql_fetch_object(),
mssql_data_seek(),
mssql_fetch_lengths(), and
mssql_result().

后退 | 起点 | 前进
mssql_fetch_object | 上一级 | mssql_field_length


mssql_field_length

(PHP 3>= 3.0.3, PHP 4 )

mssql_field_length -- Get the length of a field

Description

int mssql_field_length ( int result [, int offset])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
mssql_fetch_row | 上一级 | mssql_field_name


mssql_field_name

(PHP 3>= 3.0.3, PHP 4 )

mssql_field_name -- Get the name of a field

Description

int mssql_field_name ( int result [, int offset])

后退 | 起点 | 前进
mssql_field_length | 上一级 | mssql_field_seek


mssql_field_seek

(PHP 3, PHP 4 )

mssql_field_seek -- Set field offset

Description

int mssql_field_seek ( int result, int field_offset)

Seeks to the specified field offset. If the next call to mssql_fetch_field() won't include a field offset, this field would be returned.

See also: mssql_fetch_field().

后退 | 起点 | 前进
mssql_field_name | 上一级 | mssql_field_type


mssql_field_type

(PHP 3>= 3.0.3, PHP 4 )

mssql_field_type -- Get the type of a field

Description

string mssql_field_type ( int result [, int offset])

后退 | 起点 | 前进
mssql_field_seek | 上一级 | mssql_free_result


mssql_free_result

(PHP 3, PHP 4 )

mssql_free_result -- Free result memory

Description

int mssql_free_result ( int result)

mssql_free_result() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script ends. You may call mssql_free_result() with the result identifier as an argument and the associated result memory will be freed.

后退 | 起点 | 前进
mssql_field_type | 上一级 | mssql_get_last_message


mssql_get_last_message

(PHP 3, PHP 4 )

mssql_get_last_message -- Returns the last message from server (over min_message_severity?)

Description

string mssql_get_last_message ( void)

后退 | 起点 | 前进
mssql_free_result | 上一级 | mssql_guid_string


mssql_guid_string

(PHP 4 >= 4.1.0)

mssql_guid_string -- Converts a 16 byte binary GUID to a string

Description

string mssql_guid_string ( string binary [, int short_format])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
mssql_get_last_message | 上一级 | mssql_init


mssql_init

(PHP 4 >= 4.1.0)

mssql_init -- Initializes a stored procedure or a remote stored procedure

Description

int mssql_init ( string sp_name [, int conn_id])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
mssql_guid_string | 上一级 | mssql_min_error_severity


mssql_min_error_severity

(PHP 3, PHP 4 )

mssql_min_error_severity -- Sets the lower error severity

Description

void mssql_min_error_severity ( int severity)

后退 | 起点 | 前进
mssql_init | 上一级 | mssql_min_message_severity


mssql_min_message_severity

(PHP 3, PHP 4 )

mssql_min_message_severity -- Sets the lower message severity

Description

void mssql_min_message_severity ( int severity)

后退 | 起点 | 前进
mssql_min_error_severity | 上一级 | mssql_next_result


mssql_next_result

(PHP 4 >= 4.0.5)

mssql_next_result -- Move the internal result pointer to the next result

Description

bool mssql_next_result ( int result_id)

When sending more than one SQL statement to the server or executing a stored procedure with multiple results, it will cause the server to return multiple result sets. This function will test for additional results available form the server. If an additional result set exists it will free the existing result set and prepare to fetch the rows from the new result set. The function will return TRUE if an additional result set was available or FALSE otherwise.

例子 1. mssql_next_result() example

<?php
    $link = mssql_connect ("localhost", "userid", "secret");
    mssql_select_db("MyDB", $link);
    $SQL = "Select * from table1 select * from table2";
    $rs = mssql_query($SQL, $link);
    do {
        while ($row = mssql_fetch_row($rs)) {
        }
    } while (mssql_next_result($rs));
    mssql_free_result($rs);
    mssql_close ($link);
?>

后退 | 起点 | 前进
mssql_min_message_severity | 上一级 | mssql_num_fields


mssql_num_fields

(PHP 3, PHP 4 )

mssql_num_fields -- Get number of fields in result

Description

int mssql_num_fields ( int result)

mssql_num_fields() returns the number of fields in a result set.

See also: mssql_db_query(),
mssql_query(),
mssql_fetch_field(), and
mssql_num_rows().

后退 | 起点 | 前进
mssql_next_result | 上一级 | mssql_num_rows


mssql_num_rows

(PHP 3, PHP 4 )

mssql_num_rows -- Get number of rows in result

Description

int mssql_num_rows ( string result)

mssql_num_rows() returns the number of rows in a result set.

See also: mssql_db_query(),
mssql_query(), and
mssql_fetch_row().

后退 | 起点 | 前进
mssql_num_fields | 上一级 | mssql_pconnect


mssql_pconnect

(PHP 3, PHP 4 )

mssql_pconnect -- Open persistent MS SQL connection

Description

int mssql_pconnect ( [string servername [, string username [, string password]]])

Returns: A positive MS SQL persistent link identifier on success, or FALSE on error.

mssql_pconnect() acts very much like mssql_connect() with two major differences.

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mssql_close() will not close links established by mssql_pconnect()).

This type of links is therefore called 'persistent'.

后退 | 起点 | 前进
mssql_num_rows | 上一级 | mssql_query


mssql_query

(PHP 3, PHP 4 )

mssql_query -- Send MS SQL query

Description

int mssql_query ( string query [, int link_identifier])

Returns: A positive MS SQL result identifier on success, or FALSE on error.

mssql_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if mssql_connect() was called, and use it.

See also: mssql_db_query(),
mssql_select_db(), and
mssql_connect().

后退 | 起点 | 前进
mssql_pconnect | 上一级 | mssql_result


mssql_result

(PHP 3, PHP 4 )

mssql_result -- Get result data

Description

int mssql_result ( int result, int i, mixed field)

mssql_result() returns the contents of one cell from a MS SQL result set. The field argument can be the field's offset, the field's name or the field's table dot field's name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), it uses the alias instead of the column name.

When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than mssql_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Recommended high-performance alternatives:
mssql_fetch_row(),
mssql_fetch_array(), and
mssql_fetch_object().

后退 | 起点 | 前进
mssql_query | 上一级 | mssql_rows_affected


mssql_rows_affected

(PHP 4 >= 4.0.4)

mssql_rows_affected -- Returns the number of records affected by the query

Description

int mssql_rows_affected ( int conn_id)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
mssql_result | 上一级 | mssql_select_db


mssql_select_db

(PHP 3, PHP 4 )

mssql_select_db -- Select MS SQL database

Description

int mssql_select_db ( string database_name [, int link_identifier])

Returns: TRUE on success, FALSE on error

mssql_select_db() sets the current active database on the server that's associated with the specified link identifier. If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if mssql_connect() was called, and use it.

Every subsequent call to mssql_query() will be made on the active database.

See also:
    mssql_connect(),
    mssql_pconnect(), and
    mssql_query()

后退 | 起点 | 前进
mssql_rows_affected | 上一级 | Ming functions for Flash


Ming functions for Flash

PHP 手册
后退 前进

LVIII. Ming functions for Flash

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

介绍

First of all: Ming is not an acronym. Ming is an open-source (LGPL) library which allows you to create SWF ("Flash") format movies. Ming supports almost all of Flash 4's features, including: shapes, gradients, bitmaps (pngs and jpegs), morphs ("shape tweens"), text, buttons, actions, sprites ("movie clips"), streaming mp3, and color transforms --the only thing that's missing is sound events.

Note that all values specifying length, distance, size, etc. are in "twips", twenty units per pixel. That's pretty much arbitrary, though, since the player scales the movie to whatever pixel size is specified in the embed/object tag, or the entire frame if not embedded.

Ming offers a number of advantages over the existing PHP/libswf module. You can use Ming anywhere you can compile the code, whereas libswf is closed-source and only available for a few platforms, Windows not one of them. Ming provides some insulation from the mundane details of the SWF file format, wrapping the movie elements in PHP objects. Also, Ming is still being maintained; if there's a feature that you want to see, just let us know ming@opaque.net.

Ming was added in PHP 4.0.5.

需求

To use Ming with PHP, you first need to build and install the Ming library. Source code and installation instructions are available at the Ming home page: http://www.opaque.net/ming/ along with examples, a small tutorial, and the latest news.

Download the ming archive. Unpack the archive. Go in the Ming directory. make. make install.

This will build libming.so and install it into /usr/lib/, and copy ming.h into /usr/include/. Edit the PREFIX= line in the Makefile to change the installation directory.

安装

例子 1. built into php (unix)

mkdir <phpdir>/ext/ming
cp php_ext/* <phpdir>/ext/ming
cd <phpdir>
./buildconf
./configure --with-ming <other config options>

Build and install php as usual, restart web server if necessary.

Now either just add extension=php_ming.so to your php.ini file, or put dl('php_ming.so'); at the head of all of your Ming scripts.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

SWFBUTTON_HIT (integer)

SWFBUTTON_DOWN (integer)

SWFBUTTON_OVER (integer)

SWFBUTTON_UP (integer)

SWFBUTTON_MOUSEUPOUTSIDE (integer)

SWFBUTTON_DRAGOVER (integer)

SWFBUTTON_DRAGOUT (integer)

SWFBUTTON_MOUSEUP (integer)

SWFBUTTON_MOUSEDOWN (integer)

SWFBUTTON_MOUSEOUT (integer)

SWFBUTTON_MOUSEOVER (integer)

SWFFILL_RADIAL_GRADIENT (integer)

SWFFILL_LINEAR_GRADIENT (integer)

SWFFILL_TILED_BITMAP (integer)

SWFFILL_CLIPPED_BITMAP (integer)

SWFTEXTFIELD_HASLENGTH (integer)

SWFTEXTFIELD_NOEDIT (integer)

SWFTEXTFIELD_PASSWORD (integer)

SWFTEXTFIELD_MULTILINE (integer)

SWFTEXTFIELD_WORDWRAP (integer)

SWFTEXTFIELD_DRAWBOX (integer)

SWFTEXTFIELD_NOSELECT (integer)

SWFTEXTFIELD_HTML (integer)

SWFTEXTFIELD_ALIGN_LEFT (integer)

SWFTEXTFIELD_ALIGN_RIGHT (integer)

SWFTEXTFIELD_ALIGN_CENTER (integer)

SWFTEXTFIELD_ALIGN_JUSTIFY (integer)

SWFACTION_ONLOAD (integer)

SWFACTION_ENTERFRAME (integer)

SWFACTION_UNLOAD (integer)

SWFACTION_MOUSEMOVE (integer)

SWFACTION_MOUSEDOWN (integer)

SWFACTION_MOUSEUP (integer)

SWFACTION_KEYDOWN (integer)

SWFACTION_KEYUP (integer)

SWFACTION_DATA (integer)

预定义类

由于这些类是由该扩展模块定义的，因此它们仅在该扩展模块被编译到 PHP 内核中，或者在运行时被动态加载后才有效。

Ming introduces 13 new objects in PHP, all with matching methods and attributes. To use them, you need to know about objects.

swfshape

swffill

swfgradient

swfbitmap

swftext

swftextfield

swffont

swfdisplayitem

swfmovie

swfbutton

swfaction

swfmorph

swfsprite

目录
ming_setcubicthreshold — Set cubic threshold (?)
ming_setscale — Set scale (?)
ming_useswfversion — Use SWF version (?)
SWFAction — Creates a new Action.
SWFBitmap->getHeight — Returns the bitmap's height.
SWFBitmap->getWidth — Returns the bitmap's width.
SWFBitmap — Loads Bitmap object
swfbutton_keypress — Returns the action flag for keyPress(char)
SWFbutton->addAction — Adds an action
SWFbutton->addShape — Adds a shape to a button
SWFbutton->setAction — Sets the action
SWFbutton->setdown — Alias for addShape(shape, SWFBUTTON_DOWN))
SWFbutton->setHit — Alias for addShape(shape, SWFBUTTON_HIT)
SWFbutton->setOver — Alias for addShape(shape, SWFBUTTON_OVER)
SWFbutton->setUp — Alias for addShape(shape, SWFBUTTON_UP)
SWFbutton — Creates a new Button.
SWFDisplayItem->addColor — Adds the given color to this item's color transform.
SWFDisplayItem->move — Moves object in relative coordinates.
SWFDisplayItem->moveTo — Moves object in global coordinates.
SWFDisplayItem->multColor — Multiplies the item's color transform.
SWFDisplayItem->remove — Removes the object from the movie
SWFDisplayItem->Rotate — Rotates in relative coordinates.
SWFDisplayItem->rotateTo — Rotates the object in global coordinates.
SWFDisplayItem->scale — Scales the object in relative coordinates.
SWFDisplayItem->scaleTo — Scales the object in global coordinates.
SWFDisplayItem->setDepth — Sets z-order
SWFDisplayItem->setName — Sets the object's name
SWFDisplayItem->setRatio — Sets the object's ratio.
SWFDisplayItem->skewX — Sets the X-skew.
SWFDisplayItem->skewXTo — Sets the X-skew.
SWFDisplayItem->skewY — Sets the Y-skew.
SWFDisplayItem->skewYTo — Sets the Y-skew.
SWFDisplayItem — Creates a new displayitem object.
SWFFill->moveTo — Moves fill origin
SWFFill->rotateTo — Sets fill's rotation
SWFFill->scaleTo — Sets fill's scale
SWFFill->skewXTo — Sets fill x-skew
SWFFill->skewYTo — Sets fill y-skew
SWFFill — Loads SWFFill object
swffont->getwidth — Returns the string's width
SWFFont — Loads a font definition
SWFGradient->addEntry — Adds an entry to the gradient list.
SWFGradient — Creates a gradient object
SWFMorph->getshape1 — Gets a handle to the starting shape
SWFMorph->getshape2 — Gets a handle to the ending shape
SWFMorph — Creates a new SWFMorph object.
SWFMovie->add — Adds any type of data to a movie.
SWFMovie->nextframe — Moves to the next frame of the animation.
SWFMovie->output — Dumps your lovingly prepared movie out.
SWFMovie->remove — Removes the object instance from the display list.
SWFMovie->save — Saves your movie in a file.
SWFMovie->setbackground — Sets the background color.
SWFMovie->setdimension — Sets the movie's width and height.
SWFMovie->setframes — Sets the total number of frames in the animation.
SWFMovie->setrate — Sets the animation's frame rate.
SWFMovie->streammp3 — Streams a MP3 file.
SWFMovie — Creates a new movie object, representing an SWF version 4 movie.
SWFShape->addFill — Adds a solid fill to the shape.
SWFShape->drawCurve — Draws a curve (relative).
SWFShape->drawCurveTo — Draws a curve.
SWFShape->drawLine — Draws a line (relative).
SWFShape->drawLineTo — Draws a line.
SWFShape->movePen — Moves the shape's pen (relative).
SWFShape->movePenTo — Moves the shape's pen.
SWFShape->setLeftFill — Sets left rasterizing color.
SWFShape->setLine — Sets the shape's line style.
SWFShape->setRightFill — Sets right rasterizing color.
SWFShape — Creates a new shape object.
SWFSprite->add — Adds an object to a sprite
SWFSprite->nextframe — Moves to the next frame of the animation.
SWFSprite->remove — Removes an object to a sprite
SWFSprite->setframes — Sets the total number of frames in the animation.
SWFSprite — Creates a movie clip (a sprite)
SWFText->addString — Draws a string
SWFText->getWidth — Computes string's width
SWFText->moveTo — Moves the pen
SWFText->setColor — Sets the current font color
SWFText->setFont — Sets the current font
SWFText->setHeight — Sets the current font height
SWFText->setSpacing — Sets the current font spacing
SWFText — Creates a new SWFText object.
SWFTextField->addstring — Concatenates the given string to the text field
SWFTextField->align — Sets the text field alignment
SWFTextField->setbounds — Sets the text field width and height
SWFTextField->setcolor — Sets the color of the text field.
SWFTextField->setFont — Sets the text field font
SWFTextField->setHeight — Sets the font height of this text field font.
SWFTextField->setindentation — Sets the indentation of the first line.
SWFTextField->setLeftMargin — Sets the left margin width of the text field.
SWFTextField->setLineSpacing — Sets the line spacing of the text field.
SWFTextField->setMargins — Sets the margins width of the text field.
SWFTextField->setname — Sets the variable name
SWFTextField->setrightMargin — Sets the right margin width of the text field.
SWFTextField — Creates a text field object

后退 | 起点 | 前进
mssql_select_db | 上一级 | ming_setcubicthreshold


ming_setcubicthreshold

(PHP 4 >= 4.0.5)

ming_setcubicthreshold -- Set cubic threshold (?)

Description

void ming_setcubicthreshold ( int threshold)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
Ming functions for Flash | 上一级 | ming_setscale


ming_setscale

(PHP 4 >= 4.0.5)

ming_setscale -- Set scale (?)

Description

void ming_setscale ( int scale)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ming_setcubicthreshold | 上一级 | ming_useswfversion


ming_useswfversion

(PHP 4 >= 4.2.0)

ming_useswfversion -- Use SWF version (?)

Description

void ming_useswfversion ( int version)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
ming_setscale | 上一级 | SWFAction


SWFAction

(PHP 4 >= 4.0.5)

SWFAction -- Creates a new Action.

Description

new swfaction ( string script)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfaction() creates a new Action, and compiles the given script into an SWFAction object.

The script syntax is based on the C language, but with a lot taken out- the SWF bytecode machine is just too simpleminded to do a lot of things we might like. For instance, we can't implement function calls without a tremendous amount of hackery because the jump bytecode has a hardcoded offset value. No pushing your calling address to the stack and returning- every function would have to know exactly where to return to.

So what's left? The compiler recognises the following tokens:

  • break

  • for

  • continue

  • if

  • else

  • do

  • while

There is no typed data; all values in the SWF action machine are stored as strings. The following functions can be used in expressions:

time()

Returns the number of milliseconds (?) elapsed since the movie started.

random(seed)

Returns a pseudo-random number in the range 0-seed.

length(expr)

Returns the length of the given expression.

int(number)

Returns the given number rounded down to the nearest integer.

concat(expr, expr)

Returns the concatenation of the given expressions.

ord(expr)

Returns the ASCII code for the given character

chr(num)

Returns the character for the given ASCII code

substr(string, location, length)

Returns the substring of length length at location location of the given string string.

Additionally, the following commands may be used:

duplicateClip(clip, name, depth)

Duplicate the named movie clip (aka sprite). The new movie clip has name name and is at depth depth.

removeClip(expr)

Removes the named movie clip.

trace(expr)

Write the given expression to the trace log. Doubtful that the browser plugin does anything with this.

startDrag(target, lock, [left, top, right, bottom])

Start dragging the movie clip target. The lock argument indicates whether to lock the mouse (?)- use 0 (FALSE) or 1 (TRUE). Optional parameters define a bounding area for the dragging.

stopDrag()

Stop dragging my heart around. And this movie clip, too.

callFrame(expr)

Call the named frame as a function.

getURL(url, target, [method])

Load the given URL into the named target. The target argument corresponds to HTML document targets (such as "_top" or "_blank"). The optional method argument can be POST or GET if you want to submit variables back to the server.

loadMovie(url, target)

Load the given URL into the named target. The target argument can be a frame name (I think), or one of the magical values "_level0" (replaces current movie) or "_level1" (loads new movie on top of current movie).

nextFrame()

Go to the next frame.

prevFrame()

Go to the last (or, rather, previous) frame.

play()

Start playing the movie.

stop()

Stop playing the movie.

toggleQuality()

Toggle between high and low quality.

stopSounds()

Stop playing all sounds.

gotoFrame(num)

Go to frame number num. Frame numbers start at 0.

gotoFrame(name)

Go to the frame named name. Which does a lot of good, since I haven't added frame labels yet.

setTarget(expr)

Sets the context for action. Or so they say- I really have no idea what this does.

And there's one weird extra thing. The expression frameLoaded(num) can be used in if statements and while loops to check if the given frame number has been loaded yet. Well, it's supposed to, anyway, but I've never tested it and I seriously doubt it actually works. You can just use /:framesLoaded instead.

Movie clips (all together now- aka sprites) have properties. You can read all of them (or can you?), you can set some of them, and here they are:

  • x

  • y

  • xScale

  • yScale

  • currentFrame - (read-only)

  • totalFrames - (read-only)

  • alpha - transparency level

  • visible - 1=on, 0=off (?)

  • width - (read-only)

  • height - (read-only)

  • rotation

  • target - (read-only) (???)

  • framesLoaded - (read-only)

  • name

  • dropTarget - (read-only) (???)

  • url - (read-only) (???)

  • highQuality - 1=high, 0=low (?)

  • focusRect - (???)

  • soundBufTime - (???)

So, setting a sprite's x position is as simple as /box.x = 100;. Why the slash in front of the box, though? That's how flash keeps track of the sprites in the movie, just like a unix filesystem- here it shows that box is at the top level. If the sprite named box had another sprite named biff inside of it, you'd set its x position with /box/biff.x = 100;. At least, I think so; correct me if I'm wrong here.

This simple example will move the red square across the window.

例子 1. swfaction() example

<?php
 $s = new SWFShape();
  $f = $s->addFill(0xff, 0, 0);
  $s->setRightFill($f);

  $s->movePenTo(-500,-500);
  $s->drawLineTo(500,-500);
  $s->drawLineTo(500,500);
  $s->drawLineTo(-500,500);
  $s->drawLineTo(-500,-500);

  $p = new SWFSprite();
  $i = $p->add($s);
  $i->setDepth(1);
  $p->nextFrame();

  for($n=0; $n<5; ++$n)
  {
    $i->rotate(-15);
    $p->nextFrame();
  }

  $m = new SWFMovie();
  $m->setBackground(0xff, 0xff, 0xff);
  $m->setDimension(6000,4000);

  $i = $m->add($p);
  $i->setDepth(1);
  $i->moveTo(-500,2000);
  $i->setName("box");

  $m->add(new SWFAction("/box.x += 3;"));
  $m->nextFrame();
  $m->add(new SWFAction("gotoFrame(0); play();"));
  $m->nextFrame();

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

This simple example tracks down your mouse on the screen.

例子 2. swfaction() example

<?php

  $m = new SWFMovie();
  $m->setRate(36.0);
  $m->setDimension(1200, 800);
  $m->setBackground(0, 0, 0);

  /* mouse tracking sprite - empty, but follows mouse so we can
     get its x and y coordinates */

  $i = $m->add(new SWFSprite());
  $i->setName('mouse');

  $m->add(new SWFAction("
    startDrag('/mouse', 1); /* '1' means lock sprite to the mouse */
  "));

  /* might as well turn off antialiasing, since these are just squares. */

  $m->add(new SWFAction("
    this.quality = 0;
  "));

  /* morphing box */
  $r = new SWFMorph();
  $s = $r->getShape1();

  /* Note this is backwards from normal shapes.  No idea why. */
  $s->setLeftFill($s->addFill(0xff, 0xff, 0xff));
  $s->movePenTo(-40, -40);
  $s->drawLine(80, 0);
  $s->drawLine(0, 80);
  $s->drawLine(-80, 0);
  $s->drawLine(0, -80);

  $s = $r->getShape2();

  $s->setLeftFill($s->addFill(0x00, 0x00, 0x00));
  $s->movePenTo(-1, -1);
  $s->drawLine(2, 0);
  $s->drawLine(0, 2);
  $s->drawLine(-2, 0);
  $s->drawLine(0, -2);

  /* sprite container for morphing box -
     this is just a timeline w/ the box morphing */

  $box = new SWFSprite();
  $box->add(new SWFAction("
    stop();
  "));
  $i = $box->add($r);

  for($n=0; $n<=20; ++$n)
  {
    $i->setRatio($n/20);
    $box->nextFrame();
  }

  /* this container sprite allows us to use the same action code many times */

  $cell = new SWFSprite();
  $i = $cell->add($box);
  $i->setName('box');

  $cell->add(new SWFAction("

    setTarget('box');

    /* ...x means the x coordinate of the parent, i.e. (..).x */
    dx = (/mouse.x + random(6)-3 - ...x)/5;
    dy = (/mouse.y + random(6)-3 - ...y)/5;
    gotoFrame(int(dx*dx + dy*dy));

  "));

  $cell->nextFrame();
  $cell->add(new SWFAction("

    gotoFrame(0);
    play();

  "));

  $cell->nextFrame();

  /* finally, add a bunch of the cells to the movie */

  for($x=0; $x<12; ++$x)
  {
    for($y=0; $y<8; ++$y)
    {
      $i = $m->add($cell);
      $i->moveTo(100*$x+50, 100*$y+50);
    }
  }

  $m->nextFrame();

  $m->add(new SWFAction("

    gotoFrame(1);
    play();

  "));

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

Same as above, but with nice colored balls...

例子 3. swfaction() example

<?php

  $m = new SWFMovie();
  $m->setDimension(11000, 8000);
  $m->setBackground(0x00, 0x00, 0x00);

  $m->add(new SWFAction("

this.quality = 0;
/frames.visible = 0;
startDrag('/mouse', 1);

  "));

  // mouse tracking sprite
  $t = new SWFSprite();
  $i = $m->add($t);
  $i->setName('mouse');

  $g = new SWFGradient();
  $g->addEntry(0, 0xff, 0xff, 0xff, 0xff);
  $g->addEntry(0.1, 0xff, 0xff, 0xff, 0xff);
  $g->addEntry(0.5, 0xff, 0xff, 0xff, 0x5f);
  $g->addEntry(1.0, 0xff, 0xff, 0xff, 0);

  // gradient shape thing
  $s = new SWFShape();
  $f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
  $f->scaleTo(0.03);
  $s->setRightFill($f);
  $s->movePenTo(-600, -600);
  $s->drawLine(1200, 0);
  $s->drawLine(0, 1200);
  $s->drawLine(-1200, 0);
  $s->drawLine(0, -1200);

  // need to make this a sprite so we can multColor it
  $p = new SWFSprite();
  $p->add($s);
  $p->nextFrame();

  // put the shape in here, each frame a different color
  $q = new SWFSprite();
  $q->add(new SWFAction("gotoFrame(random(7)+1); stop();"));
  $i = $q->add($p);

  $i->multColor(1.0, 1.0, 1.0);
  $q->nextFrame();
  $i->multColor(1.0, 0.5, 0.5);
  $q->nextFrame();
  $i->multColor(1.0, 0.75, 0.5);
  $q->nextFrame();
  $i->multColor(1.0, 1.0, 0.5);
  $q->nextFrame();
  $i->multColor(0.5, 1.0, 0.5);
  $q->nextFrame();
  $i->multColor(0.5, 0.5, 1.0);
  $q->nextFrame();
  $i->multColor(1.0, 0.5, 1.0);
  $q->nextFrame();

  // finally, this one contains the action code
  $p = new SWFSprite();
  $i = $p->add($q);
  $i->setName('frames');
  $p->add(new SWFAction("

dx = (/:mousex-/:lastx)/3 + random(10)-5;
dy = (/:mousey-/:lasty)/3;
x = /:mousex;
y = /:mousey;
alpha = 100;

  "));
  $p->nextFrame();

  $p->add(new SWFAction("

this.x = x;
this.y = y;
this.alpha = alpha;
x += dx;
y += dy;
dy += 3;
alpha -= 8;

  "));
  $p->nextFrame();

  $p->add(new SWFAction("prevFrame(); play();"));
  $p->nextFrame();

  $i = $m->add($p);
  $i->setName('frames');
  $m->nextFrame();

  $m->add(new SWFAction("

lastx = mousex;
lasty = mousey;
mousex = /mouse.x;
mousey = /mouse.y;

++num;

if(num == 11)
  num = 1;

removeClip('char' & num);
duplicateClip(/frames, 'char' & num, num);

  "));

  $m->nextFrame();
  $m->add(new SWFAction("prevFrame(); play();"));

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

This simple example will handles keyboard actions. (You'll probably have to click in the window to give it focus. And you'll probably have to leave your mouse in the frame, too. If you know how to give buttons focus programatically, feel free to share, won't you?)

例子 4. swfaction() example

<?php

  /* sprite has one letter per frame */

  $p = new SWFSprite();
  $p->add(new SWFAction("stop();"));

  $chars = "abcdefghijklmnopqrstuvwxyz".
       "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
           "1234567890!@#$%^&/*()_+-=/[]{}|;:,.<>?`~";

  $f = new SWFFont("_sans");

  for($n=0; $nremove($i);
    $t = new SWFTextField();
    $t->setFont($f);
    $t->setHeight(240);
    $t->setBounds(600,240);
    $t->align(SWFTEXTFIELD_ALIGN_CENTER);
    $t->addString($c);
    $i = $p->add($t);
    $p->labelFrame($c);
    $p->nextFrame();
  }

  /* hit region for button - the entire frame */

  $s = new SWFShape();
  $s->setFillStyle0($s->addSolidFill(0, 0, 0, 0));
  $s->drawLine(600, 0);
  $s->drawLine(0, 400);
  $s->drawLine(-600, 0);
  $s->drawLine(0, -400);

  /* button checks for pressed key, sends sprite to the right frame */

  $b = new SWFButton();
  $b->addShape($s, SWFBUTTON_HIT);

  for($n=0; $naddAction(new SWFAction("

setTarget('/char');
gotoFrame('$c');

    "), SWFBUTTON_KEYPRESS($c));
  }

  $m = new SWFMovie();
  $m->setDimension(600,400);
  $i = $m->add($p);
  $i->setName('char');
  $i->moveTo(0,80);

  $m->add($b);

  header('Content-type: application/x-shockwave-flash');
  $m->output();

?>

后退 | 起点 | 前进
ming_useswfversion | 上一级 | SWFBitmap->getHeight


SWFBitmap->getHeight

(no version information, might be only in CVS)

SWFBitmap->getHeight -- Returns the bitmap's height.

Description

int swfbitmap->getheight ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfbitmap->getheight() returns the bitmap's height in pixels.

See also swfbitmap->getwidth().

后退 | 起点 | 前进
SWFAction | 上一级 | SWFBitmap->getWidth


SWFBitmap->getWidth

(no version information, might be only in CVS)

SWFBitmap->getWidth -- Returns the bitmap's width.

Description

int swfbitmap->getwidth ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfbitmap->getwidth() returns the bitmap's width in pixels.

See also swfbitmap->getheight().

后退 | 起点 | 前进
SWFBitmap->getHeight | 上一级 | SWFBitmap


SWFBitmap

(PHP 4 >= 4.0.5)

SWFBitmap -- Loads Bitmap object

Description

new swfbitmap ( string filename [, int alphafilename])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfbitmap() creates a new SWFBitmap object from the Jpeg or DBL file named filename. alphafilename indicates a MSK file to be used as an alpha mask for a Jpeg image.

注: We can only deal with baseline (frame 0) jpegs, no baseline optimized or progressive scan jpegs!

SWFBitmap has the following methods : swfbitmap->getwidth() and swfbitmap->getheight().

You can't import png images directly, though- have to use the png2dbl utility to make a dbl ("define bits lossless") file from the png. The reason for this is that I don't want a dependency on the png library in ming- autoconf should solve this, but that's not set up yet.

例子 1. Import PNG files

<?php
  $s = new SWFShape();
  $f = $s->addFill(new SWFBitmap("png.dbl"));
  $s->setRightFill($f);

  $s->drawLine(32, 0);
  $s->drawLine(0, 32);
  $s->drawLine(-32, 0);
  $s->drawLine(0, -32);

  $m = new SWFMovie();
  $m->setDimension(32, 32);
  $m->add($s);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

And you can put an alpha mask on a jpeg fill.

例子 2. swfbitmap() example

<?php

  $s = new SWFShape();

  // .msk file generated with "gif2mask" utility
  $f = $s->addFill(new SWFBitmap("alphafill.jpg", "alphafill.msk"));
  $s->setRightFill($f);

  $s->drawLine(640, 0);
  $s->drawLine(0, 480);
  $s->drawLine(-640, 0);
  $s->drawLine(0, -480);

  $c = new SWFShape();
  $c->setRightFill($c->addFill(0x99, 0x99, 0x99));
  $c->drawLine(40, 0);
  $c->drawLine(0, 40);
  $c->drawLine(-40, 0);
  $c->drawLine(0, -40);

  $m = new SWFMovie();
  $m->setDimension(640, 480);
  $m->setBackground(0xcc, 0xcc, 0xcc);

  // draw checkerboard background
  for($y=0; $y<480; $y+=40)
  {
    for($x=0; $x<640; $x+=80)
    {
      $i = $m->add($c);
      $i->moveTo($x, $y);
    }

    $y+=40;

    for($x=40; $x<640; $x+=80)
    {
      $i = $m->add($c);
      $i->moveTo($x, $y);
    }
  }

  $m->add($s);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

后退 | 起点 | 前进
SWFBitmap->getWidth | 上一级 | swfbutton_keypress


swfbutton_keypress

(PHP 4 >= 4.0.5)

swfbutton_keypress -- Returns the action flag for keyPress(char)

Description

int swfbutton_keypress ( string str)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
SWFBitmap | 上一级 | SWFbutton->addAction


SWFbutton->addAction

(no version information, might be only in CVS)

SWFbutton->addAction -- Adds an action

Description

void swfbutton->addaction ( ressource action, int flags)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfbutton->addaction() adds the action action to this button for the given conditions. The following flags are valid: SWFBUTTON_MOUSEOVER, SWFBUTTON_MOUSEOUT, SWFBUTTON_MOUSEUP, SWFBUTTON_MOUSEUPOUTSIDE, SWFBUTTON_MOUSEDOWN, SWFBUTTON_DRAGOUT and SWFBUTTON_DRAGOVER.

See also swfbutton->addshape() and SWFAction().

后退 | 起点 | 前进
swfbutton_keypress | 上一级 | SWFbutton->addShape


SWFbutton->addShape

(no version information, might be only in CVS)

SWFbutton->addShape -- Adds a shape to a button

Description

void swfbutton->addshape ( ressource shape, int flags)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfbutton->addshape() adds the shape shape to this button. The following flags' values are valid: SWFBUTTON_UP, SWFBUTTON_OVER, SWFBUTTON_DOWN or SWFBUTTON_HIT. SWFBUTTON_HIT isn't ever displayed, it defines the hit region for the button. That is, everywhere the hit shape would be drawn is considered a "touchable" part of the button.

后退 | 起点 | 前进
SWFbutton->addAction | 上一级 | SWFbutton->setAction


SWFbutton->setAction

(no version information, might be only in CVS)

SWFbutton->setAction -- Sets the action

Description

void swfbutton->setaction ( ressource action)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfbutton->setaction() sets the action to be performed when the button is clicked. Alias for addAction(shape, SWFBUTTON_MOUSEUP). action is a swfaction().

See also swfbutton->addshape() and SWFAction().

后退 | 起点 | 前进
SWFbutton->addShape | 上一级 | SWFbutton->setdown


SWFbutton->setdown

(no version information, might be only in CVS)

SWFbutton->setdown -- Alias for addShape(shape, SWFBUTTON_DOWN))

Description

void swfbutton->setdown ( ressource shape)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfbutton->setdown() alias for addShape(shape, SWFBUTTON_DOWN).

See also swfbutton->addshape() and SWFAction().

后退 | 起点 | 前进
SWFbutton->setAction | 上一级 | SWFbutton->setHit


SWFbutton->setHit

(no version information, might be only in CVS)

SWFbutton->setHit -- Alias for addShape(shape, SWFBUTTON_HIT)

Description

void swfbutton->sethit ( ressource shape)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfbutton->sethit() alias for addShape(shape, SWFBUTTON_HIT).

See also swfbutton->addshape() and SWFAction().

后退 | 起点 | 前进
SWFbutton->setdown | 上一级 | SWFbutton->setOver


SWFbutton->setOver

(no version information, might be only in CVS)

SWFbutton->setOver -- Alias for addShape(shape, SWFBUTTON_OVER)

Description

void swfbutton->setover ( ressource shape)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfbutton->setover() alias for addShape(shape, SWFBUTTON_OVER).

See also swfbutton->addshape() and SWFAction().

后退 | 起点 | 前进
SWFbutton->setHit | 上一级 | SWFbutton->setUp


SWFbutton->setUp

(no version information, might be only in CVS)

SWFbutton->setUp -- Alias for addShape(shape, SWFBUTTON_UP)

Description

void swfbutton->setup ( ressource shape)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfbutton->setup() alias for addShape(shape, SWFBUTTON_UP).

See also swfbutton->addshape() and SWFAction().

后退 | 起点 | 前进
SWFbutton->setOver | 上一级 | SWFbutton


SWFbutton

(PHP 4 >= 4.0.5)

SWFbutton -- Creates a new Button.

Description

new swfbutton ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfbutton() creates a new Button. Roll over it, click it, see it call action code. Swank.

SWFButton has the following methods : swfbutton->addshape(),
swfbutton->setup(), swfbutton->setover()
swfbutton->setdown(), swfbutton->sethit()
swfbutton->setaction() and
swfbutton->addaction().

This simple example will show your usual interactions with buttons : rollover, rollon, mouseup, mousedown, noaction.

例子 1. swfbutton() example

<?php

  $f = new SWFFont("_serif");

  $p = new SWFSprite();

  function label($string)
  {
    global $f;

    $t = new SWFTextField();
    $t->setFont($f);
    $t->addString($string);
    $t->setHeight(200);
    $t->setBounds(3200,200);
    return $t;
  }
  function addLabel($string)
  {
    global $p;

    $i = $p->add(label($string));
    $p->nextFrame();
    $p->remove($i);
  }

  $p->add(new SWFAction("stop();"));
  addLabel("NO ACTION");
  addLabel("SWFBUTTON_MOUSEUP");
  addLabel("SWFBUTTON_MOUSEDOWN");
  addLabel("SWFBUTTON_MOUSEOVER");
  addLabel("SWFBUTTON_MOUSEOUT");
  addLabel("SWFBUTTON_MOUSEUPOUTSIDE");
  addLabel("SWFBUTTON_DRAGOVER");
  addLabel("SWFBUTTON_DRAGOUT");

  function rect($r, $g, $b)
  {
    $s = new SWFShape();
    $s->setRightFill($s->addFill($r, $g, $b));
    $s->drawLine(600,0);
    $s->drawLine(0,600);
    $s->drawLine(-600,0);
    $s->drawLine(0,-600);

    return $s;
  }

  $b = new SWFButton();
  $b->addShape(rect(0xff, 0, 0), SWFBUTTON_UP | SWFBUTTON_HIT);
  $b->addShape(rect(0, 0xff, 0), SWFBUTTON_OVER);
  $b->addShape(rect(0, 0, 0xff), SWFBUTTON_DOWN);

  $b->addAction(new SWFAction("setTarget('/label'); gotoFrame(1);"),
            SWFBUTTON_MOUSEUP);

  $b->addAction(new SWFAction("setTarget('/label'); gotoFrame(2);"),
        SWFBUTTON_MOUSEDOWN);

  $b->addAction(new SWFAction("setTarget('/label'); gotoFrame(3);"),
        SWFBUTTON_MOUSEOVER);

  $b->addAction(new SWFAction("setTarget('/label'); gotoFrame(4);"),
        SWFBUTTON_MOUSEOUT);

  $b->addAction(new SWFAction("setTarget('/label'); gotoFrame(5);"),
        SWFBUTTON_MOUSEUPOUTSIDE);

  $b->addAction(new SWFAction("setTarget('/label'); gotoFrame(6);"),
        SWFBUTTON_DRAGOVER);

  $b->addAction(new SWFAction("setTarget('/label'); gotoFrame(7);"),
        SWFBUTTON_DRAGOUT);

  $m = new SWFMovie();
  $m->setDimension(4000,3000);

  $i = $m->add($p);
  $i->setName("label");
  $i->moveTo(400,1900);

  $i = $m->add($b);
  $i->moveTo(400,900);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

This simple example will enables you to drag draw a big red button on the windows. No drag-and-drop, just moving around.

例子 2. swfbutton->addaction() example

<?php

  $s = new SWFShape();
  $s->setRightFill($s->addFill(0xff, 0, 0));
  $s->drawLine(1000,0);
  $s->drawLine(0,1000);
  $s->drawLine(-1000,0);
  $s->drawLine(0,-1000);

  $b = new SWFButton();
  $b->addShape($s, SWFBUTTON_HIT | SWFBUTTON_UP | SWFBUTTON_DOWN | SWFBUTTON_OVER);

  $b->addAction(new SWFAction("startDrag('/test', 0);"), // '0' means don't lock to mouse
        SWFBUTTON_MOUSEDOWN);

  $b->addAction(new SWFAction("stopDrag();"),
        SWFBUTTON_MOUSEUP | SWFBUTTON_MOUSEUPOUTSIDE);

  $p = new SWFSprite();
  $p->add($b);
  $p->nextFrame();

  $m = new SWFMovie();
  $i = $m->add($p);
  $i->setName('test');
  $i->moveTo(1000,1000);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

后退 | 起点 | 前进
SWFbutton->setUp | 上一级 | SWFDisplayItem->addColor


SWFDisplayItem->addColor

(no version information, might be only in CVS)

SWFDisplayItem->addColor -- Adds the given color to this item's color transform.

Description

void swfdisplayitem->addcolor ( [int red [, int green [, int blue [, int a]]]])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfdisplayitem->addcolor() adds the color to this item's color transform. The color is given in its RGB form.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

后退 | 起点 | 前进
SWFbutton | 上一级 | SWFDisplayItem->move


SWFDisplayItem->move

(no version information, might be only in CVS)

SWFDisplayItem->move -- Moves object in relative coordinates.

Description

void swfdisplayitem->move ( int dx, int dy)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfdisplayitem->move() moves the current object by (dx,dy) from its current position.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

See also swfdisplayitem->moveto().

后退 | 起点 | 前进
SWFDisplayItem->addColor | 上一级 | SWFDisplayItem->moveTo


SWFDisplayItem->moveTo

(no version information, might be only in CVS)

SWFDisplayItem->moveTo -- Moves object in global coordinates.

Description

void swfdisplayitem->moveto ( int x, int y)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfdisplayitem->moveto() moves the current object to (x,y) in global coordinates.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

See also swfdisplayitem->move().

后退 | 起点 | 前进
SWFDisplayItem->move | 上一级 | SWFDisplayItem->multColor


SWFDisplayItem->multColor

(no version information, might be only in CVS)

SWFDisplayItem->multColor -- Multiplies the item's color transform.

Description

void swfdisplayitem->multcolor ( [int red [, int green [, int blue [, int a]]]])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfdisplayitem->multcolor() multiplies the item's color transform by the given values.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

This simple example will modify your picture's atmospher to Halloween (use a landscape or bright picture).

例子 1. swfdisplayitem->multcolor() example

<?php

  $b = new SWFBitmap("backyard.jpg");
  // note use your own picture :-)
  $s = new SWFShape();
  $s->setRightFill($s->addFill($b));
  $s->drawLine($b->getWidth(), 0);
  $s->drawLine(0, $b->getHeight());
  $s->drawLine(-$b->getWidth(), 0);
  $s->drawLine(0, -$b->getHeight());

  $m = new SWFMovie();
  $m->setDimension($b->getWidth(), $b->getHeight());

  $i = $m->add($s);

  for($n=0; $n<=20; ++$n)
  {
    $i->multColor(1.0-$n/10, 1.0, 1.0);
    $i->addColor(0xff*$n/20, 0, 0);
    $m->nextFrame();
  }

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

后退 | 起点 | 前进
SWFDisplayItem->moveTo | 上一级 | SWFDisplayItem->remove


SWFDisplayItem->remove

(no version information, might be only in CVS)

SWFDisplayItem->remove -- Removes the object from the movie

Description

void swfdisplayitem->remove ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfdisplayitem->remove() removes this object from the movie's display list.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

See also swfmovie->add().

后退 | 起点 | 前进
SWFDisplayItem->multColor | 上一级 | SWFDisplayItem->Rotate


SWFDisplayItem->Rotate

(no version information, might be only in CVS)

SWFDisplayItem->Rotate -- Rotates in relative coordinates.

Description

void swfdisplayitem->rotate ( float ddegrees)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfdisplayitem->rotate() rotates the current object by ddegrees degrees from its current rotation.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

See also swfdisplayitem->rotateto().

后退 | 起点 | 前进
SWFDisplayItem->remove | 上一级 | SWFDisplayItem->rotateTo


SWFDisplayItem->rotateTo

(no version information, might be only in CVS)

SWFDisplayItem->rotateTo -- Rotates the object in global coordinates.

Description

void swfdisplayitem->rotateto ( float degrees)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfdisplayitem->rotateto() set the current object rotation to degrees degrees in global coordinates.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

This example bring three rotating string from the background to the foreground. Pretty nice.

例子 1. swfdisplayitem->rotateto() example

<?php
  $thetext =  "ming!";

  $f = new SWFFont("Bauhaus 93.fdb");

  $m = new SWFMovie();
  $m->setRate(24.0);
  $m->setDimension(2400, 1600);
  $m->setBackground(0xff, 0xff, 0xff);

  // functions with huge numbers of arbitrary
  // arguments are always a good idea!  Really!

  function text($r, $g, $b, $a, $rot, $x, $y, $scale, $string)
  {
    global $f, $m;

    $t = new SWFText();
    $t->setFont($f);
    $t->setColor($r, $g, $b, $a);
    $t->setHeight(960);
    $t->moveTo(-($f->getWidth($string))/2, $f->getAscent()/2);
    $t->addString($string);

    // we can add properties just like a normal php var,
    // as long as the names aren't already used.
    // e.g., we can't set $i->scale, because that's a function

    $i = $m->add($t);
    $i->x = $x;
    $i->y = $y;
    $i->rot = $rot;
    $i->s = $scale;
    $i->rotateTo($rot);
    $i->scale($scale, $scale);

    // but the changes are local to the function, so we have to
    // return the changed object.  kinda weird..

    return $i;
 }

  function step($i)
  {
    $oldrot = $i->rot;
    $i->rot = 19*$i->rot/20;
    $i->x = (19*$i->x + 1200)/20;
    $i->y = (19*$i->y + 800)/20;
    $i->s = (19*$i->s + 1.0)/20;

    $i->rotateTo($i->rot);
    $i->scaleTo($i->s, $i->s);
    $i->moveTo($i->x, $i->y);

    return $i;
  }

  // see?  it sure paid off in legibility:

  $i1 = text(0xff, 0x33, 0x33, 0xff, 900, 1200, 800, 0.03, $thetext);
  $i2 = text(0x00, 0x33, 0xff, 0x7f, -560, 1200, 800, 0.04, $thetext);
  $i3 = text(0xff, 0xff, 0xff, 0x9f, 180, 1200, 800, 0.001, $thetext);

  for($i=1; $i<=100; ++$i)
  {
    $i1 = step($i1);
    $i2 = step($i2);
    $i3 = step($i3);

    $m->nextFrame();
  }

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

See also swfdisplayitem->rotate().

后退 | 起点 | 前进
SWFDisplayItem->Rotate | 上一级 | SWFDisplayItem->scale


SWFDisplayItem->scale

(no version information, might be only in CVS)

SWFDisplayItem->scale -- Scales the object in relative coordinates.

Description

void swfdisplayitem->scale ( int dx, int dy)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfdisplayitem->scale() scales the current object by (dx,dy) from its current size.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

See also swfdisplayitem->scaleto().

后退 | 起点 | 前进
SWFDisplayItem->rotateTo | 上一级 | SWFDisplayItem->scaleTo


SWFDisplayItem->scaleTo

(no version information, might be only in CVS)

SWFDisplayItem->scaleTo -- Scales the object in global coordinates.

Description

void swfdisplayitem->scaleto ( int x, int y)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfdisplayitem->scaleto() scales the current object to (x,y) in global coordinates.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

See also swfdisplayitem->scale().

后退 | 起点 | 前进
SWFDisplayItem->scale | 上一级 | SWFDisplayItem->setDepth


SWFDisplayItem->setDepth

(no version information, might be only in CVS)

SWFDisplayItem->setDepth -- Sets z-order

Description

void swfdisplayitem->setdepth ( float depth)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfdisplayitem->rotate() sets the object's z-order to depth. Depth defaults to the order in which instances are created (by add'ing a shape/text to a movie)- newer ones are on top of older ones. If two objects are given the same depth, only the later-defined one can be moved.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

后退 | 起点 | 前进
SWFDisplayItem->scaleTo | 上一级 | SWFDisplayItem->setName


SWFDisplayItem->setName

(no version information, might be only in CVS)

SWFDisplayItem->setName -- Sets the object's name

Description

void swfdisplayitem->setname ( string name)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfdisplayitem->setname() sets the object's name to name, for targetting with action script. Only useful on sprites.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

后退 | 起点 | 前进
SWFDisplayItem->setDepth | 上一级 | SWFDisplayItem->setRatio


SWFDisplayItem->setRatio

(no version information, might be only in CVS)

SWFDisplayItem->setRatio -- Sets the object's ratio.

Description

void swfdisplayitem->setratio ( float ratio)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfdisplayitem->setratio() sets the object's ratio to ratio. Obviously only useful for morphs.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

This simple example will morph nicely three concentric circles.

例子 1. swfdisplayitem->setname() example

<?php

  $p = new SWFMorph();

  $g = new SWFGradient();
  $g->addEntry(0.0, 0, 0, 0);
  $g->addEntry(0.16, 0xff, 0xff, 0xff);
  $g->addEntry(0.32, 0, 0, 0);
  $g->addEntry(0.48, 0xff, 0xff, 0xff);
  $g->addEntry(0.64, 0, 0, 0);
  $g->addEntry(0.80, 0xff, 0xff, 0xff);
  $g->addEntry(1.00, 0, 0, 0);

  $s = $p->getShape1();
  $f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
  $f->scaleTo(0.05);
  $s->setLeftFill($f);
  $s->movePenTo(-160, -120);
  $s->drawLine(320, 0);
  $s->drawLine(0, 240);
  $s->drawLine(-320, 0);
  $s->drawLine(0, -240);

  $g = new SWFGradient();
  $g->addEntry(0.0, 0, 0, 0);
  $g->addEntry(0.16, 0xff, 0, 0);
  $g->addEntry(0.32, 0, 0, 0);
  $g->addEntry(0.48, 0, 0xff, 0);
  $g->addEntry(0.64, 0, 0, 0);
  $g->addEntry(0.80, 0, 0, 0xff);
  $g->addEntry(1.00, 0, 0, 0);

  $s = $p->getShape2();
  $f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
  $f->scaleTo(0.05);
  $f->skewXTo(1.0);
  $s->setLeftFill($f);
  $s->movePenTo(-160, -120);
  $s->drawLine(320, 0);
  $s->drawLine(0, 240);
  $s->drawLine(-320, 0);
  $s->drawLine(0, -240);

  $m = new SWFMovie();
  $m->setDimension(320, 240);
  $i = $m->add($p);
  $i->moveTo(160, 120);

  for($n=0; $n<=1.001; $n+=0.01)
  {
    $i->setRatio($n);
    $m->nextFrame();
  }

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

后退 | 起点 | 前进
SWFDisplayItem->setName | 上一级 | SWFDisplayItem->skewX


SWFDisplayItem->skewX

(no version information, might be only in CVS)

SWFDisplayItem->skewX -- Sets the X-skew.

Description

void swfdisplayitem->skewx ( float ddegrees)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfdisplayitem->skewx() adds ddegrees to current x-skew.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

See also
swfdisplayitem->skewx(),
swfdisplayitem->skewy() and
swfdisplayitem->skewyto().

后退 | 起点 | 前进
SWFDisplayItem->setRatio | 上一级 | SWFDisplayItem->skewXTo


SWFDisplayItem->skewXTo

(no version information, might be only in CVS)

SWFDisplayItem->skewXTo -- Sets the X-skew.

Description

void swfdisplayitem->skewxto ( float degrees)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfdisplayitem->skewxto() sets the x-skew to degrees. For degrees is 1.0, it means a 45-degree forward slant. More is more forward, less is more backward.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

See also
swfdisplayitem->skewx(),
swfdisplayitem->skewy() and
swfdisplayitem->skewyto().

后退 | 起点 | 前进
SWFDisplayItem->skewX | 上一级 | SWFDisplayItem->skewY


SWFDisplayItem->skewY

(no version information, might be only in CVS)

SWFDisplayItem->skewY -- Sets the Y-skew.

Description

void swfdisplayitem->skewy ( float ddegrees)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfdisplayitem->skewy() adds ddegrees to current y-skew.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

See also
swfdisplayitem->skewyto(),
swfdisplayitem->skewx() and
swfdisplayitem->skewxto().

后退 | 起点 | 前进
SWFDisplayItem->skewXTo | 上一级 | SWFDisplayItem->skewYTo


SWFDisplayItem->skewYTo

(no version information, might be only in CVS)

SWFDisplayItem->skewYTo -- Sets the Y-skew.

Description

void swfdisplayitem->skewyto ( float degrees)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfdisplayitem->skewyto() sets the y-skew to degrees. For degrees is 1.0, it means a 45-degree forward slant. More is more upward, less is more downward.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

See also
swfdisplayitem->skewy(),
swfdisplayitem->skewx() and
swfdisplayitem->skewxto().

后退 | 起点 | 前进
SWFDisplayItem->skewY | 上一级 | SWFDisplayItem


SWFDisplayItem

(no version information, might be only in CVS)

SWFDisplayItem -- Creates a new displayitem object.

Description

new swfdisplayitem ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfdisplayitem() creates a new swfdisplayitem object.

Here's where all the animation takes place. After you define a shape, a text object, a sprite, or a button, you add it to the movie, then use the returned handle to move, rotate, scale, or skew the thing.

SWFDisplayItem has the following methods : swfdisplayitem->move(),
swfdisplayitem->moveto(), swfdisplayitem->scaleto(),
swfdisplayitem->scale(), swfdisplayitem->rotate(),
swfdisplayitem->rotateto(), swfdisplayitem->skewxto(),
swfdisplayitem->skewx(), swfdisplayitem->skewyto()
swfdisplayitem->skewyto(), swfdisplayitem->setdepth()
swfdisplayitem->remove(), swfdisplayitem->setname()
swfdisplayitem->setratio(), swfdisplayitem->addcolor()
and swfdisplayitem->multcolor().

后退 | 起点 | 前进
SWFDisplayItem->skewYTo | 上一级 | SWFFill->moveTo


SWFFill->moveTo

(no version information, might be only in CVS)

SWFFill->moveTo -- Moves fill origin

Description

void swffill->moveto ( int x, int y)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swffill->moveto() moves fill's origin to (x,y) in global coordinates.

后退 | 起点 | 前进
SWFDisplayItem | 上一级 | SWFFill->rotateTo


SWFFill->rotateTo

(no version information, might be only in CVS)

SWFFill->rotateTo -- Sets fill's rotation

Description

void swffill->rotateto ( float degrees)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swffill->rotateto() sets fill's rotation to degrees degrees.

后退 | 起点 | 前进
SWFFill->moveTo | 上一级 | SWFFill->scaleTo


SWFFill->scaleTo

(no version information, might be only in CVS)

SWFFill->scaleTo -- Sets fill's scale

Description

void swffill->scaleto ( int x, int y)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swffill->scaleto() sets fill's scale to x in the x-direction, y in the y-direction.

后退 | 起点 | 前进
SWFFill->rotateTo | 上一级 | SWFFill->skewXTo


SWFFill->skewXTo

(no version information, might be only in CVS)

SWFFill->skewXTo -- Sets fill x-skew

Description

void swffill->skewxto ( float x)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swffill->skewxto() sets fill x-skew to x. For x is 1.0, it is a is a 45-degree forward slant. More is more forward, less is more backward.

后退 | 起点 | 前进
SWFFill->scaleTo | 上一级 | SWFFill->skewYTo


SWFFill->skewYTo

(no version information, might be only in CVS)

SWFFill->skewYTo -- Sets fill y-skew

Description

void swffill->skewyto ( float y)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swffill->skewyto() sets fill y-skew to y. For y is 1.0, it is a is a 45-degree upward slant. More is more upward, less is more downward.

后退 | 起点 | 前进
SWFFill->skewXTo | 上一级 | SWFFill


SWFFill

SWFFill -- Loads SWFFill object

Description

The swffill() object allows you to transform (scale, skew, rotate) bitmap and gradient fills. swffill() objects are created by the swfshape->addfill() methods.

SWFFill has the following methods : swffill->moveto() and swffill->scaleto(), swffill->rotateto(), swffill->skewxto() and swffill->skewyto().

后退 | 起点 | 前进
SWFFill->skewYTo | 上一级 | swffont->getwidth


swffont->getwidth

(no version information, might be only in CVS)

swffont->getwidth -- Returns the string's width

Description

int swffont->getwidth ( string string)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swffont->getwidth() returns the string string's width, using font's default scaling. You'll probably want to use the SWFText() version of this method which uses the text object's scale.

后退 | 起点 | 前进
SWFFill | 上一级 | SWFFont


SWFFont

(PHP 4 >= 4.0.5)

SWFFont -- Loads a font definition

Description

new swffont ( string filename)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

If filename is the name of an FDB file (i.e., it ends in ".fdb"), load the font definition found in said file. Otherwise, create a browser-defined font reference.

FDB ("font definition block") is a very simple wrapper for the SWF DefineFont2 block which contains a full description of a font. One may create FDB files from SWT Generator template files with the included makefdb utility- look in the util directory off the main ming distribution directory.

Browser-defined fonts don't contain any information about the font other than its name. It is assumed that the font definition will be provided by the movie player. The fonts _serif, _sans, and _typewriter should always be available. For example:
<?php
$f = newSWFFont("_sans");
?>
will give you the standard sans-serif font, probably the same as what you'd get with <font name="sans-serif"> in HTML.

swffont() returns a reference to the font definition, for use in the SWFText->setFont() and the SWFTextField->setFont() methods.

SWFFont has the following methods : swffont->getwidth().

后退 | 起点 | 前进
swffont->getwidth | 上一级 | SWFGradient->addEntry


SWFGradient->addEntry

(no version information, might be only in CVS)

SWFGradient->addEntry -- Adds an entry to the gradient list.

Description

void swfgradient->addentry ( float ratio, int red, int green, int blue [, int a])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfgradient->addentry() adds an entry to the gradient list. ratio is a number between 0 and 1 indicating where in the gradient this color appears. Thou shalt add entries in order of increasing ratio.

red, green, blue is a color (RGB mode). Last parameter a is optional.

后退 | 起点 | 前进
SWFFont | 上一级 | SWFGradient


SWFGradient

(PHP 4 >= 4.0.5)

SWFGradient -- Creates a gradient object

Description

new swfgradient ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfgradient() creates a new SWFGradient object.

After you've added the entries to your gradient, you can use the gradient in a shape fill with the swfshape->addfill() method.

SWFGradient has the following methods : swfgradient->addentry().

This simple example will draw a big black-to-white gradient as background, and a redish disc in its center.

例子 1. swfgradient() example

<?php

  $m = new SWFMovie();
  $m->setDimension(320, 240);

  $s = new SWFShape();

  // first gradient- black to white
  $g = new SWFGradient();
  $g->addEntry(0.0, 0, 0, 0);
  $g->addEntry(1.0, 0xff, 0xff, 0xff);

  $f = $s->addFill($g, SWFFILL_LINEAR_GRADIENT);
  $f->scaleTo(0.01);
  $f->moveTo(160, 120);
  $s->setRightFill($f);
  $s->drawLine(320, 0);
  $s->drawLine(0, 240);
  $s->drawLine(-320, 0);
  $s->drawLine(0, -240);

  $m->add($s);

  $s = new SWFShape();

  // second gradient- radial gradient from red to transparent
  $g = new SWFGradient();
  $g->addEntry(0.0, 0xff, 0, 0, 0xff);
  $g->addEntry(1.0, 0xff, 0, 0, 0);

  $f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
  $f->scaleTo(0.005);
  $f->moveTo(160, 120);
  $s->setRightFill($f);
  $s->drawLine(320, 0);
  $s->drawLine(0, 240);
  $s->drawLine(-320, 0);
  $s->drawLine(0, -240);

  $m->add($s);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

后退 | 起点 | 前进
SWFGradient->addEntry | 上一级 | SWFMorph->getshape1


SWFMorph->getshape1

(no version information, might be only in CVS)

SWFMorph->getshape1 -- Gets a handle to the starting shape

Description

mixed swfmorph->getshape1 ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfmorph->getshape1() gets a handle to the morph's starting shape. swfmorph->getshape1() returns an swfshape() object.

后退 | 起点 | 前进
SWFGradient | 上一级 | SWFMorph->getshape2


SWFMorph->getshape2

(no version information, might be only in CVS)

SWFMorph->getshape2 -- Gets a handle to the ending shape

Description

mixed swfmorph->getshape2 ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfmorph->getshape2() gets a handle to the morph's ending shape. swfmorph->getshape2() returns an swfshape() object.

后退 | 起点 | 前进
SWFMorph->getshape1 | 上一级 | SWFMorph


SWFMorph

(PHP 4 >= 4.0.5)

SWFMorph -- Creates a new SWFMorph object.

Description

new swfmorph ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfmorph() creates a new SWFMorph object.

Also called a "shape tween". This thing lets you make those tacky twisting things that make your computer choke. Oh, joy!

The methods here are sort of weird. It would make more sense to just have newSWFMorph(shape1, shape2);, but as things are now, shape2 needs to know that it's the second part of a morph. (This, because it starts writing its output as soon as it gets drawing commands- if it kept its own description of its shapes and wrote on completion this and some other things would be much easier.)

SWFMorph has the following methods : swfmorph->getshape1() and swfmorph->getshape1().

This simple example will morph a big red square into a smaller blue black-bordered square.

例子 1. swfmorph() example

<?php
  $p = new SWFMorph();

  $s = $p->getShape1();
  $s->setLine(0,0,0,0);

  /* Note that this is backwards from normal shapes (left instead of right).
     I have no idea why, but this seems to work.. */

  $s->setLeftFill($s->addFill(0xff, 0, 0));
  $s->movePenTo(-1000,-1000);
  $s->drawLine(2000,0);
  $s->drawLine(0,2000);
  $s->drawLine(-2000,0);
  $s->drawLine(0,-2000);

  $s = $p->getShape2();
  $s->setLine(60,0,0,0);
  $s->setLeftFill($s->addFill(0, 0, 0xff));
  $s->movePenTo(0,-1000);
  $s->drawLine(1000,1000);
  $s->drawLine(-1000,1000);
  $s->drawLine(-1000,-1000);
  $s->drawLine(1000,-1000);

  $m = new SWFMovie();
  $m->setDimension(3000,2000);
  $m->setBackground(0xff, 0xff, 0xff);

  $i = $m->add($p);
  $i->moveTo(1500,1000);

  for($r=0.0; $r<=1.0; $r+=0.1)
  {
    $i->setRatio($r);
    $m->nextFrame();
  }

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

后退 | 起点 | 前进
SWFMorph->getshape2 | 上一级 | SWFMovie->add


SWFMovie->add

(no version information, might be only in CVS)

SWFMovie->add -- Adds any type of data to a movie.

Description

void swfmovie->add ( ressource instance)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfmovie->add() adds instance to the current movie. instance is any type of data : Shapes, text, fonts, etc. must all be add'ed to the movie to make this work.

For displayable types (shape, text, button, sprite), this returns an SWFDisplayItem(), a handle to the object in a display list. Thus, you can add the same shape to a movie multiple times and get separate handles back for each separate instance.

See also all other objects (adding this later), and swfmovie->remove()

See examples in : swfdisplayitem->rotateto() and swfshape->addfill().

后退 | 起点 | 前进
SWFMorph | 上一级 | SWFMovie->nextframe


SWFMovie->nextframe

(no version information, might be only in CVS)

SWFMovie->nextframe -- Moves to the next frame of the animation.

Description

void swfmovie->nextframe ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfmovie->nextframe() moves to the next frame of the animation.

后退 | 起点 | 前进
SWFMovie->add | 上一级 | SWFMovie->output


SWFMovie->output

(no version information, might be only in CVS)

SWFMovie->output -- Dumps your lovingly prepared movie out.

Description

void swfmovie->output ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfmovie->output() dumps your lovingly prepared movie out. In PHP, preceding this with the command
<?php
header('Content-type: application/x-shockwave-flash');
?>
convinces the browser to display this as a flash movie.

See also swfmovie->save().

See examples in :
swfmovie->streammp3(),
swfdisplayitem->rotateto(),
swfaction()...
Any example will use this method.

后退 | 起点 | 前进
SWFMovie->nextframe | 上一级 | SWFMovie->remove


SWFMovie->remove

(no version information, might be only in CVS)

SWFMovie->remove -- Removes the object instance from the display list.

Description

void swfmovie->remove ( resource instance)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfmovie->remove() removes the object instance instance from the display list.

See also swfmovie->add().

后退 | 起点 | 前进
SWFMovie->output | 上一级 | SWFMovie->save


SWFMovie->save

(no version information, might be only in CVS)

SWFMovie->save -- Saves your movie in a file.

Description

void swfmovie->save ( string filename)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfmovie->save() saves your movie to the file named filename.

See also output().

后退 | 起点 | 前进
SWFMovie->remove | 上一级 | SWFMovie->setbackground


SWFMovie->setbackground

(no version information, might be only in CVS)

SWFMovie->setbackground -- Sets the background color.

Description

void swfmovie->setbackground ( int red, int green, int blue)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfmovie->setbackground() sets the background color. Why is there no rgba version? Think about it. (Actually, that's not such a dumb question after all- you might want to let the html background show through. There's a way to do that, but it only works on IE4. Search the http://www.macromedia.com/ site for details.)

后退 | 起点 | 前进
SWFMovie->save | 上一级 | SWFMovie->setdimension


SWFMovie->setdimension

(no version information, might be only in CVS)

SWFMovie->setdimension -- Sets the movie's width and height.

Description

void swfmovie->setdimension ( int width, int height)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfmovie->setdimension() sets the movie's width to width and height to height.

后退 | 起点 | 前进
SWFMovie->setbackground | 上一级 | SWFMovie->setframes


SWFMovie->setframes

(no version information, might be only in CVS)

SWFMovie->setframes -- Sets the total number of frames in the animation.

Description

void swfmovie->setframes ( string numberofframes)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfmovie->setframes() sets the total number of frames in the animation to numberofframes.

后退 | 起点 | 前进
SWFMovie->setdimension | 上一级 | SWFMovie->setrate


SWFMovie->setrate

(no version information, might be only in CVS)

SWFMovie->setrate -- Sets the animation's frame rate.

Description

void swfmovie->setrate ( int rate)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfmovie->setrate() sets the frame rate to rate, in frame per seconds. Animation will slow down if the player can't render frames fast enough- unless there's a streaming sound, in which case display frames are sacrificed to keep sound from skipping.

后退 | 起点 | 前进
SWFMovie->setframes | 上一级 | SWFMovie->streammp3


SWFMovie->streammp3

(no version information, might be only in CVS)

SWFMovie->streammp3 -- Streams a MP3 file.

Description

void swfmovie->streammp3 ( string mp3FileName)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfmovie->streammp3() streams the mp3 file mp3FileName. Not very robust in dealing with oddities (can skip over an initial ID3 tag, but that's about it). Like SWFShape->addJpegFill(), this isn't a stable function- we'll probably need to make a separate SWFSound object to contain sound types.

Note that the movie isn't smart enough to put enough frames in to contain the entire mp3 stream- you'll have to add (length of song * frames per second) frames to get the entire stream in.

Yes, now you can use ming to put that rock and roll devil worship music into your SWF files. Just don't tell the RIAA.

例子 1. swfmovie->streammp3() example

<?php
  $m = new SWFMovie();
  $m->setRate(12.0);
  $m->streamMp3("distortobass.mp3");
  // use your own MP3

  // 11.85 seconds at 12.0 fps = 142 frames
  $m->setFrames(142);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

后退 | 起点 | 前进
SWFMovie->setrate | 上一级 | SWFMovie


SWFMovie

(PHP 4 >= 4.0.5)

SWFMovie -- Creates a new movie object, representing an SWF version 4 movie.

Description

new swfmovie ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfmovie() creates a new movie object, representing an SWF version 4 movie.

SWFMovie has the following methods :
swfmovie->output(),swfmovie->save(),
swfmovie->add(), swfmovie->remove(),
swfmovie->nextframe(), swfmovie->setbackground(),
swfmovie->setrate(), swfmovie->setdimension(),
swfmovie->setframes() and swfmovie->streammp3().

See examples in : swfdisplayitem->rotateto(), swfshape->setline(), swfshape->addfill()... Any example will use this object.

后退 | 起点 | 前进
SWFMovie->streammp3 | 上一级 | SWFShape->addFill


SWFShape->addFill

(no version information, might be only in CVS)

SWFShape->addFill -- Adds a solid fill to the shape.

Description

void swfshape->addfill ( int red, int green, int blue [, int a])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

void swfshape->addfill ( SWFbitmap bitmap [, int flags])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

void swfshape->addfill ( SWFGradient gradient [, int flags])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfshape->addfill() adds a solid fill to the shape's list of fill styles. swfshape->addfill() accepts three different types of arguments.

red, green, blue is a color (RGB mode). Last parameter a is optional.

The bitmap argument is an swfbitmap() object. The flags argument can be one of the following values : SWFFILL_CLIPPED_BITMAP or SWFFILL_TILED_BITMAP. Default is SWFFILL_TILED_BITMAP. I think.

The gradient argument is an swfgradient() object. The flags argument can be one of the following values : SWFFILL_RADIAL_GRADIENT or SWFFILL_LINEAR_GRADIENT. Default is SWFFILL_LINEAR_GRADIENT. I'm sure about this one. Really.

swfshape->addfill() returns an swffill()
object for use with the swfshape->setleftfill()
and swfshape->setrightfill() functions
described below.

See also swfshape->setleftfill() and swfshape->setrightfill().

This simple example will draw a frame on a bitmap. Ah, here's another buglet in the flash player- it doesn't seem to care about the second shape's bitmap's transformation in a morph. According to spec, the bitmap should stretch along with the shape in this example..

例子 1. swfshape->addfill() example

<?php

  $p = new SWFMorph();

  $b = new SWFBitmap("alphafill.jpg");
  // use your own bitmap
  $width = $b->getWidth();
  $height = $b->getHeight();

  $s = $p->getShape1();
  $f = $s->addFill($b, SWFFILL_TILED_BITMAP);
  $f->moveTo(-$width/2, -$height/4);
  $f->scaleTo(1.0, 0.5);
  $s->setLeftFill($f);
  $s->movePenTo(-$width/2, -$height/4);
  $s->drawLine($width, 0);
  $s->drawLine(0, $height/2);
  $s->drawLine(-$width, 0);
  $s->drawLine(0, -$height/2);

  $s = $p->getShape2();
  $f = $s->addFill($b, SWFFILL_TILED_BITMAP);

  // these two have no effect!
  $f->moveTo(-$width/4, -$height/2);
  $f->scaleTo(0.5, 1.0);

  $s->setLeftFill($f);
  $s->movePenTo(-$width/4, -$height/2);
  $s->drawLine($width/2, 0);
  $s->drawLine(0, $height);
  $s->drawLine(-$width/2, 0);
  $s->drawLine(0, -$height);

  $m = new SWFMovie();
  $m->setDimension($width, $height);
  $i = $m->add($p);
  $i->moveTo($width/2, $height/2);

  for($n=0; $n<1.001; $n+=0.03)
  {
    $i->setRatio($n);
    $m->nextFrame();
  }

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

后退 | 起点 | 前进
SWFMovie | 上一级 | SWFShape->drawCurve


SWFShape->drawCurve

(no version information, might be only in CVS)

SWFShape->drawCurve -- Draws a curve (relative).

Description

void swfshape->drawcurve ( int controldx, int controldy, int anchordx, int anchordy)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfshape->drawcurve() draws a quadratic curve (using the current line style,set by swfshape->setline()) from the current pen position to the relative position (anchorx,anchory) using relative control point (controlx,controly). That is, head towards the control point, then smoothly turn to the anchor point.

See also
swfshape->drawlineto(),
swfshape->drawline(),
swfshape->movepento() and
swfshape->movepen().

后退 | 起点 | 前进
SWFShape->addFill | 上一级 | SWFShape->drawCurveTo


SWFShape->drawCurveTo

(no version information, might be only in CVS)

SWFShape->drawCurveTo -- Draws a curve.

Description

void swfshape->drawcurveto ( int controlx, int controly, int anchorx, int anchory)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfshape->drawcurveto() draws a quadratic curve (using the current line style, set by swfshape->setline()) from the current pen position to (anchorx,anchory) using (controlx,controly) as a control point. That is, head towards the control point, then smoothly turn to the anchor point.

See also
swfshape->drawlineto(),
swfshape->drawline(),
swfshape->movepento() and
swfshape->movepen().

后退 | 起点 | 前进
SWFShape->drawCurve | 上一级 | SWFShape->drawLine


SWFShape->drawLine

(no version information, might be only in CVS)

SWFShape->drawLine -- Draws a line (relative).

Description

void swfshape->drawline ( int dx, int dy)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfshape->drawline() draws a line (using the current line style set by swfshape->setline()) from the current pen position to displacement (dx,dy).

See also
swfshape->movepento(),
swfshape->drawcurveto(),
swfshape->movepen() and
swfshape->drawlineto().

后退 | 起点 | 前进
SWFShape->drawCurveTo | 上一级 | SWFShape->drawLineTo


SWFShape->drawLineTo

(no version information, might be only in CVS)

SWFShape->drawLineTo -- Draws a line.

Description

void swfshape->drawlineto ( int x, int y)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfshape->setrightfill() draws a line (using the current line style, set by swfshape->setline()) from the current pen position to point (x,y) in the shape's coordinate space.

See also
swfshape->movepento(),
swfshape->drawcurveto(),
swfshape->movepen() and
swfshape->drawline().

后退 | 起点 | 前进
SWFShape->drawLine | 上一级 | SWFShape->movePen


SWFShape->movePen

(no version information, might be only in CVS)

SWFShape->movePen -- Moves the shape's pen (relative).

Description

void swfshape->movepen ( int dx, int dy)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfshape->setrightfill() move the shape's pen from coordinates (current x,current y) to (current x + dx, current y + dy) in the shape's coordinate space.

See also
swfshape->movepento(),
swfshape->drawcurveto(),
swfshape->drawlineto() and
swfshape->drawline().

后退 | 起点 | 前进
SWFShape->drawLineTo | 上一级 | SWFShape->movePenTo


SWFShape->movePenTo

(no version information, might be only in CVS)

SWFShape->movePenTo -- Moves the shape's pen.

Description

void swfshape->movepento ( int x, int y)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfshape->setrightfill() move the shape's pen to (x,y) in the shape's coordinate space.

See also
swfshape->movepen(),
swfshape->drawcurveto(),
swfshape->drawlineto() and
swfshape->drawline().

后退 | 起点 | 前进
SWFShape->movePen | 上一级 | SWFShape->setLeftFill


SWFShape->setLeftFill

(no version information, might be only in CVS)

SWFShape->setLeftFill -- Sets left rasterizing color.

Description

void swfshape->setleftfill ( swfgradient fill)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

void swfshape->setleftfill ( int red, int green, int blue [, int a])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

What this nonsense is about is, every edge segment borders at most two fills. When rasterizing the object, it's pretty handy to know what those fills are ahead of time, so the swf format requires these to be specified.

swfshape->setleftfill() sets the fill on the left side of the edge- that is, on the interior if you're defining the outline of the shape in a counter-clockwise fashion. The fill object is an SWFFill object returned from one of the addFill functions above.

This seems to be reversed when you're defining a shape in a morph, though. If your browser crashes, just try setting the fill on the other side.

Shortcut for swfshape->setleftfill($s->addfill($r, $g, $b [, $a]));.

See also swfshape->setrightfill().

后退 | 起点 | 前进
SWFShape->movePenTo | 上一级 | SWFShape->setLine


SWFShape->setLine

(no version information, might be only in CVS)

SWFShape->setLine -- Sets the shape's line style.

Description

void swfshape->setline ( int width [, int red [, int green [, int blue [, int a]]]])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfshape->setline() sets the shape's line style. width is the line's width. If width is 0, the line's style is removed (then, all other arguments are ignored). If width > 0, then line's color is set to red, green, blue. Last parameter a is optional.

swfshape->setline() accepts 1, 4 or 5 arguments (not 3 or 2).

You must declare all line styles before you use them (see example).

This simple example will draw a big "!#%*@", in funny colors and gracious style.

例子 1. swfshape->setline() example

<?php
  $s = new SWFShape();
  $f1 = $s->addFill(0xff, 0, 0);
  $f2 = $s->addFill(0xff, 0x7f, 0);
  $f3 = $s->addFill(0xff, 0xff, 0);
  $f4 = $s->addFill(0, 0xff, 0);
  $f5 = $s->addFill(0, 0, 0xff);

  // bug: have to declare all line styles before you use them
  $s->setLine(40, 0x7f, 0, 0);
  $s->setLine(40, 0x7f, 0x3f, 0);
  $s->setLine(40, 0x7f, 0x7f, 0);
  $s->setLine(40, 0, 0x7f, 0);
  $s->setLine(40, 0, 0, 0x7f);

  $f = new SWFFont('Techno.fdb');

  $s->setRightFill($f1);
  $s->setLine(40, 0x7f, 0, 0);
  $s->drawGlyph($f, '!');
  $s->movePen($f->getWidth('!'), 0);

  $s->setRightFill($f2);
  $s->setLine(40, 0x7f, 0x3f, 0);
  $s->drawGlyph($f, '#');
  $s->movePen($f->getWidth('#'), 0);

  $s->setRightFill($f3);
  $s->setLine(40, 0x7f, 0x7f, 0);
  $s->drawGlyph($f, '%');
  $s->movePen($f->getWidth('%'), 0);

  $s->setRightFill($f4);
  $s->setLine(40, 0, 0x7f, 0);
  $s->drawGlyph($f, '*');
  $s->movePen($f->getWidth('*'), 0);

  $s->setRightFill($f5);
  $s->setLine(40, 0, 0, 0x7f);
  $s->drawGlyph($f, '@');

  $m = new SWFMovie();
  $m->setDimension(3000,2000);
  $m->setRate(12.0);
  $i = $m->add($s);
  $i->moveTo(1500-$f->getWidth("!#%*@")/2, 1000+$f->getAscent()/2);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

后退 | 起点 | 前进
SWFShape->setLeftFill | 上一级 | SWFShape->setRightFill


SWFShape->setRightFill

(no version information, might be only in CVS)

SWFShape->setRightFill -- Sets right rasterizing color.

Description

void swfshape->setrightfill ( swfgradient fill)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

void swfshape->setrightfill ( int red, int green, int blue [, int a])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

See also swfshape->setleftfill().

Shortcut for swfshape->setrightfill($s->addfill($r, $g, $b [, $a]));.

后退 | 起点 | 前进
SWFShape->setLine | 上一级 | SWFShape


SWFShape

(PHP 4 >= 4.0.5)

SWFShape -- Creates a new shape object.

Description

new swfshape ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfshape() creates a new shape object.

SWFShape has the following methods : swfshape->setline(),
swfshape->addfill(), swfshape->setleftfill(),
swfshape->setrightfill(), swfshape->movepento(),
swfshape->movepen(), swfshape->drawlineto(),
swfshape->drawline(), swfshape->drawcurveto()
and swfshape->drawcurve().

This simple example will draw a big red elliptic quadrant.

例子 1. swfshape() example

<?php
  $s = new SWFShape();
  $s->setLine(40, 0x7f, 0, 0);
  $s->setRightFill($s->addFill(0xff, 0, 0));
  $s->movePenTo(200, 200);
  $s->drawLineTo(6200, 200);
  $s->drawLineTo(6200, 4600);
  $s->drawCurveTo(200, 4600, 200, 200);

  $m = new SWFMovie();
  $m->setDimension(6400, 4800);
  $m->setRate(12.0);
  $m->add($s);
  $m->nextFrame();

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

后退 | 起点 | 前进
SWFShape->setRightFill | 上一级 | SWFSprite->add


SWFSprite->add

(no version information, might be only in CVS)

SWFSprite->add -- Adds an object to a sprite

Description

void swfsprite->add ( resource object)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfsprite->add() adds a swfshape(), a
swfbutton(), a swftext(),
a swfaction() or a swfsprite() object.

For displayable types (swfshape(),
swfbutton(), swftext(),
swfaction() or swfsprite()),
this returns a handle  to the object in a display list.

后退 | 起点 | 前进
SWFShape | 上一级 | SWFSprite->nextframe


SWFSprite->nextframe

(no version information, might be only in CVS)

SWFSprite->nextframe -- Moves to the next frame of the animation.

Description

void swfsprite->nextframe ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfsprite->setframes() moves to the next frame of the animation.

后退 | 起点 | 前进
SWFSprite->add | 上一级 | SWFSprite->remove


SWFSprite->remove

(no version information, might be only in CVS)

SWFSprite->remove -- Removes an object to a sprite

Description

void swfsprite->remove ( ressource object)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfsprite->remove() remove a swfshape(), a
swfbutton(), a swftext(),
a swfaction() or a swfsprite() object
from the sprite.

后退 | 起点 | 前进
SWFSprite->nextframe | 上一级 | SWFSprite->setframes


SWFSprite->setframes

(no version information, might be only in CVS)

SWFSprite->setframes -- Sets the total number of frames in the animation.

Description

void swfsprite->setframes ( int numberofframes)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfsprite->setframes() sets the total number of frames in the animation to numberofframes.

后退 | 起点 | 前进
SWFSprite->remove | 上一级 | SWFSprite


SWFSprite

(PHP 4 >= 4.0.5)

SWFSprite -- Creates a movie clip (a sprite)

Description

new swfsprite ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swfsprite() are also known as a "movie clip", this allows one to create objects which are animated in their own timelines. Hence, the sprite has most of the same methods as the movie.

swfsprite() has the following methods :
swfsprite->add(),
swfsprite->remove(), swfsprite->nextframe()
and swfsprite->setframes().

This simple example will spin gracefully a big red square.

例子 1. swfsprite() example

<?php
  $s = new SWFShape();
  $s->setRightFill($s->addFill(0xff, 0, 0));
  $s->movePenTo(-500,-500);
  $s->drawLineTo(500,-500);
  $s->drawLineTo(500,500);
  $s->drawLineTo(-500,500);
  $s->drawLineTo(-500,-500);

  $p = new SWFSprite();
  $i = $p->add($s);
  $p->nextFrame();
  $i->rotate(15);
  $p->nextFrame();
  $i->rotate(15);
  $p->nextFrame();
  $i->rotate(15);
  $p->nextFrame();
  $i->rotate(15);
  $p->nextFrame();
  $i->rotate(15);
  $p->nextFrame();

  $m = new SWFMovie();
  $i = $m->add($p);
  $i->moveTo(1500,1000);
  $i->setName("blah");

  $m->setBackground(0xff, 0xff, 0xff);
  $m->setDimension(3000,2000);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

后退 | 起点 | 前进
SWFSprite->setframes | 上一级 | SWFText->addString


SWFText->addString

(no version information, might be only in CVS)

SWFText->addString -- Draws a string

Description

void swftext->addstring ( string string)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swftext->addstring() draws the string string at the current pen (cursor) location. Pen is at the baseline of the text; i.e., ascending text is in the -y direction.

后退 | 起点 | 前进
SWFSprite | 上一级 | SWFText->getWidth


SWFText->getWidth

(no version information, might be only in CVS)

SWFText->getWidth -- Computes string's width

Description

void swftext->addstring ( string string)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swftext->addstring() returns the rendered width of the string string at the text object's current font, scale, and spacing settings.

后退 | 起点 | 前进
SWFText->addString | 上一级 | SWFText->moveTo


SWFText->moveTo

(no version information, might be only in CVS)

SWFText->moveTo -- Moves the pen

Description

void swftext->moveto ( int x, int y)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swftext->moveto() moves the pen (or cursor, if that makes more sense) to (x,y) in text object's coordinate space. If either is zero, though, value in that dimension stays the same. Annoying, should be fixed.

后退 | 起点 | 前进
SWFText->getWidth | 上一级 | SWFText->setColor


SWFText->setColor

(no version information, might be only in CVS)

SWFText->setColor -- Sets the current font color

Description

void swftext->setcolor ( int red, int green, int blue [, int a])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swftext->setspacing() changes the current text color. Default is black. I think. Color is represented using the RGB system.

后退 | 起点 | 前进
SWFText->moveTo | 上一级 | SWFText->setFont


SWFText->setFont

(no version information, might be only in CVS)

SWFText->setFont -- Sets the current font

Description

void swftext->setfont ( string font)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swftext->setfont() sets the current font to font.

后退 | 起点 | 前进
SWFText->setColor | 上一级 | SWFText->setHeight


SWFText->setHeight

(no version information, might be only in CVS)

SWFText->setHeight -- Sets the current font height

Description

void swftext->setheight ( int height)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swftext->setheight() sets the current font height to height. Default is 240.

后退 | 起点 | 前进
SWFText->setFont | 上一级 | SWFText->setSpacing


SWFText->setSpacing

(no version information, might be only in CVS)

SWFText->setSpacing -- Sets the current font spacing

Description

void swftext->setspacing ( float spacing)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swftext->setspacing() sets the current font spacing to spacingspacing. Default is 1.0. 0 is all of the letters written at the same point. This doesn't really work that well because it inflates the advance across the letter, doesn't add the same amount of spacing between the letters. I should try and explain that better, prolly. Or just fix the damn thing to do constant spacing. This was really just a way to figure out how letter advances work, anyway.. So nyah.

后退 | 起点 | 前进
SWFText->setHeight | 上一级 | SWFText


SWFText

(PHP 4 >= 4.0.5)

SWFText -- Creates a new SWFText object.

Description

new swftext ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swftext() creates a new SWFText object, fresh for manipulating.

SWFText has the following methods : swftext->setfont(),
swftext->setheight(), swftext->setspacing(),
swftext->setcolor(), swftext->moveto(),
swftext->addstring() and swftext->getwidth().

This simple example will draw a big yellow "PHP generates Flash with Ming" text, on white background.

例子 1. swftext() example

<?php
  $f = new SWFFont("Techno.fdb");
  $t = new SWFText();
  $t->setFont($f);
  $t->moveTo(200, 2400);
  $t->setColor(0xff, 0xff, 0);
  $t->setHeight(1200);
  $t->addString("PHP generates Flash with Ming!!");

  $m = new SWFMovie();
  $m->setDimension(5400, 3600);

  $m->add($t);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

后退 | 起点 | 前进
SWFText->setSpacing | 上一级 | SWFTextField->addstring


SWFTextField->addstring

(no version information, might be only in CVS)

SWFTextField->addstring -- Concatenates the given string to the text field

Description

void swftextfield->addstring ( string string)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swftextfield->setname() concatenates the string string to the text field.

后退 | 起点 | 前进
SWFText | 上一级 | SWFTextField->align


SWFTextField->align

(no version information, might be only in CVS)

SWFTextField->align -- Sets the text field alignment

Description

void swftextfield->align ( int alignement)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swftextfield->align() sets the text field alignment to alignement. Valid values for alignement are : SWFTEXTFIELD_ALIGN_LEFT, SWFTEXTFIELD_ALIGN_RIGHT, SWFTEXTFIELD_ALIGN_CENTER and SWFTEXTFIELD_ALIGN_JUSTIFY.

后退 | 起点 | 前进
SWFTextField->addstring | 上一级 | SWFTextField->setbounds


SWFTextField->setbounds

(no version information, might be only in CVS)

SWFTextField->setbounds -- Sets the text field width and height

Description

void swftextfield->setbounds ( int width, int height)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swftextfield->setbounds() sets the text field width to width and height to height. If you don't set the bounds yourself, Ming makes a poor guess at what the bounds are.

后退 | 起点 | 前进
SWFTextField->align | 上一级 | SWFTextField->setcolor


SWFTextField->setcolor

(no version information, might be only in CVS)

SWFTextField->setcolor -- Sets the color of the text field.

Description

void swftextfield->setcolor ( int red, int green, int blue [, int a])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swftextfield->setcolor() sets the color of the text field. Default is fully opaque black. Color is represented using RGB system.

后退 | 起点 | 前进
SWFTextField->setbounds | 上一级 | SWFTextField->setFont


SWFTextField->setFont

(no version information, might be only in CVS)

SWFTextField->setFont -- Sets the text field font

Description

void swftextfield->setfont ( string font)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swftextfield->setfont() sets the text field font to the [browser-defined?] font font.

后退 | 起点 | 前进
SWFTextField->setcolor | 上一级 | SWFTextField->setHeight


SWFTextField->setHeight

(no version information, might be only in CVS)

SWFTextField->setHeight -- Sets the font height of this text field font.

Description

void swftextfield->setheight ( int height)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swftextfield->setheight() sets the font height of this text field font to the given height height. Default is 240.

后退 | 起点 | 前进
SWFTextField->setFont | 上一级 | SWFTextField->setindentation


SWFTextField->setindentation

(no version information, might be only in CVS)

SWFTextField->setindentation -- Sets the indentation of the first line.

Description

void swftextfield->setindentation ( int width)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swftextfield->setindentation() sets the indentation of the first line in the text field, to width.

后退 | 起点 | 前进
SWFTextField->setHeight | 上一级 | SWFTextField->setLeftMargin


SWFTextField->setLeftMargin

(no version information, might be only in CVS)

SWFTextField->setLeftMargin -- Sets the left margin width of the text field.

Description

void swftextfield->setleftmargin ( int width)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swftextfield->setleftmargin() sets the left margin width of the text field to width. Default is 0.

后退 | 起点 | 前进
SWFTextField->setindentation | 上一级 | SWFTextField->setLineSpacing


SWFTextField->setLineSpacing

(no version information, might be only in CVS)

SWFTextField->setLineSpacing -- Sets the line spacing of the text field.

Description

void swftextfield->setlinespacing ( int height)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swftextfield->setlinespacing() sets the line spacing of the text field to the height of height. Default is 40.

后退 | 起点 | 前进
SWFTextField->setLeftMargin | 上一级 | SWFTextField->setMargins


SWFTextField->setMargins

(no version information, might be only in CVS)

SWFTextField->setMargins -- Sets the margins width of the text field.

Description

void swftextfield->setmargins ( int left, int right)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swftextfield->setmargins() set both margins at once, for the man on the go.

后退 | 起点 | 前进
SWFTextField->setLineSpacing | 上一级 | SWFTextField->setname


SWFTextField->setname

(no version information, might be only in CVS)

SWFTextField->setname -- Sets the variable name

Description

void swftextfield->setname ( string name)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swftextfield->setname() sets the variable name of this text field to name, for form posting and action scripting purposes.

后退 | 起点 | 前进
SWFTextField->setMargins | 上一级 | SWFTextField->setrightMargin


SWFTextField->setrightMargin

(no version information, might be only in CVS)

SWFTextField->setrightMargin -- Sets the right margin width of the text field.

Description

void swftextfield->setrightmargin ( int width)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swftextfield->setrightmargin() sets the right margin width of the text field to width. Default is 0.

后退 | 起点 | 前进
SWFTextField->setname | 上一级 | SWFTextField


SWFTextField

(PHP 4 >= 4.0.5)

SWFTextField -- Creates a text field object

Description

new swftextfield ( [int flags])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

swftextfield() creates a new text field object. Text Fields are less flexible than swftext() objects- they can't be rotated, scaled non-proportionally, or skewed, but they can be used as form entries, and they can use browser-defined fonts.

The optional flags change the text field's behavior. It has the following possibles values :

  • SWFTEXTFIELD_DRAWBOX draws the outline of the textfield

  • SWFTEXTFIELD_HASLENGTH

  • SWFTEXTFIELD_HTML allows text markup using HTML-tags

  • SWFTEXTFIELD_MULTILINE allows multiple lines

  • SWFTEXTFIELD_NOEDIT indicates that the field shouldn't be user-editable

  • SWFTEXTFIELD_NOSELECT makes the field non-selectable

  • SWFTEXTFIELD_PASSWORD obscures the data entry

  • SWFTEXTFIELD_WORDWRAP allows text to wrap

Flags are combined with the bitwise OR operation. For example,
<?php
$t = newSWFTextField(SWFTEXTFIELD_PASSWORD | SWFTEXTFIELD_NOEDIT);
?>
creates a totally useless non-editable password field.

SWFTextField has the following methods : swftextfield->setfont(),
swftextfield->setbounds(), swftextfield->align(),
swftextfield->setheight(), swftextfield->setleftmargin(),
swftextfield->setrightmargin(), swftextfield->setmargins(),
swftextfield->setindentation(), swftextfield->setlinespacing(),
swftextfield->setcolor(), swftextfield->setname() and
swftextfield->addstring().

后退 | 起点 | 前进
SWFTextField->setrightMargin | 上一级 | Miscellaneous functions


Miscellaneous functions

PHP 手册
后退 前进

LIX. Miscellaneous functions

介绍

These functions were placed here because none of the other categories seemed to fit.

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

这些函数作为 PHP 核心的一部分，无需被安装即可使用。

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

目录
connection_aborted — Returns TRUE if client disconnected
connection_status — Returns connection status bitfield
connection_timeout — Return TRUE if script timed out
constant — Returns the value of a constant
define — Defines a named constant.
defined — Checks whether a given named constant exists
die — Alias of exit()
eval — Evaluate a string as PHP code
exit — Output a message and terminate the current script
get_browser — Tells what the user's browser is capable of
highlight_file — Syntax highlighting of a file
highlight_string — Syntax highlighting of a string
ignore_user_abort — Set whether a client disconnect should abort script execution
leak — Leak memory
pack — Pack data into binary string.
show_source — Syntax highlighting of a file
sleep — Delay execution
uniqid — Generate a unique ID
unpack — Unpack data from binary string
usleep — Delay execution in microseconds

后退 | 起点 | 前进
SWFTextField | 上一级 | connection_aborted


connection_aborted

(PHP 3>= 3.0.7, PHP 4 )

connection_aborted -- Returns TRUE if client disconnected

Description

int connection_aborted ( void)

Returns TRUE if client disconnected. See the Connection Handling description in the Features chapter for a complete explanation.

后退 | 起点 | 前进
Miscellaneous functions | 上一级 | connection_status


connection_status

(PHP 3>= 3.0.7, PHP 4 )

connection_status -- Returns connection status bitfield

Description

int connection_status ( void)

Returns the connection status bitfield. See the Connection Handling description in the Features chapter for a complete explanation.

后退 | 起点 | 前进
connection_aborted | 上一级 | connection_timeout


connection_timeout

(PHP 3>= 3.0.7, PHP 4 <= 4.0.4)

connection_timeout -- Return TRUE if script timed out

Description

bool connection_timeout ( void)

Returns TRUE if script timed out.

Deprecated

This function is deprecated, and doesn't even exist anymore as of 4.0.5.

See the Connection Handling description in the Features chapter for a complete explanation.

后退 | 起点 | 前进
connection_status | 上一级 | constant


constant

(PHP 4 >= 4.0.4)

constant -- Returns the value of a constant

Description

mixed constant ( string name)

constant() will return the value of the constant indicated by name.

constant() is useful if you need to retrieve the value of a constant, but do not know it's name. i.e. It is stored in a variable or returned by a function.

例子 1. constant() example

<?php

define ("MAXSIZE", 100);

echo MAXSIZE;
echo constant("MAXSIZE"); // same thing as the previous line

?>

See also define(), defined() and the section on Constants.

后退 | 起点 | 前进
connection_timeout | 上一级 | define


define

(PHP 3, PHP 4 )

define -- Defines a named constant.

Description

bool define ( string name, mixed value [, bool case_insensitive])

Defines a named constant. See the section on constants for more details.

The name of the constant is given by name; the value is given by value.

The optional third parameter case_insensitive is also available. If the value TRUE is given, then the constant will be defined case-insensitive. The default behaviour is case-sensitive; i.e. CONSTANT and Constant represent different values.

例子 1. Defining Constants

<?php
define ("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
echo Constant; // outputs "Constant" and issues a notice.

define ("GREETING", "Hello you.",TRUE);
echo GREETING; // outputs "Hello you."
echo Greeting; // outputs "Hello you."

?>

define() returns TRUE on success and FALSE if an error occurs.

See also defined(), constant() and the section on Constants.

后退 | 起点 | 前进
constant | 上一级 | defined


defined

(PHP 3, PHP 4 )

defined -- Checks whether a given named constant exists

Description

bool defined ( string name)

Returns TRUE if the named constant given by name has been defined, FALSE otherwise.

例子 1. Checking Constants

<?php
if (defined("CONSTANT")){ // Note that it should be quoted
    echo CONSTANT; //
    }
?>

See also define(),
constant(),
get_defined_constants() and the section on
Constants.

后退 | 起点 | 前进
define | 上一级 | die


die

die -- Alias of exit()

Description

This function is an alias of exit().

后退 | 起点 | 前进
defined | 上一级 | eval


eval

(no version information, might be only in CVS)

eval -- Evaluate a string as PHP code

Description

mixed eval ( string code_str)

eval() evaluates the string given in code_str as PHP code. Among other things, this can be useful for storing code in a database text field for later execution.

There are some factors to keep in mind when using eval(). Remember that the string passed must be valid PHP code, including things like terminating statements with a semicolon so the parser doesn't die on the line after the eval(), and properly escaping things in code_str.

Also remember that variables given values under eval() will retain these values in the main script afterwards.

A return statement will terminate the evaluation of the string immediately. In PHP 4, eval() returns FALSE unless return() is called in the evaluated code, in which case the value passed to return() is returned. In PHP 3, eval() does not return a value.

例子 1. eval() example - simple text merge

<?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.<br>';
echo $str;
eval ("\$str = \"$str\";");
echo $str;
?>

The above example will show:
This is a $string with my $name in it.
This is a cup with my coffee in it.

提示: 为了防止程序直接将结果输出到浏览器，您可以使用输出控制函数（output-control functions）来捕获函数的输出，并把它们保存到一个 string 型的变量中。

后退 | 起点 | 前进
die | 上一级 | exit


exit

(no version information, might be only in CVS)

exit -- Output a message and terminate the current script

Description

void exit ( [string status])

void exit ( int status)

注: This is not a real function, but a language construct.

The exit() function terminates execution of the script. It prints status just before exiting.

If status is an integer, that value will also be used as the exit status. Exit statuses should be in the range 1 to 254, the exit status 255 is reserved by PHP and shall not be used.

注: The current CVS version does NOT print the status if it is an integer.

注: The die() function is an alias for exit().

例子 1. exit() example

<?php

$filename = '/path/to/data-file';
$file = fopen ($filename, 'r')
    or exit("unable to open file ($filename)");

?>

后退 | 起点 | 前进
eval | 上一级 | get_browser


get_browser

(PHP 3, PHP 4 )

get_browser -- Tells what the user's browser is capable of

Description

object get_browser ( [string user_agent])

get_browser() attempts to determine the capabilities of the user's browser. This is done by looking up the browser's information in the browscap.ini file. By default, the value of $HTTP_USER_AGENT is used; however, you can alter this (i.e., look up another browser's info) by passing the optional user_agent parameter to get_browser().

The information is returned in an object, which will contain various data elements representing, for instance, the browser's major and minor version numbers and ID string; TRUE/false values for features such as frames, JavaScript, and cookies; and so forth.

While browscap.ini contains information on many browsers, it relies on user updates to keep the database current. The format of the file is fairly self-explanatory.

The following example shows how one might list all available information retrieved about the user's browser.

例子 1. get_browser() example

<?php
function list_array ($array) {
    while (list ($key, $value) = each ($array)) {
    $str .= "<b>$key:</b> $value<br />\n";
    }
    return $str;
}
echo "$HTTP_USER_AGENT<hr />\n";
$browser = get_browser();
echo list_array ((array) $browser);
?>

The output of the above script would look something like this:

Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586)<hr />
<b>browser_name_pattern:</b> Mozilla/4\.5.*<br />
<b>parent:</b> Netscape 4.0<br />
<b>platform:</b> Unknown<br />
<b>majorver:</b> 4<br />
<b>minorver:</b> 5<br />
<b>browser:</b> Netscape<br />
<b>version:</b> 4<br />
<b>frames:</b> 1<br />
<b>tables:</b> 1<br />
<b>cookies:</b> 1<br />
<b>backgroundsounds:</b> <br />
<b>vbscript:</b> <br />
<b>javascript:</b> 1<br />
<b>javaapplets:</b> 1<br />
<b>activexcontrols:</b> <br />
<b>beta:</b> <br />
<b>crawler:</b> <br />
<b>authenticodeupdate:</b> <br />
<b>msn:</b> <br />

In order for this to work, your browscap configuration file setting must point to the correct location of the browscap.ini file.

For more information (including locations from which you may obtain a browscap.ini file), check the PHP FAQ at http://www.php.net/FAQ.php.

后退 | 起点 | 前进
exit | 上一级 | highlight_file


highlight_file

(PHP 4 )

highlight_file -- Syntax highlighting of a file

Description

mixed highlight_file ( string filename [, bool return])

The highlight_file() function prints out a syntax higlighted version of the code contained in filename using the colors defined in the built-in syntax highlighter for PHP.

If the second parameter return is set to TRUE then highlight_file() will return the highlighted code as a string instead of printing it out. If the second parameter is not set to TRUE then highlight_file() will return TRUE on success, FALSE on failure.

注: The return parameter became available in PHP 4.2.0. Before this time it behaved like the default, which is FALSE

注: Care should be taken when using the show_source() and highlight_file() functions to make sure that you do not inadvertently reveal sensitive information such as passwords or any other type of information that might create a potential security risk.

注: Since PHP 4.2.1 this function is also affected by safe_mode and open_basedir.

例子 1. Creating a source highlighting URL

To setup a URL that can code hightlight any script that you pass to it, we will make use of the "ForceType" directive in Apache to generate a nice URL pattern, and use the function highlight_file() to show a nice looking code list.

In your httpd.conf you can add the following:

<Location /source>
    ForceType application/x-httpd-php
</Location>

And then make a file named "source" and put it in your web root directory.

<HTML>
<HEAD>
<TITLE>Source Display</TITLE>
</HEAD>
<BODY BGCOLOR="white">
<?php
    $script = getenv ("PATH_TRANSLATED");
    if(!$script) {
    echo "<BR><B>ERROR: Script Name needed</B><BR>";
    } else {
    if (ereg("(\.php|\.inc)$",$script)) {
    echo "<H1>Source of: $PATH_INFO</H1>\n<HR>\n";
    highlight_file($script);
    } else {
    echo "<H1>ERROR: Only PHP or include script names are allowed</H1>";
    }
    }
    echo "<HR>Processed: ".date("Y/M/d H:i:s",time());
?>
</BODY>
</HTML>

Then you can use an URL like the one below to display a colorized version of a script located in "/path/to/script.php" in your web site.

http://your.server.com/source/path/to/script.php

See also highlight_string(), show_source().

后退 | 起点 | 前进
get_browser | 上一级 | highlight_string


highlight_string

(PHP 4 )

highlight_string -- Syntax highlighting of a string

Description

mixed highlight_string ( string str [, bool return])

The highlight_string() function outputs a syntax highlighted version of str using the colors defined in the built-in syntax highlighter for PHP.

If the second parameter return is set to TRUE then highlight_string() will return the highlighted code as a string instead of printing it out. If the second parameter is not set to TRUE then highlight_string() will return TRUE on success, FALSE on failure.

注: The return parameter became available in PHP 4.2.0. Before this time it behaved like the default, which is FALSE

See also highlight_file(), and show_source().

后退 | 起点 | 前进
highlight_file | 上一级 | ignore_user_abort


ignore_user_abort

(PHP 3>= 3.0.7, PHP 4 )

ignore_user_abort -- Set whether a client disconnect should abort script execution

Description

int ignore_user_abort ( [int setting])

This function sets whether a client disconnect should cause a script to be aborted. It will return the previous setting and can be called without an argument to not change the current setting and only return the current setting. See the Connection Handling section in the Features chapter for a complete description of connection handling in PHP.

后退 | 起点 | 前进
highlight_string | 上一级 | leak


leak

(PHP 3, PHP 4 )

leak -- Leak memory

Description

void leak ( int bytes)

leak() leaks the specified amount of memory.

This is useful when debugging the memory manager, which automatically cleans up "leaked" memory when each request is completed.

后退 | 起点 | 前进
ignore_user_abort | 上一级 | pack


pack

(PHP 3, PHP 4 )

pack -- Pack data into binary string.

Description

string pack ( string format [, mixed args])

Pack given arguments into binary string according to format. Returns binary string containing data.

The idea to this function was taken from Perl and all formatting codes work the same as there, however, there are some formatting codes that are missing such as Perl's "u" format code. The format string consists of format codes followed by an optional repeater argument. The repeater argument can be either an integer value or * for repeating to the end of the input data. For a, A, h, H the repeat count specifies how many characters of one data argument are taken, for @ it is the absolute position where to put the next data, for everything else the repeat count specifies how many data arguments are consumed and packed into the resulting binary string. Currently implemented are

  • a NUL-padded string

  • A SPACE-padded string

  • h Hex string, low nibble first

  • H Hex string, high nibble first

  • c signed char

  • C unsigned char

  • s signed short (always 16 bit, machine byte order)

  • S unsigned short (always 16 bit, machine byte order)

  • n unsigned short (always 16 bit, big endian byte order)

  • v unsigned short (always 16 bit, little endian byte order)

  • i signed integer (machine dependent size and byte order)

  • I unsigned integer (machine dependent size and byte order)

  • l signed long (always 32 bit, machine byte order)

  • L unsigned long (always 32 bit, machine byte order)

  • N unsigned long (always 32 bit, big endian byte order)

  • V unsigned long (always 32 bit, little endian byte order)

  • f float (machine dependent size and representation)

  • d double (machine dependent size and representation)

  • x NUL byte

  • X Back up one byte

  • @ NUL-fill to absolute position

例子 1. pack() format string

$binarydata = pack ("nvc*", 0x1234, 0x5678, 65, 66);

The resulting binary string will be 6 bytes long and contain the byte sequence 0x12, 0x34, 0x78, 0x56, 0x41, 0x42.

Note that the distinction between signed and unsigned values only affects the function unpack(), where as function pack() gives the same result for signed and unsigned format codes.

Also note that PHP internally stores integer values as signed values of a machine dependent size. If you give it an unsigned integer value too large to be stored that way it is converted to a float which often yields an undesired result.

后退 | 起点 | 前进
leak | 上一级 | show_source


show_source

(PHP 4 )

show_source -- Syntax highlighting of a file

Description

bool show_source ( string filename [, bool return])

This function is an alias to highlight_file(). For more information see the documentation there.

See also highlight_string() and highlight_file().

后退 | 起点 | 前进
pack | 上一级 | sleep


sleep

(PHP 3, PHP 4 )

sleep -- Delay execution

Description

void sleep ( int seconds)

The sleep function delays program execution for the given number of seconds.

See also usleep() and set_time_limit()

后退 | 起点 | 前进
show_source | 上一级 | uniqid


uniqid

(PHP 3, PHP 4 )

uniqid -- Generate a unique ID

Description

string uniqid ( string prefix [, bool lcg])

uniqid() returns a prefixed unique identifier based on the current time in microseconds. The prefix can be useful for instance if you generate identifiers simultaneously on several hosts that might happen to generate the identifier at the same microsecond. Prefix can be up to 114 characters long.

If the optional lcg parameter is TRUE, uniqid() will add additional "combined LCG" entropy at the end of the return value, which should make the results more unique.

With an empty prefix, the returned string will be 13 characters long. If lcg is TRUE, it will be 23 characters.

注: The lcg parameter is only available in PHP 4 and PHP 3.0.13 and later.

If you need a unique identifier or token and you intend to give out that token to the user via the network (i.e. session cookies), it is recommended that you use something along the lines of

$token = md5(uniqid("")); // no prefix
$better_token = md5(uniqid(rand(),1)); // better, difficult to guess

This will create a 32 character identifier (a 128 bit hex number) that is extremely difficult to predict.

后退 | 起点 | 前进
sleep | 上一级 | unpack


unpack

(PHP 3, PHP 4 )

unpack -- Unpack data from binary string

Description

array unpack ( string format, string data)

unpack() from binary string into array according to format. Returns array containing unpacked elements of binary string.

unpack() works slightly different from Perl as the unpacked data is stored in an associative array. To accomplish this you have to name the different format codes and separate them by a slash /.

例子 1. unpack() format string

$array = unpack ("c2chars/nint", $binarydata);

The resulting array will contain the entries "chars1", "chars2" and "int".

For an explanation of the format codes see also: pack()

Note that PHP internally stores integral values as signed. If you unpack a large unsigned long and it is of the same size as PHP internally stored values the result will be a negative number even though unsigned unpacking was specified.

后退 | 起点 | 前进
uniqid | 上一级 | usleep


usleep

(PHP 3, PHP 4 )

usleep -- Delay execution in microseconds

Description

void usleep ( int micro_seconds)

The usleep() function delays program execution for the given number of micro_seconds. A microsecond is one millionth of a second.

See also sleep() and set_time_limit().

注: This function does not work on Windows systems.

后退 | 起点 | 前进
unpack | 上一级 | mnoGoSearch Functions


mnoGoSearch Functions

PHP 手册
后退 前进

LX. mnoGoSearch Functions

介绍

These functions allow you to access the mnoGoSearch (former UdmSearch) free search engine. mnoGoSearch is a full-featured search engine software for intranet and internet servers, distributed under the GNU license. mnoGoSearch has a number of unique features, which makes it appropriate for a wide range of applications from search within your site to a specialized search system such as cooking recipes or newspaper search, FTP archive search, news articles search, etc. It offers full-text indexing and searching for HTML, PDF, and text documents. mnoGoSearch consists of two parts. The first is an indexing mechanism (indexer). The purpose of the indexer is to walk through HTTP, FTP, NEWS servers or local files, recursively grabbing all the documents and storing meta-data about that documents in a SQL database in a smart and effective manner. After every document is referenced by its corresponding URL, meta-data is collected by the indexer for later use in a search process. The search is performed via Web interface. C, CGI, PHP and Perl search front ends are included.

More information about mnoGoSearch can be found at http://www.mnogosearch.ru/.

需求

Download mnoGosearch from http://www.mnogosearch.ru/ and install it on your system. You need at least version 3.1.10 of mnoGoSearch installed to use these functions.

安装

In order to have these functions available, you must compile PHP with mnoGosearch support by using the --with-mnogosearch option. If you use this option without specifying the path to mnoGosearch, PHP will look for mnoGosearch under /usr/local/mnogosearch path by default. If you installed mnoGosearch at a different location you should specify it: --with-mnogosearch=DIR.

注: PHP contains built-in MySQL access library, which can be used to access MySQL. It is known that mnoGoSearch is not compatible with this built-in library and can work only with generic MySQL libraries. Thus, if you use mnoGoSearch with MySQL, during PHP configuration you have to indicate the directory of your MySQL installation, that was used during mnoGoSearch configuration, i.e. for example: --with-mnogosearch --with-mysql=/usr.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

UDM_FIELD_URLID (integer)

UDM_FIELD_URL (integer)

UDM_FIELD_CONTENT (integer)

UDM_FIELD_TITLE (integer)

UDM_FIELD_KEYWORDS (integer)

UDM_FIELD_DESC (integer)

UDM_FIELD_DESCRIPTION (integer)

UDM_FIELD_TEXT (integer)

UDM_FIELD_SIZE (integer)

UDM_FIELD_RATING (integer)

UDM_FIELD_SCORE (integer)

UDM_FIELD_MODIFIED (integer)

UDM_FIELD_ORDER (integer)

UDM_FIELD_CRC (integer)

UDM_FIELD_CATEGORY (integer)

UDM_FIELD_LANG (integer)

UDM_FIELD_CHARSET (integer)

UDM_PARAM_PAGE_SIZE (integer)

UDM_PARAM_PAGE_NUM (integer)

UDM_PARAM_SEARCH_MODE (integer)

UDM_PARAM_CACHE_MODE (integer)

UDM_PARAM_TRACK_MODE (integer)

UDM_PARAM_PHRASE_MODE (integer)

UDM_PARAM_CHARSET (integer)

UDM_PARAM_LOCAL_CHARSET (integer)

UDM_PARAM_BROWSER_CHARSET (integer)

UDM_PARAM_STOPTABLE (integer)

UDM_PARAM_STOP_TABLE (integer)

UDM_PARAM_STOPFILE (integer)

UDM_PARAM_STOP_FILE (integer)

UDM_PARAM_WEIGHT_FACTOR (integer)

UDM_PARAM_WORD_MATCH (integer)

UDM_PARAM_MAX_WORD_LEN (integer)

UDM_PARAM_MAX_WORDLEN (integer)

UDM_PARAM_MIN_WORD_LEN (integer)

UDM_PARAM_MIN_WORDLEN (integer)

UDM_PARAM_ISPELL_PREFIXES (integer)

UDM_PARAM_ISPELL_PREFIX (integer)

UDM_PARAM_PREFIXES (integer)

UDM_PARAM_PREFIX (integer)

UDM_PARAM_CROSS_WORDS (integer)

UDM_PARAM_CROSSWORDS (integer)

UDM_PARAM_VARDIR (integer)

UDM_PARAM_DATADIR (integer)

UDM_PARAM_HLBEG (integer)

UDM_PARAM_HLEND (integer)

UDM_PARAM_SYNONYM (integer)

UDM_PARAM_SEARCHD (integer)

UDM_PARAM_QSTRING (integer)

UDM_PARAM_REMOTE_ADDR (integer)

UDM_LIMIT_CAT (integer)

UDM_LIMIT_URL (integer)

UDM_LIMIT_TAG (integer)

UDM_LIMIT_LANG (integer)

UDM_LIMIT_DATE (integer)

UDM_PARAM_FOUND (integer)

UDM_PARAM_NUM_ROWS (integer)

UDM_PARAM_WORDINFO (integer)

UDM_PARAM_WORD_INFO (integer)

UDM_PARAM_SEARCHTIME (integer)

UDM_PARAM_SEARCH_TIME (integer)

UDM_PARAM_FIRST_DOC (integer)

UDM_PARAM_LAST_DOC (integer)

UDM_MODE_ALL (integer)

UDM_MODE_ANY (integer)

UDM_MODE_BOOL (integer)

UDM_MODE_PHRASE (integer)

UDM_CACHE_ENABLED (integer)

UDM_CACHE_DISABLED (integer)

UDM_TRACK_ENABLED (integer)

UDM_TRACK_DISABLED (integer)

UDM_PHRASE_ENABLED (integer)

UDM_PHRASE_DISABLED (integer)

UDM_CROSS_WORDS_ENABLED (integer)

UDM_CROSSWORDS_ENABLED (integer)

UDM_CROSS_WORDS_DISABLED (integer)

UDM_CROSSWORDS_DISABLED (integer)

UDM_PREFIXES_ENABLED (integer)

UDM_PREFIX_ENABLED (integer)

UDM_ISPELL_PREFIXES_ENABLED (integer)

UDM_ISPELL_PREFIX_ENABLED (integer)

UDM_PREFIXES_DISABLED (integer)

UDM_PREFIX_DISABLED (integer)

UDM_ISPELL_PREFIXES_DISABLED (integer)

UDM_ISPELL_PREFIX_DISABLED (integer)

UDM_ISPELL_TYPE_AFFIX (integer)

UDM_ISPELL_TYPE_SPELL (integer)

UDM_ISPELL_TYPE_DB (integer)

UDM_ISPELL_TYPE_SERVER (integer)

UDM_MATCH_WORD (integer)

UDM_MATCH_BEGIN (integer)

UDM_MATCH_SUBSTR (integer)

UDM_MATCH_END (integer)

目录
udm_add_search_limit — Add various search limits
udm_alloc_agent — Allocate mnoGoSearch session
udm_api_version — Get mnoGoSearch API version.
udm_cat_list — Get all the categories on the same level with the current one.
udm_cat_path — Get the path to the current category.
udm_check_charset — Check if the given charset is known to mnogosearch
udm_check_stored — Check connection to stored
udm_clear_search_limits — Clear all mnoGoSearch search restrictions
udm_close_stored — Close connection to stored
udm_crc32 — Return CRC32 checksum of gived string
udm_errno — Get mnoGoSearch error number
udm_error — Get mnoGoSearch error message
udm_find — Perform search
udm_free_agent — Free mnoGoSearch session
udm_free_ispell_data — Free memory allocated for ispell data
udm_free_res — Free mnoGoSearch result
udm_get_doc_count — Get total number of documents in database.
udm_get_res_field — Fetch mnoGoSearch result field
udm_get_res_param — Get mnoGoSearch result parameters
udm_load_ispell_data — Load ispell data
udm_open_stored — Open connection to stored
udm_set_agent_param — Set mnoGoSearch agent session parameters

后退 | 起点 | 前进
usleep | 上一级 | udm_add_search_limit


udm_add_search_limit

(PHP 4 >= 4.0.5)

udm_add_search_limit -- Add various search limits

Description

int udm_add_search_limit ( int agent, int var, string val)

udm_add_search_limit() returns TRUE on success, FALSE on error. Adds search restrictions.

agent - a link to Agent, received after call to udm_alloc_agent().

var - defines parameter, indicating limit.

val - defines value of the current parameter.

Possible var values:

  • UDM_LIMIT_URL - defines document URL limitations to limit search through subsection of database. It supports SQL % and _ LIKE wildcards, where % matches any number of characters, even zero characters, and _ matches exactly one character. E.g. http://my.domain.__/catalog may stand for http://my.domain.ru/catalog and http://my.domain.ua/catalog.

  • UDM_LIMIT_TAG - defines site TAG limitations. In indexer-conf you can assign specific TAGs to various sites and parts of a site. Tags in mnoGoSearch 3.1.x are lines, that may contain metasymbols % and _. Metasymbols allow searching among groups of tags. E.g. there are links with tags ABCD and ABCE, and search restriction is by ABC_ - the search will be made among both of the tags.

  • UDM_LIMIT_LANG - defines document language limitations.

  • UDM_LIMIT_CAT - defines document category limitations. Categories are similar to tag feature, but nested. So you can have one category inside another and so on. You have to use two characters for each level. Use a hex number going from 0-F or a 36 base number going from 0-Z. Therefore a top-level category like 'Auto' would be 01. If it has a subcategory like 'Ford', then it would be 01 (the parent category) and then 'Ford' which we will give 01. Put those together and you get 0101. If 'Auto' had another subcategory named 'VW', then it's id would be 01 because it belongs to the 'Ford' category and then 02 because it's the next category. So it's id would be 0102. If VW had a sub category called 'Engine' then it's id would start at 01 again and it would get the 'VW' id 02 and 'Auto' id of 01, making it 010201. If you want to search for sites under that category then you pass it cat=010201 in the url.

  • UDM_LIMIT_DATE - defines limitation by date document was modified.

    Format of parameter value: a string with first character < or >, then with no space - date in unixtime format, for example:

    Udm_Add_Search_Limit($udm,UDM_LIMIT_DATE,"<908012006");

    If > character is used, then search will be restricted to those documents having modification date greater than entered. If <, then smaller.

后退 | 起点 | 前进
mnoGoSearch Functions | 上一级 | udm_alloc_agent


udm_alloc_agent

(PHP 4 >= 4.0.5)

udm_alloc_agent -- Allocate mnoGoSearch session

Description

int udm_alloc_agent ( string dbaddr [, string dbmode])

udm_alloc_agent() returns mnogosearch agent identifier on success, FALSE on error. This function creates a session with database parameters.

dbaddr - URL-style database description. Options (type, host, database name, port, user and password) to connect to SQL database. Do not matter for built-in text files support. Format: DBAddr DBType:[//[DBUser[:DBPass]@]DBHost[:DBPort]]/DBName/ Currently supported DBType values are: mysql, pgsql, msql, solid, mssql, oracle, ibase. Actually, it does not matter for native libraries support. But ODBC users should specify one of supported values. If your database type is not supported, you may use "unknown" instead.

dbmode - You may select SQL database mode of words storage. When "single" is specified, all words are stored in the same table. If "multi" is selected, words will be located in different tables depending of their lengths. "multi" mode is usually faster but requires more tables in database. If "crc" mode is selected, mnoGoSearch will store 32 bit integer word IDs calculated by CRC32 algorythm instead of words. This mode requres less disk space and it is faster comparing with "single" and "multi" modes. "crc-multi" uses the same storage structure with the "crc" mode, but also stores words in different tables depending on words lengths like "multi" mode. Format: DBMode single/multi/crc/crc-multi

注: dbaddr and dbmode must match those used during indexing.

注: In fact this function does not open connection to database and thus does not check entered login and password. Actual connection to database and login/password verification is done by udm_find().

后退 | 起点 | 前进
udm_add_search_limit | 上一级 | udm_api_version


udm_api_version

(PHP 4 >= 4.0.5)

udm_api_version -- Get mnoGoSearch API version.

Description

int udm_api_version ( void)

udm_api_version() returns mnoGoSearch API version number. E.g. if mnoGoSearch 3.1.10 API is used, this function will return 30110.

This function allows user to identify which API functions are available, e.g. udm_get_doc_count() function is only available in mnoGoSearch 3.1.11 or later.

Example:

if (udm_api_version() >= 30111) {
   print  "Total number of urls in database: ".udm_get_doc_count($udm)."<br>\n";
   }

后退 | 起点 | 前进
udm_alloc_agent | 上一级 | udm_cat_list


udm_cat_list

(PHP 4 >= 4.0.6)

udm_cat_list -- Get all the categories on the same level with the current one.

Description

array udm_cat_list ( int agent, string category)

udm_cat_list() returns array listing all categories of the same level as current category in the categories tree.

The function can be useful for developing categories tree browser.

Returns array with the following format:

The array consists of pairs. Elements with even index numbers contain category paths, odd elements contain corresponding category names.

$array[0] will contain '020300'
$array[1] will contain 'Audi'
$array[2] will contain '020301'
$array[3] will contain 'BMW'
$array[4] will contain '020302'
$array[5] will contain 'Opel'
...
etc.

Following is an example of displaying links of the current level in format:
Audi
BMW
Opel
...

<?php
 $cat_list_arr = udm_cat_list($udm_agent,$cat);
 $cat_list = '';
 for ($i=0; $i<count($cat_list_arr); $i+=2) {
   $path = $cat_list_arr[$i];
   $name = $cat_list_arr[$i+1];
   $cat_list .= "<a href=\"$PHP_SELF?cat=$path\">$name</a><br>";
 }
?>

后退 | 起点 | 前进
udm_api_version | 上一级 | udm_cat_path


udm_cat_path

(PHP 4 >= 4.0.6)

udm_cat_path -- Get the path to the current category.

Description

array udm_cat_path ( int agent, string category)

udm_cat_path() returns array describing path in the categories tree from the tree root to the current category.

agent - agent link identifier.

category - current category - the one to get path to.

Returns array with the following format:

The array consists of pairs. Elements with even index numbers contain category paths, odd elements contain corresponding category names.

For example, the call $array=udm_cat_path($agent, '02031D'); may return the following array:

$array[0] will contain ''
$array[1] will contain 'Root'
$array[2] will contain '02'
$array[3] will contain 'Sport'
$array[4] will contain '0203'
$array[5] will contain 'Auto'
$array[4] will contain '02031D'
$array[5] will contain 'Ferrari'

例子 1. Specifying path to the current category in the following format: '> Root > Sport > Auto > Ferrari'

<?php
  $cat_path_arr = udm_cat_path($udm_agent,$cat);
  $cat_path = '';
  for ($i=0; $i<count($cat_path_arr); $i+=2) {
    $path = $cat_path_arr[$i];
    $name = $cat_path_arr[$i+1];
    $cat_path .= " > <a href=\"$PHP_SELF?cat=$path\">$name</a> ";
  }
?>

后退 | 起点 | 前进
udm_cat_list | 上一级 | udm_check_charset


udm_check_charset

(PHP 4 >= 4.2.0)

udm_check_charset -- Check if the given charset is known to mnogosearch

Description

int udm_check_charset ( int agent, string charset)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
udm_cat_path | 上一级 | udm_check_stored


udm_check_stored

(PHP 4 >= 4.2.0)

udm_check_stored -- Check connection to stored

Description

int udm_check_stored ( int agent, int link, string doc_id)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
udm_check_charset | 上一级 | udm_clear_search_limits


udm_clear_search_limits

(PHP 4 >= 4.0.5)

udm_clear_search_limits -- Clear all mnoGoSearch search restrictions

Description

int udm_clear_search_limits ( int agent)

udm_clear_search_limits() resets defined search limitations and returns TRUE.

后退 | 起点 | 前进
udm_check_stored | 上一级 | udm_close_stored


udm_close_stored

(PHP 4 >= 4.2.0)

udm_close_stored -- Close connection to stored

Description

int udm_close_stored ( int agent, int link)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
udm_clear_search_limits | 上一级 | udm_crc32


udm_crc32

(PHP 4 >= 4.2.0)

udm_crc32 -- Return CRC32 checksum of gived string

Description

int udm_crc32 ( int agent, string str)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
udm_close_stored | 上一级 | udm_errno


udm_errno

(PHP 4 >= 4.0.5)

udm_errno -- Get mnoGoSearch error number

Description

int udm_errno ( int agent)

udm_errno() returns mnoGoSearch error number, zero if no error.

agent - link to agent identifier, received after call to udm_alloc_agent().

Receiving numeric agent error code.

后退 | 起点 | 前进
udm_crc32 | 上一级 | udm_error


udm_error

(PHP 4 >= 4.0.5)

udm_error -- Get mnoGoSearch error message

Description

string udm_error ( int agent)

udm_error() returns mnoGoSearch error message, empty string if no error.

agent - link to agent identifier, received after call to udm_alloc_agent().

Receiving agent error message.

后退 | 起点 | 前进
udm_errno | 上一级 | udm_find


udm_find

(PHP 4 >= 4.0.5)

udm_find -- Perform search

Description

int udm_find ( int agent, string query)

udm_find() returns result link identifier on success, FALSE on error.

The search itself. The first argument - session, the next one - query itself. To find something just type words you want to find and press SUBMIT button. For example, "mysql odbc". You should not use quotes " in query, they are written here only to divide a query from other text. mnoGoSearch will find all documents that contain word "mysql" and/or word "odbc". Best documents having bigger weights will be displayed first. If you use search mode ALL, search will return documents that contain both (or more) words you entered. In case you use mode ANY, the search will return list of documents that contain any of the words you entered. If you want more advanced results you may use query language. You should select "bool" match mode in the search from.

mnoGoSearch understands the following boolean operators:

& - logical AND. For example, "mysql & odbc". mnoGoSearch will find any URLs that contain both "mysql" and "odbc".

| - logical OR. For example "mysql|odbc". mnoGoSearch will find any URLs, that contain word "mysql" or word "odbc".

~ - logical NOT. For example "mysql & ~odbc". mnoGoSearch will find URLs that contain word "mysql" and do not contain word "odbc" at the same time. Note that ~ just excludes given word from results. Query "~odbc" will find nothing!

() - group command to compose more complex queries. For example "(mysql | msql) & ~postgres". Query language is simple and powerful at the same time. Just consider query as usual boolean expression.

后退 | 起点 | 前进
udm_error | 上一级 | udm_free_agent


udm_free_agent

(PHP 4 >= 4.0.5)

udm_free_agent -- Free mnoGoSearch session

Description

int udm_free_agent ( int agent)

udm_free_agent() returns TRUE on success, FALSE on error.

agent - link to agent identifier, received ` after call to udm_alloc_agent().

Freeing up memory allocated for agent session.

后退 | 起点 | 前进
udm_find | 上一级 | udm_free_ispell_data


udm_free_ispell_data

(PHP 4 >= 4.0.5)

udm_free_ispell_data -- Free memory allocated for ispell data

Description

int udm_free_ispell_data ( int agent)

udm_free_ispell_data() always returns TRUE.

agent - agent link identifier, received after call to udm_alloc_agent().

注: This function is supported beginning from version 3.1.12 of mnoGoSearch and it does not do anything in previous versions.

后退 | 起点 | 前进
udm_free_agent | 上一级 | udm_free_res


udm_free_res

(PHP 4 >= 4.0.5)

udm_free_res -- Free mnoGoSearch result

Description

int udm_free_res ( int res)

udm_free_res() returns TRUE on success, FALSE on error.

res - a link to result identifier, received after call to udm_find().

Freeing up memory allocated for results.

后退 | 起点 | 前进
udm_free_ispell_data | 上一级 | udm_get_doc_count


udm_get_doc_count

(PHP 4 >= 4.0.5)

udm_get_doc_count -- Get total number of documents in database.

Description

int udm_get_doc_count ( int agent)

udm_get_doc_count() returns number of documents in database.

agent - link to agent identifier, received after call to udm_alloc_agent().

注: This function is supported only in mnoGoSearch 3.1.11 or later.

后退 | 起点 | 前进
udm_free_res | 上一级 | udm_get_res_field


udm_get_res_field

(PHP 4 >= 4.0.5)

udm_get_res_field -- Fetch mnoGoSearch result field

Description

string udm_get_res_field ( int res, int row, int field)

udm_get_res_field() returns result field value on success, FALSE on error.

res - a link to result identifier, received after call to udm_find().

row - the number of the link on the current page. May have values from 0 to UDM_PARAM_NUM_ROWS-1.

field - field identifier, may have the following values:

  • UDM_FIELD_URL - document URL field

  • UDM_FIELD_CONTENT - document Content-type field (for example, text/html).

  • UDM_FIELD_CATEGORY - document category field. Use udm_cat_path() to get full path to current category from the categories tree root. (This parameter is available only in PHP 4.0.6 or later).

  • UDM_FIELD_TITLE - document title field.

  • UDM_FIELD_KEYWORDS - document keywords field (from META KEYWORDS tag).

  • UDM_FIELD_DESC - document description field (from META DESCRIPTION tag).

  • UDM_FIELD_TEXT - document body text (the first couple of lines to give an idea of what the document is about).

  • UDM_FIELD_SIZE - document size.

  • UDM_FIELD_URLID - unique URL ID of the link.

  • UDM_FIELD_RATING - page rating (as calculated by mnoGoSearch).

  • UDM_FIELD_MODIFIED - last-modified field in unixtime format.

  • UDM_FIELD_ORDER - the number of the current document in set of found documents.

  • UDM_FIELD_CRC - document CRC.

后退 | 起点 | 前进
udm_get_doc_count | 上一级 | udm_get_res_param


udm_get_res_param

(PHP 4 >= 4.0.5)

udm_get_res_param -- Get mnoGoSearch result parameters

Description

string udm_get_res_param ( int res, int param)

udm_get_res_param() returns result parameter value on success, FALSE on error.

res - a link to result identifier, received after call to udm_find().

param - parameter identifier, may have the following values:

  • UDM_PARAM_NUM_ROWS - number of received found links on the current page. It is equal to UDM_PARAM_PAGE_SIZE for all search pages, on the last page - the rest of links.

  • UDM_PARAM_FOUND - total number of results matching the query.

  • UDM_PARAM_WORDINFO - information on the words found. E.g. search for "a good book" will return "a: stopword, good:5637, book: 120"

  • UDM_PARAM_SEARCHTIME - search time in seconds.

  • UDM_PARAM_FIRST_DOC - the number of the first document displayed on current page.

  • UDM_PARAM_LAST_DOC - the number of the last document displayed on current page.

后退 | 起点 | 前进
udm_get_res_field | 上一级 | udm_load_ispell_data


udm_load_ispell_data

(PHP 4 >= 4.0.5)

udm_load_ispell_data -- Load ispell data

Description

int udm_load_ispell_data ( int agent, int var, string val1, string val2, int flag)

udm_load_ispell_data() loads ispell data. Returns TRUE on success, FALSE on error.

agent - agent link identifier, received after call to udm_alloc_agent().

var - parameter, indicating the source for ispell data. May have the following values:

After using this function to free memory allocated for ispell data, please use udm_free_ispell_data(), even if you use UDM_ISPELL_TYPE_SERVER mode.

The fastest mode is UDM_ISPELL_TYPE_SERVER. UDM_ISPELL_TYPE_TEXT is slower and UDM_ISPELL_TYPE_DB is the slowest. The above pattern is TRUE for mnoGoSearch 3.1.10 - 3.1.11. It is planned to speed up DB mode in future versions and it is going to be faster than TEXT mode.

  • UDM_ISPELL_TYPE_DB - indicates that ispell data should be loaded from SQL. In this case, parameters val1 and val2 are ignored and should be left blank. flag should be equal to 1.

    注: flag indicates that after loading ispell data from defined source it sould be sorted (it is necessary for correct functioning of ispell). In case of loading ispell data from files there may be several calls to udm_load_ispell_data(), and there is no sense to sort data after every call, but only after the last one. Since in db mode all the data is loaded by one call, this parameter should have the value 1. In this mode in case of error, e.g. if ispell tables are absent, the function will return FALSE and code and error message will be accessible through udm_error() and udm_errno().

    Example:

    if (! udm_load_ispell_data($udm,UDM_ISPELL_TYPE_DB,'','',1)) {
  printf("Error #%d: '%s'\n", udm_errno($udm), udm_error($udm));
  exit;
}

  • UDM_ISPELL_TYPE_AFFIX - indicates that ispell data should be loaded from file and initiates loading affixes file. In this case val1 defines double letter language code for which affixes are loaded, and val2 - file path. Please note, that if a relative path entered, the module looks for the file not in UDM_CONF_DIR, but in relation to current path, i.e. to the path where the script is executed. In case of error in this mode, e.g. if file is absent, the function will return FALSE, and an error message will be displayed. Error message text cannot be accessed through udm_error() and udm_errno(), since those functions can only return messages associated with SQL. Please, see flag parameter description in UDM_ISPELL_TYPE_DB.

    Example:

    if ((! udm_load_ispell_data($udm,UDM_ISPELL_TYPE_AFFIX,'en','/opt/ispell/en.aff',0)) ||
        (! udm_load_ispell_data($udm,UDM_ISPELL_TYPE_AFFIX,'ru','/opt/ispell/ru.aff',0)) ||
        (! udm_load_ispell_data($udm,UDM_ISPELL_TYPE_SPELL,'en','/opt/ispell/en.dict',0)) ||
        (! udm_load_ispell_data($udm,UDM_ISPELL_TYPE_SPELL,'ru','/opt/ispell/ru.dict',1))) {
     exit;
     }

    注: flag is equal to 1 only in the last call.

  • UDM_ISPELL_TYPE_SPELL - indicates that ispell data should be loaded from file and initiates loading of ispell dictionary file. In this case val1 defines double letter language code for which affixes are loaded, and val2 - file path. Please note, that if a relative path entered, the module looks for the file not in UDM_CONF_DIR, but in relation to current path, i.e. to the path where the script is executed. In case of error in this mode, e.g. if file is absent, the function will return FALSE, and an error message will be displayed. Error message text cannot be accessed through udm_error() and udm_errno(), since those functions can only return messages associated with SQL. Please, see flag parameter description in UDM_ISPELL_TYPE_DB.

    if ((! Udm_Load_Ispell_Data($udm,UDM_ISPELL_TYPE_AFFIX,'en','/opt/ispell/en.aff',0)) ||
        (! Udm_Load_Ispell_Data($udm,UDM_ISPELL_TYPE_AFFIX,'ru','/opt/ispell/ru.aff',0)) ||
        (! Udm_Load_Ispell_Data($udm,UDM_ISPELL_TYPE_SPELL,'en','/opt/ispell/en.dict',0)) ||
        (! Udm_Load_Ispell_Data($udm,UDM_ISPELL_TYPE_SPELL,'ru','/opt/ispell/ru.dict',1))) {
      exit;
      }

    注: flag is equal to 1 only in the last call.

  • UDM_ISPELL_TYPE_SERVER - enables spell server support. val1 parameter indicates address of the host running spell server. val2 ` is not used yet, but in future releases it is going to indicate number of port used by spell server. flag parameter in this case is not needed since ispell data is stored on spellserver already sorted.

    Spelld server reads spell-data from a separate configuration file (/usr/local/mnogosearch/etc/spelld.conf by default), sorts it and stores in memory. With clients server communicates in two ways: to indexer all the data is transferred (so that indexer starts faster), from search.cgi server receives word to normalize and then passes over to client (search.cgi) list of normalized word forms. This allows fastest, compared to db and text modes processing of search queries (by omitting loading and sorting all the spell data).

    udm_load_ispell_data() function in UDM_ISPELL_TYPE_SERVER mode does not actually load ispell data, but only defines server address. In fact, server is automatically used by udm_find() function when performing search. In case of errors, e.g. if spellserver is not running or invalid host indicated, there are no messages returned and ispell conversion does not work.

    注: This function is available in mnoGoSearch 3.1.12 or later.

    Example:

    if (!udm_load_ispell_data($udm,UDM_ISPELL_TYPE_SERVER,'','',1)) {
    printf("Error loading ispell data from server<br>\n");
    exit;
}

后退 | 起点 | 前进
udm_get_res_param | 上一级 | udm_open_stored


udm_open_stored

(PHP 4 >= 4.2.0)

udm_open_stored -- Open connection to stored

Description

int udm_open_stored ( int agent, string storedaddr)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
udm_load_ispell_data | 上一级 | udm_set_agent_param


udm_set_agent_param

(PHP 4 >= 4.0.5)

udm_set_agent_param -- Set mnoGoSearch agent session parameters

Description

int udm_set_agent_param ( int agent, int var, string val)

udm_set_agent_param() returns TRUE on success, FALSE on error. Defines mnoGoSearch session parameters.

The following parameters and their values are available:

  • UDM_PARAM_PAGE_NUM - used to choose search results page number (results are returned by pages beginning from 0, with UDM_PARAM_PAGE_SIZE results per page).

  • UDM_PARAM_PAGE_SIZE - number of search results displayed on one page.

  • UDM_PARAM_SEARCH_MODE - search mode. The following values available: UDM_MODE_ALL - search for all words; UDM_MODE_ANY - search for any word; UDM_MODE_PHRASE - phrase search; UDM_MODE_BOOL - boolean search. See udm_find() for details on boolean search.

  • UDM_PARAM_CACHE_MODE - turns on or off search result cache mode. When enabled, the search engine will store search results to disk. In case a similar search is performed later, the engine will take results from the cache for faster performance. Available values: UDM_CACHE_ENABLED, UDM_CACHE_DISABLED.

  • UDM_PARAM_TRACK_MODE - turns on or off trackquery mode. Since version 3.1.2 mnoGoSearch has a query tracking support. Note that tracking is implemented in SQL version only and not available in built-in database. To use tracking, you have to create tables for tracking support. For MySQL, use create/mysql/track.txt. When doing a search, front-end uses those tables to store query words, a number of found documents and current UNIX timestamp in seconds. Available values: UDM_TRACK_ENABLED, UDM_TRACK_DISABLED.

  • UDM_PARAM_PHRASE_MODE - defines whether index database using phrases ("phrase" parameter in indexer.conf). Possible values: UDM_PHRASE_ENABLED and UDM_PHRASE_DISABLED. Please note, that if phrase search is enabled (UDM_PHRASE_ENABLED), it is still possible to do search in any mode (ANY, ALL, BOOL or PHRASE). In 3.1.10 version of mnoGoSearch phrase search is supported only in sql and built-in database modes, while beginning with 3.1.11 phrases are supported in cachemode as well.

    Examples of phrase search:

    "Arizona desert" - This query returns all indexed documents that contain "Arizona desert" as a phrase. Notice that you need to put double quotes around the phrase

  • UDM_PARAM_CHARSET - defines local charset. Available values: set of charsets supported by mnoGoSearch, e.g. koi8-r, cp1251, ...

  • UDM_PARAM_STOPFILE - Defines name and path to stopwords file. (There is a small difference with mnoGoSearch - while in mnoGoSearch if relative path or no path entered, it looks for this file in relation to UDM_CONF_DIR, the module looks for the file in relation to current path, i.e. to the path where the php script is executed.)

  • UDM_PARAM_STOPTABLE - Load stop words from the given SQL table. You may use several StopwordTable commands. This command has no effect when compiled without SQL database support.

  • UDM_PARAM_WEIGHT_FACTOR - represents weight factors for specific document parts. Currently body, title, keywords, description, url are supported. To activate this feature please use degrees of 2 in *Weight commands of the indexer.conf. Let's imagine that we have these weights:

    URLWeight 1
    BodyWeight 2
    TitleWeight 4
    KeywordWeight 8
    DescWeight 16

    As far as indexer uses bit OR operation for word weights when some word presents several time in the same document, it is possible at search time to detect word appearance in different document parts. Word which appears only in the body will have 00000010 argegate weight (in binary notation). Word used in all document parts will have 00011111 aggregate weight.

    This parameter's value is a string of hex digits ABCDE. Each digit is a factor for corresponding bit in word weight. For the given above weights configuration:

    E is a factor for weight 1 (URL Weight bit)
    D is a factor for weight 2 (BodyWeight bit)
    C is a factor for weight 4 (TitleWeight bit)
    B is a factor for weight 8 (KeywordWeight bit)
    A is a factor for weight 16 (DescWeight bit)

    Examples:

    UDM_PARAM_WEIGHT_FACTOR=00001 will search through URLs only.

    UDM_PARAM_WEIGHT_FACTOR=00100 will search through Titles only.

    UDM_PARAM_WEIGHT_FACTOR=11100 will search through Title,Keywords,Description but not through URL and Body.

    UDM_PARAM_WEIGHT_FACTOR=F9421 will search through:

    Description with factor 15 (F hex)
    Keywords with factor 9
    Title with factor 4
    Body with factor 2
    URL with factor 1

    If UDM_PARAM_WEIGHT_FACTOR variable is ommited, original weight value is taken to sort results. For a given above weight configuration it means that document description has a most big weight 16.

  • UDM_PARAM_WORD_MATCH - word match. You may use this parameter to choose word match type. This feature works only in "single" and "multi" modes using SQL based and built-in database. It does not work in cachemode and other modes since they use word CRC and do not support substring search. Available values:

    UDM_MATCH_BEGIN - word beginning match;

    UDM_MATCH_END - word ending match;

    UDM_MATCH_WORD - whole word match;

    UDM_MATCH_SUBSTR - word substring match.

  • UDM_PARAM_MIN_WORD_LEN - defines minimal word length. Any word shorter this limit is considered to be a stopword. Please note that this parameter value is inclusive, i.e. if UDM_PARAM_MIN_WORD_LEN=3, a word 3 characters long will not be considered a stopword, while a word 2 characters long will be. Default value is 1.

  • UDM_PARAM_ISPELL_PREFIXES - Possible values: UDM_PREFIXES_ENABLED and UDM_PREFIXES_DISABLED, that respectively enable or disable using prefixes. E.g. if a word "tested" is in search query, also words like "test", "testing", etc. Only suffixes are supported by default. Prefixes usually change word meanings, for example if somebody is searching for the word "tested" one hardly wants "untested" to be found. Prefixes support may also be found useful for site's spelling checking purposes. In order to enable ispell, you have to load ispell data with udm_load_ispell_data().

  • UDM_PARAM_CROSS_WORDS - enables or disables crosswords support. Possible values: UDM_CROSS_WORDS_ENABLED and UDM_CROSS_WORDS_DISABLED.

    The corsswords feature allows to assign words between <a href="xxx"> and </a> also to a document this link leads to. It works in SQL database mode and is not supported in built-in database and Cachemode.

    注: Crosswords are supported only in mnoGoSearch 3.1.11 or later.

  • UDM_PARAM_VARDIR - specifies a custom path to directory where indexer stores data when using built-in database and in cache mode. By default /var directory of mnoGoSearch installation is used. Can have only string values. The parameter is available in PHP 4.1.0 or later.

  • UDM_PARAM_VARDIR - specifies a custom path to directory where indexer stores data when using built-in database and in cache mode. By default /var directory of mnoGoSearch installation is used. Can have only string values. The parameter is available in PHP 4.1.0 or later.

后退 | 起点 | 前进
udm_open_stored | 上一级 | mSQL functions


mSQL functions

PHP 手册
后退 前进

LXI. mSQL functions

介绍

These functions allow you to access mSQL database servers. More information about mSQL can be found at http://www.hughes.com.au/.

需求

安装

In order to have these functions available, you must compile PHP with msql support by using the --with-msql[=dir] option. The default location is /usr/local/Hughes.

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. mSQL configuration options

Name | Default | Changeable
msql.allow_persistent | "On" | PHP_INI_SYSTEM
msql.max_persistent | "-1" | PHP_INI_SYSTEM
msql.max_links | "-1" | PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().

Here is a short explanation of the configuration directives.

msql.allow_persistent boolean

Whether to allow persistent mSQL connections.

msql.max_persistent integer

The maximum number of persistent mSQL connections per process.

msql.max_links integer

The maximum number of mSQL connections per process, including persistent connections.

资源类型

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

MSQL_ASSOC (integer)

MSQL_NUM (integer)

MSQL_BOTH (integer)

目录
msql_affected_rows — Returns number of affected rows
msql_close — Close mSQL connection
msql_connect — Open mSQL connection
msql_create_db — Create mSQL database
msql_createdb — Create mSQL database
msql_data_seek — Move internal row pointer
msql_dbname — Get current mSQL database name
msql_drop_db — Drop (delete) mSQL database
msql_dropdb — Drop (delete) mSQL database
msql_error — Returns error message of last msql call
msql_fetch_array — Fetch row as array
msql_fetch_field — Get field information
msql_fetch_object — Fetch row as object
msql_fetch_row — Get row as enumerated array
msql_field_seek — Set field offset
msql_fieldflags — Get field flags
msql_fieldlen — Get field length
msql_fieldname — Get field name
msql_fieldtable — Get table name for field
msql_fieldtype — Get field type
msql_free_result — Free result memory
msql_freeresult — Free result memory
msql_list_dbs — List mSQL databases on server
msql_list_fields — List result fields
msql_list_tables — List tables in an mSQL database
msql_listdbs — List mSQL databases on server
msql_listfields — List result fields
msql_listtables — List tables in an mSQL database
msql_num_fields — Get number of fields in result
msql_num_rows — Get number of rows in result
msql_numfields — Get number of fields in result
msql_numrows — Get number of rows in result
msql_pconnect — Open persistent mSQL connection
msql_query — Send mSQL query
msql_regcase — Make regular expression for case insensitive match
msql_result — Get result data
msql_select_db — Select mSQL database
msql_selectdb — Select mSQL database
msql_tablename — Get table name of field
msql — Send mSQL query

后退 | 起点 | 前进
udm_set_agent_param | 上一级 | msql_affected_rows


msql_affected_rows

(PHP 3>= 3.0.6, PHP 4 )

msql_affected_rows -- Returns number of affected rows

Description

int msql_affected_rows ( int query_identifier)

Returns number of affected ("touched") rows by a specific query (i.e. the number of rows returned by a SELECT, the number of rows modified by an update, or the number of rows removed by a delete).

See also: msql_query().

后退 | 起点 | 前进
mSQL functions | 上一级 | msql_close


msql_close

(PHP 3, PHP 4 )

msql_close -- Close mSQL connection

Description

int msql_close ( int link_identifier)

Returns TRUE on success, FALSE on error.

msql_close() closes the link to a mSQL database that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.

Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

msql_close() will not close persistent links generated by msql_pconnect().

See also: msql_connect() and msql_pconnect().

后退 | 起点 | 前进
msql_affected_rows | 上一级 | msql_connect


msql_connect

(PHP 3, PHP 4 )

msql_connect -- Open mSQL connection

Description

int msql_connect ( [string hostname [, string server [, string username [, string password]]]])

Returns a positive mSQL link identifier on success, or FALSE on error.

msql_connect() establishes a connection to a mSQL server. The server parameter can also include a port number. eg. "hostname:port". It defaults to 'localhost'.

In case a second call is made to msql_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 msql_close().

See also msql_pconnect(), msql_close().

后退 | 起点 | 前进
msql_close | 上一级 | msql_create_db


msql_create_db

(PHP 3, PHP 4 )

msql_create_db -- Create mSQL database

Description

int msql_create_db ( string database name [, int link_identifier])

msql_create_db() attempts to create a new database on the server associated with the specified link identifier.

See also: msql_drop_db().

后退 | 起点 | 前进
msql_connect | 上一级 | msql_createdb


msql_createdb

(PHP 3, PHP 4 )

msql_createdb -- Create mSQL database

Description

int msql_createdb ( string database name [, int link_identifier])

Identical to msql_create_db().

后退 | 起点 | 前进
msql_create_db | 上一级 | msql_data_seek


msql_data_seek

(PHP 3, PHP 4 )

msql_data_seek -- Move internal row pointer

Description

int msql_data_seek ( int query_identifier, int row_number)

如果成功则返回 TRUE，失败则返回 FALSE。

msql_data_seek() moves the internal row pointer of the mSQL result associated with the specified query identifier to point to the specifyed row number. The next call to msql_fetch_row() would return that row.

See also: msql_fetch_row().

后退 | 起点 | 前进
msql_createdb | 上一级 | msql_dbname


msql_dbname

(PHP 3, PHP 4 )

msql_dbname -- Get current mSQL database name

Description

string msql_dbname ( int query_identifier, int i)

msql_dbname() returns the database name stored in position i of the result pointer returned from the msql_listdbs() function. The msql_numrows() function can be used to determine how many database names are available.

后退 | 起点 | 前进
msql_data_seek | 上一级 | msql_drop_db


msql_drop_db

(PHP 3, PHP 4 )

msql_drop_db -- Drop (delete) mSQL database

Description

int msql_drop_db ( string database_name, int link_identifier)

如果成功则返回 TRUE，失败则返回 FALSE。

msql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier.

See also: msql_create_db().

后退 | 起点 | 前进
msql_dbname | 上一级 | msql_dropdb


msql_dropdb

msql_dropdb -- Drop (delete) mSQL database

Description

See msql_drop_db().

后退 | 起点 | 前进
msql_drop_db | 上一级 | msql_error


msql_error

(PHP 3, PHP 4 )

msql_error -- Returns error message of last msql call

Description

string msql_error ( [int link_identifier])

Errors coming back from the mSQL database backend no longer issue warnings. Instead, use these functions to retrieve the error string.

后退 | 起点 | 前进
msql_dropdb | 上一级 | msql_fetch_array


msql_fetch_array

(PHP 3, PHP 4 )

msql_fetch_array -- Fetch row as array

Description

int msql_fetch_array ( int query_identifier [, int result_type])

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

msql_fetch_array() is an extended version of msql_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

The second optional argument result_type in msql_fetch_array() is a constant and can take the following values: MSQL_ASSOC, MSQL_NUM, and MSQL_BOTH.

Be careful if you are retrieving results from a query that may return a record that contains only one field that has a value of 0 (or an empty string, or NULL).

An important thing to note is that using msql_fetch_array() is NOT significantly slower than using msql_fetch_row(), while it provides a significant added value.

For further details, also see msql_fetch_row().

后退 | 起点 | 前进
msql_error | 上一级 | msql_fetch_field


msql_fetch_field

(PHP 3, PHP 4 )

msql_fetch_field -- Get field information

Description

object msql_fetch_field ( int query_identifier, int field_offset)

Returns an object containing field information

msql_fetch_field() can be used in order to obtain information about fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retreived by msql_fetch_field() is retreived.

The properties of the object are:

  • name - column name

  • table - name of the table the column belongs to

  • not_null - 1 if the column cannot be NULL

  • primary_key - 1 if the column is a primary key

  • unique - 1 if the column is a unique key

  • type - the type of the column

See also msql_field_seek().

后退 | 起点 | 前进
msql_fetch_array | 上一级 | msql_fetch_object


msql_fetch_object

(PHP 3, PHP 4 )

msql_fetch_object -- Fetch row as object

Description

int msql_fetch_object ( int query_identifier [, int result_type])

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

msql_fetch_object() is similar to msql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

The optional second argument result_type in msql_fetch_array() is a constant and can take the following values: MSQL_ASSOC, MSQL_NUM, and MSQL_BOTH.

Speed-wise, the function is identical to msql_fetch_array(), and almost as quick as msql_fetch_row() (the difference is insignificant).

See also: msql_fetch_array() and msql_fetch_row().

后退 | 起点 | 前进
msql_fetch_field | 上一级 | msql_fetch_row


msql_fetch_row

(PHP 3, PHP 4 )

msql_fetch_row -- Get row as enumerated array

Description

array msql_fetch_row ( int query_identifier)

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

msql_fetch_row() fetches one row of data from the result associated with the specified query identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

Subsequent call to msql_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

See also: msql_fetch_array(),
msql_fetch_object(),
msql_data_seek(), and
msql_result().

后退 | 起点 | 前进
msql_fetch_object | 上一级 | msql_field_seek


msql_field_seek

(PHP 3, PHP 4 )

msql_field_seek -- Set field offset

Description

int msql_field_seek ( int query_identifier, int field_offset)

Seeks to the specified field offset. If the next call to msql_fetch_field() won't include a field offset, this field would be returned.

See also: msql_fetch_field().

后退 | 起点 | 前进
msql_fetch_row | 上一级 | msql_fieldflags


msql_fieldflags

(PHP 3, PHP 4 )

msql_fieldflags -- Get field flags

Description

string msql_fieldflags ( int query_identifier, int i)

msql_fieldflags() returns the field flags of the specified field. Currently this is either, "not NULL", "primary key", a combination of the two or "" (an empty string).

后退 | 起点 | 前进
msql_field_seek | 上一级 | msql_fieldlen


msql_fieldlen

(PHP 3, PHP 4 )

msql_fieldlen -- Get field length

Description

int msql_fieldlen ( int query_identifier, int i)

msql_fieldlen() returns the length of the specified field.

后退 | 起点 | 前进
msql_fieldflags | 上一级 | msql_fieldname


msql_fieldname

(PHP 3, PHP 4 )

msql_fieldname -- Get field name

Description

string msql_fieldname ( int query_identifier, int field)

msql_fieldname() returns the name of the specified field. query_identifier is the query identifier, and field is the field index. msql_fieldname($result, 2); will return the name of the second field in the result associated with the result identifier.

后退 | 起点 | 前进
msql_fieldlen | 上一级 | msql_fieldtable


msql_fieldtable

(PHP 3, PHP 4 )

msql_fieldtable -- Get table name for field

Description

int msql_fieldtable ( int query_identifier, int field)

Returns the name of the table field was fetched from.

后退 | 起点 | 前进
msql_fieldname | 上一级 | msql_fieldtype


msql_fieldtype

(PHP 3, PHP 4 )

msql_fieldtype -- Get field type

Description

string msql_fieldtype ( int query_identifier, int i)

msql_fieldtype() is similar to the msql_fieldname() function. The arguments are identical, but the field type is returned. This will be one of "int", "char" or "real".

后退 | 起点 | 前进
msql_fieldtable | 上一级 | msql_free_result


msql_free_result

(PHP 3, PHP 4 )

msql_free_result -- Free result memory

Description

int msql_free_result ( int query_identifier)

msql_free_result() frees the memory associated with query_identifier. When PHP completes a request, this memory is freed automatically, so you only need to call this function when you want to make sure you don't use too much memory while the script is running.

后退 | 起点 | 前进
msql_fieldtype | 上一级 | msql_freeresult


msql_freeresult

msql_freeresult -- Free result memory

Description

See msql_free_result()

后退 | 起点 | 前进
msql_free_result | 上一级 | msql_list_dbs


msql_list_dbs

(PHP 3, PHP 4 )

msql_list_dbs -- List mSQL databases on server

Description

int msql_list_dbs ( void)

msql_list_dbs() will return a result pointer containing the databases available from the current msql daemon. Use the msql_dbname() function to traverse this result pointer.

后退 | 起点 | 前进
msql_freeresult | 上一级 | msql_list_fields


msql_list_fields

(PHP 3, PHP 4 )

msql_list_fields -- List result fields

Description

int msql_list_fields ( string database, string tablename)

msql_list_fields() retrieves information about the given tablename. Arguments are the database name and the table name. A result pointer is returned which can be used with msql_fieldflags(), msql_fieldlen(), msql_fieldname(), and msql_fieldtype(). A query identifier is a positive integer. The function returns -1 if a error occurs. A string describing the error will be placed in $phperrmsg, and unless the function was called as @msql_list_fields() then this error string will also be printed out.

See also msql_error().

后退 | 起点 | 前进
msql_list_dbs | 上一级 | msql_list_tables


msql_list_tables

(PHP 3, PHP 4 )

msql_list_tables -- List tables in an mSQL database

Description

int msql_list_tables ( string database)

msql_list_tables() takes a database name and
result pointer much like the msql()
function. The msql_tablename() function should
be used to extract the actual table names from the result
pointer.

后退 | 起点 | 前进
msql_list_fields | 上一级 | msql_listdbs


msql_listdbs

msql_listdbs -- List mSQL databases on server

Description

See msql_list_dbs().

后退 | 起点 | 前进
msql_list_tables | 上一级 | msql_listfields


msql_listfields

msql_listfields -- List result fields

Description

See msql_list_fields().

后退 | 起点 | 前进
msql_listdbs | 上一级 | msql_listtables


msql_listtables

msql_listtables -- List tables in an mSQL database

Description

See msql_list_tables().

后退 | 起点 | 前进
msql_listfields | 上一级 | msql_num_fields


msql_num_fields

(PHP 3, PHP 4 )

msql_num_fields -- Get number of fields in result

Description

int msql_num_fields ( int query_identifier)

msql_num_fields() returns the number of fields in a result set.

See also: msql(),
msql_query(),
msql_fetch_field(), and
msql_num_rows().

后退 | 起点 | 前进
msql_listtables | 上一级 | msql_num_rows


msql_num_rows

(PHP 3, PHP 4 )

msql_num_rows -- Get number of rows in result

Description

int msql_num_rows ( int query_identifier)

msql_num_rows() returns the number of rows in a result set.

See also: msql(),
msql_query(), and
msql_fetch_row().

后退 | 起点 | 前进
msql_num_fields | 上一级 | msql_numfields


msql_numfields

(PHP 3, PHP 4 )

msql_numfields -- Get number of fields in result

Description

int msql_numfields ( int query_identifier)

Identical to msql_num_fields().

后退 | 起点 | 前进
msql_num_rows | 上一级 | msql_numrows


msql_numrows

(PHP 3, PHP 4 )

msql_numrows -- Get number of rows in result

Description

int msql_numrows ( void)

Identical to msql_num_rows().

后退 | 起点 | 前进
msql_numfields | 上一级 | msql_pconnect


msql_pconnect

(PHP 3, PHP 4 )

msql_pconnect -- Open persistent mSQL connection

Description

int msql_pconnect ( [string server [, string username [, string password]]])

Returns a positive mSQL persistent link identifier on success, or FALSE on error.

msql_pconnect() acts very much like msql_connect() with two major differences.

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (msql_close() will not close links established by msql_pconnect()).

This type of links is therefore called 'persistent'.

后退 | 起点 | 前进
msql_numrows | 上一级 | msql_query


msql_query

(PHP 3, PHP 4 )

msql_query -- Send mSQL query

Description

int msql_query ( string query, int link_identifier)

msql_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if msql_connect() was called, and use it.

Returns a positive mSQL query identifier on success, or FALSE on error.

例子 1. msql_query()

<?php
$link = msql_connect("dbserver")
   or die("unable to connect to msql server: ".msql_error());
msql_select_db("db", $link)
   or die("unable to select database 'db': ".msql_error());

$result = msql_query("SELECT * FROM table WHERE id=1", $link);
if (!$result) {
   die("query failed: ".msql_error());
}

while ($row = msql_fetch_array($result)) {
    echo $row["id"];
}
?>

See also: msql(),
msql_select_db(), and
msql_connect().

后退 | 起点 | 前进
msql_pconnect | 上一级 | msql_regcase


msql_regcase

msql_regcase -- Make regular expression for case insensitive match

Description

See sql_regcase().

后退 | 起点 | 前进
msql_query | 上一级 | msql_result


msql_result

(PHP 3, PHP 4 )

msql_result -- Get result data

Description

int msql_result ( int query_identifier, int i, mixed field)

Returns the contents of the cell at the row and offset in the specified mSQL result set.

msql_result() returns the contents of one cell from a mSQL result set. The field argument can be the field's offset, or the field's name, or the field's table dot field's name (fieldname.tablename). If the column name has been aliased ('select foo as bar from ...'), use the alias instead of the column name.

When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than msql_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Recommended high-performance alternatives:
msql_fetch_row(),
msql_fetch_array(), and
msql_fetch_object().

后退 | 起点 | 前进
msql_regcase | 上一级 | msql_select_db


msql_select_db

(PHP 3, PHP 4 )

msql_select_db -- Select mSQL database

Description

int msql_select_db ( string database_name, int link_identifier)

Returns TRUE on success, FALSE on error.

msql_select_db() sets the current active database on the server that's associated with the specified link identifier. If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if msql_connect() was called, and use it.

Every subsequent call to msql_query() will be made on the active database.

See also: msql_connect(),
msql_pconnect(), and
msql_query().

后退 | 起点 | 前进
msql_result | 上一级 | msql_selectdb


msql_selectdb

msql_selectdb -- Select mSQL database

Description

See msql_select_db().

后退 | 起点 | 前进
msql_select_db | 上一级 | msql_tablename


msql_tablename

(PHP 3, PHP 4 )

msql_tablename -- Get table name of field

Description

string msql_tablename ( int query_identifier, int field)

msql_tablename() takes a result pointer returned by the msql_list_tables() function as well as an integer index and returns the name of a table. The msql_numrows() function may be used to determine the number of tables in the result pointer.

例子 1. msql_tablename() example

<?php
msql_connect ("localhost");
$result = msql_list_tables ("wisconsin");
$i = 0;
while ($i < msql_numrows ($result)) {
    $tb_names[$i] = msql_tablename ($result, $i);
    echo $tb_names[$i] . "<BR>";
    $i++;
}
?>

后退 | 起点 | 前进
msql_selectdb | 上一级 | msql


msql

(PHP 3, PHP 4 )

msql -- Send mSQL query

Description

int msql ( string database, string query, int link_identifier)

Returns a positive mSQL query identifier to the query result, or FALSE on error.

msql() selects a database and executes a query on it. If the optional link identifier isn't specified, the function will try to find an open link to the mSQL server and if no such link is found it'll try to create one as if msql_connect() was called with no arguments (see msql_connect()).

后退 | 起点 | 前进
msql_tablename | 上一级 | MySQL 函数库


MySQL 函数库

PHP 手册
后退 前进

LXII. MySQL 函数库

介绍

你可以使用该函数库访问 MySQL 数据库服务器。有关 MySQL 的详细信息可以到 http://www.mysql.com/ 查询。

MySQL 的文档可以在 http://www.mysql.com/documentation/ 找到。

需求

为了能够顺利的使用该函数库，你必须在编译 PHP 的时候添加 MySQL 的支持。

安装

当你选择了 --with-mysql 配置选项的时候，你打开了 PHP 访问 MySQL 数据库的功能。 如果你没有在配置选项中指定 MySQL 的路径信息，PHP 会使用内建的 MySQL 客户端库函数。在 PHP4 以后的版本中 MySQL 的功能是默认打开的；即使你没有选择上面的配置选项，默认的 MySQL 功能也会被打开。用户如果需要运行一些特定使用 MySQL 的应用（如：以 Apache 模块化方式运行的 PHP 3 和 PHP 4，或者 auth-mysql 模块）需要指定 MySQL的路径： --with-mysql=/path/to/mysql。 这会限制 PHP 使用 MySQL在本地安装的客户端库函数来减少未知的冲突。

警告

当该扩展模块与 recode 扩展模块共同使用的时候，可能会造成 PHP 的崩溃和启动时出现问题。请查询 recode 扩展获得更多的信息。

运行时配置

MySQL 函数库受全局的 配置文件 php.ini 中的设置所影响。

表格 1. MySQL 配置选项

选项名称 | 默认值 | 可变的
mysql.allow_persistent | "On" | PHP_INI_SYSTEM
mysql.max_persistent | "-1" | PHP_INI_SYSTEM
mysql.max_links | "-1" | PHP_INI_SYSTEM
mysql.default_port | NULL | PHP_INI_ALL
mysql.default_socket | NULL | PHP_INI_ALL
mysql.default_host | NULL | PHP_INI_ALL
mysql.default_user | NULL | PHP_INI_ALL
mysql.default_password | NULL | PHP_INI_ALL
mysql.connect_timeout | "-1" | PHP_INI_SYSTEM
更详细的信息以及 PHP_INI_* 常量的定义，请参考 ini_set()。

这里列举了配置参数的简要介绍。

mysql.allow_persistent boolean

是否允许 保持连接 到 MySQL。

mysql.max_persistent integer

每个进程中最大保持连接数。

mysql.max_links integer

每个进程中最大的连接数，包括保持连接。

mysql.default_port string

指定默认连接数据库的 TCP 端口号。如果没有指定默认端口号，侧顺序从 MYSQL_TCP_PORT 环境变量，/etc/services 文件中的 mysql-tcp 项或者编译时指定的 MYSQL_PORT 常量中获得。Win32 环境下只会使用 MYSQL_PORT 常量。

mysql.default_socket string

当使用本地连接的时候，默认的 socket 名称。

mysql.default_host string

默认连接的数据库服务器地址。 该参数不能用于 safe mode。

mysql.default_user string

默认连接数据库时使用的用户名。该参数不能用于 safe mode。

mysql.default_password string

默认连接数据库时使用的密码。该参数不能用于 safe mode。

mysql.connect_timeout integer

连接超时秒数。在 Linux 中，这个参数设定了等候来自服务器的响应的时长。

资源类型

在 MySQL 模块中含有两个资源类型。一个是数据库的连接句柄，一个是查询返回的结果集。

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

在 PHP 4.3.0 以后的版本中，允许在 mysql_connect() 函数和 mysql_pconnect() 函数中指定更多的客户端标记。下面列出所定义的常量：

表格 2. MySQL 客户端常量

常量 | 描述
MYSQL_CLIENT_COMPRESS | 使用压缩的通讯协议
MYSQL_CLIENT_IGNORE_SPACE | 允许在函数名后留空格位
MYSQL_CLIENT_INTERACTIVE | 允许设置断开连接之前所空闲等候的 interactive_timeout 时间。（代替 wait_timeout）

mysql_fetch_array() 函数使用一个常量来表示所返回数组的类型。下面是常量的定义：

表格 3. MySQL fetch 常量

常量 | 描述
MYSQL_ASSOC | 返回的数据列使用字段名作为数组的索引名。
MYSQL_BOTH | 返回的数据列使用字段名及数字索引作为数组的索引名。
MYSQL_NUM | 返回的数据列使用数字索引作为数组的索引名。索引从 0 开始，表示返回结果的第一个字段。

范例

这个简单的例子演示如何连接数据库，执行查询语句，打印返回结果集和断开数据库等一系列基本的 MySQL 操作。

例子 1. MySQL 扩展范例

<?php
    /* 连接选择数据库 */
    $link = mysql_connect("mysql_host", "mysql_user", "mysql_password")
        or die("Could not connect");
    print "Connected successfully";
    mysql_select_db("my_database") or die("Could not select database");

    /* 执行 SQL 查询 */
    $query = "SELECT * FROM my_table";
    $result = mysql_query($query) or die("Query failed");

    /* 在 HTML 中打印结果 */
    print "<table>\n";
    while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
        print "\t<tr>\n";
        foreach ($line as $col_value) {
            print "\t\t<td>$col_value</td>\n";
        }
        print "\t</tr>\n";
    }
    print "</table>\n";

    /* 释放资源 */
    mysql_free_result($result);

    /* 断开连接 */
    mysql_close($link);
?>

目录
mysql_affected_rows — 取得前一次 MySQL 操作所影响的记录行数
mysql_change_user — Change logged in user of the active connection
mysql_client_encoding — Returns the name of the character set
mysql_close — Close MySQL connection
mysql_connect — Open a connection to a MySQL Server
mysql_create_db — Create a MySQL database
mysql_data_seek — Move internal result pointer
mysql_db_name — Get result data
mysql_db_query — Send a MySQL query
mysql_drop_db — Drop (delete) a MySQL database
mysql_errno — Returns the numerical value of the error message from previous MySQL operation
mysql_error — Returns the text of the error message from previous MySQL operation
mysql_escape_string — Escapes a string for use in a mysql_query.
mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both.
mysql_fetch_assoc — Fetch a result row as an associative array
mysql_fetch_field — Get column information from a result and return as an object
mysql_fetch_lengths — Get the length of each output in a result
mysql_fetch_object — Fetch a result row as an object
mysql_fetch_row — Get a result row as an enumerated array
mysql_field_flags — Get the flags associated with the specified field in a result
mysql_field_len — Returns the length of the specified field
mysql_field_name — Get the name of the specified field in a result
mysql_field_seek — Set result pointer to a specified field offset
mysql_field_table — Get name of the table the specified field is in
mysql_field_type — Get the type of the specified field in a result
mysql_free_result — Free result memory
mysql_get_client_info — Get MySQL client info
mysql_get_host_info — Get MySQL host info
mysql_get_proto_info — Get MySQL protocol info
mysql_get_server_info — Get MySQL server info
mysql_info — Get information about the most recent query
mysql_insert_id — Get the ID generated from the previous INSERT operation
mysql_list_dbs — List databases available on a MySQL server
mysql_list_fields — List MySQL result fields
mysql_list_processes — List MySQL processes
mysql_list_tables — List tables in a MySQL database
mysql_num_fields — Get number of fields in result
mysql_num_rows — Get number of rows in result
mysql_pconnect — Open a persistent connection to a MySQL server
mysql_ping — Ping a server connection or reconnect if there is no connection
mysql_query — Send a MySQL query
mysql_real_escape_string — Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection.
mysql_result — Get result data
mysql_select_db — Select a MySQL database
mysql_stat — Get current system status
mysql_tablename — Get table name of field
mysql_thread_id — Return the current thread ID
mysql_unbuffered_query — Send an SQL query to MySQL, without fetching and buffering the result rows

后退 | 起点 | 前进
msql | 上一级 | mysql_affected_rows


mysql_affected_rows

(PHP 3, PHP 4 )

mysql_affected_rows -- 取得前一次 MySQL 操作所影响的记录行数

描述

int mysql_affected_rows ( [resource link_identifier])

mysql_affected_rows() 返回最近一次与 连接句柄 关联的 INSERT，UPDATE 或 DELETE 查询所影响的记录行数。如果连接句柄没有指定， 则默认使用最近一次由 mysql_connect() 函数打开的连接句柄。

注: 如果你使用事务处理（transactions），你需要在 INSERT，UPDATE 或 DELETE 查询后调用 mysql_affected_rows() 函数，而不是在 commit 命令之后。

如果最近一次操作是没有任何条件（WHERE）的 DELETE 查询， 在表中所有的记录都会被删除，但该函数返回值为 0。

注: 当使用 UPDATE 查询，MySQL 不会将原值和新值一样的列更新。 这样使得 mysql_affected_rows() 函数返回值不一定就是查询条件所符合的记录数。 只有真正被修改的记录数才会被返回。

mysql_affected_rows() 函数不适用于 SELECT 语句；只适用于能够修改记录的语句中。请使用 mysql_num_rows() 函数来获得 SELECT 所返回的记录行数。

如果最近一次查询失败的话，函数返回 -1。

例子 1. Delete 操作

<?php
    /* 连接数据库 */
    mysql_pconnect("localhost", "mysql_user", "mysql_password") or
        die ("Could not connect");

    /* 这会返回有效的被删除记录数。 */
    mysql_query("DELETE FROM mytable WHERE id < 10");
    printf ("Records deleted: %d\n", mysql_affected_rows());

    /* 没有任何条件（where）的删除语句，返回 0 */
    mysql_query("DELETE FROM mytable");
    printf ("Records deleted: %d\n", mysql_affected_rows());
?>

以上的例子会得出下面的运行结果：
Records deleted: 10
Records deleted: 0

例子 2. Update 操作

<?php
    /* 连接数据库 */
    mysql_pconnect("localhost", "mysql_user", "mysql_password") or
        die ("Could not connect");

    /* Update 记录 */
    mysql_query("UPDATE mytable SET used=1 WHERE id < 10");
    printf ("Updated records: %d\n", mysql_affected_rows());
    mysql_query("COMMIT");
?>

以上的例子会得出下面的运行结果：
Updated Records: 10

相关函数： mysql_num_rows()， mysql_info()。

后退 | 起点 | 前进
MySQL 函数库 | 上一级 | mysql_change_user


mysql_change_user

(PHP 3>= 3.0.13)

mysql_change_user -- Change logged in user of the active connection

Description

int mysql_change_user ( string user, string password [, string database [, resource link_identifier]])

mysql_change_user() changes the logged in user of the current active connection, or the connection given by the optional link_identifier parameter. If a database is specified, this will be the current database after the user has been changed. If the new user and password authorization fails, the current connected user stays active. 如果成功则返回 TRUE，失败则返回 FALSE。

注: This function was introduced in PHP 3.0.13 and requires MySQL 3.23.3 or higher. It is not available in PHP 4.

后退 | 起点 | 前进
mysql_affected_rows | 上一级 | mysql_client_encoding


mysql_client_encoding

(PHP 4 CVS only)

mysql_client_encoding -- Returns the name of the character set

Description

int mysql_client_encoding ( [resource link_identifier])

mysql_client_encoding() returns the default character set name for the current connection.

例子 1. mysql_client_encoding() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$charset = mysql_client_encoding($link);
printf ("current character set is %s\n", $charset);
?>

The above example would produce the following output:
current character set is latin1

See also: mysql_real_escape_string()

后退 | 起点 | 前进
mysql_change_user | 上一级 | mysql_close


mysql_close

(PHP 3, PHP 4 )

mysql_close -- Close MySQL connection

Description

bool mysql_close ( [resource link_identifier])

如果成功则返回 TRUE，失败则返回 FALSE。

mysql_close() closes the connection to the MySQL server that's associated with the specified link identifier. If link_identifier isn't specified, the last opened link is used.

Using mysql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution. See also freeing resources.

注: mysql_close() will not close persistent links created by mysql_pconnect().

例子 1. MySQL close example

<?php
    $link = mysql_connect("localhost", "mysql_user", "mysql_password")
        or exit("Could not connect");
    print ("Connected successfully");
    mysql_close($link);
?>

See also: mysql_connect(), and mysql_pconnect().

后退 | 起点 | 前进
mysql_client_encoding | 上一级 | mysql_connect


mysql_connect

(PHP 3, PHP 4 )

mysql_connect -- Open a connection to a MySQL Server

Description

resource mysql_connect ( [string server [, string username [, string password [, bool new_link [, int client_flags]]]]])

Returns a MySQL link identifier on success, or FALSE on failure.

mysql_connect() establishes a connection to a MySQL server. The following defaults are assumed for missing optional parameters: server = 'localhost:3306', username = name of the user that owns the server process and password = empty password.

The server parameter can also include a port number. eg. "hostname:port" or a path to a socket eg. ":/path/to/socket" for the localhost.

注: Support for ":port" was added in PHP 3.0B4.

Support for ":/path/to/socket" was added in PHP 3.0.10.

You can suppress the error message on failure by prepending a @ to the function name.

If a second call is made to mysql_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 new_link parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters. The client_flags parameter can be a combination of the constants MYSQL_CLIENT_SSL, MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE or MYSQL_CLIENT_INTERACTIVE.

注: The new_link parameter became available in PHP 4.2.0

The client_flags parameter became available in PHP 4.3.0

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 mysql_close().

例子 1. MySQL connect example

<?php
    $link = mysql_connect("localhost", "mysql_user", "mysql_password")
        or die("Could not connect");
    print ("Connected successfully");
    mysql_close($link);
?>

See also mysql_pconnect() and mysql_close().

后退 | 起点 | 前进
mysql_close | 上一级 | mysql_create_db


mysql_create_db

(PHP 3, PHP 4 )

mysql_create_db -- Create a MySQL database

Description

bool mysql_create_db ( string database name [, resource link_identifier])

mysql_create_db() attempts to create a new database on the server associated with the specified link identifier.

如果成功则返回 TRUE，失败则返回 FALSE。

例子 1. MySQL create database example

<?php
    $link = mysql_pconnect("localhost", "mysql_user", "mysql_password")
        or exit("Could not connect");

    if (mysql_create_db("my_db")) {
        print ("Database created successfully\n");
    } else {
        printf ("Error creating database: %s\n", mysql_error ());
    }
?>

For downwards compatibility mysql_createdb() can also be used. This is deprecated, however.

注: The function mysql_create_db() is deprecated. It is preferable to use mysql_query() to issue a SQL CREATE DATABASE Statement instead.

See also: mysql_drop_db(), mysql_query().

后退 | 起点 | 前进
mysql_connect | 上一级 | mysql_data_seek


mysql_data_seek

(PHP 3, PHP 4 )

mysql_data_seek -- Move internal result pointer

Description

bool mysql_data_seek ( resource result_identifier, int row_number)

如果成功则返回 TRUE，失败则返回 FALSE。

mysql_data_seek() moves the internal row pointer of the MySQL result associated with the specified result identifier to point to the specified row number. The next call to mysql_fetch_row() would return that row.

Row_number starts at 0. The row_number should be a value in the range from 0 to mysql_num_rows - 1.

注: The function mysql_data_seek() can be used in conjunction only with mysql_query(), not with mysql_unbuffered_query().

例子 1. MySQL data seek example

<?php
    $link = mysql_pconnect("localhost", "mysql_user", "mysql_password")
        or die("Could not connect");

    mysql_select_db("samp_db")
        or exit("Could not select database");

    $query = "SELECT last_name, first_name FROM friends";
    $result = mysql_query($query)
        or die("Query failed");

    /* fetch rows in reverse order */
    for ($i = mysql_num_rows($result) - 1; $i >= 0; $i--) {
        if (!mysql_data_seek($result, $i)) {
            echo "Cannot seek to row $i\n";
            continue;
        }

        if(!($row = mysql_fetch_object($result)))
            continue;

        echo "$row->last_name $row->first_name<br />\n";
    }

    mysql_free_result($result);
?>

See also: mysql_query(), mysql_num_rows().

后退 | 起点 | 前进
mysql_create_db | 上一级 | mysql_db_name


mysql_db_name

(PHP 3>= 3.0.6, PHP 4 )

mysql_db_name -- Get result data

Description

string mysql_db_name ( resource result, int row [, mixed field])

mysql_db_name() takes as its first parameter the result pointer from a call to mysql_list_dbs(). The row parameter is an index into the result set.

If an error occurs, FALSE is returned. Use mysql_errno() and mysql_error() to determine the nature of the error.

例子 1. mysql_db_name() example

<?php
    error_reporting(E_ALL);

    mysql_connect('dbhost', 'username', 'password');
    $db_list = mysql_list_dbs();

    $i = 0;
    $cnt = mysql_num_rows($db_list);
    while ($i < $cnt) {
        echo mysql_db_name($db_list, $i) . "\n";
        $i++;
    }
?>

For backward compatibility, mysql_dbname() is also accepted. This is deprecated, however.

后退 | 起点 | 前进
mysql_data_seek | 上一级 | mysql_db_query


mysql_db_query

(PHP 3, PHP 4 )

mysql_db_query -- Send a MySQL query

Description

resource mysql_db_query ( string database, string query [, resource link_identifier])

Returns a positive MySQL result resource to the query result, or FALSE on error. The function also returns TRUE/FALSE for INSERT/UPDATE/DELETE queries to indicate success/failure.

mysql_db_query() selects a database and executes a query on it. If the optional link identifier isn't specified, the function will try to find an open link to the MySQL server and if no such link is found it'll try to create one as if mysql_connect() was called with no arguments.

Be aware that this function does NOT switch back to the database you were connected before. In other words, you can't use this function to temporarily run a sql query on another database, you would have to manually switch back. Users are strongly encouraged to use the database.table syntax in their sql queries instead of this function.

See also mysql_connect() and mysql_query().

注: This function has been deprecated since PHP 4.0.6. Do not use this function. Use mysql_select_db() and mysql_query() instead.

后退 | 起点 | 前进
mysql_db_name | 上一级 | mysql_drop_db


mysql_drop_db

(PHP 3, PHP 4 )

mysql_drop_db -- Drop (delete) a MySQL database

Description

bool mysql_drop_db ( string database_name [, resource link_identifier])

如果成功则返回 TRUE，失败则返回 FALSE。

mysql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier.

For downward compatibility mysql_dropdb() can also be used. This is deprecated, however.

注: The function mysql_drop_db() is deprecated. It is preferable to use mysql_query() to issue a SQL DROP DATABASE statement instead.

See also: mysql_create_db(), mysql_query().

后退 | 起点 | 前进
mysql_db_query | 上一级 | mysql_errno


mysql_errno

(PHP 3, PHP 4 )

mysql_errno -- Returns the numerical value of the error message from previous MySQL operation

Description

int mysql_errno ( [resource link_identifier])

Returns the error number from the last MySQL function, or 0 (zero) if no error occurred.

Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_errno() to retrieve the error code. Note that this function only returns the error code from the most recently executed MySQL function (not including mysql_error() and mysql_errno()), so if you want to use it, make sure you check the value before calling another MySQL function.

例子 1. mysql_errno Example

<?php
    mysql_connect("localhost", "mysql_user", "mysql_password");

    mysql_select_db("nonexistentdb");
    echo mysql_errno() . ": " . mysql_error(). "\n";

    mysql_select_db("kossu");
    mysql_query("SELECT * FROM nonexistenttable");
    echo mysql_errno() . ": " . mysql_error() . "\n";
?>

The above example would produce the following output:

1049: Unknown database 'nonexistentdb'
1146: Table 'kossu.nonexistenttable' doesn't exist

注: If the optional argument is specified the given link is used to retrieve the error code. If not, the last opened link is used.

See also: mysql_error()

后退 | 起点 | 前进
mysql_drop_db | 上一级 | mysql_error


mysql_error

(PHP 3, PHP 4 )

mysql_error -- Returns the text of the error message from previous MySQL operation

Description

string mysql_error ( [resource link_identifier])

Returns the error text from the last MySQL function, or '' (the empty string) if no error occurred.

Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_error() to retrieve the error text. Note that this function only returns the error text from the most recently executed MySQL function (not including mysql_error() and mysql_errno()), so if you want to use it, make sure you check the value before calling another MySQL function.

例子 1. mysql_error Example

<?php
    mysql_connect("localhost", "mysql_user", "mysql_password");

    mysql_select_db("nonexistentdb");
    echo mysql_errno() . ": " . mysql_error(). "\n";

    mysql_select_db("kossu");
    mysql_query("SELECT * FROM nonexistenttable");
    echo mysql_errno() . ": " . mysql_error() . "\n";
?>

The above example would produce the following output:

1049: Unknown database 'nonexistentdb'
1146: Table 'kossu.nonexistenttable' doesn't exist

注: If the optional argument is specified the given link is used to retrieve the error message. If not, the last opened link is used.

See also: mysql_errno()

后退 | 起点 | 前进
mysql_errno | 上一级 | mysql_escape_string


mysql_escape_string

(PHP 4 >= 4.0.3)

mysql_escape_string -- Escapes a string for use in a mysql_query.

Description

string mysql_escape_string ( string unescaped_string)

This function will escape the unescaped_string, so that it is safe to place it in a mysql_query().

注: mysql_escape_string() does not escape % and _.

This function is identical to mysql_real_escape_string() except that mysql_real_escape_string() takes a connection handler and escapes the string according to the current character set. mysql_escape_string() does not take a connection argument and does not respect the current charset setting.

例子 1. mysql_escape_string() example

<?php
    $item = "Zak's Laptop";
    $escaped_item = mysql_escape_string($item);
    printf ("Escaped string: %s\n", $escaped_item);
?>

The above example would produce the following output:
Escaped string: Zak\'s Laptop

See also: mysql_real_escape_string(), addslashes(), and the magic_quotes_gpc directive.

后退 | 起点 | 前进
mysql_error | 上一级 | mysql_fetch_array


mysql_fetch_array

(PHP 3, PHP 4 )

mysql_fetch_array -- Fetch a result row as an associative array, a numeric array, or both.

Description

array mysql_fetch_array ( resource result [, int result_type])

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

mysql_fetch_array() is an extended version of mysql_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

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 must use the numeric index of the column or make an alias for the column. For aliased columns, you cannot access the contents with the original column name (by using 'field' in this example).

例子 1. Query with duplicate field names

select table1.field as foo table2.field as bar from table1, table2

An important thing to note is that using mysql_fetch_array() is not significantly slower than using mysql_fetch_row(), while it provides a significant added value.

The optional second argument result_type in mysql_fetch_array() is a constant and can take the following values: MYSQL_ASSOC, MYSQL_NUM, and MYSQL_BOTH. This feature was added in PHP 3.0.7. MYSQL_BOTH is the default for this argument.

By using MYSQL_BOTH, you'll get an array with both associative and number indices. Using MYSQL_ASSOC, you only get associative indices (as mysql_fetch_assoc() works), using MYSQL_NUM, you only get number indices (as mysql_fetch_row() works).

例子 2. mysql_fetch_array with MYSQL_NUM

<?php
    mysql_connect("localhost", "mysql_user", "mysql_password") or
        die("could not connect");
    mysql_select_db("mydb");

    $result = mysql_query("SELECT id, name FROM mytable");

    while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
        printf ("ID: %s  Name: %s", $row[0], $row[1]);
    }

    mysql_free_result($result);
?>

例子 3. mysql_fetch_array with MYSQL_ASSOC

<?php
    mysql_connect("localhost", "mysql_user", "mysql_password") or
        die("could not connect");
    mysql_select_db("mydb");

    $result = mysql_query("SELECT id, name FROM mytable");

    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        printf ("ID: %s  Name: %s", $row["id"], $row["name"]);
    }

    mysql_free_result($result);
?>

例子 4. mysql_fetch_array with MYSQL_BOTH

<?php
    mysql_connect("localhost", "mysql_user", "mysql_password") or
        die("could not connect");
    mysql_select_db("mydb");

    $result = mysql_query("SELECT id, name FROM mytable");

    while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
        printf ("ID: %s  Name: %s", $row[0], $row["name"]);
    }

    mysql_free_result($result);
?>

For further details, see also mysql_fetch_row() and mysql_fetch_assoc().

后退 | 起点 | 前进
mysql_escape_string | 上一级 | mysql_fetch_assoc


mysql_fetch_assoc

(PHP 4 >= 4.0.3)

mysql_fetch_assoc -- Fetch a result row as an associative array

Description

array mysql_fetch_assoc ( resource result)

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.

mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with MYSQL_ASSOC for the optional second parameter. It only returns an associative array. This is the way mysql_fetch_array() originally worked. If you need the numeric indices as well as the associative, use mysql_fetch_array().

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 mysql_fetch_row() or add alias names. See the example at the mysql_fetch_array() description about aliases.

An important thing to note is that using mysql_fetch_assoc() is not significantly slower than using mysql_fetch_row(), while it provides a significant added value.

例子 1. mysql_fetch_assoc()

<?php
    mysql_connect("localhost", "mysql_user", "mysql_password");
    mysql_select_db("mydb");
    $query = "select * from table";
    $result = mysql_query($query);
    while ($row = mysql_fetch_assoc($result)) {
        echo $row["user_id"];
        echo $row["fullname"];
    }
    mysql_free_result($result);
?>

For further details, see also
mysql_fetch_row(),
mysql_fetch_array() and
mysql_query().

后退 | 起点 | 前进
mysql_fetch_array | 上一级 | mysql_fetch_field


mysql_fetch_field

(PHP 3, PHP 4 )

mysql_fetch_field -- Get column information from a result and return as an object

Description

object mysql_fetch_field ( resource result [, int field_offset])

Returns an object containing field information.

mysql_fetch_field() can be used in order to obtain information about fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by mysql_fetch_field() is retrieved.

The properties of the object are:

  • name - column name

  • table - name of the table the column belongs to

  • max_length - maximum length of the column

  • not_null - 1 if the column cannot be NULL

  • primary_key - 1 if the column is a primary key

  • unique_key - 1 if the column is a unique key

  • multiple_key - 1 if the column is a non-unique key

  • numeric - 1 if the column is numeric

  • blob - 1 if the column is a BLOB

  • type - the type of the column

  • unsigned - 1 if the column is unsigned

  • zerofill - 1 if the column is zero-filled

例子 1. mysql_fetch_field()

<?php
mysql_connect('localhost:3306', $user, $password)
    or die ("Could not connect");
mysql_select_db("database");
$result = mysql_query("select * from table")
    or die("Query failed");
/* get column metadata */
$i = 0;
while ($i < mysql_num_fields($result)) {
    echo "Information for column $i:<br />\n";
    $meta = mysql_fetch_field($result);
    if (!$meta) {
        echo "No information available<br />\n";
    }
    echo "<pre>
blob:         $meta->blob
max_length:   $meta->max_length
multiple_key: $meta->multiple_key
name:         $meta->name
not_null:     $meta->not_null
numeric:      $meta->numeric
primary_key:  $meta->primary_key
table:        $meta->table
type:         $meta->type
unique_key:   $meta->unique_key
unsigned:     $meta->unsigned
zerofill:     $meta->zerofill
</pre>";
    $i++;
}
mysql_free_result($result);
?>

See also mysql_field_seek().

后退 | 起点 | 前进
mysql_fetch_assoc | 上一级 | mysql_fetch_lengths


mysql_fetch_lengths

(PHP 3, PHP 4 )

mysql_fetch_lengths -- Get the length of each output in a result

Description

array mysql_fetch_lengths ( resource result)

Returns an array that corresponds to the lengths of each field in the last row fetched by mysql_fetch_row(), or FALSE on error.

mysql_fetch_lengths() stores the lengths of
each result column in the last row returned by
mysql_fetch_row(),
mysql_fetch_array(), and
mysql_fetch_object() in an array, starting at
offset 0.

See also: mysql_fetch_row().

后退 | 起点 | 前进
mysql_fetch_field | 上一级 | mysql_fetch_object


mysql_fetch_object

(PHP 3, PHP 4 )

mysql_fetch_object -- Fetch a result row as an object

Description

object mysql_fetch_object ( resource result)

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

mysql_fetch_object() is similar to mysql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

<?php

/* this is valid */
echo $row->field;
/* this is invalid */
echo $row->0;

?>

Speed-wise, the function is identical to mysql_fetch_array(), and almost as quick as mysql_fetch_row() (the difference is insignificant).

例子 1. mysql_fetch_object() example

<?php
mysql_connect("hostname", "user", "password");
mysql_select_db($db);
$result = mysql_query("select * from table");
while ($row = mysql_fetch_object($result)) {
    echo $row->user_id;
    echo $row->fullname;
}
mysql_free_result($result);
?>

See also: mysql_fetch_array() and mysql_fetch_row().

后退 | 起点 | 前进
mysql_fetch_lengths | 上一级 | mysql_fetch_row


mysql_fetch_row

(PHP 3, PHP 4 )

mysql_fetch_row -- Get a result row as an enumerated array

Description

array mysql_fetch_row ( resource result)

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

mysql_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 call to mysql_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

See also: mysql_fetch_array(),
mysql_fetch_object(),
mysql_data_seek(),
mysql_fetch_lengths(), and
mysql_result().

后退 | 起点 | 前进
mysql_fetch_object | 上一级 | mysql_field_flags


mysql_field_flags

(PHP 3, PHP 4 )

mysql_field_flags -- Get the flags associated with the specified field in a result

Description

string mysql_field_flags ( resource result, int field_offset)

mysql_field_flags() returns the field flags of the specified field. The flags are reported as a single word per flag separated by a single space, so that you can split the returned value using explode().

The following flags are reported, if your version of MySQL is current enough to support them: "not_null", "primary_key", "unique_key", "multiple_key", "blob", "unsigned", "zerofill", "binary", "enum", "auto_increment", "timestamp".

For downward compatibility mysql_fieldflags() can also be used. This is deprecated, however.

后退 | 起点 | 前进
mysql_fetch_row | 上一级 | mysql_field_len


mysql_field_len

(PHP 3, PHP 4 )

mysql_field_len -- Returns the length of the specified field

Description

int mysql_field_len ( resource result, int field_offset)

mysql_field_len() returns the length of the specified field.

For downward compatibility mysql_fieldlen() can also be used. This is deprecated, however.

后退 | 起点 | 前进
mysql_field_flags | 上一级 | mysql_field_name


mysql_field_name

(PHP 3, PHP 4 )

mysql_field_name -- Get the name of the specified field in a result

Description

string mysql_field_name ( resource result, int field_index)

mysql_field_name() returns the name of the specified field index. result must be a valid result identifier and field_index is the numerical offset of the field.

注: field_index starts at 0.

e.g. The index of the third field would actually be 2, the index of the fourth field would be 3 and so on.

例子 1. mysql_field_name() example

/* The users table consists of three fields:
 *   user_id
 *   username
 *   password.
 */
$link = mysql_connect('localhost', "mysql_user", "mysql_password");
mysql_select_db($dbname, $link)
    or die("Could not set $dbname");
$res = mysql_query("select * from users", $link);

echo mysql_field_name($res, 0) . "\n";
echo mysql_field_name($res, 2);

The above example would produce the following output:
user_id
password

For downwards compatibility mysql_fieldname() can also be used. This is deprecated, however.

后退 | 起点 | 前进
mysql_field_len | 上一级 | mysql_field_seek


mysql_field_seek

(PHP 3, PHP 4 )

mysql_field_seek -- Set result pointer to a specified field offset

Description

int mysql_field_seek ( resource result, int field_offset)

Seeks to the specified field offset. If the next call to mysql_fetch_field() doesn't include a field offset, the field offset specified in mysql_field_seek() will be returned.

See also: mysql_fetch_field().

后退 | 起点 | 前进
mysql_field_name | 上一级 | mysql_field_table


mysql_field_table

(PHP 3, PHP 4 )

mysql_field_table -- Get name of the table the specified field is in

Description

string mysql_field_table ( resource result, int field_offset)

Returns the name of the table that the specifed field is in.

For downward compatibility mysql_fieldtable() can also be used. This is deprecated, however.

后退 | 起点 | 前进
mysql_field_seek | 上一级 | mysql_field_type


mysql_field_type

(PHP 3, PHP 4 )

mysql_field_type -- Get the type of the specified field in a result

Description

string mysql_field_type ( resource result, int field_offset)

mysql_field_type() is similar to the mysql_field_name() function. The arguments are identical, but the field type is returned instead. The field type will be one of "int", "real", "string", "blob", and others as detailed in the MySQL documentation.

例子 1. MySQL field types

<?php
    mysql_connect("localhost", "mysql_username", "mysql_password");
    mysql_select_db("mysql");
    $result = mysql_query("SELECT * FROM func");
    $fields = mysql_num_fields($result);
    $rows   = mysql_num_rows($result);
    $table = mysql_field_table($result, 0);
    echo "Your '".$table."' table has ".$fields." fields and ".$rows." record(s)\n";
    echo "The table has the following fields:\n";
    for ($i=0; $i < $fields; $i++) {
        $type  = mysql_field_type($result, $i);
        $name  = mysql_field_name($result, $i);
        $len   = mysql_field_len($result, $i);
        $flags = mysql_field_flags($result, $i);
        echo $type." ".$name." ".$len." ".$flags."\n";
    }
    mysql_free_result($result);
    mysql_close();
?>

The above example would produce the following output:

Your 'func' table has 4 fields and 1 record(s)
The table has the following fields:
string name 64 not_null primary_key binary
int ret 1 not_null
string dl 128 not_null
string type 9 not_null enum

For downward compatibility mysql_fieldtype() can also be used. This is deprecated, however.

后退 | 起点 | 前进
mysql_field_table | 上一级 | mysql_free_result


mysql_free_result

(PHP 3, PHP 4 )

mysql_free_result -- Free result memory

Description

bool mysql_free_result ( resource result)

mysql_free_result() will free all memory associated with the result identifier result.

mysql_free_result() only needs to be called if you are concerned about how much memory is being used for queries that return large result sets. All associated result memory is automatically freed at the end of the script's execution.

如果成功则返回 TRUE，失败则返回 FALSE。

For downward compatibility mysql_freeresult() can also be used. This is deprecated, however.

后退 | 起点 | 前进
mysql_field_type | 上一级 | mysql_get_client_info


mysql_get_client_info

(PHP 4 >= 4.0.5)

mysql_get_client_info -- Get MySQL client info

Description

string mysql_get_client_info ( void)

mysql_get_client_info() returns a string that represents the client library version.

例子 1. mysql_get_client_info Example

<?php
    printf ("MySQL client info: %s\n", mysql_get_client_info());
?>

The above example would produce the following output:

MySQL client info: 3.23.39

See also: mysql_get_host_info(),
          mysql_get_proto_info() and
          mysql_get_server_info().

后退 | 起点 | 前进
mysql_free_result | 上一级 | mysql_get_host_info


mysql_get_host_info

(PHP 4 >= 4.0.5)

mysql_get_host_info -- Get MySQL host info

Description

string mysql_get_host_info ( [resource link_identifier])

mysql_get_host_info() returns a string describing the type of connection in use for the connection link_identifier, including the server host name. If link_identifier is omitted, the last opened connection will be used.

例子 1. mysql_get_host_info Example

<?php
    mysql_connect("localhost", "mysql_user", "mysql_password") or
        die("could not connect");
    printf ("MySQL host info: %s\n", mysql_get_host_info());
?>

The above example would produce the following output:

MySQL host info: Localhost via UNIX socket

See also: mysql_get_client_info(),
          mysql_get_proto_info() and
          mysql_get_server_info().

后退 | 起点 | 前进
mysql_get_client_info | 上一级 | mysql_get_proto_info


mysql_get_proto_info

(PHP 4 >= 4.0.5)

mysql_get_proto_info -- Get MySQL protocol info

Description

int mysql_get_proto_info ( [resource link_identifier])

mysql_get_proto_info() returns the protocol version used by connection link_identifier. If link_identifier is omitted, the last opened connection will be used.

例子 1. mysql_get_proto_info Example

<?php
    mysql_connect("localhost", "mysql_user", "mysql_password") or
        die("could not connect");
    printf ("MySQL protocol version: %s\n", mysql_get_proto_info());
?>

The above example would produce the following output:

MySQL protocol version : 10

See also: mysql_get_client_info(),
          mysql_get_host_info() and
          mysql_get_server_info().

后退 | 起点 | 前进
mysql_get_host_info | 上一级 | mysql_get_server_info


mysql_get_server_info

(PHP 4 >= 4.0.5)

mysql_get_server_info -- Get MySQL server info

Description

string mysql_get_server_info ( [resource link_identifier])

mysql_get_server_info() returns the server version used by connection link_identifier. If link_identifier is omitted, the last opened connection will be used.

例子 1. mysql_get_server_info Example

<?php
    mysql_connect("localhost", "mysql_user", "mysql_password") or
        die("could not connect");
    printf ("MySQL server version: %s\n", mysql_get_server_info());
?>

The above example would produce the following output:

MySQL server version: 4.0.1-alpha

See also: mysql_get_client_info(),
          mysql_get_host_info() and
          mysql_get_proto_info().

后退 | 起点 | 前进
mysql_get_proto_info | 上一级 | mysql_info


mysql_info

(PHP 4 CVS only)

mysql_info -- Get information about the most recent query

Description

string mysql_info ( [resource link_identifier])

mysql_info() returns detailed information about the last query using the given link_identifier. If link_identifier isn't specified, the last opened link is assumed.

mysql_info() returns a string for all statements listed below. For all other FALSE. The string format depends on the given statement.

例子 1. Relevant MySQL Statements

INSERT INTO ... SELECT ...
String format: Records: 23 Duplicates: 0 Warnings: 0
INSERT INTO ... VALUES (...),(...),(...)...
String format: Records: 37 Duplicates: 0 Warnings: 0
LOAD DATA INFILE ...
String format: Records: 42 Deleted: 0 Skipped: 0 Warnings: 0
ALTER TABLE
String format: Records: 60 Duplicates: 0 Warnings: 0
UPDATE
String format: Rows matched: 65 Changed: 65 Warnings: 0
The numbers are only for illustrating purpose; their values will correspond to the query.

注: mysql_info() returns a non-FALSE value for the INSERT ... VALUES statement only if multiple value lists are specified in the statement.

See also: mysql_affected_rows()

后退 | 起点 | 前进
mysql_get_server_info | 上一级 | mysql_insert_id


mysql_insert_id

(PHP 3, PHP 4 )

mysql_insert_id -- Get the ID generated from the previous INSERT operation

Description

int mysql_insert_id ( [resource link_identifier])

mysql_insert_id() returns the ID generated for an AUTO_INCREMENT column by the previous INSERT query using the given link_identifier. If link_identifier isn't specified, the last opened link is assumed.

mysql_insert_id() returns 0 if the previous query does not generate an AUTO_INCREMENT value. If you need to save the value for later, be sure to call mysql_insert_id() immediately after the query that generates the value.

注: The value of the MySQL SQL function LAST_INSERT_ID() always contains the most recently generated AUTO_INCREMENT value, and is not reset between queries.

警告

mysql_insert_id() converts the return type of the native MySQL C API function mysql_insert_id() to a type of long (named int in PHP). If your AUTO_INCREMENT column has a column type of BIGINT, the value returned by mysql_insert_id() will be incorrect. Instead, use the internal MySQL SQL function LAST_INSERT_ID() in an SQL query.

例子 1. mysql_insert_id Example

<?php
    mysql_connect("localhost", "mysql_user", "mysql_password") or
        die("could not connect");
    mysql_select_db("mydb");

    mysql_query("INSERT INTO mytable (product) values ('kossu')");
    printf ("Last inserted record has id %d\n", mysql_insert_id());
?>

See also: mysql_query().

后退 | 起点 | 前进
mysql_info | 上一级 | mysql_list_dbs


mysql_list_dbs

(PHP 3, PHP 4 )

mysql_list_dbs -- List databases available on a MySQL server

Description

resource mysql_list_dbs ( [resource link_identifier])

mysql_list_dbs() will return a result pointer containing the databases available from the current mysql daemon. Use the mysql_tablename() function to traverse this result pointer, or any function for result tables.

例子 1. mysql_list_dbs() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$db_list = mysql_list_dbs($link);

while ($row = mysql_fetch_object($db_list)) {
    echo $row->Database . "\n";
}
?>

The above example would produce the following output:
database1
database2
database3
...

注: The above code would just as easily work with mysql_fetch_row() or other similar functions.

For downward compatibility mysql_listdbs() can also be used. This is deprecated however.

See also mysql_db_name().

后退 | 起点 | 前进
mysql_insert_id | 上一级 | mysql_list_fields


mysql_list_fields

(PHP 3, PHP 4 )

mysql_list_fields -- List MySQL result fields

Description

resource mysql_list_fields ( string database_name, string table_name [, resource link_identifier])

mysql_list_fields() retrieves information
about the given table name. Arguments are the database name and
the table name. A result pointer is returned which can be used
with mysql_field_flags(),
mysql_field_len(),
mysql_field_name(), and
mysql_field_type().

例子 1. mysql_list_fields() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');

$fields = mysql_list_fields("database1", "table1", $link);
$columns = mysql_num_fields($fields);

for ($i = 0; $i < $columns; $i++) {
    echo mysql_field_name($fields, $i) . "\n";
}

The above example would produce the following output:
field1
field2
field3
...

For downward compatibility mysql_listfields() can also be used. This is deprecated however.

后退 | 起点 | 前进
mysql_list_dbs | 上一级 | mysql_list_processes


mysql_list_processes

(PHP 4 CVS only)

mysql_list_processes -- List MySQL processes

Description

resource mysql_list_processes ( [resource link_identifier])

mysql_list_processes() returns a result pointer describing the current server threads.

例子 1. mysql_list_processes() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');

$result = mysql_list_processes($link);
while ($row = mysql_fetch_row($result)){
    printf("%s %s %s %s %s\n", $row["Id"], $row["Host"], $row["db"],
       $row["Command"], $row["Time"]);
}
mysql_free_result ($result);
?>

The above example would produce the following output:
1 localhost test Processlist 0
4 localhost mysql sleep 5

See also: mysql_thread_id()

后退 | 起点 | 前进
mysql_list_fields | 上一级 | mysql_list_tables


mysql_list_tables

(PHP 3, PHP 4 )

mysql_list_tables -- List tables in a MySQL database

Description

resource mysql_list_tables ( string database [, resource link_identifier])

mysql_list_tables() takes a database name and returns a result pointer much like the mysql_query() function. You can use the mysql_tablename() function to extract the actual table names from the result pointer, or any other result table function such as mysql_fetch_assoc().

The database parameter is the name of the database to retrieve the list of tables from. Upon failure, mysql_list_tables() returns FALSE.

For downward compatibility, the function alias named mysql_listtables() can be used. This is deprecated however and is not recommended.

例子 1. mysql_list_tables Example

<?php
    $dbname = 'mysql_dbname';

    if (!mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
        print 'Could not connect to mysql';
        exit;
    }

    $result = mysql_list_tables($dbname);

    if (!$result) {
        print "DB Error, could not list tables\n";
        print 'MySQL Error: ' . mysql_error();
        exit;
    }

    while ($row = mysql_fetch_row($result)) {
        print "Table: $row[0]\n";
    }

    mysql_free_result($result);
?>

See also: mysql_list_dbs(), and mysql_tablename().

后退 | 起点 | 前进
mysql_list_processes | 上一级 | mysql_num_fields


mysql_num_fields

(PHP 3, PHP 4 )

mysql_num_fields -- Get number of fields in result

Description

int mysql_num_fields ( resource result)

mysql_num_fields() returns the number of fields in a result set.

See also:
mysql_select_db(),
mysql_query(),
mysql_fetch_field(),
mysql_num_rows().

For downward compatibility mysql_numfields() can also be used. This is deprecated however.

后退 | 起点 | 前进
mysql_list_tables | 上一级 | mysql_num_rows


mysql_num_rows

(PHP 3, PHP 4 )

mysql_num_rows -- Get number of rows in result

Description

int mysql_num_rows ( resource result)

mysql_num_rows() returns the number of rows in a result set. This command is only valid for SELECT statements. To retrieve the number of rows affected by a INSERT, UPDATE or DELETE query, use mysql_affected_rows().

例子 1. mysql_num_rows() example

<?php

$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);

$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);

echo "$num_rows Rows\n";

?>

注: If you use mysql_unbuffered_query(), mysql_num_rows() will not return the correct value until all the rows in the result set have been retrieved.

See also:
mysql_affected_rows(),
mysql_connect(),
mysql_data_seek(),
mysql_select_db(), and
mysql_query().

For downward compatibility mysql_numrows() can also be used. This is deprecated however.

后退 | 起点 | 前进
mysql_num_fields | 上一级 | mysql_pconnect


mysql_pconnect

(PHP 3, PHP 4 )

mysql_pconnect -- Open a persistent connection to a MySQL server

Description

resource mysql_pconnect ( [string server [, string username [, string password [, int client_flags]]]])

Returns a positive MySQL persistent link identifier on success, or FALSE on error.

mysql_pconnect() establishes a connection to a MySQL server. The following defaults are assumed for missing optional parameters: server = 'localhost:3306', username = name of the user that owns the server process and password = empty password. The client_flags parameter can be a combination of the constants MYSQL_CLIENT_SSL, MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE or MYSQL_CLIENT_INTERACTIVE.

The server parameter can also include a port number. eg. "hostname:port" or a path to a socket eg. ":/path/to/socket" for the localhost.

注: Support for ":port" was added in 3.0B4.

Support for the ":/path/to/socket" was added in 3.0.10.

mysql_pconnect() acts very much like mysql_connect() with two major differences.

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mysql_close() will not close links established by mysql_pconnect()).

The optional client_flags parameter became available in PHP 4.3.0.

This type of link is therefore called 'persistent'.

注: Note, that these kind of links only work if you are using a module version of PHP. See the Persistent Database Connections section for more information.

警告

Using persistent connections can require a bit of tuning of your Apache and MySQL configurations to ensure that you do not exceed the number of connections allowed by MySQL.

后退 | 起点 | 前进
mysql_num_rows | 上一级 | mysql_ping


mysql_ping

(PHP 4 CVS only)

mysql_ping -- Ping a server connection or reconnect if there is no connection

Description

bool mysql_ping ( [resource link_identifier])

mysql_ping() checks whether or not the connection to the server is working. If it has gone down, an automatic reconnection is attempted. This function can be used by scripts that remain idle for a long while, to check whether or not the server has closed the connection and reconnect if necessary. mysql_ping() returns TRUE if the connection to the server is working, otherwise FALSE.

See also: mysql_thread_id(), mysql_list_processes().

后退 | 起点 | 前进
mysql_pconnect | 上一级 | mysql_query


mysql_query

(PHP 3, PHP 4 )

mysql_query -- Send a MySQL query

Description

resource mysql_query ( string query [, resource link_identifier [, int result_mode]])

mysql_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If link_identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if mysql_connect() was called with no arguments, and use it.

The optional result_mode parameter can be MYSQL_USE_RESULT and MYSQL_STORE_RESULT. It defaults to MYSQL_STORE_RESULT, so the result is buffered. See also mysql_unbuffered_query() for the counterpart of this behaviour.

注: The query string should not end with a semicolon.

Only for SELECT,SHOW,EXPLAIN or DESCRIBE statements mysql_query() returns a resource identifier or FALSE if the query was not executed correctly. For other type of SQL statements, mysql_query() returns TRUE on success and FALSE on error. A non-FALSE return value means that the query was legal and could be executed by the server. It does not indicate anything about the number of rows affected or returned. It is perfectly possible for a query to succeed but affect no rows or return no rows.

The following query is syntactically invalid, so mysql_query() fails and returns FALSE:

例子 1. mysql_query()

<php
$result = mysql_query("SELECT * WHERE 1=1")
    or die("Invalid query");
?>

The following query is semantically invalid if my_col is not a column in the table my_tbl, so mysql_query() fails and returns FALSE:

例子 2. mysql_query()

<?php
$result = mysql_query("SELECT my_col FROM my_tbl")
    or die ("Invalid query");
?>

mysql_query() will also fail and return FALSE if you don't have permission to access the table(s) referenced by the query.

Assuming the query succeeds, you can call mysql_num_rows() to find out how many rows were returned for a SELECT statment or mysql_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.

Only for SELECT,SHOW,DESCRIBE or EXPLAIN statements, mysql_query() returns a new result identifier that you can pass to mysql_fetch_array() and other functions dealing with result tables. When you are done with the result set, you can free the resources associated with it by calling mysql_free_result(). Although, the memory will automatically be freed at the end of the script's execution.

See also: mysql_num_rows(),
mysql_affected_rows(),
mysql_unbuffered_query(),
mysql_free_result(),
mysql_fetch_array(),
mysql_fetch_row(),
mysql_fetch_assoc(),
mysql_result(),
mysql_select_db(), and
mysql_connect().

后退 | 起点 | 前进
mysql_ping | 上一级 | mysql_real_escape_string


mysql_real_escape_string

(PHP 4 CVS only)

mysql_real_escape_string -- Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection.

Description

string mysql_real_escape_string ( string unescaped_string [, resource link_identifier])

This function will escape special characters in the unescaped_string, taking into account the current charset of the connection so that it is safe to place it in a mysql_query().

注: mysql_real_escape_string() does not escape % and _.

例子 1. mysql_real_escape_string() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$item = "Zak's and Derick's Laptop";
$escaped_item = mysql_real_escape_string($item);
printf ("Escaped string: %s\n", $escaped_item);
?>

The above example would produce the following output:
Escaped string: Zak\'s and Derick\'s Laptop

See also: mysql_escape_string(), mysql_character_set_name().

后退 | 起点 | 前进
mysql_query | 上一级 | mysql_result


mysql_result

(PHP 3, PHP 4 )

mysql_result -- Get result data

Description

mixed mysql_result ( resource result, int row [, mixed field])

mysql_result() returns the contents of one cell from a MySQL result set. The field argument can be the field's offset, or the field's name, or the field's table dot field name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name.

When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than mysql_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Calls to mysql_result() should not be mixed with calls to other functions that deal with the result set.

Recommended high-performance alternatives:
mysql_fetch_row(),
mysql_fetch_array(), and
mysql_fetch_object().

后退 | 起点 | 前进
mysql_real_escape_string | 上一级 | mysql_select_db


mysql_select_db

(PHP 3, PHP 4 )

mysql_select_db -- Select a MySQL database

Description

bool mysql_select_db ( string database_name [, resource link_identifier])

如果成功则返回 TRUE，失败则返回 FALSE。

mysql_select_db() sets the current active database on the server that's associated with the specified link identifier. If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if mysql_connect() was called without arguments, and use it.

Every subsequent call to mysql_query() will be made on the active database.

See also:
    mysql_connect(),
    mysql_pconnect(), and
    mysql_query().

For downward compatibility mysql_selectdb() can also be used. This is deprecated however.

后退 | 起点 | 前进
mysql_result | 上一级 | mysql_stat


mysql_stat

(PHP 4 CVS only)

mysql_stat -- Get current system status

Description

string mysql_stat ( [resource link_identifier])

mysql_stat() returns the current server status.

注: mysql_stat() currently only returns status for uptime, threads, queries, open tables, flush tables and queries per second. For a complete list of other status variables you have to use the SHOW STATUS SQL command.

例子 1. mysql_stat() example

<?php
$link = mysql_connect('localhost', "mysql_user", "mysql_password");
printf("%s\n", mysql_stat($link));
?>

The above example would produce the following output:
Uptime: 5380  Threads: 1  Questions: 1321299  Slow queries: 1  Opens: 26 Flush tables: 1  Open tables: 17  Queries per second avg: 245.595

后退 | 起点 | 前进
mysql_select_db | 上一级 | mysql_tablename


mysql_tablename

(PHP 3, PHP 4 )

mysql_tablename -- Get table name of field

Description

string mysql_tablename ( resource result, int i)

mysql_tablename() takes a result pointer returned by the mysql_list_tables() function as well as an integer index and returns the name of a table. The mysql_num_rows() function may be used to determine the number of tables in the result pointer.

例子 1. mysql_tablename() Example

<?php
    mysql_connect("localhost", "mysql_user", "mysql_password");
    $result = mysql_list_tables("mydb");

    for ($i = 0; $i < mysql_num_rows($result); $i++)
        printf ("Table: %s\n", mysql_tablename($result, $i));

    mysql_free_result($result);
?>

See also: mysql_list_tables().

后退 | 起点 | 前进
mysql_stat | 上一级 | mysql_thread_id


mysql_thread_id

(PHP 4 CVS only)

mysql_thread_id -- Return the current thread ID

Description

int mysql_thread_id ( [resource link_identifier])

mysql_thread_id() returns the current thread ID. If the connection is lost and you reconnect with mysql_ping(), the thread ID will change. This means you should not get the thread ID and store it for later. You should get it when you need it.

例子 1. mysql_thread_id() example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$thread_id = mysql_thread_id($link);
if ($thread_id){
    printf ("current thread id is %d\n", $thread_id);
}
?>

The above example would produce the following output:
current thread id is 73

See also: mysql_ping(), mysql_list_processes().

后退 | 起点 | 前进
mysql_tablename | 上一级 | mysql_unbuffered_query


mysql_unbuffered_query

(PHP 4 >= 4.0.6)

mysql_unbuffered_query -- Send an SQL query to MySQL, without fetching and buffering the result rows

Description

resource mysql_unbuffered_query ( string query [, resource link_identifier [, int result_mode]])

mysql_unbuffered_query() sends a SQL query query to MySQL, without fetching and buffering the result rows automatically, as mysql_query() does. On the one hand, this saves a considerable amount of memory with SQL queries that produce large result sets. On the other hand, you can start working on the result set immediately after the first row has been retrieved: you don't have to wait until the complete SQL query has been performed. When using multiple DB-connects, you have to specify the optional parameter link_identifier.

The optional result_mode parameter can be MYSQL_USE_RESULT and MYSQL_STORE_RESULT. It defaults to MYSQL_USE_RESULT, so the result is not buffered. See also mysql_query() for the counterpart of this behaviour.

注: The benefits of mysql_unbuffered_query() come at a cost: You cannot use mysql_num_rows() on a result set returned from mysql_unbuffered_query(). You also have to fetch all result rows from an unbuffered SQL query, before you can send a new SQL query to MySQL.

See also: mysql_query().

后退 | 起点 | 前进
mysql_thread_id | 上一级 | Mohawk Software session handler functions


Mohawk Software session handler functions

PHP 手册
后退 前进

LXIII. Mohawk Software session handler functions

介绍

msession is an interface to a high speed session daemon which can run either locally or remotely. It is designed to provide consistent session management for a PHP web farm. More Information about msession and the session server software itself can be found at http://www.mohawksoft.com/phoenix/.

需求

安装

运行时配置

资源类型

预定义常量

目录
msession_connect — Connect to msession server
msession_count — Get session count
msession_create — Create a session
msession_destroy — Destroy a session
msession_disconnect — Close connection to msession server
msession_find — Find value
msession_get_array — Get array of ... ?
msession_get — Get value from session
msession_getdata — Get data ... ?
msession_inc — Increment value in session
msession_list — List ... ?
msession_listvar — List sessions with variable
msession_lock — Lock a session
msession_plugin — Call an escape function within the msession personality plugin
msession_randstr — Get random string
msession_set_array — Set array of ...
msession_set — Set value in session
msession_setdata — Set data ... ?
msession_timeout — Set/get session timeout
msession_uniq — Get uniq id
msession_unlock — Unlock a session

后退 | 起点 | 前进
mysql_unbuffered_query | 上一级 | msession_connect


msession_connect

(PHP 4 >= 4.2.0)

msession_connect -- Connect to msession server

Description

bool msession_connect ( string host, string port)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
Mohawk Software session handler functions | 上一级 | msession_count


msession_count

(PHP 4 >= 4.2.0)

msession_count -- Get session count

Description

int msession_count ( void)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
msession_connect | 上一级 | msession_create


msession_create

(PHP 4 >= 4.2.0)

msession_create -- Create a session

Description

bool msession_create ( string session)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
msession_count | 上一级 | msession_destroy


msession_destroy

(PHP 4 >= 4.2.0)

msession_destroy -- Destroy a session

Description

bool msession_destroy ( string name)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
msession_create | 上一级 | msession_disconnect


msession_disconnect

(PHP 4 >= 4.2.0)

msession_disconnect -- Close connection to msession server

Description

void msession_disconnect ( void)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
msession_destroy | 上一级 | msession_find


msession_find

(PHP 4 >= 4.2.0)

msession_find -- Find value

Description

array msession_find ( string name, string value)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
msession_disconnect | 上一级 | msession_get_array


msession_get_array

(PHP 4 >= 4.2.0)

msession_get_array -- Get array of ... ?

Description

array msession_get_array ( string session)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
msession_find | 上一级 | msession_get


msession_get

(PHP 4 >= 4.2.0)

msession_get -- Get value from session

Description

string msession_get ( string session, string name, string value)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
msession_get_array | 上一级 | msession_getdata


msession_getdata

(no version information, might be only in CVS)

msession_getdata -- Get data ... ?

Description

string msession_getdata ( string session)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
msession_get | 上一级 | msession_inc


msession_inc

(PHP 4 >= 4.2.0)

msession_inc -- Increment value in session

Description

string msession_inc ( string session, string name)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
msession_getdata | 上一级 | msession_list


msession_list

(PHP 4 >= 4.2.0)

msession_list -- List ... ?

Description

array msession_list ( void)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
msession_inc | 上一级 | msession_listvar


msession_listvar

(PHP 4 >= 4.2.0)

msession_listvar -- List sessions with variable

Description

array msession_listvar ( string name)

Returns an associative array of value, session for all sessions with a variable named name.

Used for searching sessions with common attributes.

后退 | 起点 | 前进
msession_list | 上一级 | msession_lock


msession_lock

(PHP 4 >= 4.2.0)

msession_lock -- Lock a session

Description

int msession_lock ( string name)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
msession_listvar | 上一级 | msession_plugin


msession_plugin

(PHP 4 >= 4.2.0)

msession_plugin -- Call an escape function within the msession personality plugin

Description

string msession_plugin ( string session, string val [, string param])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
msession_lock | 上一级 | msession_randstr


msession_randstr

(PHP 4 >= 4.2.0)

msession_randstr -- Get random string

Description

string msession_randstr ( int param)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
msession_plugin | 上一级 | msession_set_array


msession_set_array

(PHP 4 >= 4.2.0)

msession_set_array -- Set array of ...

Description

bool msession_set_array ( string session, array tuples)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
msession_randstr | 上一级 | msession_set


msession_set

(PHP 4 >= 4.2.0)

msession_set -- Set value in session

Description

bool msession_set ( string session, string name, string value)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
msession_set_array | 上一级 | msession_setdata


msession_setdata

(no version information, might be only in CVS)

msession_setdata -- Set data ... ?

Description

bool msession_setdata ( string session, string value)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
msession_set | 上一级 | msession_timeout


msession_timeout

(PHP 4 >= 4.2.0)

msession_timeout -- Set/get session timeout

Description

int msession_timeout ( string session [, int param])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
msession_setdata | 上一级 | msession_uniq


msession_uniq

(PHP 4 >= 4.2.0)

msession_uniq -- Get uniq id

Description

string msession_uniq ( int param)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
msession_timeout | 上一级 | msession_unlock


msession_unlock

(PHP 4 >= 4.2.0)

msession_unlock -- Unlock a session

Description

int msession_unlock ( string session, int key)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
msession_uniq | 上一级 | muscat functions


muscat functions

PHP 手册
后退 前进

LXIV. muscat functions

介绍

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

目录
muscat_close — Shuts down the muscat session and releases any memory back to PHP.
muscat_get — Gets a line back from the core muscat API.
muscat_give — Sends string to the core muscat API
muscat_setup_net — Creates a new muscat session and returns the handle.
muscat_setup — Creates a new muscat session and returns the handle.

后退 | 起点 | 前进
msession_unlock | 上一级 | muscat_close


muscat_close

(4.0.5 - 4.2.3 only)

muscat_close -- Shuts down the muscat session and releases any memory back to PHP.

Description

int muscat_close ( resource muscat_handle)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

[Not back to the system, note!]

后退 | 起点 | 前进
muscat functions | 上一级 | muscat_get


muscat_get

(4.0.5 - 4.2.3 only)

muscat_get -- Gets a line back from the core muscat API.

Description

string muscat_get ( resource muscat_handle)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

Returns a literal FALSE when there is no more to get (as opposed to ""). Use === FALSE or !== FALSE to check for this.

后退 | 起点 | 前进
muscat_close | 上一级 | muscat_give


muscat_give

(4.0.5 - 4.2.3 only)

muscat_give -- Sends string to the core muscat API

Description

int muscat_give ( resource muscat_handle, string string)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
muscat_get | 上一级 | muscat_setup_net


muscat_setup_net

(4.0.5 - 4.2.3 only)

muscat_setup_net -- Creates a new muscat session and returns the handle.

Description

resource muscat_setup_net ( string muscat_host, int port)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

muscat_host is the hostname to connect to port is the port number to connect to - actually takes exactly the same args as fsockopen

后退 | 起点 | 前进
muscat_give | 上一级 | muscat_setup


muscat_setup

(4.0.5 - 4.2.3 only)

muscat_setup -- Creates a new muscat session and returns the handle.

Description

resource muscat_setup ( int size [, string muscat_dir])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

Size is the ammount of memory in bytes to allocate for muscat muscat_dir is the muscat installation dir e.g. "/usr/local/empower", it defaults to the compile time muscat directory

后退 | 起点 | 前进
muscat_setup_net | 上一级 | Network Functions


Network Functions

PHP 手册
后退 前进

LXV. Network Functions

介绍

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

这些函数作为 PHP 核心的一部分，无需被安装即可使用。

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

这里列出的所有常量将作为 PHP 核心的一部分一直有效。

表格 1. openlog() Options

Constant | Description
LOG_CONS | if there is an error while sending data to the system logger, write directly to the system console
LOG_NDELAY | open the connection to the logger immediately
LOG_ODELAY | (default) delay opening the connection until the first message is logged
LOG_PERROR | print log message also to standard error
LOG_PID | include PID with each message

表格 2. syslog() Priorities (in descending order)

Constant | Description
LOG_EMERG | system is unusable
LOG_ALERT | action must be taken immediately
LOG_CRIT | critical conditions
LOG_ERR | error conditions
LOG_WARNING | warning conditions
LOG_NOTICE | normal, but significant, condition
LOG_INFO | informational message
LOG_DEBUG | debug-level message
目录
checkdnsrr — Check DNS records corresponding to a given Internet host name or IP address
closelog — Close connection to system logger
debugger_off — Disable internal PHP debugger
debugger_on — Enable internal PHP debugger
define_syslog_variables — Initializes all syslog related constants
fsockopen — Open Internet or Unix domain socket connection
gethostbyaddr — Get the Internet host name corresponding to a given IP address
gethostbyname — Get the IP address corresponding to a given Internet host name
gethostbynamel — Get a list of IP addresses corresponding to a given Internet host name
getmxrr — Get MX records corresponding to a given Internet host name
getprotobyname — Get protocol number associated with protocol name
getprotobynumber — Get protocol name associated with protocol number
getservbyname — Get port number associated with an Internet service and protocol
getservbyport — Get Internet service which corresponds to port and protocol
ip2long — Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address.
long2ip — Converts an (IPv4) Internet network address into a string in Internet standard dotted format
openlog — Open connection to system logger
pfsockopen — Open persistent Internet or Unix domain socket connection
socket_get_status — Returns information about an existing socket stream
socket_set_blocking — Set blocking/non-blocking mode on a socket
socket_set_timeout — Set timeout period on a socket
syslog — Generate a system log message

后退 | 起点 | 前进
muscat_setup | 上一级 | checkdnsrr


checkdnsrr

(PHP 3, PHP 4 )

checkdnsrr -- Check DNS records corresponding to a given Internet host name or IP address

Description

int checkdnsrr ( string host [, string type])

Searches DNS for records of type type corresponding to host. Returns TRUE if any records are found; returns FALSE if no records were found or if an error occurred.

type may be any one of: A, MX, NS, SOA, PTR, CNAME, or ANY. The default is MX.

Host may either be the IP address in dotted-quad notation or the host name.

注: 该函数不适用于 Windows 平台！

See also getmxrr(),
gethostbyaddr(),
gethostbyname(),
gethostbynamel(), and the named(8) manual
page.

后退 | 起点 | 前进
Network Functions | 上一级 | closelog


closelog

(PHP 3, PHP 4 )

closelog -- Close connection to system logger

Description

int closelog ( void)

closelog() closes the descriptor being used to write to the system logger. The use of closelog() is optional.

See also define_syslog_variables(),
syslog() and
openlog().

后退 | 起点 | 前进
checkdnsrr | 上一级 | debugger_off


debugger_off

(PHP 3)

debugger_off -- Disable internal PHP debugger

Description

int debugger_off ( void)

Disables the internal PHP debugger. The debugger is still under development.

后退 | 起点 | 前进
closelog | 上一级 | debugger_on


debugger_on

(PHP 3)

debugger_on -- Enable internal PHP debugger

Description

int debugger_on ( string address)

Enables the internal PHP debugger, connecting it to address. The debugger is still under development.

后退 | 起点 | 前进
debugger_off | 上一级 | define_syslog_variables


define_syslog_variables

(PHP 3, PHP 4 )

define_syslog_variables -- Initializes all syslog related constants

Description

void define_syslog_variables ( void)

Initializes all constants used in the syslog functions.

See also openlog(),
syslog() and
closelog().

后退 | 起点 | 前进
debugger_on | 上一级 | fsockopen


fsockopen

(PHP 3, PHP 4 )

fsockopen -- Open Internet or Unix domain socket connection

Description

int fsockopen ( string hostname, int port [, int errno [, string errstr [, float timeout]]])

Initiates a stream connection in the Internet (AF_INET, using TCP or UDP) or Unix (AF_UNIX) domain. For the Internet domain, it will open a TCP socket connection to hostname on port port. hostname may in this case be either a fully qualified domain name or an IP address. For UDP connections, you need to explicitly specify the protocol by prefixing hostname with 'udp://'. For the Unix domain, hostname will be used as the path to the socket, port must be set to 0 in this case. The optional timeout can be used to set a timeout in seconds for the connect system call.

注: If you need to set a timeout for reading/writing data over the socket, use socket_set_timeout(), as the timeout parameter to fsockopen() only applies while connecting the socket.

As of PHP 4.3.0, if you have compiled in OpenSSL support, you may prefix the hostname with either 'ssl://' or 'tls://' to use an SSL or TLS client connection over TCP/IP to connect to the remote host.

fsockopen() returns a file pointer which may
be used together with the other file functions (such as
fgets(), fgetss(),
fputs(), fclose(), and
feof()).

If the call fails, it will return FALSE and if the optional errno and errstr arguments are present they will be set to indicate the actual system level error that occurred in the system-level connect() call. If the value returned in errno is 0 and the function returned FALSE, it is an indication that the error occurred before the connect() call. This is most likely due to a problem initializing the socket. Note that the errno and errstr arguments will always be passed by reference.

Depending on the environment, the Unix domain or the optional connect timeout may not be available.

The socket will by default be opened in blocking mode. You can switch it to non-blocking mode by using socket_set_blocking().

例子 1. fsockopen() Example

<?php
$fp = fsockopen ("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br>\n";
} else {
    fputs ($fp, "GET / HTTP/1.0\r\nHost: www.example.com\r\n\r\n");
    while (!feof($fp)) {
        echo fgets ($fp,128);
    }
    fclose ($fp);
}
?>
The example below shows how to retrieve the day and time from the UDP service "daytime" (port 13) in your own machine.

例子 2. Using UDP connection

<?php
$fp = fsockopen("udp://127.0.0.1", 13, $errno, $errstr);
if (!$fp) {
    echo "ERROR: $errno - $errstr<br>\n";
} else {
    fwrite($fp,"\n");
    echo fread($fp, 26);
    fclose($fp);
}
?>

警告

UDP sockets will sometimes appear to have opened without an error, even if the remote host is unreachable. The error will only become apparent when you read or write data to/from the socket. The reason for this is because UDP is a "connectionless" protocol, which means that the operating system does not try to establish a link for the socket until it actually needs to send or receive data.

注: The timeout parameter was introduced in PHP 3.0.9 and UDP support was added in PHP 4.

See also pfsockopen(), socket_set_blocking(), socket_set_timeout(), fgets(), fgetss(), fputs(), fclose(), feof(), and the Curl extension.

后退 | 起点 | 前进
define_syslog_variables | 上一级 | gethostbyaddr


gethostbyaddr

(PHP 3, PHP 4 )

gethostbyaddr -- Get the Internet host name corresponding to a given IP address

Description

string gethostbyaddr ( string ip_address)

Returns the host name of the Internet host specified by ip_address. If an error occurs, returns ip_address.

See also gethostbyname().

后退 | 起点 | 前进
fsockopen | 上一级 | gethostbyname


gethostbyname

(PHP 3, PHP 4 )

gethostbyname -- Get the IP address corresponding to a given Internet host name

Description

string gethostbyname ( string hostname)

Returns the IP address of the Internet host specified by hostname.

See also gethostbyaddr().

后退 | 起点 | 前进
gethostbyaddr | 上一级 | gethostbynamel


gethostbynamel

(PHP 3, PHP 4 )

gethostbynamel -- Get a list of IP addresses corresponding to a given Internet host name

Description

array gethostbynamel ( string hostname)

Returns a list of IP addresses to which the Internet host specified by hostname resolves.

See also gethostbyname(),
gethostbyaddr(),
checkdnsrr(), getmxrr(),
and the named(8) manual page.

后退 | 起点 | 前进
gethostbyname | 上一级 | getmxrr


getmxrr

(PHP 3, PHP 4 )

getmxrr -- Get MX records corresponding to a given Internet host name

Description

int getmxrr ( string hostname, array mxhosts [, array weight])

Searches DNS for MX records corresponding to hostname. Returns TRUE if any records are found; returns FALSE if no records were found or if an error occurred.

A list of the MX records found is placed into the array mxhosts. If the weight array is given, it will be filled with the weight information gathered.

注: 该函数不适用于 Windows 平台！

See also checkdnsrr(),
gethostbyname(),
gethostbynamel(),
gethostbyaddr(), and the
named(8) manual page.

后退 | 起点 | 前进
gethostbynamel | 上一级 | getprotobyname


getprotobyname

(PHP 4 )

getprotobyname -- Get protocol number associated with protocol name

Description

int getprotobyname ( string name)

getprotobyname() returns the protocol number associated with the protocol name as per /etc/protocols.

See also: getprotobynumber().

后退 | 起点 | 前进
getmxrr | 上一级 | getprotobynumber


getprotobynumber

(PHP 4 )

getprotobynumber -- Get protocol name associated with protocol number

Description

string getprotobynumber ( int number)

getprotobynumber() returns the protocol name associated with protocol number as per /etc/protocols.

See also: getprotobyname().

后退 | 起点 | 前进
getprotobyname | 上一级 | getservbyname


getservbyname

(PHP 4 )

getservbyname -- Get port number associated with an Internet service and protocol

Description

int getservbyname ( string service, string protocol)

getservbyname() returns the Internet port which corresponds to service for the specified protocol as per /etc/services. protocol is either "tcp" or "udp" (in lowercase).

See also: getservbyport().

后退 | 起点 | 前进
getprotobynumber | 上一级 | getservbyport


getservbyport

(PHP 4 )

getservbyport -- Get Internet service which corresponds to port and protocol

Description

string getservbyport ( int port, string protocol)

getservbyport() returns the Internet service associated with port for the specified protocol as per /etc/services. protocol is either "tcp" or "udp" (in lowercase).

See also: getservbyname().

后退 | 起点 | 前进
getservbyname | 上一级 | ip2long


ip2long

(PHP 4 )

ip2long -- Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address.

Description

int ip2long ( string ip_address)

The function ip2long() generates an IPv4 Internet network address from its Internet standard format (dotted string) representation.

例子 1. ip2long() Example

<?php
$ip = gethostbyname("www.example.com");
$out = "The following URLs are equivalent:<br>\n";
$out .= "http://www.example.com/, http://".$ip."/, and http://".sprintf("%u",ip2long($ip))."/<br>\n";
echo $out;
?>

注: Because PHP's integer type is signed, and many IP addresses will result in negative integers, you need to use the "%u" formatter of sprintf() or printf() to get the string representation of the unsigned IP address.

This second example shows how to print a converted address with the printf() function :

例子 2. Displaying an IP address

<?php
$ip = gethostbyname("www.example.com");
printf("%u\n", ip2long($ip));
echo $out;
?>

See also: long2ip()

后退 | 起点 | 前进
getservbyport | 上一级 | long2ip


long2ip

(PHP 4 )

long2ip -- Converts an (IPv4) Internet network address into a string in Internet standard dotted format

Description

string long2ip ( int proper_address)

The function long2ip() generates an Internet address in dotted format (i.e.: aaa.bbb.ccc.ddd) from the proper address representation.

See also: ip2long()

后退 | 起点 | 前进
ip2long | 上一级 | openlog


openlog

(PHP 3, PHP 4 )

openlog -- Open connection to system logger

Description

int openlog ( string ident, int option, int facility)

openlog() opens a connection to the system logger for a program. The string ident is added to each message. Values for option and facility are given below. The option argument is used to indicate what loggin options will be used when generating a log message. The facility argument is used to specify what type of program is logging the message. This allows you to specify (in your machine's syslog configuration) how messages coming from different facilities will be handled. The use of openlog() is optional. It will automatically be called by syslog() if necessary, in which case ident will default to FALSE.

表格 1. openlog() Options

Constant | Description
LOG_CONS | if there is an error while sending data to the system logger, write directly to the system console
LOG_NDELAY | open the connection to the logger immediately
LOG_ODELAY | (default) delay opening the connection until the first message is logged
LOG_PERROR | print log message also to standard error
LOG_PID | include PID with each message
You can use one or more of this options. When using multiple options you need to OR them, i.e. to open the connection immediately, write to the console and include the PID in each message, you will use: LOG_CONS | LOG_NDELAY | LOG_PID

表格 2. openlog() Facilities

Constant | Description
LOG_AUTH | security/authorization messages (use LOG_AUTHPRIV instead in systems where that constant is defined)
LOG_AUTHPRIV | security/authorization messages (private)
LOG_CRON | clock daemon (cron and at)
LOG_DAEMON | other system daemons
LOG_KERN | kernel messages
LOG_LOCAL0 ... LOG_LOCAL7 | reserved for local use
LOG_LPR | line printer subsystem
LOG_MAIL | mail subsystem
LOG_NEWS | USENET news subsystem
LOG_SYSLOG | messages generated internally by syslogd
LOG_USER | generic user-level messages
LOG_UUCP | UUCP subsystem

See also define_syslog_variables(),
syslog() and
closelog().

后退 | 起点 | 前进
long2ip | 上一级 | pfsockopen


pfsockopen

(PHP 3>= 3.0.7, PHP 4 )

pfsockopen -- Open persistent Internet or Unix domain socket connection

Description

int pfsockopen ( string hostname, int port [, int errno [, string errstr [, int timeout]]])

This function behaves exactly as fsockopen() with the difference that the connection is not closed after the script finishes. It is the persistent version of fsockopen().

后退 | 起点 | 前进
openlog | 上一级 | socket_get_status


socket_get_status

(PHP 4 )

socket_get_status -- Returns information about an existing socket stream

Description

array socket_get_status ( resource socketstream)

Returns information about an existing socket stream. This function only works on sockets created by fsockopen(), pfsockopen() or network sockets returned by fopen() when opening URLs. It does NOT work with sockets from the Socket extension. Currently returns four entries in the result array:

  • timed_out (bool) - The socket timed out waiting for data

  • blocked (bool) - The socket was blocked

  • eof (bool) - Indicates EOF event

  • unread_bytes (int) - Number of bytes left in the socket buffer

See also: Socket extension.

后退 | 起点 | 前进
pfsockopen | 上一级 | socket_set_blocking


socket_set_blocking

(PHP 4 )

socket_set_blocking -- Set blocking/non-blocking mode on a socket

Description

bool socket_set_blocking ( resource socket descriptor, int mode)

If mode is FALSE, the given socket descriptor will be switched to non-blocking mode, and if TRUE, it will be switched to blocking mode. This affects calls like fgets() that read from the socket. In non-blocking mode an fgets() call will always return right away while in blocking mode it will wait for data to become available on the socket.

This function was previously called as set_socket_blocking() but this usage is deprecated.

后退 | 起点 | 前进
socket_get_status | 上一级 | socket_set_timeout


socket_set_timeout

(PHP 4 )

socket_set_timeout -- Set timeout period on a socket

Description

bool socket_set_timeout ( resource socket descriptor, int seconds, int microseconds)

Sets the timeout value on socket descriptor, expressed in the sum of seconds and microseconds.

例子 1. socket_set_timeout() Example

<?php
$fp = fsockopen("www.example.com", 80);
if(!$fp) {
    echo "Unable to open\n";
} else {
    fputs($fp,"GET / HTTP/1.0\n\n");
    $start = time();
    socket_set_timeout($fp, 2);
    $res = fread($fp, 2000);
    var_dump(socket_get_status($fp));
    fclose($fp);
    print $res;
}
?>

This function was previously called as set_socket_timeout() but this usage is deprecated.

See also: fsockopen() and fopen().

后退 | 起点 | 前进
socket_set_blocking | 上一级 | syslog


syslog

(PHP 3, PHP 4 )

syslog -- Generate a system log message

Description

int syslog ( int priority, string message)

syslog() generates a log message that will be distributed by the system logger. priority is a combination of the facility and the level, values for which are given in the next section. The remaining argument is the message to send, except that the two characters %m will be replaced by the error message string (strerror) corresponding to the present value of errno.

表格 1. syslog() Priorities (in descending order)

Constant | Description
LOG_EMERG | system is unusable
LOG_ALERT | action must be taken immediately
LOG_CRIT | critical conditions
LOG_ERR | error conditions
LOG_WARNING | warning conditions
LOG_NOTICE | normal, but significant, condition
LOG_INFO | informational message
LOG_DEBUG | debug-level message

例子 1. Using syslog()

<?php
define_syslog_variables();
// open syslog, include the process ID and also send
// the log to standard error, and use a user defined
// logging mechanism
openlog("myScripLog", LOG_PID | LOG_PERROR, LOG_LOCAL0);

// some code

if (authorized_client()) {
    // do something
} else {
    // unauthorized client!
    // log the attempt
    $access = date("Y/m/d H:i:s");
    syslog(LOG_WARNING,"Unauthorized client: $access $REMOTE_ADDR ($HTTP_USER_AGENT)");
}

closelog();
?>
For information on setting up a user defined log handler, see the syslog.conf(5) Unix manual page. More information on the syslog facilities and option can be found in the man pages for syslog(3) on Unix machines.

On Windows NT, the syslog service is emulated using the Event Log.

See also define_syslog_variables(),
openlog() and
closelog().

后退 | 起点 | 前进
socket_set_timeout | 上一级 | Ncurses terminal screen control functions


Ncurses terminal screen control functions

PHP 手册
后退 前进

LXVI. Ncurses terminal screen control functions

介绍

ncurses (new curses) is a free software emulation of curses in System V Rel 4.0 (and above). It uses terminfo format, supports pads, colors, multiple highlights, form characters and function key mapping.

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Ncurses is available for the following platforms:

  • AIX

  • BeOS

  • Cygwin

  • Digital Unix (aka OSF1)

  • FreeBSD

  • GNU/Linux

  • HPUX

  • IRIX

  • OS/2

  • SCO OpenServer

  • Solaris

  • SunOS

需求

You need the ncurses libraries and headerfiles. Download the latest version from the ftp://ftp.gnu.org/pub/gnu/ncurses/ or from an other GNU-Mirror.

安装

To get these functions to work, you have to compile the CGI version of PHP with --with-ncurses.

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. Ncurses configuration options

Name | Default | Changeable
ncurses.value | "42" | PHP_INI_ALL
ncurses.string | "foobar" | PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

资源类型

该扩展模块未定义任何资源类型。

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

Error codes

On error ncurses functions return NCURSES_ERR.

Colors

表格 2. ncurses color constants

constant | meaning
NCURSES_COLOR_BLACK | no color (black)
NCURSES_COLOR_WHITE | white
NCURSES_COLOR_RED | red - supported when terminal is in color mode
NCURSES_COLOR_GREEN | green - supported when terminal is in color mod
NCURSES_COLOR_YELLOW | yellow - supported when terminal is in color mod
NCURSES_COLOR_BLUE | blue - supported when terminal is in color mod
NCURSES_COLOR_CYAN | cyan - supported when terminal is in color mod
NCURSES_COLOR_MAGENTA | magenta - supported when terminal is in color mod

Keys

表格 3. ncurses key constants

constant | meaning
NCURSES_KEY_F0 - NCURSES_KEY_F64 | function keys F1 - F64
NCURSES_KEY_DOWN | down arrow
NCURSES_KEY_UP | up arrow
NCURSES_KEY_LEFT | left arrow
NCURSES_KEY_RIGHT | right arrow
NCURSES_KEY_HOME | home key (upward+left arrow)
NCURSES_KEY_BACKSPACE | backspace
NCURSES_KEY_DL | delete line
NCURSES_KEY_IL | insert line
NCURSES_KEY_DC | delete character
NCURSES_KEY_IC | insert char or enter insert mode
NCURSES_KEY_EIC | exit insert char mode
NCURSES_KEY_CLEAR | clear screen
NCURSES_KEY_EOS | clear to end of screen
NCURSES_KEY_EOL | clear to end of line
NCURSES_KEY_SF | scroll one line forward
NCURSES_KEY_SR | scroll one line backward
NCURSES_KEY_NPAGE | next page
NCURSES_KEY_PPAGE | previous page
NCURSES_KEY_STAB | set tab
NCURSES_KEY_CTAB | clear tab
NCURSES_KEY_CATAB | clear all tabs
NCURSES_KEY_SRESET | soft (partial) reset
NCURSES_KEY_RESET | reset or hard reset
NCURSES_KEY_PRINT | print
NCURSES_KEY_LL | lower left
NCURSES_KEY_A1 | upper left of keypad
NCURSES_KEY_A3 | upper right of keypad
NCURSES_KEY_B2 | center of keypad
NCURSES_KEY_C1 | lower left of keypad
NCURSES_KEY_C3 | lower right of keypad
NCURSES_KEY_BTAB | back tab
NCURSES_KEY_BEG | beginning
NCURSES_KEY_CANCEL | cancel
NCURSES_KEY_CLOSE | close
NCURSES_KEY_COMMAND | cmd (command)
NCURSES_KEY_COPY | copy
NCURSES_KEY_CREATE | create
NCURSES_KEY_END | end
NCURSES_KEY_EXIT | exit
NCURSES_KEY_FIND | find
NCURSES_KEY_HELP | help
NCURSES_KEY_MARK | mark
NCURSES_KEY_MESSAGE | message
NCURSES_KEY_MOVE | move
NCURSES_KEY_NEXT | next
NCURSES_KEY_OPEN | open
NCURSES_KEY_OPTIONS | options
NCURSES_KEY_PREVIOUS | previous
NCURSES_KEY_REDO | redo
NCURSES_KEY_REFERENCE | ref (reference)
NCURSES_KEY_REFRESH | refresh
NCURSES_KEY_REPLACE | replace
NCURSES_KEY_RESTART | restart
NCURSES_KEY_RESUME | resume
NCURSES_KEY_SAVE | save
NCURSES_KEY_SBEG | shiftet beg (beginning)
NCURSES_KEY_SCANCEL | shifted cancel
NCURSES_KEY_SCOMMAND | shifted command
NCURSES_KEY_SCOPY | shifted copy
NCURSES_KEY_SCREATE | shifted create
NCURSES_KEY_SDC | shifted delete char
NCURSES_KEY_SDL | shifted delete line
NCURSES_KEY_SELECT | select
NCURSES_KEY_SEND | shifted end
NCURSES_KEY_SEOL | shifted end of line
NCURSES_KEY_SEXIT | shifted exit
NCURSES_KEY_SFIND | shifted find
NCURSES_KEY_SHELP | shifted help
NCURSES_KEY_SHOME | shifted home
NCURSES_KEY_SIC | shifted input
NCURSES_KEY_SLEFT | shifted left arrow
NCURSES_KEY_SMESSAGE | shifted message
NCURSES_KEY_SMOVE | shifted move
NCURSES_KEY_SNEXT | shifted next
NCURSES_KEY_SOPTIONS | shifted options
NCURSES_KEY_SPREVIOUS | shifted previous
NCURSES_KEY_SPRINT | shifted print
NCURSES_KEY_SREDO | shifted redo
NCURSES_KEY_SREPLACE | shifted replace
NCURSES_KEY_SRIGHT | shifted right arrow
NCURSES_KEY_SRSUME | shifted resume
NCURSES_KEY_SSAVE | shifted save
NCURSES_KEY_SSUSPEND | shifted suspend
NCURSES_KEY_UNDO | undo
NCURSES_KEY_MOUSE | mouse event has occured
NCURSES_KEY_MAX | maximum key value

Mouse

表格 4. mouse constants

Constant | meaning
NCURSES_BUTTON1_RELEASED - NCURSES_BUTTON4_RELEASED | button (1-4) released
NCURSES_BUTTON1_PRESSED - NCURSES_BUTTON4_PRESSED | button (1-4) pressed
NCURSES_BUTTON1_CLICKED - NCURSES_BUTTON4_CLICKED | button (1-4) clicked
NCURSES_BUTTON1_DOUBLE_CLICKED - NCURSES_BUTTON4_DOUBLE_CLICKED | button (1-4) double clicked
NCURSES_BUTTON1_TRIPLE_CLICKED - NCURSES_BUTTON4_TRIPLE_CLICKED | button (1-4) triple clicked
NCURSES_BUTTON_CTRL | ctrl pressed during click
NCURSES_BUTTON_SHIFT | shift pressed during click
NCURSES_BUTTON_ALT | alt pressed during click
NCURSES_ALL_MOUSE_EVENTS | report all mouse events
NCURSES_REPORT_MOUSE_POSITION | report mouse position
目录
ncurses_addch — Add character at current position and advance cursor
ncurses_addchnstr — Add attributed string with specified length at current position
ncurses_addchstr — Add attributed string at current position
ncurses_addnstr — Add string with specified length at current position
ncurses_addstr — Output text at current position
ncurses_assume_default_colors — Define default colors for color 0
ncurses_attroff — Turn off the given attributes
ncurses_attron — Turn on the given attributes
ncurses_attrset — Set given attributes
ncurses_baudrate — Returns baudrate of terminal
ncurses_beep — Let the terminal beep
ncurses_bkgd — Set background property for terminal screen
ncurses_bkgdset — Control screen background
ncurses_border — Draw a border around the screen using attributed characters
ncurses_can_change_color — Check if we can change terminals colors
ncurses_cbreak — Switch of input buffering
ncurses_clear — Clear screen
ncurses_clrtobot — Clear screen from current position to bottom
ncurses_clrtoeol — Clear screen from current position to end of line
ncurses_color_set — Set fore- and background color
ncurses_curs_set — Set cursor state
ncurses_def_prog_mode — Saves terminals (program) mode
ncurses_def_shell_mode — Saves terminals (shell) mode
ncurses_define_key — Define a keycode
ncurses_delay_output — Delay output on terminal using padding characters
ncurses_delch — Delete character at current position, move rest of line left
ncurses_deleteln — Delete line at current position, move rest of screen up
ncurses_delwin — Delete a ncurses window
ncurses_doupdate — Write all prepared refreshes to terminal
ncurses_echo — Activate keyboard input echo
ncurses_echochar — Single character output including refresh
ncurses_end — Stop using ncurses, clean up the screen
ncurses_erase — Erase terminal screen
ncurses_erasechar — Returns current erase character
ncurses_filter —
ncurses_flash — Flash terminal screen (visual bell)
ncurses_flushinp — Flush keyboard input buffer
ncurses_getch — Read a character from keyboard
ncurses_getmouse — Reads mouse event
ncurses_halfdelay — Put terminal into halfdelay mode
ncurses_has_colors — Check if terminal has colors
ncurses_has_ic — Check for insert- and delete-capabilities
ncurses_has_il — Check for line insert- and delete-capabilities
ncurses_has_key — Check for presence of a function key on terminal keyboard
ncurses_hline — Draw a horizontal line at current position using an attributed character and max. n characters long
ncurses_inch — Get character and attribute at current position
ncurses_init_color — Set new RGB value for color
ncurses_init_pair — Allocate a color pair
ncurses_init — Initialize ncurses
ncurses_insch — Insert character moving rest of line including character at current position
ncurses_insdelln — Insert lines before current line scrolling down (negative numbers delete and scroll up)
ncurses_insertln — Insert a line, move rest of screen down
ncurses_insstr — Insert string at current position, moving rest of line right
ncurses_instr — Reads string from terminal screen
ncurses_isendwin — Ncurses is in endwin mode, normal screen output may be performed
ncurses_keyok — Enable or disable a keycode
ncurses_killchar — Returns current line kill character
ncurses_longname — Returns terminals description
ncurses_mouseinterval — Set timeout for mouse button clicks
ncurses_mousemask — Sets mouse options
ncurses_move — Move output position
ncurses_mvaddch — Move current position and add character
ncurses_mvaddchnstr — Move position and add attrributed string with specified length
ncurses_mvaddchstr — Move position and add attributed string
ncurses_mvaddnstr — Move position and add string with specified length
ncurses_mvaddstr — Move position and add string
ncurses_mvcur — Move cursor immediately
ncurses_mvdelch — Move position and delete character, shift rest of line left
ncurses_mvgetch — Move position and get character at new position
ncurses_mvhline — Set new position and draw a horizontal line using an attributed character and max. n characters long
ncurses_mvinch — Move position and get attributed character at new position
ncurses_mvvline — Set new position and draw a vertical line using an attributed character and max. n characters long
ncurses_mvwaddstr — Add string at new position in window
ncurses_napms — Sleep
ncurses_newwin — Create a new window
ncurses_nl — Translate newline and carriage return / line feed
ncurses_nocbreak — Switch terminal to cooked mode
ncurses_noecho — Switch off keyboard input echo
ncurses_nonl — Do not translate newline and carriage return / line feed
ncurses_noqiflush — Do not flush on signal characters
ncurses_noraw — Switch terminal out of raw mode
ncurses_putp —
ncurses_qiflush — Flush on signal characters
ncurses_raw — Switch terminal into raw mode
ncurses_refresh — Refresh screen
ncurses_resetty — Restores saved terminal state
ncurses_savetty — Saves terminal state
ncurses_scr_dump — Dump screen content to file
ncurses_scr_init — Initialize screen from file dump
ncurses_scr_restore — Restore screen from file dump
ncurses_scr_set — Inherit screen from file dump
ncurses_scrl — Scroll window content up or down without changing current position
ncurses_slk_attr — Returns current soft label key attribute
ncurses_slk_attroff —
ncurses_slk_attron —
ncurses_slk_attrset —
ncurses_slk_clear — Clears soft labels from screen
ncurses_slk_color — Sets color for soft label keys
ncurses_slk_init — Initializes soft label key functions
ncurses_slk_noutrefresh — Copies soft label keys to virtual screen
ncurses_slk_refresh — Copies soft label keys to screen
ncurses_slk_restore — Restores soft label keys
ncurses_slk_touch — Fources output when ncurses_slk_noutrefresh is performed
ncurses_standend — Stop using 'standout' attribute
ncurses_standout — Start using 'standout' attribute
ncurses_start_color — Start using colors
ncurses_termattrs — Returns a logical OR of all attribute flags supported by terminal
ncurses_termname — Returns terminals (short)-name
ncurses_timeout — Set timeout for special key sequences
ncurses_typeahead — Specify different filedescriptor for typeahead checking
ncurses_ungetch — Put a character back into the input stream
ncurses_ungetmouse — Pushes mouse event to queue
ncurses_use_default_colors — Assign terminal default colors to color id -1
ncurses_use_env — Control use of environment information about terminal size
ncurses_use_extended_names — Control use of extended names in terminfo descriptions
ncurses_vidattr —
ncurses_vline — Draw a vertical line at current position using an attributed character and max. n characters long
ncurses_wrefresh — Refresh window on terminal screen

后退 | 起点 | 前进
syslog | 上一级 | ncurses_addch


ncurses_addch

(PHP 4 >= 4.1.0)

ncurses_addch -- Add character at current position and advance cursor

Description

int ncurses_addch ( int ch)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
Ncurses terminal screen control functions | 上一级 | ncurses_addchnstr


ncurses_addchnstr

(PHP 4 >= 4.2.0)

ncurses_addchnstr -- Add attributed string with specified length at current position

Description

int ncurses_addchnstr ( string s, int n)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_addch | 上一级 | ncurses_addchstr


ncurses_addchstr

(PHP 4 >= 4.2.0)

ncurses_addchstr -- Add attributed string at current position

Description

int ncurses_addchstr ( string s)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_addchnstr | 上一级 | ncurses_addnstr


ncurses_addnstr

(PHP 4 >= 4.2.0)

ncurses_addnstr -- Add string with specified length at current position

Description

int ncurses_addnstr ( string s, int n)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_addchstr | 上一级 | ncurses_addstr


ncurses_addstr

(PHP 4 >= 4.2.0)

ncurses_addstr -- Output text at current position

Description

int ncurses_addstr ( string text)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_addnstr | 上一级 | ncurses_assume_default_colors


ncurses_assume_default_colors

(PHP 4 >= 4.2.0)

ncurses_assume_default_colors -- Define default colors for color 0

Description

int ncurses_assume_default_colors ( int fg, int bg)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_addstr | 上一级 | ncurses_attroff


ncurses_attroff

(PHP 4 >= 4.1.0)

ncurses_attroff -- Turn off the given attributes

Description

int ncurses_attroff ( int attributes)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_assume_default_colors | 上一级 | ncurses_attron


ncurses_attron

(PHP 4 >= 4.1.0)

ncurses_attron -- Turn on the given attributes

Description

int ncurses_attron ( int attributes)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_attroff | 上一级 | ncurses_attrset


ncurses_attrset

(PHP 4 >= 4.1.0)

ncurses_attrset -- Set given attributes

Description

int ncurses_attrset ( int attributes)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_attron | 上一级 | ncurses_baudrate


ncurses_baudrate

(PHP 4 >= 4.1.0)

ncurses_baudrate -- Returns baudrate of terminal

Description

int ncurses_baudrate ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_attrset | 上一级 | ncurses_beep


ncurses_beep

(PHP 4 >= 4.1.0)

ncurses_beep -- Let the terminal beep

Description

int ncurses_beep ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_beep() sends an audlible alert (bell) and if its not possible flashes the screen. Returns FALSE on success, otherwise TRUE.

See also: ncurses_flash()

后退 | 起点 | 前进
ncurses_baudrate | 上一级 | ncurses_bkgd


ncurses_bkgd

(PHP 4 >= 4.1.0)

ncurses_bkgd -- Set background property for terminal screen

Description

int ncurses_bkgd ( int attrchar)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_beep | 上一级 | ncurses_bkgdset


ncurses_bkgdset

(PHP 4 >= 4.1.0)

ncurses_bkgdset -- Control screen background

Description

void ncurses_bkgdset ( int attrchar)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_bkgd | 上一级 | ncurses_border


ncurses_border

(PHP 4 >= 4.2.0)

ncurses_border -- Draw a border around the screen using attributed characters

Description

int ncurses_border ( int left, int right, int top, int bottom, int tl_corner, int tr_corner, int bl_corner, int br_corner)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_bkgdset | 上一级 | ncurses_can_change_color


ncurses_can_change_color

(PHP 4 >= 4.1.0)

ncurses_can_change_color -- Check if we can change terminals colors

Description

bool ncurses_can_change_color ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

The function ncurses_can_change_color() returns TRUE or FALSE, depending on whether the terminal has color capabilities and whether the programmer can change the colors.

后退 | 起点 | 前进
ncurses_border | 上一级 | ncurses_cbreak


ncurses_cbreak

(PHP 4 >= 4.1.0)

ncurses_cbreak -- Switch of input buffering

Description

bool ncurses_cbreak ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_cbreak() disables line buffering and character processing (interrupt and flow control characters are unaffected), making characters typed by the user immediately available to the program.

ncurses_cbreak() returns TRUE or NCURSES_ERR if any error occured.

See also: ncurses_nocbreak()

后退 | 起点 | 前进
ncurses_can_change_color | 上一级 | ncurses_clear


ncurses_clear

(PHP 4 >= 4.1.0)

ncurses_clear -- Clear screen

Description

bool ncurses_clear ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_clear() clears the screen completely without setting blanks. Returns FALSE on success, otherwise TRUE.

Note: ncurses_clear() clears the screen without setting blanks, which have the current background rendition. To clear screen with blanks, use ncurses_erase().

See also: ncurses_erase()

后退 | 起点 | 前进
ncurses_cbreak | 上一级 | ncurses_clrtobot


ncurses_clrtobot

(PHP 4 >= 4.1.0)

ncurses_clrtobot -- Clear screen from current position to bottom

Description

bool ncurses_clrtobot ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_clrtobot() erases all lines from cursor to end of screen and creates blanks. Blanks created by ncurses_clrtobot() have the current background rendition. Returns TRUE if any error occured, otherwise FALSE.

See also: ncurses_clear(), ncurses_clrtoeol()

后退 | 起点 | 前进
ncurses_clear | 上一级 | ncurses_clrtoeol


ncurses_clrtoeol

(PHP 4 >= 4.1.0)

ncurses_clrtoeol -- Clear screen from current position to end of line

Description

bool ncurses_clrtoeol ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_clrtoeol() erases the current line from cursor position to the end. Blanks created by ncurses_clrtoeol() have the current background rendition. Returns TRUE if any error occured, otherwise FALSE.

See also: ncurses_clear(), ncurses_clrtobot()

后退 | 起点 | 前进
ncurses_clrtobot | 上一级 | ncurses_color_set


ncurses_color_set

(PHP 4 >= 4.1.0)

ncurses_color_set -- Set fore- and background color

Description

int ncurses_color_set ( int pair)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_clrtoeol | 上一级 | ncurses_curs_set


ncurses_curs_set

(PHP 4 >= 4.1.0)

ncurses_curs_set -- Set cursor state

Description

int ncurses_curs_set ( int visibility)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_color_set | 上一级 | ncurses_def_prog_mode


ncurses_def_prog_mode

(PHP 4 >= 4.1.0)

ncurses_def_prog_mode -- Saves terminals (program) mode

Description

bool ncurses_def_prog_mode ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_def_prog_mode() saves the current terminal modes for program (in curses) for use by ncurses_reset_prog_mode(). Returns FALSE on success, otherwise TRUE.

See also: ncurses_reset_prog_mode()

后退 | 起点 | 前进
ncurses_curs_set | 上一级 | ncurses_def_shell_mode


ncurses_def_shell_mode

(PHP 4 >= 4.1.0)

ncurses_def_shell_mode -- Saves terminals (shell) mode

Description

bool ncurses_def_shell_mode ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_def_shell_mode() saves the current terminal modes for shell (not in curses) for use by ncurses_reset_shell_mode(). Returns FALSE on success, otherwise TRUE.

See also: ncurses_reset_shell_mode()

后退 | 起点 | 前进
ncurses_def_prog_mode | 上一级 | ncurses_define_key


ncurses_define_key

(PHP 4 >= 4.2.0)

ncurses_define_key -- Define a keycode

Description

int ncurses_define_key ( string definition, int keycode)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_def_shell_mode | 上一级 | ncurses_delay_output


ncurses_delay_output

(PHP 4 >= 4.1.0)

ncurses_delay_output -- Delay output on terminal using padding characters

Description

int ncurses_delay_output ( int milliseconds)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_define_key | 上一级 | ncurses_delch


ncurses_delch

(PHP 4 >= 4.1.0)

ncurses_delch -- Delete character at current position, move rest of line left

Description

bool ncurses_delch ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_delch() deletes the character under the cursor. All characters to the right of the cursor on the same line are moved to the left one position and the last character on the line is filled with a blank. The cursor position does not change. Returns FALSE on success, otherwise TRUE.

See also: ncurses_deleteln()

后退 | 起点 | 前进
ncurses_delay_output | 上一级 | ncurses_deleteln


ncurses_deleteln

(PHP 4 >= 4.1.0)

ncurses_deleteln -- Delete line at current position, move rest of screen up

Description

bool ncurses_deleteln ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_deleteln() deletes the current line under cursorposition. All lines below the current line are moved up one line. The bottom line of window is cleared. Cursor position does not change. Returns FALSE on success, otherwise TRUE.

See also: ncurses_delch()

后退 | 起点 | 前进
ncurses_delch | 上一级 | ncurses_delwin


ncurses_delwin

(PHP 4 >= 4.1.0)

ncurses_delwin -- Delete a ncurses window

Description

int ncurses_delwin ( resource window)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_deleteln | 上一级 | ncurses_doupdate


ncurses_doupdate

(PHP 4 >= 4.1.0)

ncurses_doupdate -- Write all prepared refreshes to terminal

Description

bool ncurses_doupdate ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_doupdate()() compares the virtual screen to the physical screen and updates the physical screen. This way is more effective than using multiple refresh calls. Returns FALSE on success, TRUE if any error occured.

后退 | 起点 | 前进
ncurses_delwin | 上一级 | ncurses_echo


ncurses_echo

(PHP 4 >= 4.1.0)

ncurses_echo -- Activate keyboard input echo

Description

bool ncurses_echo ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_echo() enables echo mode. All characters typed by user are echoed by ncurses_getch(). Returns FALSE on success, TRUE if any error occured.

To disable echo mode use ncurses_noecho().

后退 | 起点 | 前进
ncurses_doupdate | 上一级 | ncurses_echochar


ncurses_echochar

(PHP 4 >= 4.1.0)

ncurses_echochar -- Single character output including refresh

Description

int ncurses_echochar ( int character)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_echo | 上一级 | ncurses_end


ncurses_end

(PHP 4 >= 4.1.0)

ncurses_end -- Stop using ncurses, clean up the screen

Description

int ncurses_end ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_echochar | 上一级 | ncurses_erase


ncurses_erase

(PHP 4 >= 4.1.0)

ncurses_erase -- Erase terminal screen

Description

bool ncurses_erase ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_erase() fills the terminal screen with blanks. Created blanks have the current background rendition, set by ncurses_bkgd(). Returns FALSE on success, TRUE if any error occured.

See also: ncurses_bkgd(), ncurses_clear()

后退 | 起点 | 前进
ncurses_end | 上一级 | ncurses_erasechar


ncurses_erasechar

(PHP 4 >= 4.1.0)

ncurses_erasechar -- Returns current erase character

Description

string ncurses_erasechar ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_erasechar() returns the current erase char character.

See also: ncurses_killchar()

后退 | 起点 | 前进
ncurses_erase | 上一级 | ncurses_filter


ncurses_filter

(PHP 4 >= 4.1.0)

ncurses_filter --

Description

int ncurses_filter ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_erasechar | 上一级 | ncurses_flash


ncurses_flash

(PHP 4 >= 4.1.0)

ncurses_flash -- Flash terminal screen (visual bell)

Description

bool ncurses_flash ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_flash() flashes the screen, and if its not possible, sends an audible alert (bell). Returns FALSE on success, otherwise TRUE.

See also: ncurses_beep()

后退 | 起点 | 前进
ncurses_filter | 上一级 | ncurses_flushinp


ncurses_flushinp

(PHP 4 >= 4.1.0)

ncurses_flushinp -- Flush keyboard input buffer

Description

bool ncurses_flushinp ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

The ncurses_flushinp() throws away any typeahead that has been typed and has not yet been read by your program. Returns FALSE on success, otherwise TRUE.

后退 | 起点 | 前进
ncurses_flash | 上一级 | ncurses_getch


ncurses_getch

(PHP 4 >= 4.1.0)

ncurses_getch -- Read a character from keyboard

Description

int ncurses_getch ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_flushinp | 上一级 | ncurses_getmouse


ncurses_getmouse

(PHP 4 >= 4.2.0)

ncurses_getmouse -- Reads mouse event

Description

bool ncurses_getmouse ( array mevent)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_getmouse() reads mouse event out of queue. Function ncurses_getmouse() will return ;FALSE if a mouse event is actually visible in the given window, otherwise it will return TRUE. Event options will be delivered in parameter mevent, which has to be an array, passed by reference (see example below). On success an associative array with following keys will be delivered:

  • "id" : Id to distinguish multiple devices

  • "x" : screen relative x-position in character cells

  • "y" : screen relative y-position in character cells

  • "z" : currently not supported

  • "mmask" : Mouse action

例子 1. ncurses_getmouse() example

switch (ncurses_getch){
  case NCURSES_KEY_MOUSE:
    if (!ncurses_getmouse(&$mevent)){
      if ($mevent["mmask"] & NCURSES_MOUSE_BUTTON1_PRESSED){
        $mouse_x = $mevent["x"]; // Save mouse position
        $mouse_y = $mevent["y"];
      }
    }
  break;

  default:
    ....
}

See also: ncurses_ungetmouse()

后退 | 起点 | 前进
ncurses_getch | 上一级 | ncurses_halfdelay


ncurses_halfdelay

(PHP 4 >= 4.1.0)

ncurses_halfdelay -- Put terminal into halfdelay mode

Description

int ncurses_halfdelay ( int tenth)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_getmouse | 上一级 | ncurses_has_colors


ncurses_has_colors

(PHP 4 >= 4.1.0)

ncurses_has_colors -- Check if terminal has colors

Description

bool ncurses_has_colors ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_has_colors() returns TRUE or FALSE depending on whether the terminal has color capacitites.

See also: ncurses_can_change_color()

后退 | 起点 | 前进
ncurses_halfdelay | 上一级 | ncurses_has_ic


ncurses_has_ic

(PHP 4 >= 4.1.0)

ncurses_has_ic -- Check for insert- and delete-capabilities

Description

bool ncurses_has_ic ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_has_ic() checks terminals insert- and delete capabilitites. It returns TRUE when terminal has insert/delete-capabilities, otherwise FALSE.

See also: ncurses_has_il()

后退 | 起点 | 前进
ncurses_has_colors | 上一级 | ncurses_has_il


ncurses_has_il

(PHP 4 >= 4.1.0)

ncurses_has_il -- Check for line insert- and delete-capabilities

Description

bool ncurses_has_il ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_has_il() checks terminals insert- and delete-line-capabilities. It returns TRUE when terminal has insert/delete-line capabilities, otherwise FALSE

See also: ncurses_has_ic()

后退 | 起点 | 前进
ncurses_has_ic | 上一级 | ncurses_has_key


ncurses_has_key

(PHP 4 >= 4.1.0)

ncurses_has_key -- Check for presence of a function key on terminal keyboard

Description

int ncurses_has_key ( int keycode)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_has_il | 上一级 | ncurses_hline


ncurses_hline

(PHP 4 >= 4.2.0)

ncurses_hline -- Draw a horizontal line at current position using an attributed character and max. n characters long

Description

int ncurses_hline ( int charattr, int n)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_has_key | 上一级 | ncurses_inch


ncurses_inch

(PHP 4 >= 4.1.0)

ncurses_inch -- Get character and attribute at current position

Description

string ncurses_inch ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_inch() returns the character from the current position.

后退 | 起点 | 前进
ncurses_hline | 上一级 | ncurses_init_color


ncurses_init_color

(PHP 4 >= 4.2.0)

ncurses_init_color -- Set new RGB value for color

Description

int ncurses_init_color ( int color, int r, int g, int b)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_inch | 上一级 | ncurses_init_pair


ncurses_init_pair

(PHP 4 >= 4.1.0)

ncurses_init_pair -- Allocate a color pair

Description

int ncurses_init_pair ( int pair, int fg, int bg)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_init_color | 上一级 | ncurses_init


ncurses_init

(PHP 4 >= 4.1.0)

ncurses_init -- Initialize ncurses

Description

int ncurses_init ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_init_pair | 上一级 | ncurses_insch


ncurses_insch

(PHP 4 >= 4.1.0)

ncurses_insch -- Insert character moving rest of line including character at current position

Description

int ncurses_insch ( int character)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_init | 上一级 | ncurses_insdelln


ncurses_insdelln

(PHP 4 >= 4.1.0)

ncurses_insdelln -- Insert lines before current line scrolling down (negative numbers delete and scroll up)

Description

int ncurses_insdelln ( int count)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_insch | 上一级 | ncurses_insertln


ncurses_insertln

(PHP 4 >= 4.1.0)

ncurses_insertln -- Insert a line, move rest of screen down

Description

bool ncurses_insertln ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_insertln() inserts a new line above the current line. The bottom line will be lost.

后退 | 起点 | 前进
ncurses_insdelln | 上一级 | ncurses_insstr


ncurses_insstr

(PHP 4 >= 4.2.0)

ncurses_insstr -- Insert string at current position, moving rest of line right

Description

int ncurses_insstr ( string text)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_insertln | 上一级 | ncurses_instr


ncurses_instr

(PHP 4 >= 4.2.0)

ncurses_instr -- Reads string from terminal screen

Description

int ncurses_instr ( string buffer)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_instr() returns the number of charaters read from the current character position until end of line. buffer contains the characters. Atrributes are stripped from the characters.

后退 | 起点 | 前进
ncurses_insstr | 上一级 | ncurses_isendwin


ncurses_isendwin

(PHP 4 >= 4.1.0)

ncurses_isendwin -- Ncurses is in endwin mode, normal screen output may be performed

Description

bool ncurses_isendwin ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_isendwin() returns TRUE, if
ncurses_endwin() has been called without any
subsequent calls to ncurses_wrefresh(),
otherwise FALSE.

See also: ncurses_endwin() ncurses_wrefresh()()

后退 | 起点 | 前进
ncurses_instr | 上一级 | ncurses_keyok


ncurses_keyok

(PHP 4 >= 4.2.0)

ncurses_keyok -- Enable or disable a keycode

Description

int ncurses_keyok ( int keycode, bool enable)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_isendwin | 上一级 | ncurses_killchar


ncurses_killchar

(PHP 4 >= 4.1.0)

ncurses_killchar -- Returns current line kill character

Description

bool ncurses_killchar ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_killchar() returns the current line kill character.

See also: ncurses_erasechar()

后退 | 起点 | 前进
ncurses_keyok | 上一级 | ncurses_longname


ncurses_longname

(PHP 4 >= 4.2.0)

ncurses_longname -- Returns terminals description

Description

string ncurses_longname ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_longname() returns a verbose description of the terminal. The descritpion is truncated to 128 characters. On Error ncurses_longname() returns NULL.

See also: ncurses_termname()

后退 | 起点 | 前进
ncurses_killchar | 上一级 | ncurses_mouseinterval


ncurses_mouseinterval

(PHP 4 >= 4.1.0)

ncurses_mouseinterval -- Set timeout for mouse button clicks

Description

int ncurses_mouseinterval ( int milliseconds)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_longname | 上一级 | ncurses_mousemask


ncurses_mousemask

(PHP 4 >= 4.2.0)

ncurses_mousemask -- Sets mouse options

Description

int ncurses_mousemask ( int newmask, int oldmask)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Function ncurses_mousemask() will set mouse events to be reported. By default no mouse events will be reported. The function ncurses_mousemask() will return a mask to indicated which of the in parameter newmask specified mouse events can be reported. On complete failure, it returns 0. In parameter oldmask, which is passed by reference ncurses_mousemask() returns the previous value of mouse event mask. Mouse events are represented bei NCURSES_KEY_MOUSE in the ncurses_wgetch() input stream. To read the event data and pop the event of of queue, call ncurses_getmouse().

As a side effect, setting a zero mousemask in newmask turns off the mouse pointer. Setting a non zero value turns mouse pointer on.

mouse mask options can be set with the following predefined constants:

  • NCURSES_BUTTON1_PRESSED

  • NCURSES_BUTTON1_RELEASED

  • NCURSES_BUTTON1_CLICKED

  • NCURSES_BUTTON1_DOUBLE_CLICKED

  • NCURSES_BUTTON1_TRIPLE_CLICKED

  • NCURSES_BUTTON2_PRESSED

  • NCURSES_BUTTON2_RELEASED

  • NCURSES_BUTTON2_CLICKED

  • NCURSES_BUTTON2_DOUBLE_CLICKED

  • NCURSES_BUTTON2_TRIPLE_CLICKED

  • NCURSES_BUTTON3_PRESSED

  • NCURSES_BUTTON3_RELEASED

  • NCURSES_BUTTON3_CLICKED

  • NCURSES_BUTTON3_DOUBLE_CLICKED

  • NCURSES_BUTTON3_TRIPLE_CLICKED

  • NCURSES_BUTTON4_PRESSED

  • NCURSES_BUTTON4_RELEASED

  • NCURSES_BUTTON4_CLICKED

  • NCURSES_BUTTON4_DOUBLE_CLICKED

  • NCURSES_BUTTON4_TRIPLE_CLICKED

  • NCURSES_BUTTON_SHIFT>

  • NCURSES_BUTTON_CTRL

  • NCURSES_BUTTON_ALT

  • NCURSES_ALL_MOUSE_EVENTS

  • NCURSES_REPORT_MOUSE_POSITION

See also: ncurses_getmouse(),
          ncurses_ungetmouse()
          ncurese_getch()

例子 1. ncurses_mousemask() example

$newmask = NCURSES_BUTTON1_CLICKED + NCURSES_BUTTON1_RELEASED;
$mask = ncurses_mousemask($newmask, &$oldmask);
if ($mask & $newmask){
  printf ("All specified mouse options will be supported\n");
}

后退 | 起点 | 前进
ncurses_mouseinterval | 上一级 | ncurses_move


ncurses_move

(PHP 4 >= 4.1.0)

ncurses_move -- Move output position

Description

int ncurses_move ( int y, int x)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_mousemask | 上一级 | ncurses_mvaddch


ncurses_mvaddch

(PHP 4 >= 4.2.0)

ncurses_mvaddch -- Move current position and add character

Description

int ncurses_mvaddch ( int y, int x, int c)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_move | 上一级 | ncurses_mvaddchnstr


ncurses_mvaddchnstr

(PHP 4 >= 4.2.0)

ncurses_mvaddchnstr -- Move position and add attrributed string with specified length

Description

int ncurses_mvaddchnstr ( int y, int x, string s, int n)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_mvaddch | 上一级 | ncurses_mvaddchstr


ncurses_mvaddchstr

(PHP 4 >= 4.2.0)

ncurses_mvaddchstr -- Move position and add attributed string

Description

int ncurses_mvaddchstr ( int y, int x, string s)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_mvaddchnstr | 上一级 | ncurses_mvaddnstr


ncurses_mvaddnstr

(PHP 4 >= 4.2.0)

ncurses_mvaddnstr -- Move position and add string with specified length

Description

int ncurses_mvaddnstr ( int y, int x, string s, int n)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_mvaddchstr | 上一级 | ncurses_mvaddstr


ncurses_mvaddstr

(PHP 4 >= 4.2.0)

ncurses_mvaddstr -- Move position and add string

Description

int ncurses_mvaddstr ( int y, int x, string s)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_mvaddnstr | 上一级 | ncurses_mvcur


ncurses_mvcur

(PHP 4 >= 4.2.0)

ncurses_mvcur -- Move cursor immediately

Description

int ncurses_mvcur ( int old_y, int old_x, int new_y, int new_x)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_mvaddstr | 上一级 | ncurses_mvdelch


ncurses_mvdelch

(PHP 4 >= 4.2.0)

ncurses_mvdelch -- Move position and delete character, shift rest of line left

Description

int ncurses_mvdelch ( int y, int x)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_mvcur | 上一级 | ncurses_mvgetch


ncurses_mvgetch

(PHP 4 >= 4.2.0)

ncurses_mvgetch -- Move position and get character at new position

Description

int ncurses_mvgetch ( int y, int x)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_mvdelch | 上一级 | ncurses_mvhline


ncurses_mvhline

(PHP 4 >= 4.2.0)

ncurses_mvhline -- Set new position and draw a horizontal line using an attributed character and max. n characters long

Description

int ncurses_mvhline ( int y, int x, int attrchar, int n)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_mvgetch | 上一级 | ncurses_mvinch


ncurses_mvinch

(PHP 4 >= 4.2.0)

ncurses_mvinch -- Move position and get attributed character at new position

Description

int ncurses_mvinch ( int y, int x)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_mvhline | 上一级 | ncurses_mvvline


ncurses_mvvline

(no version information, might be only in CVS)

ncurses_mvvline -- Set new position and draw a vertical line using an attributed character and max. n characters long

Description

int ncurses_mvvline ( int y, int x, int attrchar, int n)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_mvinch | 上一级 | ncurses_mvwaddstr


ncurses_mvwaddstr

(PHP 4 >= 4.2.0)

ncurses_mvwaddstr -- Add string at new position in window

Description

int ncurses_mvwaddstr ( resource window, int y, int x, string text)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_mvvline | 上一级 | ncurses_napms


ncurses_napms

(PHP 4 >= 4.1.0)

ncurses_napms -- Sleep

Description

int ncurses_napms ( int milliseconds)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_mvwaddstr | 上一级 | ncurses_newwin


ncurses_newwin

(PHP 4 >= 4.1.0)

ncurses_newwin -- Create a new window

Description

int ncurses_newwin ( int rows, int cols, int y, int x)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_napms | 上一级 | ncurses_nl


ncurses_nl

(PHP 4 >= 4.1.0)

ncurses_nl -- Translate newline and carriage return / line feed

Description

bool ncurses_nl ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_newwin | 上一级 | ncurses_nocbreak


ncurses_nocbreak

(PHP 4 >= 4.1.0)

ncurses_nocbreak -- Switch terminal to cooked mode

Description

bool ncurses_nocbreak ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_nocbreak() routine returns terminal to normal (cooked) mode. Initially the terminal may or may not in cbreak mode as the mode is inherited. Therefore a program should call ncurses_cbreak() and ncurses_nocbreak() explicitly. Returns TRUE if any error occured, otherwise FALSE.

See also: ncurses_cbreak()

后退 | 起点 | 前进
ncurses_nl | 上一级 | ncurses_noecho


ncurses_noecho

(PHP 4 >= 4.1.0)

ncurses_noecho -- Switch off keyboard input echo

Description

bool ncurses_noecho ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_noecho() prevents echoing of user typed characters. Returns TRUE if any error occured, otherwise FALSE.

See also: ncurses_echo(), ncurses_getch()

后退 | 起点 | 前进
ncurses_nocbreak | 上一级 | ncurses_nonl


ncurses_nonl

(PHP 4 >= 4.1.0)

ncurses_nonl -- Do not translate newline and carriage return / line feed

Description

bool ncurses_nonl ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_noecho | 上一级 | ncurses_noqiflush


ncurses_noqiflush

(PHP 4 >= 4.1.0)

ncurses_noqiflush -- Do not flush on signal characters

Description

int ncurses_noqiflush ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_nonl | 上一级 | ncurses_noraw


ncurses_noraw

(PHP 4 >= 4.1.0)

ncurses_noraw -- Switch terminal out of raw mode

Description

bool ncurses_noraw ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_noraw() switches the terminal out of raw mode. Raw mode is similar to cbreak mode, in that characters typed are immediately passed through to the user program. The differences that are that in raw mode, the interrupt, quit, suspend and flow control characters are all passed through uninterpreted, instead of generating a signal. Returns TRUE if any error occured, otherwise FALSE.

See also: ncurses_raw(),
ncurses_cbreak(),
ncurses_nocbreak()

后退 | 起点 | 前进
ncurses_noqiflush | 上一级 | ncurses_putp


ncurses_putp

(PHP 4 >= 4.2.0)

ncurses_putp --

Description

int ncurses_putp ( string text)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_noraw | 上一级 | ncurses_qiflush


ncurses_qiflush

(PHP 4 >= 4.1.0)

ncurses_qiflush -- Flush on signal characters

Description

int ncurses_qiflush ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_putp | 上一级 | ncurses_raw


ncurses_raw

(PHP 4 >= 4.1.0)

ncurses_raw -- Switch terminal into raw mode

Description

bool ncurses_raw ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_raw() places the terminal in raw mode. Raw mode is similar to cbreak mode, in that characters typed are immediately passed through to the user program. The differences that are that in raw mode, the interrupt, quit, suspend and flow control characters are all passed through uninterpreted, instead of generating a signal. Returns TRUE if any error occured, otherwise FALSE.

See also: ncurses_noraw(),
ncurses_cbreak(),
ncurses_nocbreak()

后退 | 起点 | 前进
ncurses_qiflush | 上一级 | ncurses_refresh


ncurses_refresh

(PHP 4 >= 4.1.0)

ncurses_refresh -- Refresh screen

Description

int ncurses_refresh ( int ch)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_raw | 上一级 | ncurses_resetty


ncurses_resetty

(PHP 4 >= 4.1.0)

ncurses_resetty -- Restores saved terminal state

Description

bool ncurses_resetty ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Function ncurses_resetty() restores the terminal state, which was previously saved by calling ncurses_savetty(). This function always returns FALSE.

See also: ncurses_savetty()

后退 | 起点 | 前进
ncurses_refresh | 上一级 | ncurses_savetty


ncurses_savetty

(PHP 4 >= 4.1.0)

ncurses_savetty -- Saves terminal state

Description

bool ncurses_savetty ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Function ncurses_savetty() saves the current terminal state. The saved terminal state can be restored with function ncurses_resetty(). ncurses_savetty() always returns FALSE.

See also: ncurses_resetty()

后退 | 起点 | 前进
ncurses_resetty | 上一级 | ncurses_scr_dump


ncurses_scr_dump

(PHP 4 >= 4.2.0)

ncurses_scr_dump -- Dump screen content to file

Description

int ncurses_scr_dump ( string filename)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_savetty | 上一级 | ncurses_scr_init


ncurses_scr_init

(PHP 4 >= 4.2.0)

ncurses_scr_init -- Initialize screen from file dump

Description

int ncurses_scr_init ( string filename)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_scr_dump | 上一级 | ncurses_scr_restore


ncurses_scr_restore

(PHP 4 >= 4.2.0)

ncurses_scr_restore -- Restore screen from file dump

Description

int ncurses_scr_restore ( string filename)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_scr_init | 上一级 | ncurses_scr_set


ncurses_scr_set

(PHP 4 >= 4.2.0)

ncurses_scr_set -- Inherit screen from file dump

Description

int ncurses_scr_set ( string filename)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_scr_restore | 上一级 | ncurses_scrl


ncurses_scrl

(PHP 4 >= 4.1.0)

ncurses_scrl -- Scroll window content up or down without changing current position

Description

int ncurses_scrl ( int count)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_scr_set | 上一级 | ncurses_slk_attr


ncurses_slk_attr

(PHP 4 >= 4.1.0)

ncurses_slk_attr -- Returns current soft label key attribute

Description

bool ncurses_slk_attr ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_slk_attr() returns the current soft label key attribute. On error returns TRUE, otherwise FALSE.

后退 | 起点 | 前进
ncurses_scrl | 上一级 | ncurses_slk_attroff


ncurses_slk_attroff

(PHP 4 >= 4.1.0)

ncurses_slk_attroff --

Description

int ncurses_slk_attroff ( int intarg)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_slk_attr | 上一级 | ncurses_slk_attron


ncurses_slk_attron

(PHP 4 >= 4.1.0)

ncurses_slk_attron --

Description

int ncurses_slk_attron ( int intarg)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_slk_attroff | 上一级 | ncurses_slk_attrset


ncurses_slk_attrset

(PHP 4 >= 4.1.0)

ncurses_slk_attrset --

Description

int ncurses_slk_attrset ( int intarg)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_slk_attron | 上一级 | ncurses_slk_clear


ncurses_slk_clear

(PHP 4 >= 4.1.0)

ncurses_slk_clear -- Clears soft labels from screen

Description

bool ncurses_slk_clear ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

The function ncurses_slk_clear() clears soft label keys from screen. Returns TRUE on error, otherwise FALSE.

后退 | 起点 | 前进
ncurses_slk_attrset | 上一级 | ncurses_slk_color


ncurses_slk_color

(PHP 4 >= 4.1.0)

ncurses_slk_color -- Sets color for soft label keys

Description

int ncurses_slk_color ( int intarg)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_slk_clear | 上一级 | ncurses_slk_init


ncurses_slk_init

(PHP 4 >= 4.1.0)

ncurses_slk_init -- Initializes soft label key functions

Description

bool ncurses_slk_init ( int format)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Funtion ncurses_slk_init() must be called before ncurses_initscr() or ncurses_newterm() is called. If ncurses_initscr() eventually uses a line from stdscr to emulate the soft labels, then format determines how the labels are arranged of the screen. Setting format to 0 indicates a 3-2-3 arrangement of the labels, 1 indicates a 4-4 arrangement and 2 indicates the PC like 4-4-4 mode, but in addition an index line will be created.

后退 | 起点 | 前进
ncurses_slk_color | 上一级 | ncurses_slk_noutrefresh


ncurses_slk_noutrefresh

(PHP 4 >= 4.1.0)

ncurses_slk_noutrefresh -- Copies soft label keys to virtual screen

Description

bool ncurses_slk_noutrefresh ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_slk_init | 上一级 | ncurses_slk_refresh


ncurses_slk_refresh

(PHP 4 >= 4.1.0)

ncurses_slk_refresh -- Copies soft label keys to screen

Description

bool ncurses_slk_refresh ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_slk_refresh() copies soft label keys from virtual screen to physical screen. Returns TRUE on error, otherwise FALSE.

后退 | 起点 | 前进
ncurses_slk_noutrefresh | 上一级 | ncurses_slk_restore


ncurses_slk_restore

(PHP 4 >= 4.1.0)

ncurses_slk_restore -- Restores soft label keys

Description

bool ncurses_slk_restore ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

The function ncurses_slk_restore() restores the soft label keys after ncurses_slk_clear() has been performed.

后退 | 起点 | 前进
ncurses_slk_refresh | 上一级 | ncurses_slk_touch


ncurses_slk_touch

(PHP 4 >= 4.1.0)

ncurses_slk_touch -- Fources output when ncurses_slk_noutrefresh is performed

Description

bool ncurses_slk_touch ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

The ncurses_slk_touch() function forces all the soft labels to be output the next time a ncurses_slk_noutrefresh() is performed.

后退 | 起点 | 前进
ncurses_slk_restore | 上一级 | ncurses_standend


ncurses_standend

(PHP 4 >= 4.1.0)

ncurses_standend -- Stop using 'standout' attribute

Description

int ncurses_standend ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_slk_touch | 上一级 | ncurses_standout


ncurses_standout

(PHP 4 >= 4.1.0)

ncurses_standout -- Start using 'standout' attribute

Description

int ncurses_standout ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_standend | 上一级 | ncurses_start_color


ncurses_start_color

(PHP 4 >= 4.1.0)

ncurses_start_color -- Start using colors

Description

int ncurses_start_color ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_standout | 上一级 | ncurses_termattrs


ncurses_termattrs

(PHP 4 >= 4.1.0)

ncurses_termattrs -- Returns a logical OR of all attribute flags supported by terminal

Description

bool ncurses_termattrs ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_start_color | 上一级 | ncurses_termname


ncurses_termname

(PHP 4 >= 4.2.0)

ncurses_termname -- Returns terminals (short)-name

Description

string ncurses_termname ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_termname() returns terminals shortname. The shortname is truncated to 14 characters. On error ncurses_termname() returns NULL.

See also: ncurses_longname()

后退 | 起点 | 前进
ncurses_termattrs | 上一级 | ncurses_timeout


ncurses_timeout

(PHP 4 >= 4.1.0)

ncurses_timeout -- Set timeout for special key sequences

Description

void ncurses_timeout ( int millisec)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_termname | 上一级 | ncurses_typeahead


ncurses_typeahead

(PHP 4 >= 4.1.0)

ncurses_typeahead -- Specify different filedescriptor for typeahead checking

Description

int ncurses_typeahead ( int fd)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_timeout | 上一级 | ncurses_ungetch


ncurses_ungetch

(PHP 4 >= 4.1.0)

ncurses_ungetch -- Put a character back into the input stream

Description

int ncurses_ungetch ( int keycode)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_typeahead | 上一级 | ncurses_ungetmouse


ncurses_ungetmouse

(PHP 4 >= 4.2.0)

ncurses_ungetmouse -- Pushes mouse event to queue

Description

bool ncurses_ungetmouse ( array mevent)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

ncurses_getmouse() pushes a KEY_MOUSE event onto the unput queue and associates with this event the given state sata and screen-relative character cell coordinates, specified in mevent. Event options will be specified in associative array mevent:

  • "id" : Id to distinguish multiple devices

  • "x" : screen relative x-position in character cells

  • "y" : screen relative y-position in character cells

  • "z" : currently not supported

  • "mmask" : Mouse action

ncurses_ungetmouse() returns FALSE on success, otherwise TRUE.

See also: ncurses_getmouse()

后退 | 起点 | 前进
ncurses_ungetch | 上一级 | ncurses_use_default_colors


ncurses_use_default_colors

(PHP 4 >= 4.1.0)

ncurses_use_default_colors -- Assign terminal default colors to color id -1

Description

bool ncurses_use_default_colors ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_ungetmouse | 上一级 | ncurses_use_env


ncurses_use_env

(PHP 4 >= 4.1.0)

ncurses_use_env -- Control use of environment information about terminal size

Description

void ncurses_use_env ( bool flag)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_use_default_colors | 上一级 | ncurses_use_extended_names


ncurses_use_extended_names

(PHP 4 >= 4.1.0)

ncurses_use_extended_names -- Control use of extended names in terminfo descriptions

Description

int ncurses_use_extended_names ( bool flag)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_use_env | 上一级 | ncurses_vidattr


ncurses_vidattr

(PHP 4 >= 4.1.0)

ncurses_vidattr --

Description

int ncurses_vidattr ( int intarg)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_use_extended_names | 上一级 | ncurses_vline


ncurses_vline

(PHP 4 >= 4.2.0)

ncurses_vline -- Draw a vertical line at current position using an attributed character and max. n characters long

Description

int ncurses_vline ( int charattr, int n)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_vidattr | 上一级 | ncurses_wrefresh


ncurses_wrefresh

(PHP 4 >= 4.2.0)

ncurses_wrefresh -- Refresh window on terminal screen

Description

int ncurses_wrefresh ( resource window)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

undocumented

后退 | 起点 | 前进
ncurses_vline | 上一级 | Lotus Notes functions


Lotus Notes functions

PHP 手册
后退 前进

LXVII. Lotus Notes functions

介绍

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

目录
notes_body — Open the message msg_number in the specified mailbox on the specified server (leave serv
notes_copy_db — Create a note using form form_name
notes_create_db — Create a Lotus Notes database
notes_create_note — Create a note using form form_name
notes_drop_db — Drop a Lotus Notes database
notes_find_note — Returns a note id found in database_name. Specify the name of the note. Leaving type bla
notes_header_info — Open the message msg_number in the specified mailbox on the specified server (leave serv
notes_list_msgs — Returns the notes from a selected database_name
notes_mark_read — Mark a note_id as read for the User user_name
notes_mark_unread — Mark a note_id as unread for the User user_name
notes_nav_create — Create a navigator name, in database_name
notes_search — Find notes that match keywords in database_name
notes_unread — Returns the unread note id's for the current User user_name
notes_version — Get the version Lotus Notes

后退 | 起点 | 前进
ncurses_wrefresh | 上一级 | notes_body


notes_body

(PHP 4 >= 4.0.5)

notes_body -- Open the message msg_number in the specified mailbox on the specified server (leave serv

Description

array notes_body ( string server, string mailbox, int msg_number)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
Lotus Notes functions | 上一级 | notes_copy_db


notes_copy_db

(PHP 4 >= 4.0.5)

notes_copy_db -- Create a note using form form_name

Description

string notes_copy_db ( string from_database_name, string to_database_name)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
notes_body | 上一级 | notes_create_db


notes_create_db

(PHP 4 >= 4.0.5)

notes_create_db -- Create a Lotus Notes database

Description

bool notes_create_db ( string database_name)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
notes_copy_db | 上一级 | notes_create_note


notes_create_note

(PHP 4 >= 4.0.5)

notes_create_note -- Create a note using form form_name

Description

string notes_create_note ( string database_name, string form_name)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
notes_create_db | 上一级 | notes_drop_db


notes_drop_db

(PHP 4 >= 4.0.5)

notes_drop_db -- Drop a Lotus Notes database

Description

bool notes_drop_db ( string database_name)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
notes_create_note | 上一级 | notes_find_note


notes_find_note

(PHP 4 >= 4.0.5)

notes_find_note -- Returns a note id found in database_name. Specify the name of the note. Leaving type bla

Description

bool notes_find_note ( string database_name, string name [, string type])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
notes_drop_db | 上一级 | notes_header_info


notes_header_info

(PHP 4 >= 4.0.5)

notes_header_info -- Open the message msg_number in the specified mailbox on the specified server (leave serv

Description

object notes_header_info ( string server, string mailbox, int msg_number)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
notes_find_note | 上一级 | notes_list_msgs


notes_list_msgs

(PHP 4 >= 4.0.5)

notes_list_msgs -- Returns the notes from a selected database_name

Description

bool notes_list_msgs ( string db)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
notes_header_info | 上一级 | notes_mark_read


notes_mark_read

(PHP 4 >= 4.0.5)

notes_mark_read -- Mark a note_id as read for the User user_name

Description

string notes_mark_read ( string database_name, string user_name, string note_id)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
notes_list_msgs | 上一级 | notes_mark_unread


notes_mark_unread

(PHP 4 >= 4.0.5)

notes_mark_unread -- Mark a note_id as unread for the User user_name

Description

string notes_mark_unread ( string database_name, string user_name, string note_id)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
notes_mark_read | 上一级 | notes_nav_create


notes_nav_create

(PHP 4 >= 4.0.5)

notes_nav_create -- Create a navigator name, in database_name

Description

bool notes_nav_create ( string database_name, string name)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
notes_mark_unread | 上一级 | notes_search


notes_search

(PHP 4 >= 4.0.5)

notes_search -- Find notes that match keywords in database_name

Description

string notes_search ( string database_name, string keywords)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
notes_nav_create | 上一级 | notes_unread


notes_unread

(PHP 4 >= 4.0.5)

notes_unread -- Returns the unread note id's for the current User user_name

Description

string notes_unread ( string database_name, string user_name)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
notes_search | 上一级 | notes_version


notes_version

(PHP 4 >= 4.0.5)

notes_version -- Get the version Lotus Notes

Description

string notes_version ( string database_name)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
notes_unread | 上一级 | Unified ODBC functions


Unified ODBC functions

PHP 手册
后退 前进

LXVIII. Unified ODBC functions

介绍

In addition to normal ODBC support, the Unified ODBC functions in PHP allow you to access several databases that have borrowed the semantics of the ODBC API to implement their own API. Instead of maintaining multiple database drivers that were all nearly identical, these drivers have been unified into a single set of ODBC functions.

The following databases are supported by the Unified ODBC functions: Adabas D, IBM DB2, iODBC, Solid, and Sybase SQL Anywhere.

注: There is no ODBC involved when connecting to the above databases. The functions that you use to speak natively to them just happen to share the same names and syntax as the ODBC functions. The exception to this is iODBC. Building PHP with iODBC support enables you to use any ODBC-compliant drivers with your PHP applications. iODBC is maintained by OpenLink Software. More information on iODBC, as well as a HOWTO, is available at www.iodbc.org.

需求

To access any of the supported databases you need to have the required libraries installed.

安装

Please see the Database installation options chapter for more information about configuring PHP with these databases.

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. Unified ODBC Configuration Options

Name | Default | Changeable
odbc.default_db * | NULL | PHP_INI_ALL
odbc.default_user * | NULL | PHP_INI_ALL
odbc.default_pw * | NULL | PHP_INI_ALL
odbc.allow_persistent | "1" | PHP_INI_SYSTEM
odbc.check_persistent | "1" | PHP_INI_SYSTEM
odbc.max_persistent | "-1" | PHP_INI_SYSTEM
odbc.max_links | "-1" | PHP_INI_SYSTEM
odbc.defaultlrl | "4096" | PHP_INI_ALL
odbc.defaultbinmode | "1" | PHP_INI_ALL

注: Entries marked with * are not implemented yet.

For further details and definition of the PHP_INI_* constants see ini_set().

Here is a short explanation of the configuration directives.

odbc.default_db string

ODBC data source to use if none is specified in odbc_connect() or odbc_pconnect().

odbc.default_user string

User name to use if none is specified in odbc_connect() or odbc_pconnect().

odbc.default_pw string

Password to use if none is specified in odbc_connect() or odbc_pconnect().

odbc.allow_persistent boolean

Whether to allow persistent ODBC connections.

odbc.check_persistent boolean

Check that a connection is still valid before reuse.

odbc.max_persistent integer

The maximum number of persistent ODBC connections per process.

odbc.max_links integer

The maximum number of ODBC connections per process, including persistent connections.

odbc.defaultlrl integer

Handling of LONG fields. Specifies the number of bytes returned to variables.

odbc.defaultbinmode integer

Handling of binary data.

资源类型

该扩展模块未定义任何资源类型。

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

ODBC_TYPE (integer)

ODBC_BINMODE_PASSTHRU (integer)

ODBC_BINMODE_RETURN (integer)

ODBC_BINMODE_CONVERT (integer)

SQL_ODBC_CURSORS (integer)

SQL_CUR_USE_DRIVER (integer)

SQL_CUR_USE_IF_NEEDED (integer)

SQL_CUR_USE_ODBC (integer)

SQL_CONCURRENCY (integer)

SQL_CONCUR_READ_ONLY (integer)

SQL_CONCUR_LOCK (integer)

SQL_CONCUR_ROWVER (integer)

SQL_CONCUR_VALUES (integer)

SQL_CURSOR_TYPE (integer)

SQL_CURSOR_FORWARD_ONLY (integer)

SQL_CURSOR_KEYSET_DRIVEN (integer)

SQL_CURSOR_DYNAMIC (integer)

SQL_CURSOR_STATIC (integer)

SQL_KEYSET_SIZE (integer)

SQL_CHAR (integer)

SQL_VARCHAR (integer)

SQL_LONGVARCHAR (integer)

SQL_DECIMAL (integer)

SQL_NUMERIC (integer)

SQL_BIT (integer)

SQL_TINYINT (integer)

SQL_SMALLINT (integer)

SQL_INTEGER (integer)

SQL_BIGINT (integer)

SQL_REAL (integer)

SQL_FLOAT (integer)

SQL_DOUBLE (integer)

SQL_BINARY (integer)

SQL_VARBINARY (integer)

SQL_LONGVARBINARY (integer)

SQL_DATE (integer)

SQL_TIME (integer)

SQL_TIMESTAMP (integer)

SQL_TYPE_DATE (integer)

SQL_TYPE_TIME (integer)

SQL_TYPE_TIMESTAMP (integer)

SQL_BEST_ROWID (integer)

SQL_ROWVER (integer)

SQL_SCOPE_CURROW (integer)

SQL_SCOPE_TRANSACTION (integer)

SQL_SCOPE_SESSION (integer)

SQL_NO_NULLS (integer)

SQL_NULLABLE (integer)

SQL_INDEX_UNIQUE (integer)

SQL_INDEX_ALL (integer)

SQL_ENSURE (integer)

SQL_QUICK (integer)

目录
odbc_autocommit — Toggle autocommit behaviour
odbc_binmode — Handling of binary column data
odbc_close_all — Close all ODBC connections
odbc_close — Close an ODBC connection
odbc_columnprivileges — Returns a result identifier that can be used to fetch a list of columns and associated privileges
odbc_columns — Lists the column names in specified tables. Returns a result identifier containing the information.
odbc_commit — Commit an ODBC transaction
odbc_connect — Connect to a datasource
odbc_cursor — Get cursorname
odbc_data_source — Returns information about a current connection
odbc_do — Synonym for odbc_exec()
odbc_error — Get the last error code
odbc_errormsg — Get the last error message
odbc_exec — Prepare and execute a SQL statement
odbc_execute — Execute a prepared statement
odbc_fetch_array — Fetch a result row as an associative array
odbc_fetch_into — Fetch one result row into array
odbc_fetch_object — Fetch a result row as an object
odbc_fetch_row — Fetch a row
odbc_field_len — Get the length (precision) of a field
odbc_field_name — Get the columnname
odbc_field_num — Return column number
odbc_field_precision — Synonym for odbc_field_len()
odbc_field_scale — Get the scale of a field
odbc_field_type — Datatype of a field
odbc_foreignkeys — Returns a list of foreign keys in the specified table or a list of foreign keys in other tables that refer to the primary key in the specified table
odbc_free_result — Free resources associated with a result
odbc_gettypeinfo — Returns a result identifier containing information about data types supported by the data source.
odbc_longreadlen — Handling of LONG columns
odbc_next_result — Checks if multiple results are avaiable
odbc_num_fields — Number of columns in a result
odbc_num_rows — Number of rows in a result
odbc_pconnect — Open a persistent database connection
odbc_prepare — Prepares a statement for execution
odbc_primarykeys — Returns a result identifier that can be used to fetch the column names that comprise the primary key for a table
odbc_procedurecolumns — Retrieve information about parameters to procedures
odbc_procedures — Get the list of procedures stored in a specific data source. Returns a result identifier containing the information.
odbc_result_all — Print result as HTML table
odbc_result — Get result data
odbc_rollback — Rollback a transaction
odbc_setoption — Adjust ODBC settings. Returns FALSE if an error occurs, otherwise TRUE.
odbc_specialcolumns — Returns either the optimal set of columns that uniquely identifies a row in the table or columns that are automatically updated when any value in the row is updated by a transaction
odbc_statistics — Retrieve statistics about a table
odbc_tableprivileges — Lists tables and the privileges associated with each table
odbc_tables — Get the list of table names stored in a specific data source. Returns a result identifier containing the information.

后退 | 起点 | 前进
notes_version | 上一级 | odbc_autocommit


odbc_autocommit

(PHP 3>= 3.0.6, PHP 4 )

odbc_autocommit -- Toggle autocommit behaviour

Description

bool odbc_autocommit ( resource connection_id [, bool OnOff])

Without the OnOff parameter, this function returns auto-commit status for connection_id. TRUE is returned if auto-commit is on, FALSE if it is off or an error occurs.

If OnOff is TRUE, auto-commit is enabled, if it is FALSE auto-commit is disabled. Returns TRUE on success, FALSE on failure.

By default, auto-commit is on for a connection. Disabling auto-commit is equivalent with starting a transaction.

See also odbc_commit() and odbc_rollback().

后退 | 起点 | 前进
Unified ODBC functions | 上一级 | odbc_binmode


odbc_binmode

(PHP 3>= 3.0.6, PHP 4 )

odbc_binmode -- Handling of binary column data

Description

int odbc_binmode ( resource result_id, int mode)

(ODBC SQL types affected: BINARY, VARBINARY, LONGVARBINARY)

  • ODBC_BINMODE_PASSTHRU: Passthru BINARY data

  • ODBC_BINMODE_RETURN: Return as is

  • ODBC_BINMODE_CONVERT: Convert to char and return

When binary SQL data is converted to character C data, each byte (8 bits) of source data is represented as two ASCII characters. These characters are the ASCII character representation of the number in its hexadecimal form. For example, a binary 00000001 is converted to "01" and a binary 11111111 is converted to "FF".

表格 1. LONGVARBINARY handling

binmode | longreadlen | result
ODBC_BINMODE_PASSTHRU | 0 | passthru
ODBC_BINMODE_RETURN | 0 | passthru
ODBC_BINMODE_CONVERT | 0 | passthru
ODBC_BINMODE_PASSTHRU | 0 | passthru
ODBC_BINMODE_PASSTHRU | >0 | passthru
ODBC_BINMODE_RETURN | >0 | return as is
ODBC_BINMODE_CONVERT | >0 | return as char

If odbc_fetch_into() is used, passthru means that an empty string is returned for these columns.

If result_id is 0, the settings apply as default for new results.

注: Default for longreadlen is 4096 and binmode defaults to ODBC_BINMODE_RETURN. Handling of binary long columns is also affected by odbc_longreadlen()

后退 | 起点 | 前进
odbc_autocommit | 上一级 | odbc_close_all


odbc_close_all

(PHP 3>= 3.0.6, PHP 4 )

odbc_close_all -- Close all ODBC connections

Description

void odbc_close_all ( void)

odbc_close_all() will close down all connections to database server(s).

注: This function will fail if there are open transactions on a connection. This connection will remain open in this case.

后退 | 起点 | 前进
odbc_binmode | 上一级 | odbc_close


odbc_close

(PHP 3>= 3.0.6, PHP 4 )

odbc_close -- Close an ODBC connection

Description

void odbc_close ( resource connection_id)

odbc_close() will close down the connection to the database server associated with the given connection identifier.

注: This function will fail if there are open transactions on this connection. The connection will remain open in this case.

后退 | 起点 | 前进
odbc_close_all | 上一级 | odbc_columnprivileges


odbc_columnprivileges

(PHP 4 )

odbc_columnprivileges -- Returns a result identifier that can be used to fetch a list of columns and associated privileges

Description

int odbc_columnprivileges ( resource connection_id [, string qualifier [, string owner [, string table_name [, string column_name]]]])

Lists columns and associated privileges for the given table. Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER

  • TABLE_OWNER

  • TABLE_NAME

  • GRANTOR

  • GRANTEE

  • PRIVILEGE

  • IS_GRANTABLE

The result set is ordered by TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.

The column_name argument accepts search patterns ('%' to match zero or more characters and '_' to match a single character).

后退 | 起点 | 前进
odbc_close | 上一级 | odbc_columns


odbc_columns

(PHP 4 )

odbc_columns -- Lists the column names in specified tables. Returns a result identifier containing the information.

Description

int odbc_columns ( resource connection_id [, string qualifier [, string schema [, string table_name [, string column_name]]]])

Lists all columns in the requested range. Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER

  • TABLE_SCHEM

  • TABLE_NAME

  • COLUMN_NAME

  • DATA_TYPE

  • TYPE_NAME

  • PRECISION

  • LENGTH

  • SCALE

  • RADIX

  • NULLABLE

  • REMARKS

The result set is ordered by TABLE_QUALIFIER, TABLE_SCHEM and TABLE_NAME.

The schema, table_name and column_name arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).

See also odbc_columnprivileges() to retrieve associated privileges.

后退 | 起点 | 前进
odbc_columnprivileges | 上一级 | odbc_commit


odbc_commit

(PHP 3>= 3.0.6, PHP 4 )

odbc_commit -- Commit an ODBC transaction

Description

bool odbc_commit ( resource connection_id)

Returns: TRUE on success, FALSE on failure. All pending transactions on connection_id are committed.

后退 | 起点 | 前进
odbc_columns | 上一级 | odbc_connect


odbc_connect

(PHP 3>= 3.0.6, PHP 4 )

odbc_connect -- Connect to a datasource

Description

resource odbc_connect ( string dsn, string user, string password [, int cursor_type])

Returns an ODBC connection id or 0 (FALSE) on error.

The connection id returned by this functions is needed by other ODBC functions. You can have multiple connections open at once. The optional fourth parameter sets the type of cursor to be used for this connection. This parameter is not normally needed, but can be useful for working around problems with some ODBC drivers.

With some ODBC drivers, executing a complex stored procedure may fail with an error similar to: "Cannot open a cursor on a stored procedure that has anything other than a single select statement in it". Using SQL_CUR_USE_ODBC may avoid that error. Also, some drivers don't support the optional row_number parameter in odbc_fetch_row(). SQL_CUR_USE_ODBC might help in that case, too.

The following constants are defined for cursortype:

  • SQL_CUR_USE_IF_NEEDED

  • SQL_CUR_USE_ODBC

  • SQL_CUR_USE_DRIVER

  • SQL_CUR_DEFAULT

For persistent connections see odbc_pconnect().

后退 | 起点 | 前进
odbc_commit | 上一级 | odbc_cursor


odbc_cursor

(PHP 3>= 3.0.6, PHP 4 )

odbc_cursor -- Get cursorname

Description

string odbc_cursor ( resource result_id)

odbc_cursor will return a cursorname for the given result_id.

后退 | 起点 | 前进
odbc_connect | 上一级 | odbc_data_source


odbc_data_source

(PHP 4 CVS only)

odbc_data_source -- Returns information about a current connection

Description

resource odbc_data_source ( resource connection_id, constant fetch_type)

Returns FALSE on error, and an array upon success.

This function will return information about the active connection following the information from within the DSN. The connection_id is required to be a valid ODBC connection. The fetch_type can be one of two constant types: SQL_FETCH_FIRST, SQL_FETCH_NEXT. Use SQL_FETCH_FIRST the first time this function is called, thereafter use the SQL_FETCH_NEXT.

后退 | 起点 | 前进
odbc_cursor | 上一级 | odbc_do


odbc_do

(PHP 3>= 3.0.6, PHP 4 )

odbc_do -- Synonym for odbc_exec()

Description

resource odbc_do ( resource conn_id, string query)

odbc_do() will execute a query on the given connection.

后退 | 起点 | 前进
odbc_data_source | 上一级 | odbc_error


odbc_error

(PHP 4 >= 4.0.5)

odbc_error -- Get the last error code

Description

string odbc_error ( [resource connection_id])

Returns a six-digit ODBC state, or an empty string if there has been no errors. If connection_id is specified, the last state of that connection is returned, else the last state of any connection is returned.

See also: odbc_errormsg() and odbc_exec().

后退 | 起点 | 前进
odbc_do | 上一级 | odbc_errormsg


odbc_errormsg

(PHP 4 >= 4.0.5)

odbc_errormsg -- Get the last error message

Description

string odbc_errormsg ( [resource connection_id])

Returns a string containing the last ODBC error message, or an empty string if there has been no errors. If connection_id is specified, the last state of that connection is returned, else the last state of any connection is returned.

See also: odbc_error() and odbc_exec().

后退 | 起点 | 前进
odbc_error | 上一级 | odbc_exec


odbc_exec

(PHP 3>= 3.0.6, PHP 4 )

odbc_exec -- Prepare and execute a SQL statement

Description

resource odbc_exec ( resource connection_id, string query_string)

Returns FALSE on error. Returns an ODBC result identifier if the SQL command was executed successfully.

odbc_exec() will send an SQL statement to the database server specified by connection_id. This parameter must be a valid identifier returned by odbc_connect() or odbc_pconnect().

See also: odbc_prepare() and odbc_execute() for multiple execution of SQL statements.

后退 | 起点 | 前进
odbc_errormsg | 上一级 | odbc_execute


odbc_execute

(PHP 3>= 3.0.6, PHP 4 )

odbc_execute -- Execute a prepared statement

Description

resource odbc_execute ( resource result_id [, array parameters_array])

Executes a statement prepared with odbc_prepare(). Returns TRUE on successful execution; FALSE otherwise. The array parameters_array only needs to be given if you really have parameters in your statement.

Parameters in parameter_array will be substituted for placeholders in the prepared statement in order.

Any parameters in parameter_array which start and end with single quotes will be taken as the name of a file to read and send to the database server as the data for the appropriate placeholder.

注: As of PHP 4.1.1, this file reading functionality has the following restrictions:

  • File reading is not subject to any safe mode or safe mode restrictions. This is fixed in PHP 4.2.0.

  • Remote files are not supported.

  • If you wish to store a string which actually begins and ends with single quotes, you must escape them or add a space or other non-single-quote character to the beginning or end of the parameter, which will prevent the parameter's being taken as a file name. If this is not an option, then you must use another mechanism to store the string, such as executing the query directly with odbc_exec()).

后退 | 起点 | 前进
odbc_exec | 上一级 | odbc_fetch_array


odbc_fetch_array

(PHP 4 >= 4.0.2)

odbc_fetch_array -- Fetch a result row as an associative array

Description

array odbc_fetch_array ( resource result [, int rownumber])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
odbc_execute | 上一级 | odbc_fetch_into


odbc_fetch_into

(PHP 3>= 3.0.6, PHP 4 )

odbc_fetch_into -- Fetch one result row into array

Description

bool odbc_fetch_into ( resource result_id [, int rownumber, array result_array])

resource odbc_fetch_into ( resource result_id, array result_array [, int rownumber])

Returns the number of columns in the result; FALSE on error. result_array must be passed by reference, but it can be of any type since it will be converted to type array. The array will contain the column values starting at array index 0.

As of PHP 4.0.5 the result_array does not need to be passed by reference any longer.

As of PHP 4.0.6 the rownumber cannot be passed as a constant, but rather as a variable.

As of PHP 4.2.0 the result_array and rownumber have been swapped. This allows the rownumber to be a constant again. This change will also be the last one to this function.

例子 1. odbc_fetch_into() pre 4.0.6 example

$rc = odbc_fetch_into($res_id, $my_array);

or

$rc = odbc_fetch_into($res_id, $row, $my_array);

$rc = odbc_fetch_into($res_id, 1, $my_array);

例子 2. odbc_fetch_into() 4.0.6 example

$rc = odbc_fetch_into($res_id, $my_array);

or

$row = 1;
$rc = odbc_fetch_into($res_id, $row, $my_array);

例子 3. odbc_fetch_into() 4.2.0 example

$rc = odbc_fetch_into($res_id, $my_array);

or

$rc = odbc_fetch_into($res_id,$my_array, 2);

后退 | 起点 | 前进
odbc_fetch_array | 上一级 | odbc_fetch_object


odbc_fetch_object

(PHP 4 >= 4.0.2)

odbc_fetch_object -- Fetch a result row as an object

Description

object odbc_fetch_object ( resource result [, int rownumber])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
odbc_fetch_into | 上一级 | odbc_fetch_row


odbc_fetch_row

(PHP 3>= 3.0.6, PHP 4 )

odbc_fetch_row -- Fetch a row

Description

bool odbc_fetch_row ( resource result_id [, int row_number])

If odbc_fetch_row() was succesful (there was a row), TRUE is returned. If there are no more rows, FALSE is returned.

odbc_fetch_row() fetches a row of the data that was returned by odbc_do() / odbc_exec(). After odbc_fetch_row() is called, the fields of that row can be accessed with odbc_result().

If row_number is not specified, odbc_fetch_row() will try to fetch the next row in the result set. Calls to odbc_fetch_row() with and without row_number can be mixed.

To step through the result more than once, you can call odbc_fetch_row() with row_number 1, and then continue doing odbc_fetch_row() without row_number to review the result. If a driver doesn't support fetching rows by number, the row_number parameter is ignored.

后退 | 起点 | 前进
odbc_fetch_object | 上一级 | odbc_field_len


odbc_field_len

(PHP 3>= 3.0.6, PHP 4 )

odbc_field_len -- Get the length (precision) of a field

Description

int odbc_field_len ( resource result_id, int field_number)

odbc_field_len() will return the length of the field referecend by number in the given ODBC result identifier. Field numbering starts at 1.

See also: odbc_field_scale() to get the scale of a floating point number.

后退 | 起点 | 前进
odbc_fetch_row | 上一级 | odbc_field_name


odbc_field_name

(PHP 3>= 3.0.6, PHP 4 )

odbc_field_name -- Get the columnname

Description

string odbc_field_name ( resource result_id, int field_number)

odbc_field_name() will return the name of the field occupying the given column number in the given ODBC result identifier. Field numbering starts at 1. FALSE is returned on error.

后退 | 起点 | 前进
odbc_field_len | 上一级 | odbc_field_num


odbc_field_num

(PHP 3>= 3.0.6, PHP 4 )

odbc_field_num -- Return column number

Description

int odbc_field_num ( resource result_id, string field_name)

odbc_field_num() will return the number of the column slot that corresponds to the named field in the given ODBC result identifier. Field numbering starts at 1. FALSE is returned on error.

后退 | 起点 | 前进
odbc_field_name | 上一级 | odbc_field_precision


odbc_field_precision

(PHP 4 )

odbc_field_precision -- Synonym for odbc_field_len()

Description

string odbc_field_precision ( resource result_id, int field_number)

odbc_field_precision() will return the precision of the field referecend by number in the given ODBC result identifier.

See also: odbc_field_scale() to get the scale of a floating point number.

后退 | 起点 | 前进
odbc_field_num | 上一级 | odbc_field_scale


odbc_field_scale

(PHP 4 )

odbc_field_scale -- Get the scale of a field

Description

string odbc_field_scale ( resource result_id, int field_number)

odbc_field_precision() will return the scale of the field referecend by number in the given ODBC result identifier.

后退 | 起点 | 前进
odbc_field_precision | 上一级 | odbc_field_type


odbc_field_type

(PHP 3>= 3.0.6, PHP 4 )

odbc_field_type -- Datatype of a field

Description

string odbc_field_type ( resource result_id, int field_number)

odbc_field_type() will return the SQL type of the field referecend by number in the given ODBC result identifier. Field numbering starts at 1.

后退 | 起点 | 前进
odbc_field_scale | 上一级 | odbc_foreignkeys


odbc_foreignkeys

(PHP 4 )

odbc_foreignkeys -- Returns a list of foreign keys in the specified table or a list of foreign keys in other tables that refer to the primary key in the specified table

Description

resource odbc_foreignkeys ( resource connection_id, string pk_qualifier, string pk_owner, string pk_table, string fk_qualifier, string fk_owner, string fk_table)

odbc_foreignkeys() retrieves information about foreign keys. Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • PKTABLE_QUALIFIER

  • PKTABLE_OWNER

  • PKTABLE_NAME

  • PKCOLUMN_NAME

  • FKTABLE_QUALIFIER

  • FKTABLE_OWNER

  • FKTABLE_NAME

  • FKCOLUMN_NAME

  • KEY_SEQ

  • UPDATE_RULE

  • DELETE_RULE

  • FK_NAME

  • PK_NAME

If pk_table contains a table name, odbc_foreignkeys() returns a result set containing the primary key of the specified table and all of the foreign keys that refer to it.

If fk_table contains a table name, odbc_foreignkeys() returns a result set containing all of the foreign keys in the specified table and the primary keys (in other tables) to which they refer.

If both pk_table and fk_table contain table names, odbc_foreignkeys() returns the foreign keys in the table specified in fk_table that refer to the primary key of the table specified in pk_table. This should be one key at most.

后退 | 起点 | 前进
odbc_field_type | 上一级 | odbc_free_result


odbc_free_result

(PHP 3>= 3.0.6, PHP 4 )

odbc_free_result -- Free resources associated with a result

Description

bool odbc_free_result ( resource result_id)

Always returns TRUE.

odbc_free_result() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script is finished. But, if you are sure you are not going to need the result data anymore in a script, you may call odbc_free_result(), and the memory associated with result_id will be freed.

注: If auto-commit is disabled (see odbc_autocommit()) and you call odbc_free_result() before commiting, all pending transactions are rolled back.

后退 | 起点 | 前进
odbc_foreignkeys | 上一级 | odbc_gettypeinfo


odbc_gettypeinfo

(PHP 4 )

odbc_gettypeinfo -- Returns a result identifier containing information about data types supported by the data source.

Description

int odbc_gettypeinfo ( resource connection_id [, int data_type])

Retrieves information about data types supported by the data source. Returns an ODBC result identifier or FALSE on failure. The optional argument data_type can be used to restrict the information to a single data type.

The result set has the following columns:

  • TYPE_NAME

  • DATA_TYPE

  • PRECISION

  • LITERAL_PREFIX

  • LITERAL_SUFFIX

  • CREATE_PARAMS

  • NULLABLE

  • CASE_SENSITIVE

  • SEARCHABLE

  • UNSIGNED_ATTRIBUTE

  • MONEY

  • AUTO_INCREMENT

  • LOCAL_TYPE_NAME

  • MINIMUM_SCALE

  • MAXIMUM_SCALE

The result set is ordered by DATA_TYPE and TYPE_NAME.

后退 | 起点 | 前进
odbc_free_result | 上一级 | odbc_longreadlen


odbc_longreadlen

(PHP 3>= 3.0.6, PHP 4 )

odbc_longreadlen -- Handling of LONG columns

Description

int odbc_longreadlen ( resource result_id, int length)

(ODBC SQL types affected: LONG, LONGVARBINARY) The number of bytes returned to PHP is controled by the parameter length. If it is set to 0, Long column data is passed thru to the client.

注: Handling of LONGVARBINARY columns is also affected by odbc_binmode().

后退 | 起点 | 前进
odbc_gettypeinfo | 上一级 | odbc_next_result


odbc_next_result

(PHP 4 >= 4.0.5)

odbc_next_result -- Checks if multiple results are avaiable

Description

bool odbc_next_result ( resource result_id)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
odbc_longreadlen | 上一级 | odbc_num_fields


odbc_num_fields

(PHP 3>= 3.0.6, PHP 4 )

odbc_num_fields -- Number of columns in a result

Description

int odbc_num_fields ( resource result_id)

odbc_num_fields() will return the number of fields (columns) in an ODBC result. This function will return -1 on error. The argument is a valid result identifier returned by odbc_exec().

后退 | 起点 | 前进
odbc_next_result | 上一级 | odbc_num_rows


odbc_num_rows

(PHP 3>= 3.0.6, PHP 4 )

odbc_num_rows -- Number of rows in a result

Description

int odbc_num_rows ( resource result_id)

odbc_num_rows() will return the number of rows in an ODBC result. This function will return -1 on error. For INSERT, UPDATE and DELETE statements odbc_num_rows() returns the number of rows affected. For a SELECT clause this can be the number of rows available.

Note: Using odbc_num_rows() to determine the number of rows available after a SELECT will return -1 with many drivers.

后退 | 起点 | 前进
odbc_num_fields | 上一级 | odbc_pconnect


odbc_pconnect

(PHP 3>= 3.0.6, PHP 4 )

odbc_pconnect -- Open a persistent database connection

Description

int odbc_pconnect ( string dsn, string user, string password [, int cursor_type])

Returns an ODBC connection id or 0 (FALSE) on error. This function is much like odbc_connect(), except that the connection is not really closed when the script has finished. Future requests for a connection with the same dsn, user, password combination (via odbc_connect() and odbc_pconnect()) can reuse the persistent connection.

注: Persistent connections have no effect if PHP is used as a CGI program.

For information about the optional cursor_type parameter see the odbc_connect() function. For more information on persistent connections, refer to the PHP FAQ.

后退 | 起点 | 前进
odbc_num_rows | 上一级 | odbc_prepare


odbc_prepare

(PHP 3>= 3.0.6, PHP 4 )

odbc_prepare -- Prepares a statement for execution

Description

resource odbc_prepare ( resource connection_id, string query_string)

Returns FALSE on error.

Returns an ODBC result identifier if the SQL command was prepared successfully. The result identifier can be used later to execute the statement with odbc_execute().

后退 | 起点 | 前进
odbc_pconnect | 上一级 | odbc_primarykeys


odbc_primarykeys

(PHP 4 )

odbc_primarykeys -- Returns a result identifier that can be used to fetch the column names that comprise the primary key for a table

Description

resource odbc_primarykeys ( resource connection_id, string qualifier, string owner, string table)

Returns the column names that comprise the primary key for a table. Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER

  • TABLE_OWNER

  • TABLE_NAME

  • COLUMN_NAME

  • KEY_SEQ

  • PK_NAME

后退 | 起点 | 前进
odbc_prepare | 上一级 | odbc_procedurecolumns


odbc_procedurecolumns

(PHP 4 )

odbc_procedurecolumns -- Retrieve information about parameters to procedures

Description

resource odbc_procedurecolumns ( resource connection_id [, string qualifier [, string owner [, string proc [, string column]]]])

Returns the list of input and output parameters, as well as the columns that make up the result set for the specified procedures. Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • PROCEDURE_QUALIFIER

  • PROCEDURE_OWNER

  • PROCEDURE_NAME

  • COLUMN_NAME

  • COLUMN_TYPE

  • DATA_TYPE

  • TYPE_NAME

  • PRECISION

  • LENGTH

  • SCALE

  • RADIX

  • NULLABLE

  • REMARKS

The result set is ordered by PROCEDURE_QUALIFIER, PROCEDURE_OWNER, PROCEDURE_NAME and COLUMN_TYPE.

The owner, proc and column arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).

后退 | 起点 | 前进
odbc_primarykeys | 上一级 | odbc_procedures


odbc_procedures

(PHP 4 )

odbc_procedures -- Get the list of procedures stored in a specific data source. Returns a result identifier containing the information.

Description

resource odbc_procedures ( resource connection_id [, string qualifier [, string owner [, string name]]])

Lists all procedures in the requested range. Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • PROCEDURE_QUALIFIER

  • PROCEDURE_OWNER

  • PROCEDURE_NAME

  • NUM_INPUT_PARAMS

  • NUM_OUTPUT_PARAMS

  • NUM_RESULT_SETS

  • REMARKS

  • PROCEDURE_TYPE

The owner and name arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).

后退 | 起点 | 前进
odbc_procedurecolumns | 上一级 | odbc_result_all


odbc_result_all

(PHP 3>= 3.0.6, PHP 4 )

odbc_result_all -- Print result as HTML table

Description

int odbc_result_all ( resource result_id [, string format])

Returns the number of rows in the result or FALSE on error.

odbc_result_all() will print all rows from a result identifier produced by odbc_exec(). The result is printed in HTML table format. With the optional string argument format, additional overall table formatting can be done.

后退 | 起点 | 前进
odbc_procedures | 上一级 | odbc_result


odbc_result

(PHP 3>= 3.0.6, PHP 4 )

odbc_result -- Get result data

Description

string odbc_result ( resource result_id, mixed field)

Returns the contents of the field.

field can either be an integer containing the column number of the field you want; or it can be a string containing the name of the field. For example:

$item_3 = odbc_result ($Query_ID, 3);
$item_val = odbc_result ($Query_ID, "val");

The first call to odbc_result() returns the value of the third field in the current record of the query result. The second function call to odbc_result() returns the value of the field whose field name is "val" in the current record of the query result. An error occurs if a column number parameter for a field is less than one or exceeds the number of columns (or fields) in the current record. Similarly, an error occurs if a field with a name that is not one of the fieldnames of the table(s) that is(are) being queried.

Field indices start from 1. Regarding the way binary or long column data is returned refer to odbc_binmode() and odbc_longreadlen().

后退 | 起点 | 前进
odbc_result_all | 上一级 | odbc_rollback


odbc_rollback

(PHP 3>= 3.0.6, PHP 4 )

odbc_rollback -- Rollback a transaction

Description

int odbc_rollback ( resource connection_id)

Rolls back all pending statements on connection_id. Returns TRUE on success, FALSE on failure.

后退 | 起点 | 前进
odbc_result | 上一级 | odbc_setoption


odbc_setoption

(PHP 3>= 3.0.6, PHP 4 )

odbc_setoption -- Adjust ODBC settings. Returns FALSE if an error occurs, otherwise TRUE.

Description

int odbc_setoption ( resource id, int function, int option, int param)

This function allows fiddling with the ODBC options for a particular connection or query result. It was written to help find work arounds to problems in quirky ODBC drivers. You should probably only use this function if you are an ODBC programmer and understand the effects the various options will have. You will certainly need a good ODBC reference to explain all the different options and values that can be used. Different driver versions support different options.

Because the effects may vary depending on the ODBC driver, use of this function in scripts to be made publicly available is strongly discouraged. Also, some ODBC options are not available to this function because they must be set before the connection is established or the query is prepared. However, if on a particular job it can make PHP work so your boss doesn't tell you to use a commercial product, that's all that really matters.

id is a connection id or result id on which to change the settings.For SQLSetConnectOption(), this is a connection id. For SQLSetStmtOption(), this is a result id.

Function is the ODBC function to use. The value should be 1 for SQLSetConnectOption() and 2 for SQLSetStmtOption().

Parameter option is the option to set.

Parameter param is the value for the given option.

例子 1. ODBC Setoption Examples

// 1. Option 102 of SQLSetConnectOption() is SQL_AUTOCOMMIT.
//    Value 1 of SQL_AUTOCOMMIT is SQL_AUTOCOMMIT_ON.
//    This example has the same effect as
//    odbc_autocommit($conn, true);

odbc_setoption ($conn, 1, 102, 1);

// 2. Option 0 of SQLSetStmtOption() is SQL_QUERY_TIMEOUT.
//    This example sets the query to timeout after 30 seconds.

$result = odbc_prepare ($conn, $sql);
odbc_setoption ($result, 2, 0, 30);
odbc_execute ($result);

后退 | 起点 | 前进
odbc_rollback | 上一级 | odbc_specialcolumns


odbc_specialcolumns

(PHP 4 )

odbc_specialcolumns -- Returns either the optimal set of columns that uniquely identifies a row in the table or columns that are automatically updated when any value in the row is updated by a transaction

Description

resource odbc_specialcolumns ( resource connection_id, int type, string qualifier, string owner, string table, int scope, int nullable)

When the type argument is SQL_BEST_ROWID, odbc_specialcolumns() returns the column or columns that uniquely identify each row in the table.

When the type argument is SQL_ROWVER, odbc_specialcolumns() returns the optimal column or set of columns that, by retrieving values from the column or columns, allows any row in the specified table to be uniquely identified.

Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • SCOPE

  • COLUMN_NAME

  • DATA_TYPE

  • TYPE_NAME

  • PRECISION

  • LENGTH

  • SCALE

  • PSEUDO_COLUMN

The result set is ordered by SCOPE.

后退 | 起点 | 前进
odbc_setoption | 上一级 | odbc_statistics


odbc_statistics

(PHP 4 )

odbc_statistics -- Retrieve statistics about a table

Description

resource odbc_statistics ( resource connection_id, string qualifier, string owner, string table_name, int unique, int accuracy)

Get statistics about a table and it's indexes. Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER

  • TABLE_OWNER

  • TABLE_NAME

  • NON_UNIQUE

  • INDEX_QUALIFIER

  • INDEX_NAME

  • TYPE

  • SEQ_IN_INDEX

  • COLUMN_NAME

  • COLLATION

  • CARDINALITY

  • PAGES

  • FILTER_CONDITION

The result set is ordered by NON_UNIQUE, TYPE, INDEX_QUALIFIER, INDEX_NAME and SEQ_IN_INDEX.

后退 | 起点 | 前进
odbc_specialcolumns | 上一级 | odbc_tableprivileges


odbc_tableprivileges

(PHP 4 )

odbc_tableprivileges -- Lists tables and the privileges associated with each table

Description

int odbc_tableprivileges ( resource connection_id [, string qualifier [, string owner [, string name]]])

Lists tables in the requested range and the privileges associated with each table. Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER

  • TABLE_OWNER

  • TABLE_NAME

  • GRANTOR

  • GRANTEE

  • PRIVILEGE

  • IS_GRANTABLE

The result set is ordered by TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.

The owner and name arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).

后退 | 起点 | 前进
odbc_statistics | 上一级 | odbc_tables


odbc_tables

(PHP 3>= 3.0.17, PHP 4 )

odbc_tables -- Get the list of table names stored in a specific data source. Returns a result identifier containing the information.

Description

int odbc_tables ( resource connection_id [, string qualifier [, string owner [, string name [, string types]]]])

Lists all tables in the requested range. Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER

  • TABLE_OWNER

  • TABLE_NAME

  • TABLE_TYPE

  • REMARKS

The result set is ordered by TABLE_TYPE, TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.

The owner and name arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).

To support enumeration of qualifiers, owners, and table types, the following special semantics for the qualifier, owner, name, and table_type are available:

  • If qualifier is a single percent character (%) and owner and name are empty strings, then the result set contains a list of valid qualifiers for the data source. (All columns except the TABLE_QUALIFIER column contain NULLs.)

  • If owner is a single percent character (%) and qualifier and name are empty strings, then the result set contains a list of valid owners for the data source. (All columns except the TABLE_OWNER column contain NULLs.)

  • If table_type is a single percent character (%) and qualifier, owner and name are empty strings, then the result set contains a list of valid table types for the data source. (All columns except the TABLE_TYPE column contain NULLs.)

If table_type is not an empty string, it must contain a list of comma-separated values for the types of interest; each value may be enclosed in single quotes (') or unquoted. For example, "'TABLE','VIEW'" or "TABLE, VIEW". If the data source does not support a specified table type, odbc_tables() does not return any results for that type.

See also odbc_tableprivileges() to retrieve associated privileges.

后退 | 起点 | 前进
odbc_tableprivileges | 上一级 | Object Aggregation/Composition Functions


Object Aggregation/Composition Functions

PHP 手册
后退 前进

LXIX. Object Aggregation/Composition Functions

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

介绍

In Object Oriented Programming, it is common to see the composition of simple classes (and/or instances) into a more complex one. This is a flexible strategy for building complicated objects and object hierachies and can function as a dynamic alternative to multiple inheritance. There are two ways to perform class (and/or object) composition depending on the relationship between the composed elements: Association and Aggregation.

An Association is a composition of independently constructed and externally visible parts. When we associate classes or objects, each one keeps a reference to the ones it is associated with. When we associate classes statically, one class will contain a reference to an instance of the other class. For example:

例子 1. Class association

class DateTime {

   function DateTime() {
       // empty constructor
   }

   function now() {
       return date("Y-m-d H:i:s");
   }
}

class Report {
   var $_dt = new DateTime();
   // more properties ...

   function Report() {
       // initialization code ...
   }

   function generateReport() {
       $dateTime = $_dt->now();
       // more code ...
   }

   // more methods ...
}

$rep = new Report();
We can also associate instances at runtime by passing a reference in a constructor (or any othe method), which allow us to dynamically change the association relationship between objects. We will modify the example above to illustrate this point:

例子 2. Object association

class DateTime {
   // same as previous example
}

class DateTimePlus {
   var $_format;

   function DateTimePlus($format="Y-m-d H:i:s") {
       $this->_format = $format
   }

   function now() {
       return date($this->_format);
   }
}

class Report {
   var $_dt;    // we'll keep the reference to DateTime here
   // more properties ...

   function Report() {
       // do some initialization
   }

   function setDateTime(&$dt) {
       $this->_dt =& $dt;
   }

   function generateReport() {
       $dateTime = $_dt->now();
       // more code ...
   }

   // more methods ...
}

$rep = new Report();
$dt = new DateTime();
$dtp = new DateTimePlus("l, F j, Y (h:i:s a, T)");

// generate report with simple date for web display
$rep->setDateTime(&$dt);
echo $rep->generateReport();

// later on in the code ...

// generate report with fancy date
$rep->setDateTime(&$dtp);
$output = $rep->generateReport();
// save $output in database
// ... etc ...

Aggregation, on the other hand, implies encapsulation (hidding) of the parts of the composition. We can aggregate classes by using a (static) inner class (PHP does not yet support inner classes), in this case the aggregated class definition is not accessible, except through the class that contains it. The aggregation of instances (object aggregation) involves the dynamic creation of subobjects inside an object, in the process, expanding the properties and methods of that object.

Object aggregation is a natural way of representing a whole-part relationship, (for example, molecules are aggregates of atoms), or can be used to obtain an effect equivalent to multiple inheritance, without having to permanently bind a subclass to two or more parent classes and their interfaces. In fact object aggregation can be more flexible, in which we can select what methods or properties to "inherit" in the aggregated object.

范例

We define 3 classes, each implementing a different storage method:

例子 3. storage_classes.inc

<?php
class FileStorage {
    var $data;

    function FileStorage($data) {
        $this->data = $data;
    }
    function write($name) {
        $fp = fopen(name, "w");
        fwrite($fp, $this->data);
        fclose($data);
    }
}

class WDDXStorage {
    var $data;
    var $version = "1.0";
    var $_id; // "private" variable

    function WDDXStorage($data) {
        $this->data = $data;
        $this->_id = $this->_genID();
    }

    function store() {
        if ($this->_id) {
            $pid = wddx_packet_start($this->_id);
            wddx_add_vars($pid, "this->data");
            $packet = wddx_packet_end($pid);
        } else {
            $packet = wddx_serialize_value($this->data);
        }
        $dbh = dba_open("varstore", "w", "gdbm");
        dba_insert(md5(uniqid("",true)), $packet, $dbh);
        dba_close($dbh);
    }

    // a private method
    function _genID() {
        return md5(uniqid(rand(),true));
    }
}

class DBStorage {
    var $data;
    var $dbtype = "mysql";

    function DBStorage($data) {
        $this->data = $data;
    }

    function save() {
        $dbh = mysql_connect();
        mysql_select_db("storage", $dbh);
        $serdata = serialize($this->data);
        mysql_query("insert into vars ('$serdata',now())", $dbh);
        mysql_close($dbh);
    }
}

?>

We then instantiate a couple of objects from the defined classes, and perform some aggregations and deaggregations, printing some object information along the way:

例子 4. test_aggregation.php

<?php
include "storageclasses.inc";

// some utilty functions

function p_arr($arr) {
    foreach($arr as $k=>$v)
        $out[] = "\t$k => $v";
    return implode("\n", $out);
}

function object_info($obj) {
    $out[] = "Class: ".get_class($obj);
    foreach(get_object_vars($obj) as $var=>$val)
        if (is_array($val))
            $out[] = "property: $var (array)\n".p_arr($val);
        else
            $out[] = "property: $var = $val";
    foreach(get_class_methods($obj) as $method)
        $out[] = "method: $method";
    return implode("\n", $out);
}

$data = array(M_PI, "kludge != cruft");

// we create some basic objects
$fs = new FileStorage($data);
$ws = new WDDXStorage($data);

// print information on the objects
echo "\$fs object\n";
echo object_info($fs)."\n";
echo "\n\$ws object\n";
echo object_info($ws)."\n";

// do some aggregation

echo "\nLet's aggregate \$fs to the WDDXStorage class\n";
aggregate($fs, "WDDXStorage");
echo "\$fs object\n";
echo object_info($fs)."\n";

echo "\nNow let us aggregate it to the DBStorage class\n";
aggregate($fs, "DBStorage");
echo "\$fs object\n";
echo object_info($fs)."\n";

echo "\nAnd finally deaggregate WDDXStorage\n";
deaggregate($fs, "WDDXStorage");
echo "\$fs object\n";
echo object_info($fs)."\n";

?>

We will now consider the output to understand some of the side-effects and limitation of object aggregation in PHP. First, the newly created $fs and $ws objects give the expected output (according to their respective class declaration). Note that for the purposes of object aggregation, private elements of a class/object begin with an underscore character ("_"), even though there is not real distinction between public and private class/object elements in PHP.

$fs object
Class: filestorage
property: data (array)
    0 => 3.1415926535898
    1 => kludge != cruft
method: filestorage
method: write

$ws object
Class: wddxstorage
property: data (array)
    0 => 3.1415926535898
    1 => kludge != cruft
property: version = 1.0
property: _id = ID::9bb2b640764d4370eb04808af8b076a5
method: wddxstorage
method: store
method: _genid

We then aggregate $fs with the WDDXStorage class, and print out the object information. We can see now that even though nominally the $fs object is still of FileStorage, it now has the property $version, and the method store(), both defined in WDDXStorage. One important thing to note is that it has not aggregated the private elements defined in the class, which are present in the $ws object. Also absent is the constructor from WDDXStorage, which will not be logical to aggegate.

Let's aggregate $fs to the WDDXStorage class
$fs object
Class: filestorage
property: data (array)
    0 => 3.1415926535898
    1 => kludge != cruft
property: version = 1.0
method: filestorage
method: write
method: store

The proccess of aggregation is cummulative, so when we aggregate $fs with the class DBStorage, generating an object that can use the storage methods of all the defined classes.

Now let us aggregate it to the DBStorage class
$fs object
Class: filestorage
property: data (array)
    0 => 3.1415926535898
    1 => kludge != cruft
property: version = 1.0
property: dbtype = mysql
method: filestorage
method: write
method: store
method: save

Finally, the same way we aggregated properties and methods dynamically, we can also deaggregate them from the object. So, if we deaggregate the class WDDXStorage from $fs, we will obtain:

And deaggregate the WDDXStorage methods and properties
$fs object
Class: filestorage
property: data (array)
    0 => 3.1415926535898
    1 => kludge != cruft
property: dbtype = mysql
method: filestorage
method: write
method: save

One point that we have not mentioned above, is that the process of aggregation will not override existing properties or methods in the objects. For example, the class FileStorage defines a $data property, and the class WDDXStorage also defines a similar property which will not override the one in the object acquired during instantiation from the class FileStorage.

目录
aggregate_methods_by_list — selective dynamic class methods aggregation to an object
aggregate_methods_by_regexp — selective class methods aggregation to an object using a regular expression
aggregate_methods — dynamic class and object aggregation of methods
aggregate_properties_by_list — selective dynamic class properties aggregation to an object
aggregate_properties_by_regexp — selective class properties aggregation to an object using a regular expression
aggregate_properties — dynamic aggregation of class properties to an object
aggregate — dynamic class and object aggregation of methods and properties
aggregation_info — returns an associative array of the methods and properties from each class that has been aggregated to the object.
deaggregate — removes the aggregated methods and properties from an object

后退 | 起点 | 前进
odbc_tables | 上一级 | aggregate_methods_by_list


aggregate_methods_by_list

(PHP 4 >= 4.2.0)

aggregate_methods_by_list -- selective dynamic class methods aggregation to an object

Description

void aggregate_methods_by_list ( object object, string class_name, array methods_list [, boolean exclude])

Aggregates methods from a class to an existing object using a list of method names. The optional paramater exclude is used to decide whether the list contains the names of methods to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).

The class constructor or methods whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

See also
aggregate(),
aggregate_info(),
aggregate_methods(),
aggregate_methods_by_regexp(),
aggregate_properties(),
aggregate_properties_by_list(),
aggregate_properties_by_regexp(),
deaggregate()

后退 | 起点 | 前进
Object Aggregation/Composition Functions | 上一级 | aggregate_methods_by_regexp


aggregate_methods_by_regexp

(PHP 4 >= 4.2.0)

aggregate_methods_by_regexp -- selective class methods aggregation to an object using a regular expression

Description

void aggregate_methods_by_regexp ( object object, string class_name, string regexp [, boolean exclude])

Aggregates methods from a class to an existing object using a regular expresion to match method names. The optional paramater exclude is used to decide whether the regular expression will select the names of methods to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).

The class constructor or methods whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

See also
aggregate(),
aggregate_info(),
aggregate_methods(),
aggregate_methods_by_list(),
aggregate_properties(),
aggregate_properties_by_list(),
aggregate_properties_by_regexp(),
deaggregate()

后退 | 起点 | 前进
aggregate_methods_by_list | 上一级 | aggregate_methods


aggregate_methods

(PHP 4 >= 4.2.0)

aggregate_methods -- dynamic class and object aggregation of methods

Description

void aggregate_methods ( object object, string class_name)

Aggregates all methods defined in a class to an existing object, except for the class constructor, or methods whose names start with an underscore character (_) which are considered private to the aggregated class.

See also
aggregate(),
aggregate_info(),
aggregate_methods_by_list(),
aggregate_methods_by_regexp(),
aggregate_properties(),
aggregate_properties_by_list(),
aggregate_properties_by_regexp(),
deaggregate()

后退 | 起点 | 前进
aggregate_methods_by_regexp | 上一级 | aggregate_properties_by_list


aggregate_properties_by_list

(PHP 4 >= 4.2.0)

aggregate_properties_by_list -- selective dynamic class properties aggregation to an object

Description

void aggregate_properties_by_list ( object object, string class_name, array properties_list [, boolean exclude])

Aggregates properties from a class to an existing object using a list of property names. The optional paramater exclude is used to decide whether the list contains the names of class properties to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).

The properties whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

See also
aggregate(),
aggregate_methods(),
aggregate_methods_by_list(),
aggregate_methods_by_regexp(),
aggregate_properties(),
aggregate_properties_by_regexp(),
aggregate_info(),
deaggregate()

后退 | 起点 | 前进
aggregate_methods | 上一级 | aggregate_properties_by_regexp


aggregate_properties_by_regexp

(PHP 4 >= 4.2.0)

aggregate_properties_by_regexp -- selective class properties aggregation to an object using a regular expression

Description

void aggregate_properties_by_regexp ( object object, string class_name, string regexp [, boolean exclude])

Aggregates properties from a class to an existing object using a regular expresion to match their names. The optional paramater exclude is used to decide whether the regular expression will select the names of class properties to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).

The properties whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

See also
aggregate(),
aggregate_methods(),
aggregate_methods_by_list(),
aggregate_methods_by_regexp(),
aggregate_properties(),
aggregate_properties_by_list(),
aggregate_info(),
deaggregate()

后退 | 起点 | 前进
aggregate_properties_by_list | 上一级 | aggregate_properties


aggregate_properties

(PHP 4 >= 4.2.0)

aggregate_properties -- dynamic aggregation of class properties to an object

Description

void aggregate_properties ( object object, string class_name)

Aggregates all properties defined in a class to an existing object, except for properties whose names start with an underscore character (_) which are considered private to the aggregated class.

See also
aggregate(),
aggregate_methods(),
aggregate_methods_by_list(),
aggregate_methods_by_regexp(),
aggregate_properties_by_list(),
aggregate_properties_by_regexp(),
aggregate_info(),
deaggregate()

后退 | 起点 | 前进
aggregate_properties_by_regexp | 上一级 | aggregate


aggregate

(PHP 4 >= 4.2.0)

aggregate -- dynamic class and object aggregation of methods and properties

Description

void aggregate ( object object, string class_name)

Aggregates methods and properties defined in a class to an existing object. Methods and properties with names starting with an underscore character (_) are considered private to the aggregated class and are not used, constructors are also excluded from the aggregation procedure.

See also
aggregate_info(),
aggregate_methods(),
aggregate_methods_by_list(),
aggregate_methods_by_regexp(),
aggregate_properties(),
aggregate_properties_by_list(),
aggregate_properties_by_regexp(),
deaggregate()

后退 | 起点 | 前进
aggregate_properties | 上一级 | aggregation_info


aggregation_info

(PHP 4 >= 4.2.0)

aggregation_info -- returns an associative array of the methods and properties from each class that has been aggregated to the object.

Description

array aggregation_info ( object object)

Will return the aggretaion information for a particular object as an associative array of arrays of methods and properties. The key for the main array is the name of the aggregated class.

For example the code below

例子 1. Using aggregation_info()

<?php

class Slicer {
    var $vegetable;

    function Slicer($vegetable) {
        $this->vegetable = $vegetable;
    }

    function slice_it($num_cuts) {
        echo "Doing some simple slicing\n";
        for ($i=0; $i < $num_cuts; $i++) {
            // do some slicing
        }
    }
}

class Dicer {
    var $vegetable;
    var $rotation_angle = 90;   // degrees

    function Dicer($vegetable) {
        $this->vegetable = $vegetable;
    }

    function dice_it($num_cuts) {
        echo "Cutting in one direction\n";
        for ($i=0; $i < $num_cuts; $i++) {
            // do some cutting
        }
        $this->rotate($this->rotation_angle);
        echo "Cutting in a second direction\n";
        for ($i=0; $i < $num_cuts; $i++) {
            // do some more cutting
        }
    }

    function rotate($deg) {
        echo "Now rotating {$this->vegetable} {$deg} degrees\n";
    }

    function _secret_super_dicing($num_cuts) {
        // so secret we cannot show you ;-)
    }
}

$obj = new Slicer('onion');
aggregate($obj, 'Dicer');
print_r(aggregate_info($obj));
?>

Will produce the output

Array
(
    [dicer] => Array
        (
            [methods] => Array
                (
                    [0] => dice_it
                    [1] => rotate
                )

            [properties] => Array
                (
                    [0] => rotation_angle
                )

        )

)

As you can see, all properties and methods of the Dicer class have been aggregated into our new object, with the exception of the class constructor and the method _secret_super_dicing

See also
aggregate(),
aggregate_methods(),
aggregate_methods_by_list(),
aggregate_methods_by_regexp(),
aggregate_properties(),
aggregate_properties_by_list(),
aggregate_properties_by_regexp(),
deaggregate()

后退 | 起点 | 前进
aggregate | 上一级 | deaggregate


deaggregate

(PHP 4 >= 4.2.0)

deaggregate -- removes the aggregated methods and properties from an object

Description

void object_aggregation ( object object [, string class_name])

Removes the methods and properties from classes that were aggregated to an object. If the optional class_name parameters is passed, only those methods and properties defined in that class are removed, otherwise all aggregated methods and properties are eliminated.

See also
aggregate(),
aggregate_methods(),
aggregate_methods_by_list(),
aggregate_methods_by_regexp(),
aggregate_properties(),
aggregate_properties_by_list(),
aggregate_properties_by_regexp(),
aggregate_info()

后退 | 起点 | 前进
aggregation_info | 上一级 | Oracle 8 functions


Oracle 8 functions

PHP 手册
后退 前进

LXX. Oracle 8 functions

介绍

These functions allow you to access Oracle8 and Oracle7 databases. It uses the Oracle8 Call-Interface (OCI8)

This extension is more flexible than the standard Oracle extension. It supports binding of global and local PHP variables to Oracle placeholders, has full LOB, FILE and ROWID support and allows you to use user-supplied define variables.

需求

You will need the Oracle8 client libraries to use this extension.

Before using this extension, make sure that you have set up your Oracle environment variables properly for the Oracle user, as well as your web daemon user. The variables you might need to set are as follows:

  • ORACLE_HOME

  • ORACLE_SID

  • LD_PRELOAD

  • LD_LIBRARY_PATH

  • NLS_LANG

  • ORA_NLS33

After setting up the environment variables for your webserver user, be sure to also add the webserver user (nobody, www) to the oracle group.

If your webserver doesn't start or crashes at startup: Check that Apache is linked with the pthread library:

# ldd /www/apache/bin/httpd
    libpthread.so.0 => /lib/libpthread.so.0 (0x4001c000)
    libm.so.6 => /lib/libm.so.6 (0x4002f000)
    libcrypt.so.1 => /lib/libcrypt.so.1 (0x4004c000)
    libdl.so.2 => /lib/libdl.so.2 (0x4007a000)
    libc.so.6 => /lib/libc.so.6 (0x4007e000)
    /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)

If the libpthread is not listed you have to reinstall Apache:

# cd /usr/src/apache_1.3.xx
# make clean
# LIBS=-lpthread ./config.status
# make
# make install

Please note that on some systems like UnixWare it is libthread instead of libpthread. PHP and Apache have to be configured with EXTRA_LIBS=-lthread.

安装

You have to compile PHP with the option --with-oci8[=DIR], where DIR defaults to your environmment variable ORACLE_HOME.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

OCI_DEFAULT (integer)

OCI_DESCRIBE_ONLY (integer)

OCI_COMMIT_ON_SUCCESS (integer)

OCI_EXACT_FETCH (integer)

SQLT_BFILEE (integer)

SQLT_CFILEE (integer)

SQLT_CLOB (integer)

SQLT_BLOB (integer)

SQLT_RDD (integer)

OCI_B_SQLT_NTY (integer)

OCI_SYSDATE (integer)

OCI_B_BFILE (integer)

OCI_B_CFILEE (integer)

OCI_B_CLOB (integer)

OCI_B_BLOB (integer)

OCI_B_ROWID (integer)

OCI_B_CURSOR (integer)

OCI_B_BIN (integer)

OCI_FETCHSTATEMENT_BY_COLUMN (integer)

OCI_FETCHSTATEMENT_BY_ROW (integer)

OCI_ASSOC (integer)

OCI_NUM (integer)

OCI_BOTH (integer)

OCI_RETURN_NULLS (integer)

OCI_RETURN_LOBS (integer)

OCI_DTYPE_FILE (integer)

OCI_DTYPE_LOB (integer)

OCI_DTYPE_ROWID (integer)

OCI_D_FILE (integer)

OCI_D_LOB (integer)

OCI_D_ROWID (integer)

范例

例子 1. OCI Hints

<?php
// by sergo@bacup.ru

// Use option: OCI_DEFAULT for execute command to delay execution
OCIExecute($stmt, OCI_DEFAULT);

// for retrieve data use (after fetch):

$result = OCIResult($stmt, $n);
if (is_object ($result)) $result = $result->load();

// For INSERT or UPDATE statement use:

$sql = "insert into table (field1, field2) values (field1 = 'value',
 field2 = empty_clob()) returning field2 into :field2";
OCIParse($conn, $sql);
$clob = OCINewDescriptor($conn, OCI_D_LOB);
OCIBindByName ($stmt, ":field2", &$clob, -1, OCI_B_CLOB);
OCIExecute($stmt, OCI_DEFAULT);
$clob->save ("some text");
OCICommit($conn);

?>

You can easily access stored procedures in the same way as you would from the commands line.

例子 2. Using Stored Procedures

<?php
// by webmaster@remoterealty.com
$sth = OCIParse ( $dbh, "begin sp_newaddress( :address_id, '$firstname',
 '$lastname', '$company', '$address1', '$address2', '$city', '$state',
 '$postalcode', '$country', :error_code );end;" );

// This calls stored procedure sp_newaddress, with :address_id being an
// in/out variable and :error_code being an out variable.
// Then you do the binding:

   OCIBindByName ( $sth, ":address_id", $addr_id, 10 );
   OCIBindByName ( $sth, ":error_code", $errorcode, 10 );
   OCIExecute ( $sth );

?>

目录
OCIBindByName — Bind a PHP variable to an Oracle Placeholder
OCICancel — Cancel reading from cursor
OCICollAppend — Coming soon
OCICollAssign — Coming soon
OCICollAssignElem — Coming soon
OCICollGetElem — Coming soon
OCICollMax — Coming soon
OCICollSize — Coming soon
OCICollTrim — Coming soon
OCIColumnIsNULL — Test whether a result column is NULL
OCIColumnName — Returns the name of a column
OCIColumnPrecision — Coming soon
OCIColumnScale — Coming soon
OCIColumnSize — Return result column size
OCIColumnType — Returns the data type of a column
OCIColumnTypeRaw — Coming soon
OCICommit — Commits outstanding transactions
OCIDefineByName — Use a PHP variable for the define-step during a SELECT
OCIError — Return the last error of stmt|conn|global
OCIExecute — Execute a statement
OCIFetch — Fetches the next row into result-buffer
OCIFetchInto — Fetches the next row into result-array
OCIFetchStatement — Fetch all rows of result data into an array
OCIFreeCollection — Coming soon
OCIFreeCursor — Free all resources associated with a cursor
OCIFreeDesc — Deletes a large object descriptor
OCIFreeStatement — Free all resources associated with a statement
OCIInternalDebug — Enables or disables internal debug output
OCILoadLob — Coming soon
OCILogOff — Disconnects from Oracle
OCILogon — Establishes a connection to Oracle
OCINewCollection — Coming soon
OCINewCursor — Return a new cursor (Statement-Handle)
OCINewDescriptor — Initialize a new empty LOB or FILE descriptor
OCINLogon — Establishes a new connection to Oracle
OCINumCols — Return the number of result columns in a statement
OCIParse — Parse a query and return a statement
OCIPLogon — Connect to an Oracle database using a persistent connection
OCIResult — Returns column value for fetched row
OCIRollback — Rolls back outstanding transactions
OCIRowCount — Gets the number of affected rows
OCISaveLob — Coming soon
OCISaveLobFile — Coming soon
OCIServerVersion — Return a string containing server version information
OCISetPrefetch — Sets number of rows to be prefetched
OCIStatementType — Return the type of an OCI statement
OCIWriteLobToFile — Coming soon

后退 | 起点 | 前进
deaggregate | 上一级 | OCIBindByName


OCIBindByName

(PHP 3>= 3.0.4, PHP 4 )

OCIBindByName -- Bind a PHP variable to an Oracle Placeholder

Description

int OCIBindByName ( int stmt, string ph_name, mixed & variable, int length [, int type])

OCIBindByName() binds the PHP variable variable to the Oracle placeholder ph_name. Whether it will be used for input or output will be determined run-time, and the necessary storage space will be allocated. The length parameter sets the maximum length for the bind. If you set length to -1 OCIBindByName() will use the current length of variable to set the maximum length.

If you need to bind an abstract Datatype (LOB/ROWID/BFILE) you need to allocate it first using OCINewDescriptor() function. The length is not used for abstract Datatypes and should be set to -1. The type variable tells oracle, what kind of descriptor we want to use. Possible values are: OCI_B_FILE (Binary-File), OCI_B_CFILE (Character-File), OCI_B_CLOB (Character-LOB), OCI_B_BLOB (Binary-LOB) and OCI_B_ROWID (ROWID).

例子 1. OCIDefineByName

<?php
/* OCIBindByPos example thies@thieso.net (980221)
  inserts 3 records into emp, and uses the ROWID for updating the
  records just after the insert.
*/

$conn = OCILogon("scott","tiger");

$stmt = OCIParse($conn,"insert into emp (empno, ename) ".
                       "values (:empno,:ename) ".
                       "returning ROWID into :rid");

$data = array(1111 => "Larry", 2222 => "Bill", 3333 => "Jim");

$rowid = OCINewDescriptor($conn,OCI_D_ROWID);

OCIBindByName($stmt,":empno",&$empno,32);
OCIBindByName($stmt,":ename",&$ename,32);
OCIBindByName($stmt,":rid",&$rowid,-1,OCI_B_ROWID);

$update = OCIParse($conn,"update emp set sal = :sal where ROWID = :rid");
OCIBindByName($update,":rid",&$rowid,-1,OCI_B_ROWID);
OCIBindByName($update,":sal",&$sal,32);

$sal = 10000;

while (list($empno,$ename) = each($data)) {
    OCIExecute($stmt);
    OCIExecute($update);
}

$rowid->free();

OCIFreeStatement($update);
OCIFreeStatement($stmt);

$stmt = OCIParse($conn,"select * from emp where empno in (1111,2222,3333)");
OCIExecute($stmt);
while (OCIFetchInto($stmt,&$arr,OCI_ASSOC)) {
    var_dump($arr);
}
OCIFreeStatement($stmt);

/* delete our "junk" from the emp table.... */
$stmt = OCIParse($conn,"delete from emp where empno in (1111,2222,3333)");
OCIExecute($stmt);
OCIFreeStatement($stmt);

OCILogoff($conn);
?>

警告

It is a bad idea to use magic quotes and OciBindByName() simultaneously as no quoting is needed on quoted variables and any quotes magically applied will be written into your database as OciBindByName() is not able to distinguish magically added quotings from those added by intention.

后退 | 起点 | 前进
Oracle 8 functions | 上一级 | OCICancel


OCICancel

(PHP 3>= 3.0.8, PHP 4 )

OCICancel -- Cancel reading from cursor

Description

int OCICancel ( int stmt)

If you do not want read more data from a cursor, then call OCICancel().

后退 | 起点 | 前进
OCIBindByName | 上一级 | OCICollAppend


OCICollAppend

(PHP 4 >= 4.0.6)

OCICollAppend -- Coming soon

Description

string OCICollAppend ( object collection, object object)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
OCICancel | 上一级 | OCICollAssign


OCICollAssign

(PHP 4 >= 4.0.6)

OCICollAssign -- Coming soon

Description

string OCICollAssign ( object collection, object object)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
OCICollAppend | 上一级 | OCICollAssignElem


OCICollAssignElem

(PHP 4 >= 4.0.6)

OCICollAssignElem -- Coming soon

Description

string OCICollAssignElem ( object collection, string ndx, string val)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
OCICollAssign | 上一级 | OCICollGetElem


OCICollGetElem

(PHP 4 >= 4.0.6)

OCICollGetElem -- Coming soon

Description

string OCICollGetElem ( object collection, string ndx)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
OCICollAssignElem | 上一级 | OCICollMax


OCICollMax

(PHP 4 >= 4.0.6)

OCICollMax -- Coming soon

Description

string OCICollMax ( object collection)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
OCICollGetElem | 上一级 | OCICollSize


OCICollSize

(PHP 4 >= 4.0.6)

OCICollSize -- Coming soon

Description

string OCICollSize ( object collection)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
OCICollMax | 上一级 | OCICollTrim


OCICollTrim

(PHP 4 >= 4.0.6)

OCICollTrim -- Coming soon

Description

string OCICollTrim ( object collection, int num)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
OCICollSize | 上一级 | OCIColumnIsNULL


OCIColumnIsNULL

(PHP 3>= 3.0.4, PHP 4 )

OCIColumnIsNULL -- Test whether a result column is NULL

Description

int OCIColumnIsNULL ( int stmt, mixed column)

OCIColumnIsNULL() returns TRUE if the returned column column in the result from the statement stmt is NULL. You can either use the column-number (1-Based) or the column-name for the col parameter.

后退 | 起点 | 前进
OCICollTrim | 上一级 | OCIColumnName


OCIColumnName

(PHP 3>= 3.0.4, PHP 4 )

OCIColumnName -- Returns the name of a column

Description

string OCIColumnName ( int stmt, int col)

OCIColumnName() returns the name of the column corresponding to the column number (1-based) that is passed in.

例子 1. OCIColumnName

<?php
    print "<HTML><PRE>\n";
    $conn = OCILogon("scott", "tiger");
    $stmt = OCIParse($conn,"select * from emp");
    OCIExecute($stmt);
    print "<TABLE BORDER=\"1\">";
    print "<TR>";
    print "<TH>Name</TH>";
    print "<TH>Type</TH>";
    print "<TH>Length</TH>";
    print "</TR>";
    $ncols = OCINumCols($stmt);
    for ( $i = 1; $i <= $ncols; $i++ ) {
        $column_name  = OCIColumnName($stmt,$i);
        $column_type  = OCIColumnType($stmt,$i);
        $column_size  = OCIColumnSize($stmt,$i);
        print "<TR>";
        print "<TD>$column_name</TD>";
        print "<TD>$column_type</TD>";
        print "<TD>$column_size</TD>";
        print "</TR>";
    }
    print "</TABLE>\n";
    OCIFreeStatement($stmt);
    OCILogoff($conn);
    print "</PRE>";
    print "</HTML>\n";
?>

See also OCINumCols(),
OCIColumnType(),
and OCIColumnSize().

后退 | 起点 | 前进
OCIColumnIsNULL | 上一级 | OCIColumnPrecision


OCIColumnPrecision

(PHP 4 )

OCIColumnPrecision -- Coming soon

Description

int OCIColumnPrecision ( int stmt, int col)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
OCIColumnName | 上一级 | OCIColumnScale


OCIColumnScale

(PHP 4 )

OCIColumnScale -- Coming soon

Description

int OCIColumnScale ( int stmt, int col)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
OCIColumnPrecision | 上一级 | OCIColumnSize


OCIColumnSize

(PHP 3>= 3.0.4, PHP 4 )

OCIColumnSize -- Return result column size

Description

int OCIColumnSize ( int stmt, mixed column)

OCIColumnSize() returns the size of the column as given by Oracle. You can either use the column-number (1-Based) or the column-name for the col parameter.

例子 1. OCIColumnSize

<?php
    print "<HTML><PRE>\n";
    $conn = OCILogon("scott", "tiger");
    $stmt = OCIParse($conn,"select * from emp");
    OCIExecute($stmt);
    print "<TABLE BORDER=\"1\">";
    print "<TR>";
    print "<TH>Name</TH>";
    print "<TH>Type</TH>";
    print "<TH>Length</TH>";
    print "</TR>";
    $ncols = OCINumCols($stmt);
    for ( $i = 1; $i <= $ncols; $i++ ) {
        $column_name  = OCIColumnName($stmt,$i);
        $column_type  = OCIColumnType($stmt,$i);
        $column_size  = OCIColumnSize($stmt,$i);
        print "<TR>";
        print "<TD>$column_name</TD>";
        print "<TD>$column_type</TD>";
        print "<TD>$column_size</TD>";
        print "</TR>";
    }
    print "</TABLE>";
    OCIFreeStatement($stmt);
    OCILogoff($conn);
    print "</PRE>";
    print "</HTML>\n";
?>

See also OCINumCols(),
OCIColumnName(), and
OCIColumnSize().

后退 | 起点 | 前进
OCIColumnScale | 上一级 | OCIColumnType


OCIColumnType

(PHP 3>= 3.0.4, PHP 4 )

OCIColumnType -- Returns the data type of a column

Description

mixed OCIColumnType ( int stmt, int col)

OCIColumnType() returns the data type of the column corresponding to the column number (1-based) that is passed in.

例子 1. OCIColumnType

<?php
    print "<HTML><PRE>\n";
    $conn = OCILogon("scott", "tiger");
    $stmt = OCIParse($conn,"select * from emp");
    OCIExecute($stmt);
    print "<TABLE BORDER=\"1\">";
    print "<TR>";
    print "<TH>Name</TH>";
    print "<TH>Type</TH>";
    print "<TH>Length</TH>";
    print "</TR>";
    $ncols = OCINumCols($stmt);
    for ( $i = 1; $i <= $ncols; $i++ ) {
        $column_name  = OCIColumnName($stmt,$i);
        $column_type  = OCIColumnType($stmt,$i);
        $column_size  = OCIColumnSize($stmt,$i);
        print "<TR>";
        print "<TD>$column_name</TD>";
        print "<TD>$column_type</TD>";
        print "<TD>$column_size</TD>";
        print "</TR>";
    }
    print "</TABLE>\n";
    OCIFreeStatement($stmt);
    OCILogoff($conn);
    print "</PRE>";
    print "</HTML>\n";
?>

See also OCINumCols(),
OCIColumnName(),
and OCIColumnSize().

后退 | 起点 | 前进
OCIColumnSize | 上一级 | OCIColumnTypeRaw


OCIColumnTypeRaw

(PHP 4 )

OCIColumnTypeRaw -- Coming soon

Description

mixed OCIColumnTypeRaw ( int stmt, int col)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
OCIColumnType | 上一级 | OCICommit


OCICommit

(PHP 3>= 3.0.7, PHP 4 )

OCICommit -- Commits outstanding transactions

Description

int OCICommit ( int connection)

OCICommit() commits all outstanding statements for Oracle connection connection.

后退 | 起点 | 前进
OCIColumnTypeRaw | 上一级 | OCIDefineByName


OCIDefineByName

(PHP 3>= 3.0.7, PHP 4 )

OCIDefineByName -- Use a PHP variable for the define-step during a SELECT

Description

int OCIDefineByName ( int stmt, string Column-Name, mixed variable [, int type])

OCIDefineByName() binds PHP variables for fetches of SQL-Columns. Be careful that Oracle uses ALL-UPPERCASE column-names, whereby in your select you can also write lowercase. OCIDefineByName() expects the Column-Name to be in uppercase. If you define a variable that doesn't exists in you select statement, no error will be given!

If you need to define an abstract datatype (LOB/ROWID/BFILE) you need to allocate it first using OCINewDescriptor() function. See also the OCIBindByName() function.

例子 1. OCIDefineByName

<?php
/* OCIDefineByName example - thies@thieso.net (980219) */

$conn = OCILogon("scott","tiger");

$stmt = OCIParse($conn,"select empno, ename from emp");

/* the define MUST be done BEFORE ociexecute! */

OCIDefineByName($stmt,"EMPNO",$empno);
OCIDefineByName($stmt,"ENAME",$ename);

OCIExecute($stmt);

while (OCIFetch($stmt)) {
    echo "empno:".$empno."\n";
    echo "ename:".$ename."\n";
}

OCIFreeStatement($stmt);
OCILogoff($conn);
?>

后退 | 起点 | 前进
OCICommit | 上一级 | OCIError


OCIError

(PHP 3>= 3.0.7, PHP 4 )

OCIError -- Return the last error of stmt|conn|global

Description

array OCIError ( [int stmt|conn|global])

OCIError() returns the last error found. If the optional stmt|conn|global is not provided, the last error encountered is returned. If no error is found, OCIError() returns FALSE. OCIError() returns the error as an associative array. In this array, code consists the oracle error code and message the oracle errorstring.

后退 | 起点 | 前进
OCIDefineByName | 上一级 | OCIExecute


OCIExecute

(PHP 3>= 3.0.4, PHP 4 )

OCIExecute -- Execute a statement

Description

int OCIExecute ( int statement [, int mode])

OCIExecute() executes a previously parsed statement. (see OCIParse()). The optional mode allows you to specify the execution-mode (default is OCI_COMMIT_ON_SUCCESS). If you don't want statements to be committed automatically specify OCI_DEFAULT as your mode.

如果成功则返回 TRUE，失败则返回 FALSE。

后退 | 起点 | 前进
OCIError | 上一级 | OCIFetch


OCIFetch

(PHP 3>= 3.0.4, PHP 4 )

OCIFetch -- Fetches the next row into result-buffer

Description

int OCIFetch ( int statement)

OCIFetch() fetches the next row (for SELECT statements) into the internal result-buffer.

后退 | 起点 | 前进
OCIExecute | 上一级 | OCIFetchInto


OCIFetchInto

(PHP 3>= 3.0.4, PHP 4 )

OCIFetchInto -- Fetches the next row into result-array

Description

int OCIFetchInto ( int stmt, array & result [, int mode])

OCIFetchInto() fetches the next row (for SELECT statements) into the result array. OCIFetchInto() will overwrite the previous content of result. By default result will contain a zero-based array of all columns that are not NULL.

The mode parameter allows you to change the default behaviour. You can specify more than one flag by simply adding them up (eg OCI_ASSOC+OCI_RETURN_NULLS). The known flags are:

OCI_ASSOC Return an associative array.
OCI_NUM Return an numbered array starting with zero. (DEFAULT)
OCI_RETURN_NULLS Return empty columns.
OCI_RETURN_LOBS Return the value of a LOB instead of the descriptor.

后退 | 起点 | 前进
OCIFetch | 上一级 | OCIFetchStatement


OCIFetchStatement

(PHP 3>= 3.0.8, PHP 4 )

OCIFetchStatement -- Fetch all rows of result data into an array

Description

int OCIFetchStatement ( int stmt, array & variable)

OCIFetchStatement() fetches all the rows from a result into a user-defined array. OCIFetchStatement() returns the number of rows fetched.

例子 1. OCIFetchStatement

<?php
/* OCIFetchStatement example mbritton@verinet.com (990624) */

$conn = OCILogon("scott","tiger");

$stmt = OCIParse($conn,"select * from emp");

OCIExecute($stmt);

$nrows = OCIFetchStatement($stmt,$results);
if ( $nrows > 0 ) {
   print "<TABLE BORDER=\"1\">\n";
   print "<TR>\n";
   while ( list( $key, $val ) = each( $results ) ) {
      print "<TH>$key</TH>\n";
   }
   print "</TR>\n";

   for ( $i = 0; $i < $nrows; $i++ ) {
      reset($results);
      print "<TR>\n";
      while ( $column = each($results) ) {
         $data = $column['value'];
         print "<TD>$data[$i]</TD>\n";
      }
      print "</TR>\n";
   }
   print "</TABLE>\n";
} else {
   echo "No data found<BR>\n";
}
print "$nrows Records Selected<BR>\n";

OCIFreeStatement($stmt);
OCILogoff($conn);
?>

后退 | 起点 | 前进
OCIFetchInto | 上一级 | OCIFreeCollection


OCIFreeCollection

(PHP 4 >= 4.1.0)

OCIFreeCollection -- Coming soon

Description

string OCIFreeCollection ( object lob)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
OCIFetchStatement | 上一级 | OCIFreeCursor


OCIFreeCursor

(PHP 3>= 3.0.8, PHP 4 )

OCIFreeCursor -- Free all resources associated with a cursor

Description

int OCIFreeCursor ( int stmt)

OCIFreeCursor() returns TRUE if successful, or FALSE if unsuccessful.

后退 | 起点 | 前进
OCIFreeCollection | 上一级 | OCIFreeDesc


OCIFreeDesc

(PHP 4 )

OCIFreeDesc -- Deletes a large object descriptor

Description

int OCIFreeDesc ( object lob)

OCIFreeDesc() returns TRUE if successful, or FALSE if unsuccessful.

后退 | 起点 | 前进
OCIFreeCursor | 上一级 | OCIFreeStatement


OCIFreeStatement

(PHP 3>= 3.0.5, PHP 4 )

OCIFreeStatement -- Free all resources associated with a statement

Description

int OCIFreeStatement ( int stmt)

OCIFreeStatement() returns TRUE if successful, or FALSE if unsuccessful.

后退 | 起点 | 前进
OCIFreeDesc | 上一级 | OCIInternalDebug


OCIInternalDebug

(PHP 3>= 3.0.4, PHP 4 )

OCIInternalDebug -- Enables or disables internal debug output

Description

void OCIInternalDebug ( int onoff)

OCIInternalDebug() enables internal debug output. Set onoff to 0 to turn debug output off, 1 to turn it on.

后退 | 起点 | 前进
OCIFreeStatement | 上一级 | OCILoadLob


OCILoadLob

(PHP 4 )

OCILoadLob -- Coming soon

Description

string OCILoadLob ( object lob)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
OCIInternalDebug | 上一级 | OCILogOff


OCILogOff

(PHP 3>= 3.0.4, PHP 4 )

OCILogOff -- Disconnects from Oracle

Description

int OCILogOff ( int connection)

OCILogOff() closes an Oracle connection.

后退 | 起点 | 前进
OCILoadLob | 上一级 | OCILogon


OCILogon

(PHP 3>= 3.0.4, PHP 4 )

OCILogon -- Establishes a connection to Oracle

Description

int OCILogon ( string username, string password [, string db])

OCILogon() returns an connection identifier needed for most other OCI calls. The optional third parameter can either contain the name of the local Oracle instance or the name of the entry in tnsnames.ora to which you want to connect. If the optional third parameter is not specified, PHP uses the environment variables ORACLE_SID (Oracle instance) or TWO_TASK (tnsnames.ora) to determine which database to connect to.

Connections are shared at the page level when using OCILogon(). This means that commits and rollbacks apply to all open transactions in the page, even if you have created multiple connections.

This example demonstrates how the connections are shared.

例子 1. OCILogon

<?php
print "<HTML><PRE>";
$db = "";

$c1 = ocilogon("scott","tiger",$db);
$c2 = ocilogon("scott","tiger",$db);

function create_table($conn)
{ $stmt = ociparse($conn,"create table scott.hallo (test varchar2(64))");
  ociexecute($stmt);
  echo $conn." created table\n\n";
}

function drop_table($conn)
{ $stmt = ociparse($conn,"drop table scott.hallo");
  ociexecute($stmt);
  echo $conn." dropped table\n\n";
}

function insert_data($conn)
{ $stmt = ociparse($conn,"insert into scott.hallo
            values('$conn' || ' ' || to_char(sysdate,'DD-MON-YY HH24:MI:SS'))");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn." inserted hallo\n\n";
}

function delete_data($conn)
{ $stmt = ociparse($conn,"delete from scott.hallo");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn." deleted hallo\n\n";
}

function commit($conn)
{ ocicommit($conn);
  echo $conn." committed\n\n";
}

function rollback($conn)
{ ocirollback($conn);
  echo $conn." rollback\n\n";
}

function select_data($conn)
{ $stmt = ociparse($conn,"select * from scott.hallo");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn."----selecting\n\n";
  while (ocifetch($stmt))
    echo $conn." <".ociresult($stmt,"TEST").">\n\n";
  echo $conn."----done\n\n";
}

create_table($c1);
insert_data($c1);   // Insert a row using c1
insert_data($c2);   // Insert a row using c2

select_data($c1);   // Results of both inserts are returned
select_data($c2);

rollback($c1);      // Rollback using c1

select_data($c1);   // Both inserts have been rolled back
select_data($c2);

insert_data($c2);   // Insert a row using c2
commit($c2);        // commit using c2

select_data($c1);   // result of c2 insert is returned

delete_data($c1);   // delete all rows in table using c1
select_data($c1);   // no rows returned
select_data($c2);   // no rows returned
commit($c1);        // commit using c1

select_data($c1);   // no rows returned
select_data($c2);   // no rows returned

drop_table($c1);
print "</PRE></HTML>";
?>

See also OCIPLogon() and OCINLogon().

后退 | 起点 | 前进
OCILogOff | 上一级 | OCINewCollection


OCINewCollection

(PHP 4 >= 4.0.6)

OCINewCollection -- Coming soon

Description

string OCINewCollection ( int conn, string tdo [, string shema])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
OCILogon | 上一级 | OCINewCursor


OCINewCursor

(PHP 3>= 3.0.8, PHP 4 )

OCINewCursor -- Return a new cursor (Statement-Handle)

Description

int OCINewCursor ( int conn)

OCINewCursor() allocates a new statement handle on the specified connection.

例子 1. Using a REF CURSOR from a stored procedure

<?php
// suppose your stored procedure info.output returns a ref cursor in :data

$conn = OCILogon("scott","tiger");
$curs = OCINewCursor($conn);
$stmt = OCIParse($conn,"begin info.output(:data); end;");

ocibindbyname($stmt,"data",&$curs,-1,OCI_B_CURSOR);
ociexecute($stmt);
ociexecute($curs);

while (OCIFetchInto($curs,&$data)) {
    var_dump($data);
}

OCIFreeStatement($stmt);
OCIFreeCursor($curs);
OCILogoff($conn);
?>

例子 2. Using a REF CURSOR in a select statement

<?php
print "<HTML><BODY>";
$conn = OCILogon("scott","tiger");
$count_cursor = "CURSOR(select count(empno) num_emps from emp " .
                "where emp.deptno = dept.deptno) as EMPCNT from dept";
$stmt = OCIParse($conn,"select deptno,dname,$count_cursor");

ociexecute($stmt);
print "<TABLE BORDER=\"1\">";
print "<TR>";
print "<TH>DEPT NAME</TH>";
print "<TH>DEPT #</TH>";
print "<TH># EMPLOYEES</TH>";
print "</TR>";

while (OCIFetchInto($stmt,&$data,OCI_ASSOC)) {
    print "<TR>";
    $dname  = $data["DNAME"];
    $deptno = $data["DEPTNO"];
    print "<TD>$dname</TD>";
    print "<TD>$deptno</TD>";
    ociexecute($data["EMPCNT"]);
    while (OCIFetchInto($data["EMPCNT"],&$subdata,OCI_ASSOC)) {
        $num_emps = $subdata["NUM_EMPS"];
        print  "<TD>$num_emps</TD>";
    }
    print "</TR>";
}
print "</TABLE>";
print "</BODY></HTML>";
OCIFreeStatement($stmt);
OCILogoff($conn);
?>

后退 | 起点 | 前进
OCINewCollection | 上一级 | OCINewDescriptor


OCINewDescriptor

(PHP 3>= 3.0.7, PHP 4 )

OCINewDescriptor -- Initialize a new empty LOB or FILE descriptor

Description

string OCINewDescriptor ( int connection [, int type])

OCINewDescriptor() allocates storage to hold descriptors or LOB locators. Valid values for type are OCI_D_FILE, OCI_D_LOB, OCI_D_ROWID. For LOB descriptors, the methods load, save, and savefile are associated with the descriptor, for BFILE only the load method exists. See the second example usage hints.

例子 1. OCINewDescriptor

<?php
    /* This script is designed to be called from a HTML form.
     * It expects $user, $password, $table, $where, and $commitsize
     * to be passed in from the form.  The script then deletes
     * the selected rows using the ROWID and commits after each
     * set of $commitsize rows. (Use with care, there is no rollback)
     */
    $conn = OCILogon($user, $password);
    $stmt = OCIParse($conn,"select rowid from $table $where");
    $rowid = OCINewDescriptor($conn,OCI_D_ROWID);
    OCIDefineByName($stmt,"ROWID",&$rowid);
    OCIExecute($stmt);
    while ( OCIFetch($stmt) ) {
       $nrows = OCIRowCount($stmt);
       $delete = OCIParse($conn,"delete from $table where ROWID = :rid");
       OCIBindByName($delete,":rid",&$rowid,-1,OCI_B_ROWID);
       OCIExecute($delete);
       print "$nrows\n";
       if ( ($nrows % $commitsize) == 0 ) {
           OCICommit($conn);
       }
    }
    $nrows = OCIRowCount($stmt);
    print "$nrows deleted...\n";
    OCIFreeStatement($stmt);
    OCILogoff($conn);
?>
<?php
    /* This script demonstrates file upload to LOB columns
     * The formfield used for this example looks like this
     * <form action="upload.php" method="post" enctype="multipart/form-data">
     * <input type="file" name="lob_upload">
     * ...
     */
  if(!isset($lob_upload) || $lob_upload == 'none'){
?>
<form action="upload.php" method="post" enctype="multipart/form-data">
Upload file: <input type="file" name="lob_upload"><br>
<input type="submit" value="Upload"> - <input type="reset">
</form>
<?php
  } else {

     // $lob_upload contains the temporary filename of the uploaded file

     // see also the features section on file upload,
     // if you would like to use secure uploads

     $conn = OCILogon($user, $password);
     $lob = OCINewDescriptor($conn, OCI_D_LOB);
     $stmt = OCIParse($conn,"insert into $table (id, the_blob)
               values(my_seq.NEXTVAL, EMPTY_BLOB()) returning the_blob into :the_blob");
     OCIBindByName($stmt, ':the_blob', &$lob, -1, OCI_B_BLOB);
     OCIExecute($stmt, OCI_DEFAULT);
     if($lob->savefile($lob_upload)){
        OCICommit($conn);
        echo "Blob successfully uploaded\n";
     }else{
        echo "Couldn't upload Blob\n";
     }
     OCIFreeDesc($lob);
     OCIFreeStatement($stmt);
     OCILogoff($conn);
  }
?>

例子 2. OCINewDescriptor

<?php
    /* Calling PL/SQL stored procedures which contain clobs as input
     * parameters (PHP 4 >= 4.0.6).
     * Example PL/SQL stored procedure signature is:
     *
     * PROCEDURE save_data
     *   Argument Name                  Type                    In/Out Default?
     *   ------------------------------ ----------------------- ------ --------
     *   KEY                            NUMBER(38)              IN
     *   DATA                           CLOB                    IN
     *
     */

    $conn = OCILogon($user, $password);
    $stmt = OCIParse($conn, "begin save_data(:key, :data); end;");
    $clob = OCINewDescriptor($conn, OCI_D_LOB);
    OCIBindByName($stmt, ':key', $key);
    OCIBindByName($stmt, ':data', $clob, -1, OCI_B_CLOB);
    $clob->WriteTemporary($data);
    OCIExecute($stmt, OCI_DEFAULT);
    OCICommit($conn);
    $clob->close();
    $clob->free();
    OCIFreeStatement($stmt);
?>

后退 | 起点 | 前进
OCINewCursor | 上一级 | OCINLogon


OCINLogon

(PHP 3>= 3.0.8, PHP 4 )

OCINLogon -- Establishes a new connection to Oracle

Description

int OCINLogon ( string username, string password [, string db])

OCINLogon() creates a new connection to an Oracle 8 database and logs on. The optional third parameter can either contain the name of the local Oracle instance or the name of the entry in tnsnames.ora to which you want to connect. If the optional third parameter is not specified, PHP uses the environment variables ORACLE_SID (Oracle instance) or TWO_TASK (tnsnames.ora) to determine which database to connect to.

OCINLogon() forces a new connection. This should be used if you need to isolate a set of transactions. By default, connections are shared at the page level if using OCILogon() or at the web server process level if using OCIPLogon(). If you have multiple connections open using OCINLogon(), all commits and rollbacks apply to the specified connection only.

This example demonstrates how the connections are separated.

例子 1. OCINLogon

<?php
print "<HTML><PRE>";
$db = "";

$c1 = ocilogon("scott","tiger",$db);
$c2 = ocinlogon("scott","tiger",$db);

function create_table($conn)
{ $stmt = ociparse($conn,"create table scott.hallo (test
varchar2(64))");
  ociexecute($stmt);
  echo $conn." created table\n\n";
}

function drop_table($conn)
{ $stmt = ociparse($conn,"drop table scott.hallo");
  ociexecute($stmt);
  echo $conn." dropped table\n\n";
}

function insert_data($conn)
{ $stmt = ociparse($conn,"insert into scott.hallo
            values('$conn' || ' ' || to_char(sysdate,'DD-MON-YY HH24:MI:SS'))");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn." inserted hallo\n\n";
}

function delete_data($conn)
{ $stmt = ociparse($conn,"delete from scott.hallo");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn." deleted hallo\n\n";
}

function commit($conn)
{ ocicommit($conn);
  echo $conn." committed\n\n";
}

function rollback($conn)
{ ocirollback($conn);
  echo $conn." rollback\n\n";
}

function select_data($conn)
{ $stmt = ociparse($conn,"select * from scott.hallo");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn."----selecting\n\n";
  while (ocifetch($stmt))
    echo $conn." <".ociresult($stmt,"TEST").">\n\n";
  echo $conn."----done\n\n";
}

create_table($c1);
insert_data($c1);

select_data($c1);
select_data($c2);

rollback($c1);

select_data($c1);
select_data($c2);

insert_data($c2);
commit($c2);

select_data($c1);

delete_data($c1);
select_data($c1);
select_data($c2);
commit($c1);

select_data($c1);
select_data($c2);

drop_table($c1);
print "</PRE></HTML>";
?>

See also OCILogon() and OCIPLogon().

后退 | 起点 | 前进
OCINewDescriptor | 上一级 | OCINumCols


OCINumCols

(PHP 3>= 3.0.4, PHP 4 )

OCINumCols -- Return the number of result columns in a statement

Description

int OCINumCols ( int stmt)

OCINumCols() returns the number of columns in a statement.

例子 1. OCINumCols

<?php
    print "<HTML><PRE>\n";
    $conn = OCILogon("scott", "tiger");
    $stmt = OCIParse($conn,"select * from emp");
    OCIExecute($stmt);
    while ( OCIFetch($stmt) ) {
        print "\n";
        $ncols = OCINumCols($stmt);
        for ( $i = 1; $i <= $ncols; $i++ ) {
            $column_name  = OCIColumnName($stmt,$i);
            $column_value = OCIResult($stmt,$i);
            print $column_name . ': ' . $column_value . "\n";
        }
        print "\n";
    }
    OCIFreeStatement($stmt);
    OCILogoff($conn);
    print "</PRE>";
    print "</HTML>\n";
?>

后退 | 起点 | 前进
OCINLogon | 上一级 | OCIParse


OCIParse

(PHP 3>= 3.0.4, PHP 4 )

OCIParse -- Parse a query and return a statement

Description

int OCIParse ( int conn, string query)

OCIParse() parses the query using conn. It returns the statement identity if the query is valid, FALSE if not. The query can be any valid SQL statement or PL/SQL block.

后退 | 起点 | 前进
OCINumCols | 上一级 | OCIPLogon


OCIPLogon

(PHP 3>= 3.0.8, PHP 4 )

OCIPLogon -- Connect to an Oracle database using a persistent connection

Description

int OCIPLogon ( string username, string password [, string db])

OCIPLogon() creates a persistent connection to an Oracle 8 database and logs on. The optional third parameter can either contain the name of the local Oracle instance or the name of the entry in tnsnames.ora to which you want to connect. If the optional third parameter is not specified, PHP uses the environment variables ORACLE_SID (Oracle instance) or TWO_TASK (tnsnames.ora) to determine which database to connect to.

See also OCILogon() and OCINLogon().

后退 | 起点 | 前进
OCIParse | 上一级 | OCIResult


OCIResult

(PHP 3>= 3.0.4, PHP 4 )

OCIResult -- Returns column value for fetched row

Description

mixed OCIResult ( int statement, mixed column)

OCIResult() returns the data for column column in the current row (see OCIFetch()).OCIResult() will return everything as strings except for abstract types (ROWIDs, LOBs and FILEs).

后退 | 起点 | 前进
OCIPLogon | 上一级 | OCIRollback


OCIRollback

(PHP 3>= 3.0.7, PHP 4 )

OCIRollback -- Rolls back outstanding transactions

Description

int OCIRollback ( int connection)

OCIRollback() rolls back all outstanding statements for Oracle connection connection.

后退 | 起点 | 前进
OCIResult | 上一级 | OCIRowCount


OCIRowCount

(PHP 3>= 3.0.7, PHP 4 )

OCIRowCount -- Gets the number of affected rows

Description

int OCIRowCount ( int statement)

OCIRowCount() returns the number of rows affected for eg update-statements. This function will not tell you the number of rows that a select will return!

例子 1. OCIRowCount

<?php
    print "<HTML><PRE>";
    $conn = OCILogon("scott","tiger");
    $stmt = OCIParse($conn,"create table emp2 as select * from emp");
    OCIExecute($stmt);
    print OCIRowCount($stmt) . " rows inserted.<BR>";
    OCIFreeStatement($stmt);
    $stmt = OCIParse($conn,"delete from emp2");
    OCIExecute($stmt);
    print OCIRowCount($stmt) . " rows deleted.<BR>";
    OCICommit($conn);
    OCIFreeStatement($stmt);
    $stmt = OCIParse($conn,"drop table emp2");
    OCIExecute($stmt);
    OCIFreeStatement($stmt);
    OCILogOff($conn);
    print "</PRE></HTML>";
?>

后退 | 起点 | 前进
OCIRollback | 上一级 | OCISaveLob


OCISaveLob

(PHP 4 )

OCISaveLob -- Coming soon

Description

string OCISaveLob ( object lob)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
OCIRowCount | 上一级 | OCISaveLobFile


OCISaveLobFile

(PHP 4 )

OCISaveLobFile -- Coming soon

Description

string OCISaveLobFile ( object lob)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
OCISaveLob | 上一级 | OCIServerVersion


OCIServerVersion

(PHP 3>= 3.0.4, PHP 4 )

OCIServerVersion -- Return a string containing server version information

Description

string OCIServerVersion ( int conn)

例子 1. OCIServerVersion

<?php
   $conn = OCILogon("scott","tiger");
   print "Server Version: " . OCIServerVersion($conn);
   OCILogOff($conn);
?>

后退 | 起点 | 前进
OCISaveLobFile | 上一级 | OCISetPrefetch


OCISetPrefetch

(PHP 3>= 3.0.12, PHP 4 )

OCISetPrefetch -- Sets number of rows to be prefetched

Description

int OCISetPrefetch ( int stmt, int rows)

Sets the number of top level rows to be prefetched. The default value is 1 row.

后退 | 起点 | 前进
OCIServerVersion | 上一级 | OCIStatementType


OCIStatementType

(PHP 3>= 3.0.5, PHP 4 )

OCIStatementType -- Return the type of an OCI statement

Description

string OCIStatementType ( int stmt)

OCIStatementType() returns one of the following values:

  1. "SELECT"

  2. "UPDATE"

  3. "DELETE"

  4. "INSERT"

  5. "CREATE"

  6. "DROP"

  7. "ALTER"

  8. "BEGIN"

  9. "DECLARE"

  10. "UNKNOWN"

例子 1. OCIStatementType() examples

<?php
    print "<HTML><PRE>";
    $conn = OCILogon("scott","tiger");
    $sql  = "delete from emp where deptno = 10";

    $stmt = OCIParse($conn,$sql);
    if ( OCIStatementType($stmt) == "DELETE" ) {
        die "You are not allowed to delete from this table<BR>";
    }

    OCILogoff($conn);
    print "</PRE></HTML>";
?>

后退 | 起点 | 前进
OCISetPrefetch | 上一级 | OCIWriteLobToFile


OCIWriteLobToFile

(PHP 4 )

OCIWriteLobToFile -- Coming soon

Description

void OCIWriteLobToFile ( object lob [, string filename [, int start [, int lenght]]])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
OCIStatementType | 上一级 | OpenSSL functions


OpenSSL functions

PHP 手册
后退 前进

LXXI. OpenSSL functions

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

介绍

This module uses the functions of OpenSSL for generation and verification of signatures and for sealing (encrypting) and opening (decrypting) data. OpenSSL offers many features that this module currently doesn't support. Some of these may be added in the future.

需求

In order to use the OpenSSL functions you need to install the OpenSSL package. PHP-4.0.4pl1 requires OpenSSL >= 0.9.6, but PHP-4.0.5 and greater will also work with OpenSSL >= 0.9.5.

安装

To use PHP's OpenSSL support you must also compile PHP --with-openssl[=DIR].

运行时配置

该扩展模块未定义任何设置指令。

资源类型

Key/Certificate parameters

Quite a few of the openssl functions require a key or a certificate parameter. PHP 4.0.5 and earlier have to use a key or certificate resource returned by one of the openssl_get_xxx functions. Later versions may use one of the following methods:

  • Certificates

    1. An X.509 resource returned from openssl_x509_read()

    2. A string having the format file://path/to/cert.pem; the named file must contain a PEM encoded certificate

    3. A string containing the content of a certificate, PEM encoded

  • Public/Private Keys

    1. A key resource returned from openssl_get_publickey() or openssl_get_privatekey()

    2. For public keys only: an X.509 resource

    3. A string having the format file://path/to/file.pem - the named file must contain a PEM encoded certificate/private key (it may contain both)

    4. A string containing the content of a certificate/key, PEM encoded

    5. For private keys, you may also use the syntax array($key, $passphrase) where $key represents a key specified using the file:// or textual content notation above, and $passphrase represents a string containing the passphrase for that private key

Certificate Verification

When calling a function that will verify a signature/certificate, the cainfo parameter is an array containing file and directory names that specify the locations of trusted CA files. If a directory is specified, then it must be a correctly formed hashed directory as the openssl command would use.

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

X509_PURPOSE_SSL_CLIENT (integer)

X509_PURPOSE_SSL_SERVER (integer)

X509_PURPOSE_NS_SSL_SERVER (integer)

X509_PURPOSE_SMIME_SIGN (integer)

X509_PURPOSE_SMIME_ENCRYPT (integer)

X509_PURPOSE_CRL_SIGN (integer)

X509_PURPOSE_ANY (integer)

OPENSSL_PKCS1_PADDING (integer)

OPENSSL_SSLV23_PADDING (integer)

OPENSSL_NO_PADDING (integer)

OPENSSL_PKCS1_OAEP_PADDING (integer)

OPENSSL_KEYTYPE_RSA (integer)

OPENSSL_KEYTYPE_DSA (integer)

OPENSSL_KEYTYPE_DH (integer)

PKCS7 Flags/Constants

The S/MIME functions make use of flags which are specified using a bitfield which can include one or more of the following values:

表格 1. PKCS7 CONSTANTS

Constant | Description
PKCS7_TEXT | adds text/plain content type headers to encrypted/signed message. If decrypting or verifying, it strips those headers from the output - if the decrypted or verified message is not of MIME type text/plain then an error will occur.
PKCS7_BINARY | normally the input message is converted to "canonical" format which is effectively using CR and LF as end of line: as required by the S/MIME specification. When this options is present, no translation occurs. This is useful when handling binary data which may not be in MIME format.
PKCS7_NOINTERN | when verifying a message, certificates (if any) included in the message are normally searched for the signing certificate. With this option only the certificates specified in the extracerts parameter of openssl_pkcs7_verify() are used. The supplied certificates can still be used as untrusted CAs however.
PKCS7_NOVERIFY | do not verify the signers certificate of a signed message.
PKCS7_NOCHAIN | do not chain verification of signers certificates: that is don't use the certificates in the signed message as untrusted CAs.
PKCS7_NOCERTS | when signing a message the signer's certificate is normally included - with this option it is excluded. This will reduce the size of the signed message but the verifier must have a copy of the signers certificate available locally (passed using the extracerts to openssl_pkcs7_verify() for example.
PKCS7_NOATTR | normally when a message is signed, a set of attributes are included which include the signing time and the supported symmetric algorithms. With this option they are not included.
PKCS7_DETACHED | When signing a message, use cleartext signing with the MIME type multipart/signed. This is the default if the flags parameter to openssl_pkcs7_sign() if you do not specify any flags. If you turn this option off, the message will be signed using opaque signing, which is more resistant to translation by mail relays but cannot be read by mail agents that do not support S/MIME.
PKCS7_NOSIGS | Don't try and verify the signatures on a message

注: These constants were added in 4.0.6.

目录
openssl_csr_export_to_file — Exports a CSR to a file
openssl_csr_export — Exports a CSR to file or a var
openssl_csr_new — Generates a privkey and CSR
openssl_csr_sign — Signs a cert with another CERT
openssl_error_string — Return openSSL error message
openssl_free_key — Free key resource
openssl_get_privatekey — Prepare a PEM formatted private key for use
openssl_get_publickey — Extract public key from certificate and prepare it for use
openssl_open — Open sealed data
openssl_pkcs7_decrypt — Decrypts an S/MIME encrypted message
openssl_pkcs7_encrypt — Encrypt an S/MIME message
openssl_pkcs7_sign — sign an S/MIME message
openssl_pkcs7_verify — Verifies the signature of an S/MIME signed message
openssl_pkey_export_to_file — Gets an exportable representation of a key into a file
openssl_pkey_export — Gets an exportable representation of a key into a string or file
openssl_pkey_new — Generates a new private key
openssl_private_decrypt — Decrypts data with private key
openssl_private_encrypt — Encrypts data with private key
openssl_public_decrypt — Decrypts data with public key
openssl_public_encrypt — Encrypts data with public key
openssl_seal — Seal (encrypt) data
openssl_sign — Generate signature
openssl_verify — Verify signature
openssl_x509_check_private_key — Checks if a private key corresponds to a CERT
openssl_x509_checkpurpose — Verifies if a certificate can be used for a particular purpose
openssl_x509_export_to_file — Exports a CERT to file or a var
openssl_x509_export — Exports a CERT to file or a var
openssl_x509_free — Free certificate resource
openssl_x509_parse — Parse an X509 certificate and return the information as an array
openssl_x509_read — Parse an X.509 certificate and return a resource identifier for it

后退 | 起点 | 前进
OCIWriteLobToFile | 上一级 | openssl_csr_export_to_file


openssl_csr_export_to_file

(PHP 4 >= 4.2.0)

openssl_csr_export_to_file -- Exports a CSR to a file

Description

bool openssl_csr_export_to_file ( resource csr, string outfilename [, bool notext])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

openssl_csr_export_to_file() takes the CSR represented by csr and saves it into the file named by outfilename. The optional notext affects the verbosity of the output; if it is FALSE then additional human-readable information is included in the output.

后退 | 起点 | 前进
OpenSSL functions | 上一级 | openssl_csr_export


openssl_csr_export

(PHP 4 >= 4.2.0)

openssl_csr_export -- Exports a CSR to file or a var

Description

bool openssl_csr_export ( resource csr, string out [, bool notext])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
openssl_csr_export_to_file | 上一级 | openssl_csr_new


openssl_csr_new

(PHP 4 >= 4.2.0)

openssl_csr_new -- Generates a privkey and CSR

Description

bool openssl_csr_new ( array dn, resource privkey [, array extraattribs [, array configargs]])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

openssl_csr_new() generates a new CSR (Certificate Signing Request) based on the information provided by dn, which represents the Distinguished Name to be used in the certificate.

后退 | 起点 | 前进
openssl_csr_export | 上一级 | openssl_csr_sign


openssl_csr_sign

(PHP 4 >= 4.2.0)

openssl_csr_sign -- Signs a cert with another CERT

Description

resource openssl_csr_sign ( mixed csr, mixed x509, mixed priv_key, long days)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
openssl_csr_new | 上一级 | openssl_error_string


openssl_error_string

(PHP 4 >= 4.0.6)

openssl_error_string -- Return openSSL error message

Description

mixed openssl_error_string ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Returns an error message string, or FALSE if there are no more error messages to return.

openssl_error_string() returns the last error from the openSSL library. Error messages are stacked, so this function should be called multiple times to collect all of the information.

The parameters/return type of this function may change before it appears in a release version of PHP

例子 1. openssl_error_string() example

// lets assume you just called an openssl function that failed
while($msg = openssl_error_string())
    echo $msg . "<br />\n";

注: This function was added in 4.0.6.

后退 | 起点 | 前进
openssl_csr_sign | 上一级 | openssl_free_key


openssl_free_key

(PHP 4 >= 4.0.4)

openssl_free_key -- Free key resource

Description

void openssl_free_key ( resource key_identifier)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

openssl_free_key() frees the key associated with the specified key_identifier from memory.

后退 | 起点 | 前进
openssl_error_string | 上一级 | openssl_get_privatekey


openssl_get_privatekey

(PHP 4 >= 4.0.4)

openssl_get_privatekey -- Prepare a PEM formatted private key for use

Description

resource openssl_get_privatekey ( mixed key [, string passphrase])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Returns a positive key resource identifier on success, or FALSE on error.

openssl_get_privatekey() parses the PEM formatted private key specified by key and prepares it for use by other functions. The optional parameter passphrase must be used if the specified key is encrypted (protected by a passphrase).

后退 | 起点 | 前进
openssl_free_key | 上一级 | openssl_get_publickey


openssl_get_publickey

(PHP 4 >= 4.0.4)

openssl_get_publickey -- Extract public key from certificate and prepare it for use

Description

resource openssl_get_publickey ( mixed certificate)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Returns a positive key resource identifier on success, or FALSE on error.

openssl_get_publickey() extracts the public key from an X.509 certificate specified by certificate and prepares it for use by other functions.

后退 | 起点 | 前进
openssl_get_privatekey | 上一级 | openssl_open


openssl_open

(PHP 4 >= 4.0.4)

openssl_open -- Open sealed data

Description

bool openssl_open ( string sealed_data, string open_data, string env_key, mixed priv_key_id)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

如果成功则返回 TRUE，失败则返回 FALSE。 If successful the opened data is returned in open_data.

openssl_open() opens (decrypts) sealed_data using the private key associated with the key identifier priv_key_id and the envelope key env_key, and fills open_data with the decrypted data. The envelope key is generated when the data are sealed and can only be used by one specific private key. See openssl_seal() for more information.

例子 1. openssl_open() example

// $sealed and $env_key are assumed to contain the sealed data
// and our envelope key, both given to us by the sealer.

// fetch private key from file and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/key.pem", "r");
$priv_key = fread($fp, 8192);
fclose($fp);
$pkeyid = openssl_get_privatekey($priv_key);

// decrypt the data and store it in $open
if (openssl_open($sealed, $open, $env_key, $pkeyid))
    echo "here is the opened data: ", $open;
else
    echo "failed to open data";

// free the private key from memory
openssl_free_key($pkeyid);

See also openssl_seal().

后退 | 起点 | 前进
openssl_get_publickey | 上一级 | openssl_pkcs7_decrypt


openssl_pkcs7_decrypt

(PHP 4 >= 4.0.6)

openssl_pkcs7_decrypt -- Decrypts an S/MIME encrypted message

Description

bool openssl_pkcs7_decrypt ( string infilename, string outfilename, mixed recipcert, mixed recipkey)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Decrypts the S/MIME encrypted message contained in the file specified by infilename using the certificate and it's associated private key specified by recipcert and recipkey.

The decrypted message is output to the file specified by outfilename

例子 1. openssl_pkcs7_decrypt() example

// $cert and $key are assumed to contain your personal certificate and private
// key pair, and that you are the recipient of an S/MIME message
$infilename = "encrypted.msg";  // this file holds your encrypted message
$outfilename = "decrypted.msg"; // make sure you can write to this file

if (openssl_pkcs7_decrypt($infilename, $outfilename, $cert, $key))
    echo "decrypted!";
else
    echo "failed to decrypt!";

注: This function was added in 4.0.6.

后退 | 起点 | 前进
openssl_open | 上一级 | openssl_pkcs7_encrypt


openssl_pkcs7_encrypt

(PHP 4 >= 4.0.6)

openssl_pkcs7_encrypt -- Encrypt an S/MIME message

Description

bool openssl_pkcs7_encrypt ( string infile, string outfile, mixed recipcerts, array headers [, long flags])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

openssl_pkcs7_encrypt() takes the contents of the file named infile and encrypts them using an RC2 40-bit cipher so that they can only be read by the intended recipients specified by recipcerts, which is either a lone X.509 certificate, or an array of X.509 certificates. headers is an array of headers that will be prepended to the data after it has been encrypted. flags can be used to specify options that affect the encoding process - see PKCS7 constants. headers can be either an associative array keyed by header name, or an indexed array, where each element contains a single header line.

例子 1. openssl_pkcs7_encrypt() example

// the message you want to encrypt and send to your secret agent
// in the field, known as nighthawk.  You have his certificate
// in the file nighthawk.pem
$data = <<<EOD
Nighthawk,

Top secret, for your eyes only!

The enemy is closing in! Meet me at the cafe at 8.30am
to collect your forged passport!

HQ
EOD;

// load key
$key = implode("", file("nighthawk.pem"));

// save message to file
$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);

// encrypt it
if (openssl_pkcs7_encrypt("msg.txt", "enc.txt", $key,
    array("To" => "nighthawk@example.com", // keyed
syntax
          "From: HQ <hq@example.com>", // indexed syntax
          "Subject" => "Eyes only")))
{
    // message encrypted - send it!
    exec(ini_get("sendmail_path") . " < enc.txt");
}

后退 | 起点 | 前进
openssl_pkcs7_decrypt | 上一级 | openssl_pkcs7_sign


openssl_pkcs7_sign

(PHP 4 >= 4.0.6)

openssl_pkcs7_sign -- sign an S/MIME message

Description

bool openssl_pkcs7_sign ( string infilename, string outfilename, mixed signcert, mixed privkey, array headers [, long flags [, string extracertsfilename]])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

openssl_pkcs7_sign() takes the contents of the file named infilename and signs them using the certificate and it's matching private key specified by signcert and privkey parameters.

headers is an array of headers that will be prepended to the data after it has been signed (see openssl_pkcs7_encrypt() for more information about the format of this parameter.

flags can be used to alter the output - see PKCS7 constants - if not specified, it defaults to PKCS7_DETACHED.

extracerts specifies the name of a file containing a bunch of extra certificates to include in the signature which can for example be used to help the recipient to verify the certificate that you used.

例子 1. openssl_pkcs7_sign() example

// the message you want to sign so that recipient can be sure it was you that
// sent it
$data = <<<EOD

You have my authorization to spend $10,000 on dinner expenses.

The CEO
EOD;
// save message to file
$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);
// encrypt it
if (openssl_pkcs7_sign("msg.txt", "signed.txt", "mycert.pem",
    array("mycert.pem", "mypassphrase"),
    array("To" => "joes@sales.com", // keyed syntax
          "From: HQ <ceo@sales.com>", // indexed syntax
          "Subject" => "Eyes only"))
{
    // message signed - send it!
    exec(ini_get("sendmail_path") . " < signed.txt");
}

注: This function was added in 4.0.6.

后退 | 起点 | 前进
openssl_pkcs7_encrypt | 上一级 | openssl_pkcs7_verify


openssl_pkcs7_verify

(PHP 4 >= 4.0.6)

openssl_pkcs7_verify -- Verifies the signature of an S/MIME signed message

Description

bool openssl_pkcs7_verify ( string filename, int flags [, string outfilename [, array cainfo [, string extracerts]]])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

openssl_pkcs7_verify() reads the S/MIME message contained in the filename specified by filename and examines the digital signature. It returns TRUE if the signature is verified, FALSE if it is not correct (the message has been tampered with, or the signing certificate is invalid), or -1 on error.

flags can be used to affect how the signature is verified - see PKCS7 constants for more information.

If the outfilename is specified, it should be a string holding the name of a file into which the certificates of the persons that signed the messages will be stored in PEM format.

If the cainfo is specified, it should hold information about the trusted CA certificates to use in the verification process - see certificate verification for more information about this parameter.

If the extracerts is specified, it is the filename of a file containing a bunch of certificates to use as untrusted CAs.

注: This function was added in 4.0.6.

后退 | 起点 | 前进
openssl_pkcs7_sign | 上一级 | openssl_pkey_export_to_file


openssl_pkey_export_to_file

(PHP 4 >= 4.2.0)

openssl_pkey_export_to_file -- Gets an exportable representation of a key into a file

Description

bool openssl_pkey_export_to_file ( mixed key, string outfilename [, string passphrase [, array config_args]])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
openssl_pkcs7_verify | 上一级 | openssl_pkey_export


openssl_pkey_export

(PHP 4 >= 4.2.0)

openssl_pkey_export -- Gets an exportable representation of a key into a string or file

Description

bool openssl_pkey_export ( mixed key, mixed out [, string passphrase [, array config_args]])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
openssl_pkey_export_to_file | 上一级 | openssl_pkey_new


openssl_pkey_new

(PHP 4 >= 4.2.0)

openssl_pkey_new -- Generates a new private key

Description

resource openssl_pkey_new ( [array configargs])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
openssl_pkey_export | 上一级 | openssl_private_decrypt


openssl_private_decrypt

(PHP 4 >= 4.0.6)

openssl_private_decrypt -- Decrypts data with private key

Description

bool openssl_private_decrypt ( string data, string crypted, mixed key [, int padding])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
openssl_pkey_new | 上一级 | openssl_private_encrypt


openssl_private_encrypt

(PHP 4 >= 4.0.6)

openssl_private_encrypt -- Encrypts data with private key

Description

bool openssl_private_encrypt ( string data, string crypted, mixed key [, int padding])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
openssl_private_decrypt | 上一级 | openssl_public_decrypt


openssl_public_decrypt

(PHP 4 >= 4.0.6)

openssl_public_decrypt -- Decrypts data with public key

Description

bool openssl_public_decrypt ( string data, string crypted, resource key [, int padding])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
openssl_private_encrypt | 上一级 | openssl_public_encrypt


openssl_public_encrypt

(PHP 4 >= 4.0.6)

openssl_public_encrypt -- Encrypts data with public key

Description

bool openssl_public_encrypt ( string data, string crypted, mixed key [, int padding])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
openssl_public_decrypt | 上一级 | openssl_seal


openssl_seal

(PHP 4 >= 4.0.4)

openssl_seal -- Seal (encrypt) data

Description

int openssl_seal ( string data, string sealed_data, array env_keys, array pub_key_ids)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Returns the length of the sealed data on success, or FALSE on error. If successful the sealed data is returned in sealed_data, and the envelope keys in env_keys.

openssl_seal() seals (encrypts) data by using RC4 with a randomly generated secret key. The key is encrypted with each of the public keys associated with the identifiers in pub_key_ids and each encrypted key is returned in env_keys. This means that one can send sealed data to multiple recipients (provided one has obtained their public keys). Each recipient must receive both the sealed data and the envelope key that was encrypted with the recipient's public key.

例子 1. openssl_seal() example

// $data is assumed to contain the data to be sealed

// fetch public keys for our recipients, and ready them
$fp = fopen("/src/openssl-0.9.6/demos/maurice/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pk1 = openssl_get_publickey($cert);
// Repeat for second recipient
$fp = fopen("/src/openssl-0.9.6/demos/sign/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pk2 = openssl_get_publickey($cert);

// seal message, only owners of $pk1 and $pk2 can decrypt $sealed with keys
// $ekeys[0] and $ekeys[1] respectively.
openssl_seal($data, $sealed, $ekeys, array($pk1,$pk2));

// free the keys from memory
openssl_free_key($pk1);
openssl_free_key($pk2);

See also openssl_open().

后退 | 起点 | 前进
openssl_public_encrypt | 上一级 | openssl_sign


openssl_sign

(PHP 4 >= 4.0.4)

openssl_sign -- Generate signature

Description

bool openssl_sign ( string data, string signature, mixed priv_key_id)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

如果成功则返回 TRUE，失败则返回 FALSE。 If successful the signature is returned in signature.

openssl_sign() computes a signature for the specified data by using SHA1 for hashing followed by encryption using the private key associated with priv_key_id. Note that the data itself is not encrypted.

例子 1. openssl_sign() example

// $data is assumed to contain the data to be signed

// fetch private key from file and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/key.pem", "r");
$priv_key = fread($fp, 8192);
fclose($fp);
$pkeyid = openssl_get_privatekey($priv_key);

// compute signature
openssl_sign($data, $signature, $pkeyid);

// free the key from memory
openssl_free_key($pkeyid);

See also openssl_verify().

后退 | 起点 | 前进
openssl_seal | 上一级 | openssl_verify


openssl_verify

(PHP 4 >= 4.0.4)

openssl_verify -- Verify signature

Description

int openssl_verify ( string data, string signature, mixed pub_key_id)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Returns 1 if the signature is correct, 0 if it is incorrect, and -1 on error.

openssl_verify() verifies that the signature is correct for the specified data using the public key associated with pub_key_id. This must be the public key corresponding to the private key used for signing.

例子 1. openssl_verify() example

// $data and $signature are assumed to contain the data and the signature

// fetch public key from certificate and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pubkeyid = openssl_get_publickey($cert);

// state whether signature is okay or not
$ok = openssl_verify($data, $signature, $pubkeyid);
if ($ok == 1)
    echo "good";
elseif ($ok == 0)
    echo "bad";
else
    echo "ugly, error checking signature";

// free the key from memory
openssl_free_key($pubkeyid);

See also openssl_sign().

后退 | 起点 | 前进
openssl_sign | 上一级 | openssl_x509_check_private_key


openssl_x509_check_private_key

(PHP 4 >= 4.2.0)

openssl_x509_check_private_key -- Checks if a private key corresponds to a CERT

Description

bool openssl_x509_check_private_key ( mixed cert, mixed key)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
openssl_verify | 上一级 | openssl_x509_checkpurpose


openssl_x509_checkpurpose

(PHP 4 >= 4.0.6)

openssl_x509_checkpurpose -- Verifies if a certificate can be used for a particular purpose

Description

bool openssl_x509_checkpurpose ( mixed x509cert, int purpose, array cainfo [, string untrustedfile])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Returns TRUE if the certificate can be used for the intended purpose, FALSE if it cannot, or -1 on error.

openssl_x509_checkpurpose() examines the certificate specified by x509cert to see if it can be used for the purpose specified by purpose.

cainfo should be an array of trusted CA files/dirs as described in Certificate Verification.

untrustedfile, if specified, is the name of a PEM encoded file holding certificates that can be used to help verify the certificate, although no trust in placed in the certificates that come from that file.

表格 1. openssl_x509_checkpurpose() purposes

Constant | Description
X509_PURPOSE_SSL_CLIENT | Can the certificate be used for the client side of an SSL connection?
X509_PURPOSE_SSL_SERVER | Can the certificate be used for the server side of an SSL connection?
X509_PURPOSE_NS_SSL_SERVER | Can the cert be used for Netscape SSL server?
X509_PURPOSE_SMIME_SIGN | Can the cert be used to sign S/MIME email?
X509_PURPOSE_SMIME_ENCRYPT | Can the cert be used to encrypt S/MIME email?
X509_PURPOSE_CRL_SIGN | Can the cert be used to sign a certificate revocation list (CRL)?
X509_PURPOSE_ANY | Can the cert be used for Any/All purposes?
These options are not bitfields - you may specify one only!

注: This function was added in 4.0.6.

后退 | 起点 | 前进
openssl_x509_check_private_key | 上一级 | openssl_x509_export_to_file


openssl_x509_export_to_file

(PHP 4 >= 4.2.0)

openssl_x509_export_to_file -- Exports a CERT to file or a var

Description

bool openssl_x509_export_to_file ( mixed x509, string outfilename [, bool notext])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
openssl_x509_checkpurpose | 上一级 | openssl_x509_export


openssl_x509_export

(PHP 4 >= 4.2.0)

openssl_x509_export -- Exports a CERT to file or a var

Description

bool openssl_x509_export ( mixed x509, string outfilename [, bool notext])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
openssl_x509_export_to_file | 上一级 | openssl_x509_free


openssl_x509_free

(PHP 4 >= 4.0.6)

openssl_x509_free -- Free certificate resource

Description

void openssl_x509_free ( resource x509cert)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

openssl_x509_free() frees the certificate associated with the specified x509cert resource from memory.

注: This function was added in 4.0.6.

后退 | 起点 | 前进
openssl_x509_export | 上一级 | openssl_x509_parse


openssl_x509_parse

(PHP 4 >= 4.0.6)

openssl_x509_parse -- Parse an X509 certificate and return the information as an array

Description

array openssl_x509_parse ( mixed x509cert [, bool shortnames])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

openssl_x509_parse() returns information about the supplied x509cert, including fields such as subject name, issuer name, purposes, valid from and valid to dates etc. shortnames controls how the data is indexed in the array - if shortnames is TRUE (the default) then fields will be indexed with the short name form, otherwise, the long name form will be used - e.g.: CN is the shortname form of commonName.

The structure of the returned data is (deliberately) not yet documented, as it is still subject to change.

注: This function was added in 4.0.6.

后退 | 起点 | 前进
openssl_x509_free | 上一级 | openssl_x509_read


openssl_x509_read

(PHP 4 >= 4.0.6)

openssl_x509_read -- Parse an X.509 certificate and return a resource identifier for it

Description

resource openssl_x509_read ( mixed x509certdata)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

openssl_x509_read() parses the certificate supplied by x509certdata and returns a resource identifier for it.

注: This function was added in 4.0.6.

后退 | 起点 | 前进
openssl_x509_parse | 上一级 | Oracle functions


Oracle functions

PHP 手册
后退 前进

LXXII. Oracle functions

介绍

This extension adds support for Oracle database server access. See also the OCI8 extension.

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

ORA_BIND_INOUT (integer)

ORA_BIND_IN (integer)

ORA_BIND_OUT (integer)

ORA_FETCHINTO_ASSOC (integer)

ORA_FETCHINTO_NULLS (integer)

目录
Ora_Bind — bind a PHP variable to an Oracle parameter
Ora_Close — close an Oracle cursor
Ora_ColumnName — get name of Oracle result column
Ora_ColumnSize — get size of Oracle result column
Ora_ColumnType — get type of Oracle result column
Ora_Commit — commit an Oracle transaction
Ora_CommitOff — disable automatic commit
Ora_CommitOn — enable automatic commit
Ora_Do — Parse, Exec, Fetch
Ora_Error — get Oracle error message
Ora_ErrorCode — get Oracle error code
Ora_Exec — execute parsed statement on an Oracle cursor
Ora_Fetch_Into — Fetch a row into the specified result array
Ora_Fetch — fetch a row of data from a cursor
Ora_GetColumn — get data from a fetched column
Ora_Logoff — close an Oracle connection
Ora_Logon — open an Oracle connection
Ora_Numcols — Returns the number of columns
Ora_Numrows — Returns the number of rows
Ora_Open — open an Oracle cursor
Ora_Parse — parse an SQL statement
Ora_pLogon — Open a persistent Oracle connection
Ora_Rollback — roll back transaction

后退 | 起点 | 前进
openssl_x509_read | 上一级 | Ora_Bind


Ora_Bind

(PHP 3, PHP 4 )

Ora_Bind -- bind a PHP variable to an Oracle parameter

Description

int ora_bind ( int cursor, string PHP variable name, string SQL parameter name, int length [, int type])

Returns TRUE if the bind succeeds, otherwise FALSE. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

This function binds the named PHP variable with a SQL parameter. The SQL parameter must be in the form ":name". With the optional type parameter, you can define whether the SQL parameter is an in/out (0, default), in (1) or out (2) parameter. As of PHP 3.0.1, you can use the constants ORA_BIND_INOUT, ORA_BIND_IN and ORA_BIND_OUT instead of the numbers.

ora_bind must be called after ora_parse() and before ora_exec(). Input values can be given by assignment to the bound PHP variables, after calling ora_exec() the bound PHP variables contain the output values if available.

<?php
ora_parse($curs, "declare tmp INTEGER; begin tmp := :in; :out := tmp; :x := 7.77; end;");
ora_bind($curs, "result", ":x", $len, 2);
ora_bind($curs, "input", ":in", 5, 1);
ora_bind($curs, "output", ":out", 5, 2);
$input = 765;
ora_exec($curs);
echo "Result: $result<BR>Out: $output<BR>In: $input";
?>

后退 | 起点 | 前进
Oracle functions | 上一级 | Ora_Close


Ora_Close

(PHP 3, PHP 4 )

Ora_Close -- close an Oracle cursor

Description

int ora_close ( int cursor)

Returns TRUE if the close succeeds, otherwise FALSE. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

This function closes a data cursor opened with ora_open().

后退 | 起点 | 前进
Ora_Bind | 上一级 | Ora_ColumnName


Ora_ColumnName

(PHP 3, PHP 4 )

Ora_ColumnName -- get name of Oracle result column

Description

string Ora_ColumnName ( int cursor, int column)

Returns the name of the field/column column on the cursor cursor. The returned name is in all uppercase letters. Column 0 is the first column.

后退 | 起点 | 前进
Ora_Close | 上一级 | Ora_ColumnSize


Ora_ColumnSize

(PHP 3, PHP 4 )

Ora_ColumnSize -- get size of Oracle result column

Description

int Ora_ColumnSize ( int cursor, int column)

Returns the size of the Oracle column column on the cursor cursor. Column 0 is the first column.

后退 | 起点 | 前进
Ora_ColumnName | 上一级 | Ora_ColumnType


Ora_ColumnType

(PHP 3, PHP 4 )

Ora_ColumnType -- get type of Oracle result column

Description

string Ora_ColumnType ( int cursor, int column)

Returns the Oracle data type name of the field/column column on the cursor cursor. Column 0 is the first column. The returned type will be one of the following:

"VARCHAR2"
"VARCHAR"
"CHAR"
"NUMBER"
"LONG"
"LONG RAW"
"ROWID"
"DATE"
"CURSOR"

后退 | 起点 | 前进
Ora_ColumnSize | 上一级 | Ora_Commit


Ora_Commit

(PHP 3, PHP 4 )

Ora_Commit -- commit an Oracle transaction

Description

int ora_commit ( int conn)

Returns TRUE on success, FALSE on error. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

This function commits an Oracle transaction. A transaction is defined as all the changes on a given connection since the last commit/rollback, autocommit was turned off or when the connection was established.

后退 | 起点 | 前进
Ora_ColumnType | 上一级 | Ora_CommitOff


Ora_CommitOff

(PHP 3, PHP 4 )

Ora_CommitOff -- disable automatic commit

Description

int ora_commitoff ( int conn)

Returns TRUE on success, FALSE on error. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

This function turns off automatic commit after each ora_exec().

后退 | 起点 | 前进
Ora_Commit | 上一级 | Ora_CommitOn


Ora_CommitOn

(PHP 3, PHP 4 )

Ora_CommitOn -- enable automatic commit

Description

int ora_commiton ( int conn)

This function turns on automatic commit after each ora_exec() on the given connection.

Returns TRUE on success, FALSE on error. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

后退 | 起点 | 前进
Ora_CommitOff | 上一级 | Ora_Do


Ora_Do

(PHP 3, PHP 4 )

Ora_Do -- Parse, Exec, Fetch

Description

int ora_do ( int conn, string query)

This function is quick combination of ora_parse(), ora_exec() and ora_fetch(). It will parse and execute a statement, then fetch the first result row.

Returns TRUE on success, FALSE on error. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

See also ora_parse(),ora_exec(), and ora_fetch().

后退 | 起点 | 前进
Ora_CommitOn | 上一级 | Ora_Error


Ora_Error

(PHP 3, PHP 4 )

Ora_Error -- get Oracle error message

Description

string Ora_Error ( int cursor_or_connection)

Returns an error message of the form XXX-NNNNN where XXX is where the error comes from and NNNNN identifies the error message.

注: Support for connection ids was added in 3.0.4.

On UNIX versions of Oracle, you can find details about an error message like this: $ oerr ora 00001 00001, 00000, "unique constraint (%s.%s) violated" // *Cause: An update or insert statement attempted to insert a duplicate key // For Trusted ORACLE configured in DBMS MAC mode, you may see // this message if a duplicate entry exists at a different level. // *Action: Either remove the unique restriction or do not insert the key

后退 | 起点 | 前进
Ora_Do | 上一级 | Ora_ErrorCode


Ora_ErrorCode

(PHP 3, PHP 4 )

Ora_ErrorCode -- get Oracle error code

Description

int Ora_ErrorCode ( int cursor_or_connection)

Returns the numeric error code of the last executed statement on the specified cursor or connection.

注: Support for connection ids was added in 3.0.4.

后退 | 起点 | 前进
Ora_Error | 上一级 | Ora_Exec


Ora_Exec

(PHP 3, PHP 4 )

Ora_Exec -- execute parsed statement on an Oracle cursor

Description

int ora_exec ( int cursor)

Returns TRUE on success, FALSE on error. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

See also ora_parse(), ora_fetch(), and ora_do().

后退 | 起点 | 前进
Ora_ErrorCode | 上一级 | Ora_Fetch_Into


Ora_Fetch_Into

(PHP 3, PHP 4 )

Ora_Fetch_Into -- Fetch a row into the specified result array

Description

int ora_fetch_into ( int cursor, array result [, int flags])

Fetches a row of data into an array. The flags has two flag values: if the ORA_FETCHINTO_NULLS flag is set, columns with NULL values are set in the array; and if the ORA_FETCHINTO_ASSOC flag is set, an associative array is created.

Returns the number of columns fetched.

例子 1. ora_fetch_into()()

<?php
$results = array();
ora_fetch_into($cursor, $results);
echo $results[0];
echo $results[1];
$results = array();
ora_fetch_into($cursor, $results, ORA_FETCHINTO_NULLS|ORA_FETCHINTO_ASSOC);
echo $results['MyColumn'];
?>

See also ora_parse(),ora_exec(), ora_fetch(), and ora_do().

后退 | 起点 | 前进
Ora_Exec | 上一级 | Ora_Fetch


Ora_Fetch

(PHP 3, PHP 4 )

Ora_Fetch -- fetch a row of data from a cursor

Description

int ora_fetch ( int cursor)

Returns TRUE (a row was fetched) or FALSE (no more rows, or an
error occured). If an error occured, details can be retrieved
using the ora_error() and
ora_errorcode() functions. If there was no
error, ora_errorcode() will return 0.

Retrieves a row of data from the specified cursor.

See also ora_parse(),ora_exec(), and ora_do().

后退 | 起点 | 前进
Ora_Fetch_Into | 上一级 | Ora_GetColumn


Ora_GetColumn

(PHP 3, PHP 4 )

Ora_GetColumn -- get data from a fetched column

Description

mixed ora_getcolumn ( int cursor, mixed column)

Returns the column data. If an error occurs, FALSE is returned and ora_errorcode() will return a non-zero value. Note, however, that a test for FALSE on the results from this function may be TRUE in cases where there is not error as well (NULL result, empty string, the number 0, the string "0").

Fetches the data for a column or function result.

后退 | 起点 | 前进
Ora_Fetch | 上一级 | Ora_Logoff


Ora_Logoff

(PHP 3, PHP 4 )

Ora_Logoff -- close an Oracle connection

Description

int ora_logoff ( int connection)

Returns TRUE on success, FALSE on error. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

Logs out the user and disconnects from the server.

See also ora_logon().

后退 | 起点 | 前进
Ora_GetColumn | 上一级 | Ora_Logon


Ora_Logon

(PHP 3, PHP 4 )

Ora_Logon -- open an Oracle connection

Description

int ora_logon ( string user, string password)

Establishes a connection between PHP and an Oracle database with the given username and password.

Connections can be made using SQL*Net by supplying the TNS name to user like this:

$conn = Ora_Logon("user<emphasis>@TNSNAME</emphasis>", "pass");

If you have character data with non-ASCII characters, you should make sure that NLS_LANG is set in your environment. For server modules, you should set it in the server's environment before starting the server.

Returns a connection index on success, or FALSE on failure. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

后退 | 起点 | 前进
Ora_Logoff | 上一级 | Ora_Numcols


Ora_Numcols

(PHP 3, PHP 4 )

Ora_Numcols -- Returns the number of columns

Description

int ora_numcols ( int cursor_ind)

ora_numcols() returns the number of columns in a result. Only returns meaningful values after an parse/exec/fetch sequence.

See also ora_parse(),ora_exec(), ora_fetch(), and ora_do().

后退 | 起点 | 前进
Ora_Logon | 上一级 | Ora_Numrows


Ora_Numrows

(PHP 3, PHP 4 )

Ora_Numrows -- Returns the number of rows

Description

int ora_numrows ( int cursor_ind)

ora_numrows() returns the number of rows in a result.

后退 | 起点 | 前进
Ora_Numcols | 上一级 | Ora_Open


Ora_Open

(PHP 3, PHP 4 )

Ora_Open -- open an Oracle cursor

Description

int ora_open ( int connection)

Opens an Oracle cursor associated with connection.

Returns a cursor index or FALSE on failure. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

后退 | 起点 | 前进
Ora_Numrows | 上一级 | Ora_Parse


Ora_Parse

(PHP 3, PHP 4 )

Ora_Parse -- parse an SQL statement

Description

int ora_parse ( int cursor_ind, string sql_statement, int defer)

This function parses an SQL statement or a PL/SQL block and associates it with the given cursor.

如果成功则返回 TRUE，失败则返回 FALSE。

See also ora_exec(), ora_fetch(), and ora_do().

后退 | 起点 | 前进
Ora_Open | 上一级 | Ora_pLogon


Ora_pLogon

(PHP 3, PHP 4 )

Ora_pLogon -- Open a persistent Oracle connection

Description

int ora_plogon ( string user, string password)

Establishes a persistent connection between PHP and an Oracle database with the given username and password.

See also ora_logon().

后退 | 起点 | 前进
Ora_Parse | 上一级 | Ora_Rollback


Ora_Rollback

(PHP 3, PHP 4 )

Ora_Rollback -- roll back transaction

Description

int ora_rollback ( int connection)

This function undoes an Oracle transaction. (See ora_commit() for the definition of a transaction.)

Returns TRUE on success, FALSE on error. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

后退 | 起点 | 前进
Ora_pLogon | 上一级 | Ovrimos SQL functions


Ovrimos SQL functions

PHP 手册
后退 前进

LXXIII. Ovrimos SQL functions

介绍

Ovrimos SQL Server, is a client/server, transactional RDBMS combined with Web capabilities and fast transactions.

需求

Ovrimos SQL Server is available at http://www.ovrimos.com/. You'll need to install the sqlcli library available in the Ovrimos SQL Server distribution.

安装

To enable Ovrimos support in PHP just compile PHP with the --with-ovrimos parameter to configure script.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

范例

例子 1. Connect to Ovrimos SQL Server and select from a system table

<?php
$conn = ovrimos_connect ("server.domain.com", "8001", "admin", "password");
if ($conn != 0) {
    echo ("Connection ok!");
    $res = ovrimos_exec ($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        ovrimos_result_all ($res);
        ovrimos_free_result ($res);
    }
    ovrimos_close($conn);
}
?>
This will just connect to an Ovrimos SQL server.

目录
ovrimos_close — Closes the connection to ovrimos
ovrimos_commit — Commits the transaction
ovrimos_connect — Connect to the specified database
ovrimos_cursor — Returns the name of the cursor
ovrimos_exec — Executes an SQL statement
ovrimos_execute — Executes a prepared SQL statement
ovrimos_fetch_into — Fetches a row from the result set
ovrimos_fetch_row — Fetches a row from the result set
ovrimos_field_len — Returns the length of the output column
ovrimos_field_name — Returns the output column name
ovrimos_field_num — Returns the (1-based) index of the output column
ovrimos_field_type — Returns the (numeric) type of the output column
ovrimos_free_result — Frees the specified result_id
ovrimos_longreadlen — Specifies how many bytes are to be retrieved from long datatypes
ovrimos_num_fields — Returns the number of columns
ovrimos_num_rows — Returns the number of rows affected by update operations
ovrimos_prepare — Prepares an SQL statement
ovrimos_result_all — Prints the whole result set as an HTML table
ovrimos_result — Retrieves the output column
ovrimos_rollback — Rolls back the transaction

后退 | 起点 | 前进
Ora_Rollback | 上一级 | ovrimos_close


ovrimos_close

(PHP 4 >= 4.0.3)

ovrimos_close -- Closes the connection to ovrimos

Description

void ovrimos_close ( int connection)

ovrimos_close() is used to close the specified connection.

ovrimos_close() closes a connection to Ovrimos. This has the effect of rolling back uncommitted transactions.

后退 | 起点 | 前进
Ovrimos SQL functions | 上一级 | ovrimos_commit


ovrimos_commit

(PHP 4 >= 4.0.3)

ovrimos_commit -- Commits the transaction

Description

int ovrimos_commit ( int connection_id)

ovrimos_commit() is used to commit the transaction.

ovrimos_commit() commits the transaction.

后退 | 起点 | 前进
ovrimos_close | 上一级 | ovrimos_connect


ovrimos_connect

(PHP 4 >= 4.0.3)

ovrimos_connect -- Connect to the specified database

Description

int ovrimos_connect ( string host, string db, string user, string password)

ovrimos_connect() is used to connect to the specified database.

ovrimos_connect() returns a connection id (greater than 0) or 0 for failure. The meaning of 'host' and 'port' are those used everywhere in Ovrimos APIs. 'Host' is a host name or IP address and 'db' is either a database name, or a string containing the port number.

例子 1. ovrimos_connect() Example

<?php
$conn = ovrimos_connect ("server.domain.com", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res=ovrimos_exec ($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        ovrimos_result_all ($res);
        ovrimos_free_result ($res);
    }
    ovrimos_close($conn);
}
?>
The above example will connect to the database and print out the specified table.

后退 | 起点 | 前进
ovrimos_commit | 上一级 | ovrimos_cursor


ovrimos_cursor

(PHP 4 >= 4.0.3)

ovrimos_cursor -- Returns the name of the cursor

Description

int ovrimos_cursor ( int result_id)

ovrimos_cursor() is used to get the name of the cursor.

ovrimos_cursor() returns the name of the cursor. Useful when wishing to perform positioned updates or deletes.

后退 | 起点 | 前进
ovrimos_connect | 上一级 | ovrimos_exec


ovrimos_exec

(PHP 4 >= 4.0.3)

ovrimos_exec -- Executes an SQL statement

Description

int ovrimos_exec ( int connection_id, string query)

ovrimos_exec() is used to execute an SQL statement.

ovrimos_exec() executes an SQL statement (query or update) and returns a result_id or FALSE. Evidently, the SQL statement should not contain parameters.

后退 | 起点 | 前进
ovrimos_cursor | 上一级 | ovrimos_execute


ovrimos_execute

(PHP 4 >= 4.0.3)

ovrimos_execute -- Executes a prepared SQL statement

Description

bool ovrimos_execute ( int result_id [, array parameters_array])

ovrimos_execute() is used to execute an SQL statement.

ovrimos_execute() executes a prepared statement. Returns TRUE or FALSE. If the prepared statement contained parameters (question marks in the statement), the correct number of parameters should be passed in an array. Notice that I don't follow the PHP convention of placing just the name of the optional parameter inside square brackets. I couldn't bring myself on liking it.

后退 | 起点 | 前进
ovrimos_exec | 上一级 | ovrimos_fetch_into


ovrimos_fetch_into

(PHP 4 >= 4.0.3)

ovrimos_fetch_into -- Fetches a row from the result set

Description

bool ovrimos_fetch_into ( int result_id, array result_array [, string how [, int rownumber]])

ovrimos_fetch_into() is used to fetch a row from the result set.

ovrimos_fetch_into() fetches a row from the result set into 'result_array', which should be passed by reference. Which row is fetched is determined by the two last parameters. 'how' is one of 'Next' (default), 'Prev', 'First', 'Last', 'Absolute', corresponding to forward direction from current position, backward direction from current position, forward direction from the start, backward direction from the end and absolute position from the start (essentially equivalent to 'first' but needs 'rownumber'). Case is not significant. 'Rownumber' is optional except for absolute positioning. Returns TRUE or FALSE.

例子 1. A fetch into example

<?php
$conn=ovrimos_connect ("neptune", "8001", "admin", "password");
if ($conn!=0) {
    echo "Connection ok!";
    $res=ovrimos_exec ($conn,"select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        if (ovrimos_fetch_into ($res, &$row)) {
            list ($table_id, $table_name) = $row;
            echo "table_id=".$table_id.", table_name=".$table_name."\n";
            if (ovrimos_fetch_into ($res, &$row)) {
                list ($table_id, $table_name) = $row;
                echo "table_id=".$table_id.", table_name=".$table_name."\n";
            } else {
                echo "Next: error\n";
            }
        } else {
            echo "First: error\n";
        }
        ovrimos_free_result ($res);
    }
    ovrimos_close($conn);
}
?>
This example will fetch a row.

后退 | 起点 | 前进
ovrimos_execute | 上一级 | ovrimos_fetch_row


ovrimos_fetch_row

(PHP 4 >= 4.0.3)

ovrimos_fetch_row -- Fetches a row from the result set

Description

bool ovrimos_fetch_row ( int result_id [, int how [, int row_number]])

ovrimos_fetch_row() is used to fetch a row from the result set.

ovrimos_fetch_row() fetches a row from the result set. Column values should be retrieved with other calls. Returns TRUE or FALSE.

例子 1. A fetch row example

<?php
$conn = ovrimos_connect ("remote.host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res=ovrimos_exec ($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        if (ovrimos_fetch_row ($res, "First")) {
            $table_id = ovrimos_result ($res, 1);
            $table_name = ovrimos_result ($res, 2);
            echo "table_id=".$table_id.", table_name=".$table_name."\n";
            if (ovrimos_fetch_row ($res, "Next")) {
                $table_id = ovrimos_result ($res, "table_id");
                $table_name = ovrimos_result ($res, "table_name");
                echo "table_id=".$table_id.", table_name=".$table_name."\n";
            } else {
                echo "Next: error\n";
            }
        } else {
            echo "First: error\n";
        }
        ovrimos_free_result ($res);
    }
    ovrimos_close($conn);
}
?>
This will fetch a row and print the result.

后退 | 起点 | 前进
ovrimos_fetch_into | 上一级 | ovrimos_field_len


ovrimos_field_len

(PHP 4 >= 4.0.3)

ovrimos_field_len -- Returns the length of the output column

Description

int ovrimos_field_len ( int result_id, int field_number)

ovrimos_field_len() is used to get the length of the output column with number field_number, in result result_id.

ovrimos_field_len() returns the length of the output column at the (1-based) index specified.

后退 | 起点 | 前进
ovrimos_fetch_row | 上一级 | ovrimos_field_name


ovrimos_field_name

(PHP 4 >= 4.0.3)

ovrimos_field_name -- Returns the output column name

Description

int ovrimos_field_name ( int result_id, int field_number)

ovrimos_field_name() is used to get the output column name.

ovrimos_field_name() returns the output column name at the (1-based) index specified.

后退 | 起点 | 前进
ovrimos_field_len | 上一级 | ovrimos_field_num


ovrimos_field_num

(PHP 4 >= 4.0.3)

ovrimos_field_num -- Returns the (1-based) index of the output column

Description

int ovrimos_field_num ( int result_id, string field_name)

ovrimos_field_num() is used to get the (1-based) index of the output column.

ovrimos_field_num() returns the (1-based) index of the output column specified by name, or FALSE.

后退 | 起点 | 前进
ovrimos_field_name | 上一级 | ovrimos_field_type


ovrimos_field_type

(PHP 4 >= 4.0.3)

ovrimos_field_type -- Returns the (numeric) type of the output column

Description

int ovrimos_field_type ( int result_id, int field_number)

ovrimos_field_type() is used to get the (numeric) type of the output column.

ovrimos_field_type() returns the (numeric) type of the output column at the (1-based) index specified.

后退 | 起点 | 前进
ovrimos_field_num | 上一级 | ovrimos_free_result


ovrimos_free_result

(PHP 4 >= 4.0.3)

ovrimos_free_result -- Frees the specified result_id

Description

bool ovrimos_free_result ( int result_id)

ovrimos_free_result() is used to free the result_id.

ovrimos_free_result() frees the specified result_id result_id. Returns TRUE.

后退 | 起点 | 前进
ovrimos_field_type | 上一级 | ovrimos_longreadlen


ovrimos_longreadlen

(PHP 4 >= 4.0.3)

ovrimos_longreadlen -- Specifies how many bytes are to be retrieved from long datatypes

Description

int ovrimos_longreadlen ( int result_id, int length)

ovrimos_longreadlen() is used to specify how many bytes are to be retrieved from long datatypes.

ovrimos_longreadlen() specifies how many bytes are to be retrieved from long datatypes (long varchar and long varbinary). Default is zero. It currently sets this parameter the specified result set. Returns TRUE.

后退 | 起点 | 前进
ovrimos_free_result | 上一级 | ovrimos_num_fields


ovrimos_num_fields

(PHP 4 >= 4.0.3)

ovrimos_num_fields -- Returns the number of columns

Description

int ovrimos_num_fields ( int result_id)

ovrimos_num_fields() is used to get the number of columns.

ovrimos_num_fields() returns the number of columns in a result_id resulting from a query.

后退 | 起点 | 前进
ovrimos_longreadlen | 上一级 | ovrimos_num_rows


ovrimos_num_rows

(PHP 4 >= 4.0.3)

ovrimos_num_rows -- Returns the number of rows affected by update operations

Description

int ovrimos_num_rows ( int result_id)

ovrimos_num_rows() is used to get the number of rows affected by update operations.

ovrimos_num_rows() returns the number of rows affected by update operations.

后退 | 起点 | 前进
ovrimos_num_fields | 上一级 | ovrimos_prepare


ovrimos_prepare

(PHP 4 >= 4.0.3)

ovrimos_prepare -- Prepares an SQL statement

Description

int ovrimos_prepare ( int connection_id, string query)

ovrimos_prepare() is used to prepare an SQL statement.

ovrimos_prepare() prepares an SQL statement and returns a result_id (or FALSE on failure).

例子 1. Connect to Ovrimos SQL Server and prepare a statement

<?php
$conn=ovrimos_connect ("db_host", "8001", "admin", "password");
if ($conn!=0) {
    echo "Connection ok!";
    $res=ovrimos_prepare ($conn, "select table_id, table_name
                                  from sys.tables where table_id=1");
    if ($res != 0) {
        echo "Prepare ok!";
        if (ovrimos_execute ($res)) {
            echo "Execute ok!\n";
            ovrimos_result_all ($res);
        } else {
            echo "Execute not ok!";
        }
        ovrimos_free_result ($res);
    } else {
        echo "Prepare not ok!\n";
    }
    ovrimos_close($conn);
}
?>
This will connect to Ovrimos SQL Server, prepare a statement and the execute it.

后退 | 起点 | 前进
ovrimos_num_rows | 上一级 | ovrimos_result_all


ovrimos_result_all

(PHP 4 >= 4.0.3)

ovrimos_result_all -- Prints the whole result set as an HTML table

Description

bool ovrimos_result_all ( int result_id [, string format])

ovrimos_result_all() is used to print an HTML table containing the whole result set.

ovrimos_result_all() prints the whole result set as an HTML table. Returns TRUE or FALSE.

例子 1. Prepare a statement, execute, and view the result

<?php
$conn = ovrimos_connect ("db_host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res = ovrimos_prepare ($conn, "select table_id, table_name
                                    from sys.tables where table_id = 7");
    if ($res != 0) {
        echo "Prepare ok!";
        if (ovrimos_execute ($res, array(3))) {
            echo "Execute ok!\n";
            ovrimos_result_all ($res);
        } else {
            echo "Execute not ok!";
        }
        ovrimos_free_result ($res);
    } else {
        echo "Prepare not ok!\n";
    }
    ovrimos_close($conn);
}
?>
This will execute an SQL statement and print the result in an HTML table.

例子 2. Ovrimos_result_all with meta-information

<?php
$conn = ovrimos_connect ("db_host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res = ovrimos_exec ($conn, "select table_id, table_name
                                 from sys.tables where table_id = 1")
    if ($res != 0) {
        echo "Statement ok! cursor=".ovrimos_cursor ($res)."\n";
        $colnb = ovrimos_num_fields ($res);
        echo "Output columns=".$colnb."\n";
        for ($i=1; $i <= $colnb; $i++) {
            $name = ovrimos_field_name ($res, $i);
            $type = ovrimos_field_type ($res, $i);
            $len = ovrimos_field_len ($res, $i);
            echo "Column ".$i." name=".$name." type=".$type." len=".$len."\n";
        }
        ovrimos_result_all ($res);
        ovrimos_free_result ($res);
    }
    ovrimos_close($conn);
}
?>

例子 3. ovrimos_result_all example

<?php
$conn = ovrimos_connect ("db_host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res = ovrimos_exec ($conn, "update test set i=5");
    if ($res != 0) {
        echo "Statement ok!";
        echo ovrimos_num_rows ($res)." rows affected\n";
        ovrimos_free_result ($res);
    }
    ovrimos_close($conn);
}
?>

后退 | 起点 | 前进
ovrimos_prepare | 上一级 | ovrimos_result


ovrimos_result

(PHP 4 >= 4.0.3)

ovrimos_result -- Retrieves the output column

Description

int ovrimos_result ( int result_id, mixed field)

ovrimos_result() is used to retrieve the output column.

ovrimos_result() retrieves the output column specified by 'field', either as a string or as an 1-based index.

后退 | 起点 | 前进
ovrimos_result_all | 上一级 | ovrimos_rollback


ovrimos_rollback

(PHP 4 >= 4.0.3)

ovrimos_rollback -- Rolls back the transaction

Description

int ovrimos_rollback ( int connection_id)

ovrimos_rollback() is used to roll back the transaction.

ovrimos_rollback() rolls back the transaction.

后退 | 起点 | 前进
ovrimos_result | 上一级 | Output Control Functions


Output Control Functions

PHP 手册
后退 前进

LXXIV. Output Control Functions

介绍

The Output Control functions allow you to control when output is sent from the script. This can be useful in several different situations, especially if you need to send headers to the browser after your script has began outputting data. The Output Control functions do not affect headers sent using header() or setcookie(), only functions such as echo() and data between blocks of PHP code.

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

这些函数作为 PHP 核心的一部分，无需被安装即可使用。

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. Output Control configuration options

Name | Default | Changeable
output_buffering | "0" | PHP_INI_PERDIR|PHP_INI_SYSTEM
output_handler | NULL | PHP_INI_PERDIR|PHP_INI_SYSTEM
implicit_flush | "0" | PHP_INI_PERDIR|PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().

Here is a short explanation of the configuration directives.

output_buffering boolean/integer

You can enable output buffering for all files by setting this directive to 'On'. If you wish to limit the size of the buffer to a certain size - you can use a maximum number of bytes instead of 'On', as a value for this directive (e.g., output_buffering=4096).

output_handler string

You can redirect all of the output of your scripts to a function. For example, if you set output_handler to mb_output_handler(), character encoding will be transparently converted to the specified encoding. Setting any output handler automatically turns on output buffering.

注:
      You cannot use both mb_output_handler() with
      ob_inconv_handler() and you cannot use both
      ob_gzhandler() and
      zlib.output_compression.

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

范例

例子 1. Output Control example

<?php

ob_start();
echo "Hello\n";

setcookie ("cookiename", "cookiedata");

ob_end_flush();

?>

In the above example, the output from echo() would be stored in the output buffer until ob_end_flush() was called. In the mean time, the call to setcookie() successfully stored a cookie without causing an error. (You can not normally send headers to the browser after data has already been sent.)

相关参考

See also header(), setcookie() and .

目录
flush — Flush the output buffer
ob_clean — Clean (erase) the output buffer
ob_end_clean — Clean (erase) the output buffer and turn off output buffering
ob_end_flush — Flush (send) the output buffer and turn off output buffering
ob_flush — Flush (send) the output buffer
ob_get_contents — Return the contents of the output buffer
ob_get_length — Return the length of the output buffer
ob_get_level — Return the nesting level of the output buffering mechanism
ob_get_status — Get status of output buffers
ob_gzhandler — ob_start callback function to gzip output buffer
ob_implicit_flush — Turn implicit flush on/off
ob_start — Turn on output buffering

后退 | 起点 | 前进
ovrimos_rollback | 上一级 | flush


flush

(PHP 3, PHP 4 )

flush -- Flush the output buffer

Description

void flush ( void)

Flushes the output buffers of PHP and whatever backend PHP is using (CGI, a web server, etc). This effectively tries to push all the output so far to the user's browser.

注: flush() has no effect on the buffering scheme of your webserver or the browser on the client side.

Several servers, especially on Win32, will still buffer the output from your script until it terminates before transmitting the results to the browser.

Server modules for Apache like mod_gzip may do buffering of their own that will cause flush() to not result in data being sent immediately to the client.

Even the browser may buffer its input before displaying it. Netscape, for example, buffers text until it receives an end-of-line or the beginning of a tag, and it won't render tables until the </table> tag of the outermost table is seen.

Some versions of Microsoft Internet Explorer will only start to display the page after they have received 256 bytes of output, so you may need to send extra whitespace before flushing to get those browsers to display the page.

后退 | 起点 | 前进
Output Control Functions | 上一级 | ob_clean


ob_clean

(PHP 4 >= 4.2.0)

ob_clean -- Clean (erase) the output buffer

Description

void ob_clean ( void)

This function discards the contents of the output buffer.

This function does not destroy the output buffer like ob_end_clean() does.

See also ob_flush(),
ob_end_flush() and
ob_end_clean().

后退 | 起点 | 前进
flush | 上一级 | ob_end_clean


ob_end_clean

(PHP 4 )

ob_end_clean -- Clean (erase) the output buffer and turn off output buffering

Description

void ob_end_clean ( void)

This function discards the contents of the output buffer and turns off output buffering.

See also ob_start(),
ob_clean() and
ob_end_flush().

后退 | 起点 | 前进
ob_clean | 上一级 | ob_end_flush


ob_end_flush

(PHP 4 )

ob_end_flush -- Flush (send) the output buffer and turn off output buffering

Description

void ob_end_flush ( void)

This function will send the contents of the output buffer (if any) and turn output buffering off. If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_flush() as the buffer contents are discarded after ob_end_flush() is called.

See also ob_start(),
ob_get_contents(),
ob_flush() and
ob_end_clean().

后退 | 起点 | 前进
ob_end_clean | 上一级 | ob_flush


ob_flush

(PHP 4 >= 4.2.0)

ob_flush -- Flush (send) the output buffer

Description

void ob_flush ( void)

This function will send the contents of the output buffer (if any). If you want to further process the buffer's contents you have to call ob_get_contents() before ob_flush() as the buffer contents are discarded after ob_flush() is called.

This function does not destroy the output buffer like ob_end_flush() does.

See also ob_get_contents(),
ob_clean(),
ob_end_flush() and
ob_end_clean().

后退 | 起点 | 前进
ob_end_flush | 上一级 | ob_get_contents


ob_get_contents

(PHP 4 )

ob_get_contents -- Return the contents of the output buffer

Description

string ob_get_contents ( void)

This will return the contents of the output buffer or FALSE, if output buffering isn't active.

See also ob_start() and ob_get_length().

后退 | 起点 | 前进
ob_flush | 上一级 | ob_get_length


ob_get_length

(PHP 4 >= 4.0.2)

ob_get_length -- Return the length of the output buffer

Description

string ob_get_length ( void)

This will return the length of the contents in the output buffer or FALSE, if output buffering isn't active.

See also ob_start() and ob_get_contents().

后退 | 起点 | 前进
ob_get_contents | 上一级 | ob_get_level


ob_get_level

(PHP 4 >= 4.2.0)

ob_get_level -- Return the nesting level of the output buffering mechanism

Description

int ob_get_level ( void)

This will return the level of nested output buffering handlers.

See also ob_start() and ob_get_contents().

后退 | 起点 | 前进
ob_get_length | 上一级 | ob_get_status


ob_get_status

(PHP 4 >= 4.2.0)

ob_get_status -- Get status of output buffers

Description

array ob_get_status ( [bool full_status])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

This will return the current status of output buffers. It returns array contains buffer status or FALSE for error.

See also ob_get_level().

后退 | 起点 | 前进
ob_get_level | 上一级 | ob_gzhandler


ob_gzhandler

(PHP 4 >= 4.0.4)

ob_gzhandler -- ob_start callback function to gzip output buffer

Description

string ob_gzhandler ( string buffer [, int mode])

注: mode was added in PHP 4.0.5.

ob_gzhandler() is intended to be used as a callback function for ob_start() to help facilitate sending gz-encoded data to web browsers that support compressed web pages. Before ob_gzhandler() actually sends compressed data, it determines what type of content encoding the browser will accept ("gzip", "deflate" or none at all) and will return it's output accordingly. All browsers are supported since it's up to the browser to send the correct header saying that it accepts compressed web pages.

例子 1. ob_gzhandler() Example

<?php

ob_start("ob_gzhandler");

?>
<html>
<body>
<p>This should be a compressed page.
</html>
<body>

See also ob_start() and ob_end_flush().

后退 | 起点 | 前进
ob_get_status | 上一级 | ob_implicit_flush


ob_implicit_flush

(PHP 4 )

ob_implicit_flush -- Turn implicit flush on/off

Description

void ob_implicit_flush ( [int flag])

ob_implicit_flush() will turn implicit flushing on or off (if no flag is given, it defaults to on). Implicit flushing will result in a flush operation after every output call, so that explicit calls to flush() will no longer be needed.

Turning implicit flushing on will disable output buffering, the output buffers current output will be sent as if ob_end_flush() had been called.

See also flush(),
ob_start(), and
ob_end_flush().

后退 | 起点 | 前进
ob_gzhandler | 上一级 | ob_start


ob_start

(PHP 4 )

ob_start -- Turn on output buffering

Description

void ob_start ( [string output_callback])

This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.

The contents of this internal buffer may be copied into a string variable using ob_get_contents(). To output what is stored in the internal buffer, use ob_end_flush(). Alternatively, ob_end_clean() will silently discard the buffer contents.

An optional output_callback function may be specified. This function takes a string as a parameter and should return a string. The function will be called when ob_end_flush() is called, or when the output buffer is flushed to the browser at the end of the request. When output_callback is called, it will receive the contents of the output buffer as its parameter and is expected to return a new output buffer as a result, which will be sent to the browser.

注: In PHP 4.0.4, ob_gzhandler() was introduced to facilitate sending gz-encoded data to web browsers that support compressed web pages. ob_gzhandler() determines what type of content encoding the browser will accept and will return it's output accordingly.

Output buffers are stackable, that is, you may call ob_start() while another ob_start() is active. Just make sure that you call ob_end_flush() the appropriate number of times. If multiple output callback functions are active, output is being filtered sequentially through each of them in nesting order.

ob_end_clean(), ob_end_flush(), ob_clean(), ob_flush() and ob_start() may not be called from a callback function. If you call them from callback function, the behavior is undefined. If you would like to delete the contents of a buffer, return "" (a null string) from callback function.

例子 1. User defined callback function example

<?php

function callback($buffer) {

  // replace all the apples with oranges
  return (ereg_replace("apples", "oranges", $buffer));

}

ob_start("callback");

?>

<html>
<body>
<p>It's like comparing apples to oranges.
</body>
</html>

<?php

ob_end_flush();

?>

Would produce:

<html>
<body>
<p>It's like comparing oranges to oranges.
</body>
</html>

See also ob_get_contents(),
ob_end_flush(),
ob_end_clean(),
ob_implicit_flush() and
ob_gzhandler().

后退 | 起点 | 前进
ob_implicit_flush | 上一级 | Object property and method call overloading


Object property and method call overloading

PHP 手册
后退 前进

LXXV. Object property and method call overloading

介绍

The purpose of this extension is to allow overloading of object property access and method calls. Only one function is defined in this extension, overload() which takes the name of the class that should have this functionality enabled. The class named has to define appropriate methods if it wants to have this functionality: __get(), __set() and __call() respectively for getting/setting a property, or calling a method. This way overloading can be selective. Inside these handler functions the overloading is disabled so you can access object properties normally.

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

In order to use these functions, you must compile PHP with the --enable-overload option.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

范例

Some simple examples on using the overload() function:

例子 1. Overloading a PHP class

<?php

class OO
{
    var $a = 111;
    var $elem = array('b' => 9, 'c' => 42);

    // Callback method for getting a property
    function __get($prop_name, &$prop_value)
    {
        if (isset($this->elem[$prop_name])) {
            $prop_value = $this->elem[$prop_name];
            return true;
        } else {
            return false;
        }
    }

    // Callback method for setting a property
    function __set($prop_name, $prop_value)
    {
        $this->elem[$prop_name] = $prop_value;
        return true;
    }
}

// Here we overload the OO object
overload('OO');

$o = new OO;
print "\$o->a: $o->a\n"; // print: $o->a:
print "\$o->b: $o->b\n"; // print: $o->b: 9
print "\$o->c: $o->c\n"; // print: $o->c: 42
print "\$o->d: $o->d\n"; // print: $o->d:

// add a new item to the $elem array in OO
$o->x = 56;

// instantiate stdclass (it is built-in in PHP 4)
// $val is not overloaded!
$val = new stdclass;
$val->prop = 555;

// Set "a" to be an array with the $val object in it
// But __set() will put this in the $elem array
$o->a = array($val);
var_dump($o->a[0]->prop);

?>

警告

As this is an experimental extension, not all things work. There is no __call() support currently, you can only overload the get and set operations for properties. You cannot invoke the original overloading handlers of the class, and __set() only works to one level of property access.

目录
overload — Enable property and method call overloading for a class

后退 | 起点 | 前进
ob_start | 上一级 | overload


overload

(PHP 4 >= 4.2.0)

overload -- Enable property and method call overloading for a class

Description

void overload ( [string class_name])

The overload() function will enable property and method call overloading for a class identified by class_name. See an example in the introductory section of this part.

后退 | 起点 | 前进
Object property and method call overloading | 上一级 | PDF functions


PDF functions

PHP 手册
后退 前进

LXXVI. PDF functions

介绍

The PDF functions in PHP can create PDF files using the PDFlib library created by Thomas Merz.

The documentation in this section is only meant to be an overview of the available functions in the PDFlib library and should not be considered an exhaustive reference. Please consult the documentation included in the source distribution of PDFlib for the full and detailed explanation of each function here. It provides a very good overview of what PDFlib is capable of doing and contains the most up-to-date documentation of all functions.

All of the functions in PDFlib and the PHP module have identical function names and parameters. You will need to understand some of the basic concepts of PDF and PostScript to efficiently use this extension. All lengths and coordinates are measured in PostScript points. There are generally 72 PostScript points to an inch, but this depends on the output resolution. Please see the PDFlib documentation included with the source distribution of PDFlib for a more thorough explanation of the coordinate system used.

Please note that most of the PDF functions require a pdf object as its first parameter. Please see the examples below for more information.

需求

PDFlib is available for download at http://www.pdflib.com/pdflib/index.html, but requires that you purchase a license for commercial use. The JPEG and TIFF libraries are required to compile this extension.

PDFlib 3.x Installation Hints

When using version 3.x of PDFlib, you should configure PDFlib with the option --enable-shared-pdflib.

Issues with older versions of PDFlib

Any version of PHP 4 after March 9, 2000 does not support versions of PDFlib older than 3.0.

PDFlib 3.0 or greater is supported by PHP 3.0.19 and later.

安装

Please see the PDFlib installation section for more information about compiling PDF support into PHP.

运行时配置

该扩展模块未定义任何设置指令。

Confusion with old PDFlib versions

Starting with PHP 4.0.5, the PHP extension for PDFlib is officially supported by PDFlib GmbH. This means that all the functions described in the PDFlib manual (V3.00 or greater) are supported by PHP 4 with exactly the same meaning and the same parameters. Only the return values may differ from the PDFlib manual, because the PHP convention of returning FALSE was adopted. For compatibility reasons, this binding for PDFlib still supports the old functions, but they should be replaced by their new versions. PDFlib GmbH will not support any problems arising from the use of these deprecated functions.

表格 1. Deprecated functions and their replacements

Old function | Replacement
pdf_put_image() | Not needed anymore.
pdf_execute_image() | Not needed anymore.
pdf_get_annotation() | pdf_get_bookmark() using the same parameters.
pdf_get_font() | pdf_get_value() passing "font" as the second parameter.
pdf_get_fontsize() | pdf_get_value() passing "fontsize" as the second parameter.
pdf_get_fontname() | pdf_get_parameter() passing "fontname" as the second parameter.
pdf_set_info_creator() | pdf_set_info() passing "Creator" as the second parameter.
pdf_set_info_title() | pdf_set_info() passing "Title" as the second parameter.
pdf_set_info_subject() | pdf_set_info() passing "Subject" as the second parameter.
pdf_set_info_author() | pdf_set_info() passing "Author" as the second parameter.
pdf_set_info_keywords() | pdf_set_info() passing "Keywords" as the second parameter.
pdf_set_leading() | pdf_set_value() passing "leading" as the second parameter.
pdf_set_text_rendering() | pdf_set_value() passing "textrendering" as the second parameter.
pdf_set_text_rise() | pdf_set_value() passing "textrise" as the second parameter.
pdf_set_horiz_scaling() | pdf_set_value() passing "horizscaling" as the second parameter.
pdf_set_text_matrix() | Not available anymore
pdf_set_char_spacing() | pdf_set_value() passing "charspacing" as the second parameter.
pdf_set_word_spacing() | pdf_set_value() passing "wordspacing" as the second parameter.
pdf_set_transition() | pdf_set_parameter() passing "transition" as the second parameter.
pdf_open() | pdf_new() plus an subsequent call of pdf_open_file()
pdf_set_font() | pdf_findfont() plus an subsequent call of pdf_setfont()
pdf_set_duration() | pdf_set_value() passing "duration" as the second parameter.
pdf_open_gif() | pdf_open_image_file() passing "gif" as the second parameter.
pdf_open_jpeg() | pdf_open_image_file() passing "jpeg" as the second parameter.
pdf_open_tiff() | pdf_open_image_file() passing "tiff" as the second parameter.
pdf_open_png() | pdf_open_image_file() passing "png" as the second parameter.
pdf_get_image_width() | pdf_get_value() passing "imagewidth" as the second parameter and the image as the third parameter.
pdf_get_image_height() | pdf_get_value() passing "imageheight" as the second parameter and the image as the third parameter.

范例

Most of the functions are fairly easy to use. The most difficult part is probably creating your first PDF document. The following example should help to get you started. It creates test.pdf with one page. The page contains the text "Times Roman outlined" in an outlined, 30pt font. The text is also underlined.

例子 1. Creating a PDF document with PDFlib

<?php
$pdf = pdf_new();
pdf_open_file($pdf, "test.pdf");
pdf_set_info($pdf, "Author", "Uwe Steinmann");
pdf_set_info($pdf, "Title", "Test for PHP wrapper of PDFlib 2.0");
pdf_set_info($pdf, "Creator", "See Author");
pdf_set_info($pdf, "Subject", "Testing");
pdf_begin_page($pdf, 595, 842);
pdf_add_outline($pdf, "Page 1");
pdf_set_font($pdf, "Times-Roman", 30, "host");
pdf_set_value($pdf, "textrendering", 1);
pdf_show_xy($pdf, "Times Roman outlined", 50, 750);
pdf_moveto($pdf, 50, 740);
pdf_lineto($pdf, 330, 740);
pdf_stroke($pdf);
pdf_end_page($pdf);
pdf_close($pdf);
pdf_delete($pdf);
echo "<A HREF=getpdf.php>finished</A>";
?>

The script getpdf.php just returns the pdf document.

<?php
$len = filesize($filename);
header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=foo.pdf");
readfile($filename);
?>

The PDFlib distribution contains a more complex example which creates a page with an analog clock. Here we use the in-memory creation feature of PDFlib to alleviate the need to use temporary files. The example was converted to PHP from the PDFlib example. (The same example is available in the CLibPDF documentation.)

例子 2. pdfclock example from PDFlib distribution

<?php
$radius = 200;
$margin = 20;
$pagecount = 10;

$pdf = pdf_new();

if (!pdf_open_file($pdf, "")) {
    print error;
    exit;
};

pdf_set_parameter($pdf, "warning", "true");

pdf_set_info($pdf, "Creator", "pdf_clock.php");
pdf_set_info($pdf, "Author", "Uwe Steinmann");
pdf_set_info($pdf, "Title", "Analog Clock");

while($pagecount-- > 0) {
    pdf_begin_page($pdf, 2 * ($radius + $margin), 2 * ($radius + $margin));

    pdf_set_parameter($pdf, "transition", "wipe");
    pdf_set_value($pdf, "duration", 0.5);

    pdf_translate($pdf, $radius + $margin, $radius + $margin);
    pdf_save($pdf);
    pdf_setrgbcolor($pdf, 0.0, 0.0, 1.0);

    /* minute strokes */
    pdf_setlinewidth($pdf, 2.0);
    for ($alpha = 0; $alpha < 360; $alpha += 6) {
        pdf_rotate($pdf, 6.0);
        pdf_moveto($pdf, $radius, 0.0);
        pdf_lineto($pdf, $radius-$margin/3, 0.0);
        pdf_stroke($pdf);
    }

    pdf_restore($pdf);
    pdf_save($pdf);

    /* 5 minute strokes */
    pdf_setlinewidth($pdf, 3.0);
    for ($alpha = 0; $alpha < 360; $alpha += 30) {
        pdf_rotate($pdf, 30.0);
        pdf_moveto($pdf, $radius, 0.0);
        pdf_lineto($pdf, $radius-$margin, 0.0);
        pdf_stroke($pdf);
    }

    $ltime = getdate();

    /* draw hour hand */
    pdf_save($pdf);
    pdf_rotate($pdf,-(($ltime['minutes']/60.0)+$ltime['hours']-3.0)*30.0);
    pdf_moveto($pdf, -$radius/10, -$radius/20);
    pdf_lineto($pdf, $radius/2, 0.0);
    pdf_lineto($pdf, -$radius/10, $radius/20);
    pdf_closepath($pdf);
    pdf_fill($pdf);
    pdf_restore($pdf);

    /* draw minute hand */
    pdf_save($pdf);
    pdf_rotate($pdf,-(($ltime['seconds']/60.0)+$ltime['minutes']-15.0)*6.0);
    pdf_moveto($pdf, -$radius/10, -$radius/20);
    pdf_lineto($pdf, $radius * 0.8, 0.0);
    pdf_lineto($pdf, -$radius/10, $radius/20);
    pdf_closepath($pdf);
    pdf_fill($pdf);
    pdf_restore($pdf);

    /* draw second hand */
    pdf_setrgbcolor($pdf, 1.0, 0.0, 0.0);
    pdf_setlinewidth($pdf, 2);
    pdf_save($pdf);
    pdf_rotate($pdf, -(($ltime['seconds'] - 15.0) * 6.0));
    pdf_moveto($pdf, -$radius/5, 0.0);
    pdf_lineto($pdf, $radius, 0.0);
    pdf_stroke($pdf);
    pdf_restore($pdf);

    /* draw little circle at center */
    pdf_circle($pdf, 0, 0, $radius/30);
    pdf_fill($pdf);

    pdf_restore($pdf);

    pdf_end_page($pdf);

    # to see some difference
    sleep(1);
}

pdf_close($pdf);

$buf = pdf_get_buffer($pdf);
$len = strlen($buf);

header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=foo.pdf");
print $buf;

pdf_delete($pdf);
?>

相关参考

注: An alternative PHP module for PDF document creation based on FastIO's ClibPDF is available. Please see the ClibPDF section for details. Note that ClibPDF has a slightly different API than PDFlib.

目录
pdf_add_annotation — Deprecated: Adds annotation
pdf_add_bookmark — Adds bookmark for current page
pdf_add_launchlink — Add a launch annotation for current page
pdf_add_locallink — Add a link annotation for current page
pdf_add_note — Add a note annotation for current page
pdf_add_outline — Deprecated: Adds bookmark for current page
pdf_add_pdflink — Adds file link annotation for current page
pdf_add_thumbnail — Adds thumbnail for current page
pdf_add_weblink — Adds weblink for current page
pdf_arc — Draws an arc (counterclockwise)
pdf_arcn — Draws an arc (clockwise)
pdf_attach_file — Adds a file attachement for current page
pdf_begin_page — Starts new page
pdf_begin_pattern — Starts new pattern
pdf_begin_template — Starts new template
pdf_circle — Draws a circle
pdf_clip — Clips to current path
pdf_close_image — Closes an image
pdf_close_pdi_page — Close the page handle
pdf_close_pdi — Close the input PDF document
pdf_close — Closes a pdf object
pdf_closepath_fill_stroke — Closes, fills and strokes current path
pdf_closepath_stroke — Closes path and draws line along path
pdf_closepath — Closes path
pdf_concat — Concatenate a matrix to the CTM
pdf_continue_text — Outputs text in next line
pdf_curveto — Draws a curve
pdf_delete — Deletes a PDF object
pdf_end_page — Ends a page
pdf_end_pattern — Finish pattern
pdf_end_template — Finish template
pdf_endpath — Deprecated: Ends current path
pdf_fill_stroke — Fills and strokes current path
pdf_fill — Fills current path
pdf_findfont — Prepare font for later use with pdf_setfont().
pdf_get_buffer — Fetch the buffer containig the generated PDF data.
pdf_get_font — Deprecated: font handling
pdf_get_fontname — Deprecated: font handling
pdf_get_fontsize — Deprecated: font handling
pdf_get_image_height — Returns height of an image
pdf_get_image_width — Returns width of an image
pdf_get_majorversion — Returns the major version number of the PDFlib
pdf_get_minorversion — Returns the minor version number of the PDFlib
pdf_get_parameter — Gets certain parameters
pdf_get_pdi_parameter — Get some PDI string parameters
pdf_get_pdi_value — Gets some PDI numerical parameters
pdf_get_value — Gets certain numerical value
pdf_initgraphics — Resets graphic state
pdf_lineto — Draws a line
pdf_makespotcolor — Makes a spotcolor
pdf_moveto — Sets current point
pdf_new — Creates a new pdf object
pdf_open_CCITT — Opens a new image file with raw CCITT data
pdf_open_file — Opens a new pdf object
pdf_open_gif — Deprecated: Opens a GIF image
pdf_open_image_file — Reads an image from a file
pdf_open_image — Versatile function for images
pdf_open_jpeg — Deprecated: Opens a JPEG image
pdf_open_memory_image — Opens an image created with PHP's image functions
pdf_open_pdi_page — Prepare a page
pdf_open_pdi — Opens a PDF file
pdf_open_png — Deprecated: Opens a PNG image
pdf_open_tiff — Deprecated: Opens a TIFF image
pdf_open — Deprecated: Open a new pdf object
pdf_place_image — Places an image on the page
pdf_place_pdi_page — Places an image on the page
pdf_rect — Draws a rectangle
pdf_restore — Restores formerly saved environment
pdf_rotate — Sets rotation
pdf_save — Saves the current environment
pdf_scale — Sets scaling
pdf_set_border_color — Sets color of border around links and annotations
pdf_set_border_dash — Sets dash style of border around links and annotations
pdf_set_border_style — Sets style of border around links and annotations
pdf_set_char_spacing — Deprecated: Sets character spacing
pdf_set_duration — Deprecated: Sets duration between pages
pdf_set_font — Deprecated: Selects a font face and size
pdf_set_horiz_scaling — Sets horizontal scaling of text
pdf_set_info_author — Fills the author field of the document
pdf_set_info_creator — Fills the creator field of the document
pdf_set_info_keywords — Fills the keywords field of the document
pdf_set_info_subject — Fills the subject field of the document
pdf_set_info_title — Fills the title field of the document
pdf_set_info — Fills a field of the document information
pdf_set_leading — Deprecated: Sets distance between text lines
pdf_set_parameter — Sets certain parameters
pdf_set_text_matrix — Deprecated: Sets the text matrix
pdf_set_text_pos — Sets text position
pdf_set_text_rendering — Deprecated: Determines how text is rendered
pdf_set_text_rise — Deprecated: Sets the text rise
pdf_set_value — Sets certain numerical value
pdf_set_word_spacing — Depriciated: Sets spacing between words
pdf_setcolor — Sets fill and stroke color
pdf_setdash — Sets dash pattern
pdf_setflat — Sets flatness
pdf_setfont — Set the current font
pdf_setgray_fill — Sets filling color to gray value
pdf_setgray_stroke — Sets drawing color to gray value
pdf_setgray — Sets drawing and filling color to gray value
pdf_setlinecap — Sets linecap parameter
pdf_setlinejoin — Sets linejoin parameter
pdf_setlinewidth — Sets line width
pdf_setmatrix — Sets current transformation matrix
pdf_setmiterlimit — Sets miter limit
pdf_setpolydash — Sets complicated dash pattern
pdf_setrgbcolor_fill — Sets filling color to rgb color value
pdf_setrgbcolor_stroke — Sets drawing color to rgb color value
pdf_setrgbcolor — Sets drawing and filling color to rgb color value
pdf_show_boxed — Output text in a box
pdf_show_xy — Output text at given position
pdf_show — Output text at current position
pdf_skew — Skews the coordinate system
pdf_stringwidth — Returns width of text using current font
pdf_stroke — Draws line along path
pdf_translate — Sets origin of coordinate system

后退 | 起点 | 前进
overload | 上一级 | pdf_add_annotation


pdf_add_annotation

pdf_add_annotation -- Deprecated: Adds annotation

Description

pdf_add_outline() is replaced by pdf_add_note()

See also pdf_add_note().

后退 | 起点 | 前进
PDF functions | 上一级 | pdf_add_bookmark


pdf_add_bookmark

(PHP 4 >= 4.0.1)

pdf_add_bookmark -- Adds bookmark for current page

Description

int pdf_add_bookmark ( int pdf object, string text [, int parent [, int open]])

Add a nested bookmark under parent, or a new top-level bookmark if parent = 0. Returns a bookmark descriptor which may be used as parent for subsequent nested bookmarks. If open = 1, child bookmarks will be folded out, and invisible if open = 0.

后退 | 起点 | 前进
pdf_add_annotation | 上一级 | pdf_add_launchlink


pdf_add_launchlink

(PHP 4 >= 4.0.5)

pdf_add_launchlink -- Add a launch annotation for current page

Description

int pdf_add_launchlink ( int pdf object, float llx, float lly, float urx, float ury, string filename)

Add a launch annotation (to a target of arbitrary file type).

后退 | 起点 | 前进
pdf_add_bookmark | 上一级 | pdf_add_locallink


pdf_add_locallink

(PHP 4 >= 4.0.5)

pdf_add_locallink -- Add a link annotation for current page

Description

int pdf_add_locallink ( int pdf object, float llx, float lly, float urx, float ury, int page, string dest)

Add a link annotation to a target within the current PDF file.

后退 | 起点 | 前进
pdf_add_launchlink | 上一级 | pdf_add_note


pdf_add_note

(PHP 4 >= 4.0.5)

pdf_add_note -- Add a note annotation for current page

Description

int pdf_add_note ( int pdf object, float llx, float lly, float urx, float ury, string contents, string title, string icon, int open)

Add a note annotation. icon is one of of "comment, "insert", "note", "paragraph", "newparagraph", "key", or "help".

后退 | 起点 | 前进
pdf_add_locallink | 上一级 | pdf_add_outline


pdf_add_outline

pdf_add_outline -- Deprecated: Adds bookmark for current page

Description

Deprecated.

See pdf_add_bookmark().

后退 | 起点 | 前进
pdf_add_note | 上一级 | pdf_add_pdflink


pdf_add_pdflink

(PHP 3>= 3.0.12, PHP 4 )

pdf_add_pdflink -- Adds file link annotation for current page

Description

int pdf_add_pdflink ( int pdf object, float llx, float lly, float urx, float ury, string filename, int page, string dest)

Add a file link annotation (to a PDF target).

后退 | 起点 | 前进
pdf_add_outline | 上一级 | pdf_add_thumbnail


pdf_add_thumbnail

(PHP 4 >= 4.0.5)

pdf_add_thumbnail -- Adds thumbnail for current page

Description

int pdf_add_thumbnail ( int pdf object, int image)

Add an existing image as thumbnail for the current page.

后退 | 起点 | 前进
pdf_add_pdflink | 上一级 | pdf_add_weblink


pdf_add_weblink

(PHP 3>= 3.0.12, PHP 4 )

pdf_add_weblink -- Adds weblink for current page

Description

int pdf_add_weblink ( int pdf object, float llx, float lly, float urx, float ury, string url)

Add a weblink annotation to a target URL on the Web.

后退 | 起点 | 前进
pdf_add_thumbnail | 上一级 | pdf_arc


pdf_arc

(PHP 3>= 3.0.6, PHP 4 )

pdf_arc -- Draws an arc (counterclockwise)

Description

void pdf_arc ( resource pdf object, float x, float y, float r, float alpha, float beta)

Draw a counterclockwise circular arc from alpha to beta degrees

See also: pdf_arcn()

后退 | 起点 | 前进
pdf_add_weblink | 上一级 | pdf_arcn


pdf_arcn

(PHP 4 >= 4.0.5)

pdf_arcn -- Draws an arc (clockwise)

Description

void pdf_arc ( resource pdf object, float x, float y, float r, float alpha, float beta)

Draw a clockwise circular arc from alpha to beta degrees

See also: pdf_arc()

后退 | 起点 | 前进
pdf_arc | 上一级 | pdf_attach_file


pdf_attach_file

(PHP 4 >= 4.0.5)

pdf_attach_file -- Adds a file attachement for current page

Description

int pdf_attach_file ( int pdf object, float llx, float lly, float urx, float ury, string filename, string description, string author, string mimetype, string icon)

Add a file attachment annotation. icon is one of "graph, "paperclip", "pushpin", or "tag".

后退 | 起点 | 前进
pdf_arcn | 上一级 | pdf_begin_page


pdf_begin_page

(PHP 3>= 3.0.6, PHP 4 )

pdf_begin_page -- Starts new page

Description

void pdf_begin_page ( int pdf object, float width, float height)

Add a new page to the document. The width and height are specified in points, which are 1/72 of an inch.

表格 1. Common Page Sizes in Points

name | size
A0 | 2380✗3368
A1 | 1684✗2380
A2 | 1190✗1684
A3 | 842✗1190
A4 | 595✗842
A5 | 421✗595
A6 | 297✗421
B5 | 501✗709
letter (8.5"✗11") | 612✗792
legal (8.5"✗14") | 612✗1008
ledger (17"✗11") | 1224✗792
11"✗17" | 792✗1224

后退 | 起点 | 前进
pdf_attach_file | 上一级 | pdf_begin_pattern


pdf_begin_pattern

(PHP 4 >= 4.0.5)

pdf_begin_pattern -- Starts new pattern

Description

int pdf_begin_pattern ( int pdf object, float width, float height, float xstep, float ystep, int painttype)

Starts a new pattern definition and returns a pattern handle. width, and height define the bounding box for the pattern. xstep and ystep give the repeated pattern offsets. painttype=1 means that the pattern has its own colour settings whereas a value of 2 indicates that the current colour is used when the pattern is applied.

后退 | 起点 | 前进
pdf_begin_page | 上一级 | pdf_begin_template


pdf_begin_template

(PHP 4 >= 4.0.5)

pdf_begin_template -- Starts new template

Description

void pdf_begin_template ( int pdf object, float width, float height)

Start a new template definition.

后退 | 起点 | 前进
pdf_begin_pattern | 上一级 | pdf_circle


pdf_circle

(PHP 3>= 3.0.6, PHP 4 )

pdf_circle -- Draws a circle

Description

void pdf_circle ( int pdf object, float x, float y, float r)

Draw a circle with center (x, y) and radius r.

后退 | 起点 | 前进
pdf_begin_template | 上一级 | pdf_clip


pdf_clip

(PHP 3>= 3.0.6, PHP 4 )

pdf_clip -- Clips to current path

Description

void pdf_clip ( int pdf object)

Use the current path as clipping path.

后退 | 起点 | 前进
pdf_circle | 上一级 | pdf_close_image


pdf_close_image

(PHP 3>= 3.0.7, PHP 4 )

pdf_close_image -- Closes an image

Description

void pdf_close_image ( int pdf object, int image)

Close an image retrieved with one of the pdf_open_image*() functions.

后退 | 起点 | 前进
pdf_clip | 上一级 | pdf_close_pdi_page


pdf_close_pdi_page

(PHP 4 >= 4.0.5)

pdf_close_pdi_page -- Close the page handle

Description

void pdf_close_pdi_page ( int pdf object, int pagehandle)

Close the page handle, and free all page-related resources.

后退 | 起点 | 前进
pdf_close_image | 上一级 | pdf_close_pdi


pdf_close_pdi

(PHP 4 >= 4.0.5)

pdf_close_pdi -- Close the input PDF document

Description

void pdf_close_pdi ( int pdf object, int dochandle)

Close all open page handles, and close the input PDF document.

后退 | 起点 | 前进
pdf_close_pdi_page | 上一级 | pdf_close


pdf_close

(PHP 3>= 3.0.6, PHP 4 )

pdf_close -- Closes a pdf object

Description

void pdf_close ( int pdf object)

Close the generated PDF file, and free all document-related resources.

后退 | 起点 | 前进
pdf_close_pdi | 上一级 | pdf_closepath_fill_stroke


pdf_closepath_fill_stroke

(PHP 3>= 3.0.6, PHP 4 )

pdf_closepath_fill_stroke -- Closes, fills and strokes current path

Description

void pdf_closepath_fill_stroke ( int pdf object)

Close the path, fill, and stroke it.

后退 | 起点 | 前进
pdf_close | 上一级 | pdf_closepath_stroke


pdf_closepath_stroke

(PHP 3>= 3.0.6, PHP 4 )

pdf_closepath_stroke -- Closes path and draws line along path

Description

void pdf_closepath_stroke ( int pdf object)

Close the path, and stroke it.

后退 | 起点 | 前进
pdf_closepath_fill_stroke | 上一级 | pdf_closepath


pdf_closepath

(PHP 3>= 3.0.6, PHP 4 )

pdf_closepath -- Closes path

Description

void pdf_closepath ( int pdf object)

Close the current path.

后退 | 起点 | 前进
pdf_closepath_stroke | 上一级 | pdf_concat


pdf_concat

(PHP 4 >= 4.0.5)

pdf_concat -- Concatenate a matrix to the CTM

Description

void pdf_concat ( int pdf object, float a, float b, float c, float d, float e, float f)

Concatenate a matrix to the CTM.

后退 | 起点 | 前进
pdf_closepath | 上一级 | pdf_continue_text


pdf_continue_text

(PHP 3>= 3.0.6, PHP 4 )

pdf_continue_text -- Outputs text in next line

Description

void pdf_continue_text ( int pdf object, string text)

Print text at the next line. The spacing between lines is determined by the leading parameter.

后退 | 起点 | 前进
pdf_concat | 上一级 | pdf_curveto


pdf_curveto

(PHP 3>= 3.0.6, PHP 4 )

pdf_curveto -- Draws a curve

Description

void pdf_curveto ( int pdf object, float x1, float y1, float x2, float y2, float x3, float y3)

Draw a Bezier curve from the current point, using 3 more control points.

后退 | 起点 | 前进
pdf_continue_text | 上一级 | pdf_delete


pdf_delete

(PHP 4 >= 4.0.5)

pdf_delete -- Deletes a PDF object

Description

void pdf_delete ( int pdf object)

Delete the PDF object, and free all internal resources.

后退 | 起点 | 前进
pdf_curveto | 上一级 | pdf_end_page


pdf_end_page

(PHP 3>= 3.0.6, PHP 4 )

pdf_end_page -- Ends a page

Description

void pdf_end_page ( int pdf object)

Finish the page.

后退 | 起点 | 前进
pdf_delete | 上一级 | pdf_end_pattern


pdf_end_pattern

(PHP 4 >= 4.0.5)

pdf_end_pattern -- Finish pattern

Description

void pdf_end_pattern ( int pdf object)

Finish the pattern definition.

后退 | 起点 | 前进
pdf_end_page | 上一级 | pdf_end_template


pdf_end_template

(PHP 4 >= 4.0.5)

pdf_end_template -- Finish template

Description

void pdf_end_template ( int pdf object)

Finish the template definition.

后退 | 起点 | 前进
pdf_end_pattern | 上一级 | pdf_endpath


pdf_endpath

pdf_endpath -- Deprecated: Ends current path

Description

Deprecated, use one of the stroke, fill, or clip functions instead.

后退 | 起点 | 前进
pdf_end_template | 上一级 | pdf_fill_stroke


pdf_fill_stroke

(PHP 3>= 3.0.6, PHP 4 )

pdf_fill_stroke -- Fills and strokes current path

Description

void pdf_fill_stroke ( int pdf object)

Fill and stroke the path with the current fill and stroke color.

后退 | 起点 | 前进
pdf_endpath | 上一级 | pdf_fill


pdf_fill

(PHP 3>= 3.0.6, PHP 4 )

pdf_fill -- Fills current path

Description

void pdf_fill_stroke ( int pdf object)

Fill the interior of the path with the current fill color.

后退 | 起点 | 前进
pdf_fill_stroke | 上一级 | pdf_findfont


pdf_findfont

(PHP 4 >= 4.0.5)

pdf_findfont -- Prepare font for later use with pdf_setfont().

Description

int pdf_findfont ( int pdf object, string fontname, string encoding, int embed)

Prepare a font for later use with pdf_setfont(). The metrics will be loaded, and if embed is nonzero, the font file will be checked, but not yet used. encoding is one of "builtin", "macroman", "winansi", "host", or a user-defined encoding name, or the name of a CMap.

pdf_findfont() returns a font handle or FALSE on error.

例子 1. pdf_findfont() example

<?php

$font = pdf_findfont($pdf, "Times New Roman", "winansi", 1);
if ($font) {
    pdf_setfont($pdf, $font, 10);
}

?>

后退 | 起点 | 前进
pdf_fill | 上一级 | pdf_get_buffer


pdf_get_buffer

(PHP 4 >= 4.0.5)

pdf_get_buffer -- Fetch the buffer containig the generated PDF data.

Description

string pdf_get_buffer ( int pdf object)

Get the contents of the PDF output buffer. The result must be used by the client before calling any other PDFlib function.

后退 | 起点 | 前进
pdf_findfont | 上一级 | pdf_get_font


pdf_get_font

pdf_get_font -- Deprecated: font handling

Description

Deprecated.

See pdf_get_value().

后退 | 起点 | 前进
pdf_get_buffer | 上一级 | pdf_get_fontname


pdf_get_fontname

pdf_get_fontname -- Deprecated: font handling

Description

Deprecated.

See pdf_get_parameter().

后退 | 起点 | 前进
pdf_get_font | 上一级 | pdf_get_fontsize


pdf_get_fontsize

pdf_get_fontsize -- Deprecated: font handling

Description

Deprecated.

See pdf_get_value().

后退 | 起点 | 前进
pdf_get_fontname | 上一级 | pdf_get_image_height


pdf_get_image_height

(PHP 3>= 3.0.12, PHP 4 )

pdf_get_image_height -- Returns height of an image

Description

string pdf_get_image_height ( int pdf object, int image)

pdf_get_image_height() is deprecated, use pdf_get_value() instead.

后退 | 起点 | 前进
pdf_get_fontsize | 上一级 | pdf_get_image_width


pdf_get_image_width

(PHP 3>= 3.0.12, PHP 4 )

pdf_get_image_width -- Returns width of an image

Description

string pdf_get_image_width ( int pdf object, int image)

The pdf_get_image_width() is deprecated, use pdf_get_value() instead.

后退 | 起点 | 前进
pdf_get_image_height | 上一级 | pdf_get_majorversion


pdf_get_majorversion

(PHP 4 >= 4.2.0)

pdf_get_majorversion -- Returns the major version number of the PDFlib

Description

int pdf_get_majorversion ( void)

Returns the major version number of the PDFlib.

后退 | 起点 | 前进
pdf_get_image_width | 上一级 | pdf_get_minorversion


pdf_get_minorversion

(PHP 4 >= 4.2.0)

pdf_get_minorversion -- Returns the minor version number of the PDFlib

Description

int pdf_get_majorversion ( void)

Returns the minor version number of the PDFlib.

后退 | 起点 | 前进
pdf_get_majorversion | 上一级 | pdf_get_parameter


pdf_get_parameter

(PHP 4 >= 4.0.1)

pdf_get_parameter -- Gets certain parameters

Description

string pdf_get_parameter ( int pdf object, string key [, float modifier])

Get the contents of some PDFlib parameter with string type.

后退 | 起点 | 前进
pdf_get_minorversion | 上一级 | pdf_get_pdi_parameter


pdf_get_pdi_parameter

(PHP 4 >= 4.0.5)

pdf_get_pdi_parameter -- Get some PDI string parameters

Description

string pdf_get_pdi_parameter ( int pdf object, string key, int doc, int page, int index)

Get the contents of some PDI document parameter with string type.

后退 | 起点 | 前进
pdf_get_parameter | 上一级 | pdf_get_pdi_value


pdf_get_pdi_value

(PHP 4 >= 4.0.5)

pdf_get_pdi_value -- Gets some PDI numerical parameters

Description

string pdf_get_pdi_value ( int pdf object, string key, int doc, int page, int index)

Get the contents of some PDI document parameter with numerical type.

后退 | 起点 | 前进
pdf_get_pdi_parameter | 上一级 | pdf_get_value


pdf_get_value

(PHP 4 >= 4.0.1)

pdf_get_value -- Gets certain numerical value

Description

float pdf_get_value ( int pdf object, string key [, float modifier])

Get the contents of some PDFlib parameter with float type.

后退 | 起点 | 前进
pdf_get_pdi_value | 上一级 | pdf_initgraphics


pdf_initgraphics

(PHP 4 >= 4.0.5)

pdf_initgraphics -- Resets graphic state

Description

void pdf_initgraphics ( int pdf object)

Reset all implicit color and graphics state parameters to their defaults.

后退 | 起点 | 前进
pdf_get_value | 上一级 | pdf_lineto


pdf_lineto

(PHP 3>= 3.0.6, PHP 4 )

pdf_lineto -- Draws a line

Description

void pdf_lineto ( int pdf object, float x, float y)

Draw a line from the current point to (x, y).

后退 | 起点 | 前进
pdf_initgraphics | 上一级 | pdf_makespotcolor


pdf_makespotcolor

(PHP 4 >= 4.0.5)

pdf_makespotcolor -- Makes a spotcolor

Description

void pdf_makespotcolor ( int pdf object, string spotname)

Make a named spot color from the current color.

后退 | 起点 | 前进
pdf_lineto | 上一级 | pdf_moveto


pdf_moveto

(PHP 3>= 3.0.6, PHP 4 )

pdf_moveto -- Sets current point

Description

void pdf_moveto ( int pdf object, float x, float y)

Set the current point.

注: The current point for graphics and the current text output position are maintained separately. See pdf_set_text_pos() to set the text output position.

后退 | 起点 | 前进
pdf_makespotcolor | 上一级 | pdf_new


pdf_new

(PHP 4 >= 4.0.5)

pdf_new -- Creates a new pdf object

Description

int pdf_new ( )

Create a new PDF object, using default error handling and memory management.

后退 | 起点 | 前进
pdf_moveto | 上一级 | pdf_open_CCITT


pdf_open_CCITT

(PHP 4 >= 4.0.5)

pdf_open_CCITT -- Opens a new image file with raw CCITT data

Description

int pdf_open_CCITT ( int pdf object, string filename, int width, int height, int BitReverse, int k, int Blackls1)

Open a raw CCITT image.

后退 | 起点 | 前进
pdf_new | 上一级 | pdf_open_file


pdf_open_file

(PHP 4 >= 4.0.5)

pdf_open_file -- Opens a new pdf object

Description

int pdf_open_file ( int pdf object [, string filename])

Create a new PDF file using the supplied file name. If filename is empty the PDF document will be generated in memory instead of on file. The result must be fetched by the client with the pdf_get_buffer() function.

The following example shows how to create a pdf document in memory and how to output it correctly.

例子 1. Creating a PDF document in memory

<?php

$pdf = pdf_new();

pdf_open_file($pdf);
pdf_begin_page($pdf, 595, 842);
pdf_set_font($pdf, "Times-Roman", 30, "host");
pdf_set_value($pdf, "textrendering", 1);
pdf_show_xy($pdf, "A PDF document created in memory!", 50, 750);
pdf_end_page($pdf);
pdf_close($pdf);

$data = pdf_get_buffer($pdf);

header("Content-type: application/pdf");
header("Content-disposition: inline; filename=test.pdf");
header("Content-length: " . strlen($data));

echo $data;

?>

后退 | 起点 | 前进
pdf_open_CCITT | 上一级 | pdf_open_gif


pdf_open_gif

pdf_open_gif -- Deprecated: Opens a GIF image

Description

Deprecated.

See pdf_open_image(),

后退 | 起点 | 前进
pdf_open_file | 上一级 | pdf_open_image_file


pdf_open_image_file

(PHP 3 CVS only, PHP 4 )

pdf_open_image_file -- Reads an image from a file

Description

int pdf_open_image_file ( int PDF-document, string imagetype, string filename [, string stringparam [, string intparam]])

Open an image file. Supported types are "jpeg", "tiff", "gif", and "png". stringparam is either "", "mask", "masked", or "page". intparamis either 0, the image id of the applied mask, or the page.

后退 | 起点 | 前进
pdf_open_gif | 上一级 | pdf_open_image


pdf_open_image

(PHP 4 >= 4.0.5)

pdf_open_image -- Versatile function for images

Description

int pdf_open_image ( int PDF-document, string imagetype, string source, string data, long length, int width, int height, int components, int bpc, string params)

Use image data from a variety of data sources. Supported types are "jpeg", "ccitt", "raw". Supported sources are "memory", "fileref", "url". len is only used for type="raw", params is only used for type="ccitt".

后退 | 起点 | 前进
pdf_open_image_file | 上一级 | pdf_open_jpeg


pdf_open_jpeg

pdf_open_jpeg -- Deprecated: Opens a JPEG image

Description

Deprecated.

See also pdf_open_image(),

后退 | 起点 | 前进
pdf_open_image | 上一级 | pdf_open_memory_image


pdf_open_memory_image

(PHP 3>= 3.0.10, PHP 4 )

pdf_open_memory_image -- Opens an image created with PHP's image functions

Description

int pdf_open_memory_image ( int pdf object, int image)

The pdf_open_memory_image() function takes an image created with the PHP's image functions and makes it available for the pdf object. The function returns a pdf image identifier.

例子 1. Including a memory image

<?php
$im = ImageCreate(100, 100);
$col = ImageColorAllocate($im, 80, 45, 190);
ImageFill($im, 10, 10, $col);
$pim = pdf_open_memory_image($pdf, $im);
ImageDestroy($im);
pdf_place_image($pdf, $pim, 100, 100, 1);
pdf_close_image($pdf, $pim);
?>

See also pdf_close_image(), pdf_place_image().

后退 | 起点 | 前进
pdf_open_jpeg | 上一级 | pdf_open_pdi_page


pdf_open_pdi_page

(PHP 4 >= 4.0.5)

pdf_open_pdi_page -- Prepare a page

Description

int pdf_open_pdi_page ( int pdf object, int dochandle, int pagenumber, string pagelabel)

Prepare a page for later use with pdf_place_image()

后退 | 起点 | 前进
pdf_open_memory_image | 上一级 | pdf_open_pdi


pdf_open_pdi

(PHP 4 >= 4.0.5)

pdf_open_pdi -- Opens a PDF file

Description

int pdf_open_pdi ( int pdf object, string filename, string stringparam, int intparam)

Open an existing PDF document for later use.

后退 | 起点 | 前进
pdf_open_pdi_page | 上一级 | pdf_open_png


pdf_open_png

pdf_open_png -- Deprecated: Opens a PNG image

Description

Deprecated.

See pdf_open_image().

后退 | 起点 | 前进
pdf_open_pdi | 上一级 | pdf_open_tiff


pdf_open_tiff

(PHP 4 )

pdf_open_tiff -- Deprecated: Opens a TIFF image

Description

int pdf_open_tiff ( int PDF-document, string filename)

Deprecated.

See also pdf_open_image(),

后退 | 起点 | 前进
pdf_open_png | 上一级 | pdf_open


pdf_open

pdf_open -- Deprecated: Open a new pdf object

Description

pdf_open() is deprecated, use pdf_new() plus pdf_open_file() instead.

See also pdf_new(), pdf_open_file().

后退 | 起点 | 前进
pdf_open_tiff | 上一级 | pdf_place_image


pdf_place_image

(PHP 3>= 3.0.7, PHP 4 )

pdf_place_image -- Places an image on the page

Description

void pdf_place_image ( int pdf object, int image, float x, float y, float scale)

Place an image with the lower left corner at (x, y), and scale it.

后退 | 起点 | 前进
pdf_open | 上一级 | pdf_place_pdi_page


pdf_place_pdi_page

(PHP 4 >= 4.0.6)

pdf_place_pdi_page -- Places an image on the page

Description

void pdf_place_pdi_page ( int pdf object, int page, float x, float y, float sx, float sy)

Place a PDF page with the lower left corner at (x, y), and scale it.

后退 | 起点 | 前进
pdf_place_image | 上一级 | pdf_rect


pdf_rect

(PHP 3>= 3.0.6, PHP 4 )

pdf_rect -- Draws a rectangle

Description

void pdf_rect ( int pdf object, float x, float y, float width, float height)

Draw a rectangle at lower left (x, y) with width and height.

后退 | 起点 | 前进
pdf_place_pdi_page | 上一级 | pdf_restore


pdf_restore

(PHP 3>= 3.0.6, PHP 4 )

pdf_restore -- Restores formerly saved environment

Description

void pdf_restore ( int pdf object)

Restore the most recently saved graphics state.

后退 | 起点 | 前进
pdf_rect | 上一级 | pdf_rotate


pdf_rotate

(PHP 3>= 3.0.6, PHP 4 )

pdf_rotate -- Sets rotation

Description

void pdf_rotate ( int pdf object, float phi)

Rotate the coordinate system by phi degrees.

后退 | 起点 | 前进
pdf_restore | 上一级 | pdf_save


pdf_save

(PHP 3>= 3.0.6, PHP 4 )

pdf_save -- Saves the current environment

Description

void pdf_save ( int pdf object)

Save the current graphics state.

后退 | 起点 | 前进
pdf_rotate | 上一级 | pdf_scale


pdf_scale

(PHP 3>= 3.0.6, PHP 4 )

pdf_scale -- Sets scaling

Description

void pdf_scale ( int pdf object, float x-scale, float y-scale)

Scale the coordinate system.

后退 | 起点 | 前进
pdf_save | 上一级 | pdf_set_border_color


pdf_set_border_color

(PHP 3>= 3.0.12, PHP 4 )

pdf_set_border_color -- Sets color of border around links and annotations

Description

void pdf_set_border_color ( int pdf object, float red, float green, float blue)

Set the border color for all kinds of annotations.

后退 | 起点 | 前进
pdf_scale | 上一级 | pdf_set_border_dash


pdf_set_border_dash

(PHP 4 >= 4.0.1)

pdf_set_border_dash -- Sets dash style of border around links and annotations

Description

void pdf_set_border_dash ( int pdf object, float black, float white)

Set the border dash style for all kinds of annotations. See pdf_setdash().

后退 | 起点 | 前进
pdf_set_border_color | 上一级 | pdf_set_border_style


pdf_set_border_style

(PHP 3>= 3.0.12, PHP 4 )

pdf_set_border_style -- Sets style of border around links and annotations

Description

void pdf_set_border_style ( int pdf object, string style, float width)

Set the border style for all kinds of annotations. style is "solid" or "dashed".

后退 | 起点 | 前进
pdf_set_border_dash | 上一级 | pdf_set_char_spacing


pdf_set_char_spacing

pdf_set_char_spacing -- Deprecated: Sets character spacing

Description

Deprecated.

See also pdf_set_value(),

后退 | 起点 | 前进
pdf_set_border_style | 上一级 | pdf_set_duration


pdf_set_duration

pdf_set_duration -- Deprecated: Sets duration between pages

Description

Deprecated.

See pdf_set_value().

后退 | 起点 | 前进
pdf_set_char_spacing | 上一级 | pdf_set_font


pdf_set_font

pdf_set_font -- Deprecated: Selects a font face and size

Description

Deprecated. You should use pdf_findfont() plus pdf_setfont() instead.

See pdf_findfont(), pdf_setfont().

后退 | 起点 | 前进
pdf_set_duration | 上一级 | pdf_set_horiz_scaling


pdf_set_horiz_scaling

(PHP 3>= 3.0.6, PHP 4 )

pdf_set_horiz_scaling -- Sets horizontal scaling of text

Description

void pdf_set_horiz_scaling ( int pdf object, float scale)

Deprecated.

See also pdf_set_value(),

后退 | 起点 | 前进
pdf_set_font | 上一级 | pdf_set_info_author


pdf_set_info_author

(PHP 3>= 3.0.6, PHP 4 )

pdf_set_info_author -- Fills the author field of the document

Description

bool pdf_set_info_author ( int pdfdoc, string author)

This function is deprecate, use pdf_set_info() instead.

后退 | 起点 | 前进
pdf_set_horiz_scaling | 上一级 | pdf_set_info_creator


pdf_set_info_creator

(PHP 3>= 3.0.6, PHP 4 )

pdf_set_info_creator -- Fills the creator field of the document

Description

bool pdf_set_info_creator ( int pdfdoc, string creator)

This function is deprecate, use pdf_set_info() instead.

后退 | 起点 | 前进
pdf_set_info_author | 上一级 | pdf_set_info_keywords


pdf_set_info_keywords

(PHP 3>= 3.0.6, PHP 4 )

pdf_set_info_keywords -- Fills the keywords field of the document

Description

bool pdf_set_info_keywords ( int pdfdoc, string keywords)

This function is deprecate, use pdf_set_info() instead.

后退 | 起点 | 前进
pdf_set_info_creator | 上一级 | pdf_set_info_subject


pdf_set_info_subject

(PHP 3>= 3.0.6, PHP 4 )

pdf_set_info_subject -- Fills the subject field of the document

Description

bool pdf_set_info_subject ( int pdfdoc, string subject)

This function is deprecate, use pdf_set_info() instead.

后退 | 起点 | 前进
pdf_set_info_keywords | 上一级 | pdf_set_info_title


pdf_set_info_title

(PHP 3>= 3.0.6, PHP 4 )

pdf_set_info_title -- Fills the title field of the document

Description

bool pdf_set_info_title ( int pdfdoc, string title)

This function is deprecate, use pdf_set_info() instead.

后退 | 起点 | 前进
pdf_set_info_subject | 上一级 | pdf_set_info


pdf_set_info

(PHP 4 >= 4.0.1)

pdf_set_info -- Fills a field of the document information

Description

void pdf_set_info ( int pdf object, string key, string value)

Fill document information field key with value. key is one of "Subject", "Title", "Creator", "Author", "Keywords", or a user-defined key.

后退 | 起点 | 前进
pdf_set_info_title | 上一级 | pdf_set_leading


pdf_set_leading

pdf_set_leading -- Deprecated: Sets distance between text lines

Description

Deprecated.

See also pdf_set_value(),

后退 | 起点 | 前进
pdf_set_info | 上一级 | pdf_set_parameter


pdf_set_parameter

(PHP 4 )

pdf_set_parameter -- Sets certain parameters

Description

void pdf_set_parameter ( int pdf object, string key, string value)

Set some PDFlib parameter with string type.

后退 | 起点 | 前进
pdf_set_leading | 上一级 | pdf_set_text_matrix


pdf_set_text_matrix

pdf_set_text_matrix -- Deprecated: Sets the text matrix

Description

See pdf_set_paramter().

后退 | 起点 | 前进
pdf_set_parameter | 上一级 | pdf_set_text_pos


pdf_set_text_pos

(PHP 3>= 3.0.6, PHP 4 )

pdf_set_text_pos -- Sets text position

Description

void pdf_set_text_pos ( int pdf object, float x, float y)

Set the text output position.

后退 | 起点 | 前进
pdf_set_text_matrix | 上一级 | pdf_set_text_rendering


pdf_set_text_rendering

pdf_set_text_rendering -- Deprecated: Determines how text is rendered

Description

Deprecated.

See pdf_set_value(),

后退 | 起点 | 前进
pdf_set_text_pos | 上一级 | pdf_set_text_rise


pdf_set_text_rise

pdf_set_text_rise -- Deprecated: Sets the text rise

Description

Deprecated.

See pdf_set_value(),

后退 | 起点 | 前进
pdf_set_text_rendering | 上一级 | pdf_set_value


pdf_set_value

(PHP 4 >= 4.0.1)

pdf_set_value -- Sets certain numerical value

Description

void pdf_set_value ( int pdf object, string key, float value)

Set the value of some PDFlib parameter with float type.

后退 | 起点 | 前进
pdf_set_text_rise | 上一级 | pdf_set_word_spacing


pdf_set_word_spacing

pdf_set_word_spacing -- Depriciated: Sets spacing between words

Description

Deprecated.

See also pdf_set_value(),

后退 | 起点 | 前进
pdf_set_value | 上一级 | pdf_setcolor


pdf_setcolor

(PHP 4 >= 4.0.5)

pdf_setcolor -- Sets fill and stroke color

Description

void pdf_setcolor ( int pdf object, string type, string colorspace, float c1 [, float c2 [, float c3 [, float c4]]])

Set the current color space and color. The parameter type can be "fill", "stroke", or "both" to specify that the color is set for filling, stroking or both filling and stroking. The parameter colorspace can be gray, rgb, cmyk, spot or pattern. The parameters c1, c2, c3 and c4 represent the color components for the color space specified by colorspace. Except as otherwise noted, the color components are floating-point values that range from 0 to 1.

For gray only c1 is used.

For rgb parameters c1, c2, and c3 specify the red, green and blue values respectively.

// Set fill and stroke colors to white.
pdf_setcolor($pdf, "both", "rgb", 1, 1, 1);

For cmyk, parameters c1, c2, c3, and c4 are the cyan, magenta, yellow and black values, respectively.

// Set fill and stroke colors to white.
pdf_setcolor($pdf, "both", "cmyk", 0, 0, 0, 1);

For spot, c1 should be a spot color handles returned by pdf_makespotcolor() and c2 is a tint value between 0 and 1.

For pattern, c1 should be a pattern handle returned by pdf_begin_pattern().

后退 | 起点 | 前进
pdf_set_word_spacing | 上一级 | pdf_setdash


pdf_setdash

(PHP 3>= 3.0.6, PHP 4 )

pdf_setdash -- Sets dash pattern

Description

void pdf_setdash ( int pdf object, float b, float w)

Set the current dash pattern to b black and w white units.

后退 | 起点 | 前进
pdf_setcolor | 上一级 | pdf_setflat


pdf_setflat

(PHP 3>= 3.0.6, PHP 4 )

pdf_setflat -- Sets flatness

Description

void pdf_setflat ( int pdf object, float flatness)

Set the flatness to a value between 0 and 100 inclusive.

后退 | 起点 | 前进
pdf_setdash | 上一级 | pdf_setfont


pdf_setfont

(PHP 4 >= 4.0.5)

pdf_setfont -- Set the current font

Description

void pdf_setfont ( int pdf object, int font, float size)

Set the current font in the given size, using a font handle returned by pdf_findfont()

See Also: pdf_findfont().

后退 | 起点 | 前进
pdf_setflat | 上一级 | pdf_setgray_fill


pdf_setgray_fill

(PHP 3>= 3.0.6, PHP 4 )

pdf_setgray_fill -- Sets filling color to gray value

Description

void pdf_setgray_fill ( int pdf object, float gray)

Set the current fill color to a gray value between 0 and 1 inclusive.

注: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.

后退 | 起点 | 前进
pdf_setfont | 上一级 | pdf_setgray_stroke


pdf_setgray_stroke

(PHP 3>= 3.0.6, PHP 4 )

pdf_setgray_stroke -- Sets drawing color to gray value

Description

void pdf_setgray_stroke ( int pdf object, float gray)

Set the current stroke color to a gray value between 0 and 1 inclusive

注: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.

后退 | 起点 | 前进
pdf_setgray_fill | 上一级 | pdf_setgray


pdf_setgray

(PHP 3>= 3.0.6, PHP 4 )

pdf_setgray -- Sets drawing and filling color to gray value

Description

void pdf_setgray ( int pdf object, float gray)

Set the current fill and stroke color.

注: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.

后退 | 起点 | 前进
pdf_setgray_stroke | 上一级 | pdf_setlinecap


pdf_setlinecap

(PHP 3>= 3.0.6, PHP 4 )

pdf_setlinecap -- Sets linecap parameter

Description

void pdf_setlinecap ( int pdf object, int linecap)

Set the linecap parameter to a value between 0 and 2 inclusive.

后退 | 起点 | 前进
pdf_setgray | 上一级 | pdf_setlinejoin


pdf_setlinejoin

(PHP 3>= 3.0.6, PHP 4 )

pdf_setlinejoin -- Sets linejoin parameter

Description

void pdf_setlinejoin ( int pdf object, long linejoin)

Set the line join parameter to a value between 0 and 2 inclusive.

后退 | 起点 | 前进
pdf_setlinecap | 上一级 | pdf_setlinewidth


pdf_setlinewidth

(PHP 3>= 3.0.6, PHP 4 )

pdf_setlinewidth -- Sets line width

Description

void pdf_setlinewidth ( int pdf object, float width)

Set the current linewidth to width.

后退 | 起点 | 前进
pdf_setlinejoin | 上一级 | pdf_setmatrix


pdf_setmatrix

(PHP 4 >= 4.0.5)

pdf_setmatrix -- Sets current transformation matrix

Description

void pdf_setmatrix ( int pdf object, float a, float b, float c, float d, float e, float f)

Explicitly set the current transformation matrix.

后退 | 起点 | 前进
pdf_setlinewidth | 上一级 | pdf_setmiterlimit


pdf_setmiterlimit

(PHP 3>= 3.0.6, PHP 4 )

pdf_setmiterlimit -- Sets miter limit

Description

void pdf_setmiterlimit ( int pdf object, float miter)

Set the miter limit to a value greater than or equal to 1.

后退 | 起点 | 前进
pdf_setmatrix | 上一级 | pdf_setpolydash


pdf_setpolydash

(PHP 4 >= 4.0.5)

pdf_setpolydash -- Sets complicated dash pattern

Description

void pdf_setpolydash ( int pdf object, float * dasharray)

Set a more complicated dash pattern defined by an array.

后退 | 起点 | 前进
pdf_setmiterlimit | 上一级 | pdf_setrgbcolor_fill


pdf_setrgbcolor_fill

(PHP 3>= 3.0.6, PHP 4 )

pdf_setrgbcolor_fill -- Sets filling color to rgb color value

Description

void pdf_setrgbcolor_fill ( int pdf object, float red value, float green value, float blue value)

Set the current fill color to the supplied RGB values.

注: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.

后退 | 起点 | 前进
pdf_setpolydash | 上一级 | pdf_setrgbcolor_stroke


pdf_setrgbcolor_stroke

(PHP 3>= 3.0.6, PHP 4 )

pdf_setrgbcolor_stroke -- Sets drawing color to rgb color value

Description

void pdf_setrgbcolor_stroke ( int pdf object, float red value, float green value, float blue value)

Set the current stroke color to the supplied RGB values.

注: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.

后退 | 起点 | 前进
pdf_setrgbcolor_fill | 上一级 | pdf_setrgbcolor


pdf_setrgbcolor

(PHP 3>= 3.0.6, PHP 4 )

pdf_setrgbcolor -- Sets drawing and filling color to rgb color value

Description

void pdf_setrgbcolor ( int pdf object, float red value, float green value, float blue value)

Set the current fill and stroke color to the supplied RGB values.

注: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.

后退 | 起点 | 前进
pdf_setrgbcolor_stroke | 上一级 | pdf_show_boxed


pdf_show_boxed

(PHP 4 )

pdf_show_boxed -- Output text in a box

Description

int pdf_show_boxed ( int pdf object, string text, float left, float top, float width, float height, string hmode [, string feature])

Format text in the current font and size into the supplied text box according to the requested formatting mode, which must be one of "left", "right", "center", "justify", or "fulljustify". If width and height are 0, only a single line is placed at the point (left, top) in the requested mode.

Returns the number of characters that did not fit in the specified box. Returns 0 if all characters fit or the width and height parameters were set to 0 for single-line formattting.

后退 | 起点 | 前进
pdf_setrgbcolor | 上一级 | pdf_show_xy


pdf_show_xy

(PHP 3>= 3.0.6, PHP 4 )

pdf_show_xy -- Output text at given position

Description

void pdf_show_xy ( int pdf object, string text, float x, float y)

Print text in the current font at (x, y).

后退 | 起点 | 前进
pdf_show_boxed | 上一级 | pdf_show


pdf_show

(PHP 3>= 3.0.6, PHP 4 )

pdf_show -- Output text at current position

Description

void pdf_show ( int pdf object, string text)

Print text in the current font and size at the current position.

后退 | 起点 | 前进
pdf_show_xy | 上一级 | pdf_skew


pdf_skew

(PHP 4 )

pdf_skew -- Skews the coordinate system

Description

void pdf_skew ( int pdf object, float alpha, float beta)

Skew the coordinate system in x and y direction by alpha and beta degrees.

后退 | 起点 | 前进
pdf_show | 上一级 | pdf_stringwidth


pdf_stringwidth

(PHP 3>= 3.0.6, PHP 4 )

pdf_stringwidth -- Returns width of text using current font

Description

float pdf_stringwidth ( int pdf object, string text [, int font [, float size]])

Returns the width of text using the last font set by pdf_setfont(). If the optional parameters font and size are specified, the width will be calculated using that font and size instead. Please note that font is a font handle returned by pdf_findfont().

注: Both the font and size parameters must used together.

See Also: pdf_setfont() and pdf_findfont().

后退 | 起点 | 前进
pdf_skew | 上一级 | pdf_stroke


pdf_stroke

(PHP 3>= 3.0.6, PHP 4 )

pdf_stroke -- Draws line along path

Description

void pdf_stroke ( int pdf object)

Stroke the path with the current color and line width, and clear it.

后退 | 起点 | 前进
pdf_stringwidth | 上一级 | pdf_translate


pdf_translate

(PHP 3>= 3.0.6, PHP 4 )

pdf_translate -- Sets origin of coordinate system

Description

void pdf_translate ( int pdf object, float tx, float ty)

Translate the origin of the coordinate system.

后退 | 起点 | 前进
pdf_stroke | 上一级 | Verisign Payflow Pro functions


Verisign Payflow Pro functions

PHP 手册
后退 前进

LXXVII. Verisign Payflow Pro functions

介绍

This extension allows you to process credit cards and other financial transactions using Verisign Payment Services, formerly known as Signio (http://www.verisign.com/products/payflow/pro/index.html).

When using these functions, you may omit calls to pfpro_init() and pfpro_cleanup() as this extension will do so automatically if required. However the functions are still available in case you are processing a number of transactions and require fine control over the library. You may perform any number of transactions using pfpro_process() between the two.

These functions were added in PHP 4.0.2.

注: These functions only provide a link to Verisign Payment Services. Be sure to read the Payflow Pro Developers Guide for full details of the required parameters.

需求

You will require the appropriate SDK for your platform, which may be downloaded from within the manager interface once you have registered. If you are going to use this extension in an SSL-enabled webserver or with other SSL components (such as the CURL+SSL extension) you MUST get the beta SDK.

Once you have downloaded the SDK you should copy the files from the lib directory of the distribution. Copy the header file pfpro.h to /usr/local/include and the library file libpfpro.so to /usr/local/lib.

安装

These functions are only available if PHP has been compiled with the --with-pfpro[=DIR] option.

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. Verisign Payflow Pro configuration options

Name | Default | Changeable
pfpro.defaulthost/PFPRO_VERSION < 3 | "test.signio.com" | PHP_INI_ALL
pfpro.defaulthost | "test-payflow.verisign.com" | PHP_INI_ALL
pfpro.defaultport | "443" | PHP_INI_ALL
pfpro.defaulttimeout | "30" | PHP_INI_ALL
pfpro.proxyaddress | "" | PHP_INI_ALL
pfpro.proxyport | "" | PHP_INI_ALL
pfpro.proxylogon | "" | PHP_INI_ALL
pfpro.proxypassword | "" | PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

目录
pfpro_cleanup — Shuts down the Payflow Pro library
pfpro_init — Initialises the Payflow Pro library
pfpro_process_raw — Process a raw transaction with Payflow Pro
pfpro_process — Process a transaction with Payflow Pro
pfpro_version — Returns the version of the Payflow Pro software

后退 | 起点 | 前进
pdf_translate | 上一级 | pfpro_cleanup


pfpro_cleanup

(PHP 4 >= 4.0.2)

pfpro_cleanup -- Shuts down the Payflow Pro library

Description

void pfpro_cleanup ( void)

pfpro_cleanup() is used to shutdown the Payflow Pro library cleanly. It should be called after you have processed any transactions and before the end of your script. However you may omit this call, in which case this extension will automatically call pfpro_cleanup() after your script terminates.

See also pfpro_init().

后退 | 起点 | 前进
Verisign Payflow Pro functions | 上一级 | pfpro_init


pfpro_init

(PHP 4 >= 4.0.2)

pfpro_init -- Initialises the Payflow Pro library

Description

void pfpro_init ( void)

pfpro_init() is used to initialise the Payflow Pro library. You may omit this call, in which case this extension will automatically call pfpro_init() before the first transaction.

See also pfpro_cleanup().

后退 | 起点 | 前进
pfpro_cleanup | 上一级 | pfpro_process_raw


pfpro_process_raw

(PHP 4 >= 4.0.2)

pfpro_process_raw -- Process a raw transaction with Payflow Pro

Description

string pfpro_process_raw ( string parameters [, string address [, int port [, int timeout [, string proxy address [, int proxy port [, string proxy logon [, string proxy password]]]]]]])

Returns: A string containing the response.

pfpro_process_raw() processes a raw transaction string with Payflow Pro. You should really use pfpro_process() instead, as the encoding rules of these transactions are non-standard.

The first parameter in this case is a string containing the raw transaction request. All other parameters are the same as with pfpro_process(). The return value is a string containing the raw response.

注: Be sure to read the Payflow Pro Developers Guide for full details of the required parameters and encoding rules. You would be well advised to use pfpro_process() instead.

例子 1. Payflow Pro raw example

<?php

pfpro_init();

$response = pfpro_process("USER=mylogin&PWD[5]=m&ndy&TRXTYPE=S&TENDER=C&AMT=1.50&ACCT=4111111111111111&EXPDATE=0904");

if (!$response) {
  die("Couldn't establish link to Verisign.\n");
}

echo "Verisign raw response was ".$response;

pfpro_cleanup();

?>

后退 | 起点 | 前进
pfpro_init | 上一级 | pfpro_process


pfpro_process

(PHP 4 >= 4.0.2)

pfpro_process -- Process a transaction with Payflow Pro

Description

array pfpro_process ( array parameters [, string address [, int port [, int timeout [, string proxy address [, int proxy port [, string proxy logon [, string proxy password]]]]]]])

Returns: An associative array containing the response

pfpro_process() processes a transaction with Payflow Pro. The first parameter is an associative array containing keys and values that will be encoded and passed to the processor.

The second parameter is optional and specifies the host to connect to. By default this is "test.signio.com", so you will certainly want to change this to "connect.signio.com" in order to process live transactions.

The third parameter specifies the port to connect on. It defaults to 443, the standard SSL port.

The fourth parameter specifies the timeout to be used, in seconds. This defaults to 30 seconds. Note that this timeout appears to only begin once a link to the processor has been established and so your script could potentially continue for a very long time in the event of DNS or network problems.

The fifth parameter, if required, specifies the hostname of your SSL proxy. The sixth parameter specifies the port to use.

The seventh and eighth parameters specify the logon identity and password to use on the proxy.

The function returns an associative array of the keys and values in the response.

注: Be sure to read the Payflow Pro Developers Guide for full details of the required parameters.

例子 1. Payflow Pro example

<?php

pfpro_init();

$transaction = array(USER	=> 'mylogin',
             PWD	=> 'mypassword',
             TRXTYPE	=> 'S',
             TENDER	=> 'C',
             AMT	=> 1.50,
             ACCT	=> '4111111111111111',
             EXPDATE	=> '0904'
             );

$response = pfpro_process($transaction);

if (!$response) {
  die("Couldn't establish link to Verisign.\n");
}

echo "Verisign response code was ".$response[RESULT];
echo ", which means: ".$response[RESPMSG]."\n";

echo "\nThe transaction request: ";
print_r($transaction);

echo "\nThe response: ";
print_r($response);

pfpro_cleanup();

?>

后退 | 起点 | 前进
pfpro_process_raw | 上一级 | pfpro_version


pfpro_version

(PHP 4 >= 4.0.2)

pfpro_version -- Returns the version of the Payflow Pro software

Description

string pfpro_version ( void)

pfpro_version() returns the version string of the Payflow Pro library. At the time of writing, this was L211.

后退 | 起点 | 前进
pfpro_process | 上一级 | PHP Options&Information


PHP Options&Information

PHP 手册
后退 前进

LXXVIII. PHP Options&Information

介绍

This functions enable you to get a lot of information about PHP itself, e.g. runtime configuration, loaded extensions, version and much more. You'll also find functions to set options for your running PHP. The probably best known function of PHP - phpinfo() - can be found here.

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

这些函数作为 PHP 核心的一部分，无需被安装即可使用。

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

这里列出的所有常量将作为 PHP 核心的一部分一直有效。

表格 1. Pre-defined phpcredits() constants

Constant | Description
CREDITS_ALL | All the credits, equivalent to using: CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES + CREDITS_FULLPAGE. It generates a complete stand-alone HTML page with the appropriate tags.
CREDITS_DOCS | The credits for the documentation team
CREDITS_FULLPAGE | Usually used in combination with the other flags. Indicates that the a complete stand-alone HTML page needs to be printed including the information indicated by the other flags.
CREDITS_GENERAL | General credits: Language design and concept, PHP 4.0 authors and SAPI module.
CREDITS_GROUP | A list of the core developers
CREDITS_MODULES | A list of the extension modules for PHP, and their authors
CREDITS_SAPI | A list of the server API modules for PHP, and their authors

表格 2. phpinfo() constants

Constant | Value | Description
INFO_GENERAL | 1 | The configuration line, php.ini location, build date, Web Server, System and more.
INFO_CREDITS | 2 | PHP 4 Credits. See also phpcredits().
INFO_CONFIGURATION | 4 | Current Local and Master values for php directives. See also ini_get().
INFO_MODULES | 8 | Loaded modules and their respective settings.
INFO_ENVIRONMENT | 16 | Environment Variable information that's also available in $_ENV.
INFO_VARIABLES | 32 | Shows all predefined variables from EGPCS (Environment, GET, POST, Cookie, Server).
INFO_LICENSE | 64 | PHP License information. See also the license faq.
INFO_ALL | -1 | Shows all of the above. This is the default value.
目录
assert_options — Set/get the various assert flags
assert — Checks if assertion is FALSE
dl — Loads a PHP extension at runtime
extension_loaded — Find out whether an extension is loaded
get_cfg_var — Gets the value of a PHP configuration option
get_current_user — Gets the name of the owner of the current PHP script
get_defined_constants — Returns an associative array with the names of all the constants and their values
get_extension_funcs — Returns an array with the names of the functions of a module
get_included_files — Returns an array with the names of included or required files
get_loaded_extensions — Returns an array with the names of all modules compiled and loaded
get_magic_quotes_gpc — Gets the current active configuration setting of magic quotes gpc
get_magic_quotes_runtime — Gets the current active configuration setting of magic_quotes_runtime
get_required_files — Returns an array with the names of included or required files
getenv — Gets the value of an environment variable
getlastmod — Gets time of last page modification
getmygid — Get PHP script owner's GID
getmyinode — Gets the inode of the current script
getmypid — Gets PHP's process ID
getmyuid — Gets PHP script owner's UID
getrusage — Gets the current resource usages
ini_alter — Changes the value of a configuration option
ini_get_all — Gets all configuration options
ini_get — Gets the value of a configuration option
ini_restore — Restores the value of a configuration option
ini_set — Sets the value of a configuration option
php_logo_guid — Gets the logo guid
php_sapi_name — Returns the type of interface between web server and PHP
php_uname — Returns information about the operating system PHP was built on
phpcredits — Prints out the credits for PHP
phpinfo — Outputs lots of PHP information
phpversion — Gets the current PHP version
putenv — Sets the value of an environment variable
set_magic_quotes_runtime — Sets the current active configuration setting of magic_quotes_runtime
set_time_limit — Limits the maximum execution time
version_compare — Compares two "PHP-standardized" version number strings
zend_logo_guid — Gets the zend guid
zend_version — Gets the version of the current Zend engine

后退 | 起点 | 前进
pfpro_version | 上一级 | assert_options


assert_options

(PHP 4 )

assert_options -- Set/get the various assert flags

Description

mixed assert_options ( int what [, mixed value])

Using assert_options() you may set the various assert() control options or just query their current settings.

表格 1. Assert Options

option | ini-parameter | default | description
ASSERT_ACTIVE | assert.active | 1 | enable assert() evaluation
ASSERT_WARNING | assert.warning | 1 | issue a PHP warning for each failed assertion
ASSERT_BAIL | assert.bail | 0 | terminate execution on failed assertions
ASSERT_QUIET_EVAL | assert.quiet_eval | 0 | disable error_reporting during assertion expression evaluation
ASSERT_CALLBACK | assert_callback | (NULL) | user function to call on failed assertions

assert_options() will return the original setting of any option or FALSE on errors.

后退 | 起点 | 前进
PHP Options&Information | 上一级 | assert


assert

(PHP 4 )

assert -- Checks if assertion is FALSE

Description

int assert ( string|bool assertion)

assert() will check the given assertion and take appropriate action if its result is FALSE.

If the assertion is given as a string it will be evaluated as PHP code by assert(). The advantages of a string assertion are less overhead when assertion checking is off and messages containing the assertion expression when an assertion fails.

Assertions should be used as a debugging feature only. You may use them for sanity-checks that test for conditions that should always be TRUE and that indicate some programming errors if not or to check for the presence of certain features like extension functions or certain system limits and features.

Assertions should not be used for normal runtime operations like input parameter checks. As a rule of thumb your code should always be able to work correctly if assertion checking is not activated.

The behavior of assert() may be configured by assert_options() or by .ini-settings described in that functions manual page.

The assert_options() function and/or ASSERT_CALLBACK configuration directive allow a callback function to be set to handle failed assertions.

assert() callbacks are particularly useful for building automated test suites because they allow you to easily capture the code passed to the assertion, along with information on where the assertion was made. While this information can be captured via other methods, using assertions makes it much faster and easier!

The callback function should accept three arguments. The first argument will contain the file the assertion failed in. The second argument will contain the line the assertion failed on and the third argument will contain the expression that failed (if any - literal values such as 1 or "two" will not be passed via this argument)

例子 1. Handle a failed assertion with a custom handler

<?php
// Active assert and make it quiet
assert_options (ASSERT_ACTIVE, 1);
assert_options (ASSERT_WARNING, 0);
assert_options (ASSERT_QUIET_EVAL, 1);

// Create a handler function
function my_assert_handler ($file, $line, $code) {
    echo "<hr>Assertion Failed:
        File '$file'<br>
        Line '$line'<br>
        Code '$code'<br><hr>";
}

// Set up the callback
assert_options (ASSERT_CALLBACK, 'my_assert_handler');

// Make an assertion that should fail
assert ('mysql_query ("")');
?>

后退 | 起点 | 前进
assert_options | 上一级 | dl


dl

(PHP 3, PHP 4 )

dl -- Loads a PHP extension at runtime

Description

bool dl ( string library)

Loads the PHP extension given by the parameter library. The library parameter is only the filename of the extension to load which also depends on your platform. For example, the sockets extension (if compiled as a shared module, not the default!) would be called sockets.so on unix platforms whereas it is called php_sockets.dll on the windows platform.

如果成功则返回 TRUE，失败则返回 FALSE。 If the functionality of loading modules is not available (see Note) or has been disabled (either by turning it off enable_dl or by enabling safe_mode in php.ini) an E_ERROR is emitted and execution is stopped. If dl() fails because the specified library couldn't be loaded, in addition to FALSE an E_WARNING message is emitted.

Use extension_loaded() to test whether a given extension is already available or not. This works on both built-in extensions and dynamically loaded ones (either through php.ini or dl()).

Example:
if (!extension_loaded('gd')) {
    if (!dl('gd.so')) {
        exit;
    }
}

The directory where the extension is loaded from depends on your platform:

Windows - If not explicitly set in the php.ini, the extension is loaded from c:\php4\extensions\ by default.

Unix - If not explicitly set in the php.ini, the default extension directory depends on

  • whether PHP has been built with --enable-debug or not

  • whether PHP has been built with (experimental) ZTS (Zend Thread Safety) support or not

  • the current internal ZEND_MODULE_API_NO (Zend internal module API number, which is basically the date on which a major module API change happened, e.g. 20010901)

Taking into account the above, the directory then defaults to <php-install-directory>/lib/php/extension/<debug-or-not>-<zts-or-not>-ZEND_MODULE_API_NO, e.g. /usr/local/php/lib/php/extensions/debug-non-zts-20010901 or /usr/local/php/lib/php/extensions/no-debug-zts-20010901.

注: dl() is not supported in multithreaded Web servers. Use the extensions statement in your php.ini when operating under such an environment. However, the CGI and CLI build are not affected !

注: dl() is case sensitive on unix platforms.

See also Extension Loading Directives and extension_loaded().

后退 | 起点 | 前进
assert | 上一级 | extension_loaded


extension_loaded

(PHP 3>= 3.0.10, PHP 4 )

extension_loaded -- Find out whether an extension is loaded

Description

bool extension_loaded ( string name)

Returns TRUE if the extension identified by name is loaded, FALSE otherwise.

Example:
if (!extension_loaded('gd')) {
    if (!dl('gd.so')) {
        exit;
    }
}

You can see the names of various extensions by using phpinfo() or if you're usnig the CGI or CLI version of PHP you can use the -m switch to list all available extensions:
$ php -m
[PHP Modules]
xml
tokenizer
standard
sockets
session
posix
pcre
overload
mysql
mbstring
ctype

[Zend Modules]

注: extension_loaded() uses the internal extension name to test whether a certain extension is available or not. Most internal extension names are written in lower case but there may be extension available which also use uppercase letters. Be warned that this function compares case sensitive !

See also phpinfo() and dl().

后退 | 起点 | 前进
dl | 上一级 | get_cfg_var


get_cfg_var

(PHP 3, PHP 4 )

get_cfg_var -- Gets the value of a PHP configuration option

Description

string get_cfg_var ( string varname)

Returns the current value of the PHP configuration variable specified by varname, or FALSE if an error occurs.

It will not return configuration information set when the PHP was compiled, or read from an Apache configuration file (using the php3_configuration_option directives).

To check whether the system is using a configuration file, try retrieving the value of the cfg_file_path configuration setting. If this is available, a configuration file is being used.

See also ini_get().

后退 | 起点 | 前进
extension_loaded | 上一级 | get_current_user


get_current_user

(PHP 3, PHP 4 )

get_current_user -- Gets the name of the owner of the current PHP script

Description

string get_current_user ( void)

Returns the name of the owner of the current PHP script.

See also getmyuid(),
getmygid(), getmypid(),
getmyinode(), and
getlastmod().

后退 | 起点 | 前进
get_cfg_var | 上一级 | get_defined_constants


get_defined_constants

(PHP 4 >= 4.1.0)

get_defined_constants -- Returns an associative array with the names of all the constants and their values

Description

array get_defined_constants ( void)

This function returns the names and values of all the constants currently defined. This includes those created by extensions as well as those created with the define() function.

For example the line below

print_r (get_defined_constants());

will print a list like:

Array
(
    [E_ERROR] => 1
    [E_WARNING] => 2
    [E_PARSE] => 4
    [E_NOTICE] => 8
    [E_CORE_ERROR] => 16
    [E_CORE_WARNING] => 32
    [E_COMPILE_ERROR] => 64
    [E_COMPILE_WARNING] => 128
    [E_USER_ERROR] => 256
    [E_USER_WARNING] => 512
    [E_USER_NOTICE] => 1024
    [E_ALL] => 2047
    [TRUE] => 1
)

See also get_loaded_extensions(),
get_defined_functions() and
get_defined_vars().

后退 | 起点 | 前进
get_current_user | 上一级 | get_extension_funcs


get_extension_funcs

(PHP 4 )

get_extension_funcs -- Returns an array with the names of the functions of a module

Description

array get_extension_funcs ( string module_name)

This function returns the names of all the functions defined in the module indicated by module_name.

For example the lines below

print_r (get_extension_funcs ("xml"));
print_r (get_extension_funcs ("gd"));

will print a list of the functions in the modules xml and gd respectively.

See also: get_loaded_extensions()

后退 | 起点 | 前进
get_defined_constants | 上一级 | get_included_files


get_included_files

(PHP 4 )

get_included_files -- Returns an array with the names of included or required files

Description

array get_included_files ( void)

Returns an array of the names of all files that have been
included using include(),
include_once(), require()
or require_once().

Files that are included or required multiple times only show up once in the returned array.

注: Files included using the auto_prepend_file configuration directive are not included in the returned array.

例子 1. get_included_files() Example

<?php

include("test1.php");
include_once("test2.php");
require("test3.php");
require_once("test4.php");

$included_files = get_included_files();

foreach($included_files as $filename) {
    echo "$filename\n";
}

?>
will generate the following output:

test1.php
test2.php
test3.php
test4.php

注: In PHP 4.0.1pl2 and previous versions get_included_files() assumed that the required files ended in the extension .php; other extensions would not be returned. The array returned by get_included_files() was an associative array and only listed files included by include() and include_once().

See also: include(),
include_once(), require(),
require_once(), and
get_required_files().

后退 | 起点 | 前进
get_extension_funcs | 上一级 | get_loaded_extensions


get_loaded_extensions

(PHP 4 )

get_loaded_extensions -- Returns an array with the names of all modules compiled and loaded

Description

array get_loaded_extensions ( void)

This function returns the names of all the modules compiled and loaded in the PHP interpreter.

For example the line below

print_r (get_loaded_extensions());

will print a list like:

Array
(
   [0] => xml
   [1] => wddx
   [2] => standard
   [3] => session
   [4] => posix
   [5] => pgsql
   [6] => pcre
   [7] => gd
   [8] => ftp
   [9] => db
   [10] => calendar
   [11] => bcmath
)

See also: get_extension_funcs().

后退 | 起点 | 前进
get_included_files | 上一级 | get_magic_quotes_gpc


get_magic_quotes_gpc

(PHP 3>= 3.0.6, PHP 4 )

get_magic_quotes_gpc -- Gets the current active configuration setting of magic quotes gpc

Description

long get_magic_quotes_gpc ( void)

Returns the current active configuration setting of magic_quotes_gpc (0 for off, 1 for on).

See also get_magic_quotes_runtime() and set_magic_quotes_runtime().

后退 | 起点 | 前进
get_loaded_extensions | 上一级 | get_magic_quotes_runtime


get_magic_quotes_runtime

(PHP 3>= 3.0.6, PHP 4 )

get_magic_quotes_runtime -- Gets the current active configuration setting of magic_quotes_runtime

Description

long get_magic_quotes_runtime ( void)

Returns the current active configuration setting of magic_quotes_runtime (0 for off, 1 for on).

See also get_magic_quotes_gpc() and set_magic_quotes_runtime().

后退 | 起点 | 前进
get_magic_quotes_gpc | 上一级 | get_required_files


get_required_files

(PHP 4 )

get_required_files -- Returns an array with the names of included or required files

Description

array get_required_files ( void)

As of PHP 4.0.4, this function is an alias for get_included_files()

In PHP 4.0.1pl2 and previous versions get_required_files() assumed that the required files ended in the extension .php, other extensions would not be returned. The array returned by get_required_files() was an associative array and only listed files included by require() and require_once().

See also: require(),
require_once(), include(),
include_once(), and
get_included_files().

后退 | 起点 | 前进
get_magic_quotes_runtime | 上一级 | getenv


getenv

(PHP 3, PHP 4 )

getenv -- Gets the value of an environment variable

Description

string getenv ( string varname)

Returns the value of the environment variable varname, or FALSE on an error.

$ip = getenv ("REMOTE_ADDR"); // get the ip number of the user

You can see a list of all the environmental variables by using phpinfo(). You can find out what many of them mean by taking a look at the CGI specification, specifically the page on environmental variables.

注: This function does not work in ISAPI mode.

See also putenv().

后退 | 起点 | 前进
get_required_files | 上一级 | getlastmod


getlastmod

(PHP 3, PHP 4 )

getlastmod -- Gets time of last page modification

Description

int getlastmod ( void)

Returns the time of the last modification of the current page. The value returned is a Unix timestamp, suitable for feeding to date(). Returns FALSE on error.

例子 1. getlastmod() example

// outputs e.g. 'Last modified: March 04 1998 20:43:59.'
echo "Last modified: " . date ("F d Y H:i:s.", getlastmod());

See also date(),
getmyuid(), getmygid(),
get_current_user(),
getmyinode(), and
getmypid().

后退 | 起点 | 前进
getenv | 上一级 | getmygid


getmygid

(PHP 4 >= 4.1.0)

getmygid -- Get PHP script owner's GID

Description

int getmygid ( void)

Returns the group ID of the current script, or FALSE on error.

See also getmyuid(),
getmypid(),
get_current_user(),
getmyinode(), and
getlastmod().

后退 | 起点 | 前进
getlastmod | 上一级 | getmyinode


getmyinode

(PHP 3, PHP 4 )

getmyinode -- Gets the inode of the current script

Description

int getmyinode ( void)

Returns the current script's inode, or FALSE on error.

See also getmygid(),
getmyuid(),
get_current_user(),
getmypid(), and
getlastmod().

注: 该函数不适用于 Windows 平台！

后退 | 起点 | 前进
getmygid | 上一级 | getmypid


getmypid

(PHP 3, PHP 4 )

getmypid -- Gets PHP's process ID

Description

int getmypid ( void)

Returns the current PHP process ID, or FALSE on error.

警告

Process IDs are not unique, thus they are a weak entropy source. We recommend against relying on pids in security-dependent contexts.

See also getmygid(),
getmyuid(),
get_current_user(),
getmyinode(), and
getlastmod().

后退 | 起点 | 前进
getmyinode | 上一级 | getmyuid


getmyuid

(PHP 3, PHP 4 )

getmyuid -- Gets PHP script owner's UID

Description

int getmyuid ( void)

Returns the user ID of the current script, or FALSE on error.

See also getmygid(),
getmypid(),
get_current_user(),
getmyinode(), and
getlastmod().

后退 | 起点 | 前进
getmypid | 上一级 | getrusage


getrusage

(PHP 3>= 3.0.7, PHP 4 )

getrusage -- Gets the current resource usages

Description

array getrusage ( [int who])

This is an interface to getrusage(2). It returns an associative array containing the data returned from the system call. If who is 1, getrusage will be called with RUSAGE_CHILDREN.

All entries are accessible by using their documented field names.

例子 1. Getrusage Example

$dat = getrusage();
echo $dat["ru_nswap"];         # number of swaps
echo $dat["ru_majflt"];        # number of page faults
echo $dat["ru_utime.tv_sec"];  # user time used (seconds)
echo $dat["ru_utime.tv_usec"]; # user time used (microseconds)
See your system's man page on getrusage(2) for more details.

后退 | 起点 | 前进
getmyuid | 上一级 | ini_alter


ini_alter

(PHP 4 )

ini_alter -- Changes the value of a configuration option

Description

string ini_alter ( string varname, string newvalue)

Changes the value of a configuration option, returns FALSE on failure, and the previous value of the configuration option on success.

注: This is an alias of ini_set()

See also ini_get(),
ini_get_all(),
ini_restore(), and
ini_set()

后退 | 起点 | 前进
getrusage | 上一级 | ini_get_all


ini_get_all

(PHP 4 >= 4.2.0)

ini_get_all -- Gets all configuration options

Description

array ini_get_all ( [string extension])

Returns all the registered configuration options as an associative array. If optional extension parameter is set, returns only options specific for that extension.

See also: ini_alter(),
ini_restore(), ini_get(),
and ini_set()

后退 | 起点 | 前进
ini_alter | 上一级 | ini_get


ini_get

(PHP 4 )

ini_get -- Gets the value of a configuration option

Description

string ini_get ( string varname)

Returns the value of the configuration option on success, an empty string on failure.

See also get_cfg_var(),
ini_get_all(),
ini_alter(),
ini_restore(), and
ini_set()

后退 | 起点 | 前进
ini_get_all | 上一级 | ini_restore


ini_restore

(PHP 4 )

ini_restore -- Restores the value of a configuration option

Description

string ini_restore ( string varname)

Restores a given configuration option to its original value.

See also: ini_alter(),
ini_get(), ini_get_all(),
and ini_set()

后退 | 起点 | 前进
ini_get | 上一级 | ini_set


ini_set

(PHP 4 )

ini_set -- Sets the value of a configuration option

Description

string ini_set ( string varname, string newvalue)

Sets the value of the given configuration option. Returns the old value on success, FALSE on failure. The configuration option will keep this new value during the script's execution, and will be restored at the script's ending.

Not all the available options can be changed using ini_set(). Below is a table with a list of all PHP options (as of PHP 4.2.0), indicating which ones can be changed/set and at what level.

表格 1. Configuration options

Name | Default | Changeable
com.allow_dcom | "0" | PHP_INI_SYSTEM
com.autoregister_typelib | "0" | PHP_INI_SYSTEM
com.autoregister_verbose | "0" | PHP_INI_SYSTEM
com.autoregister_casesensitive | "1" | PHP_INI_SYSTEM
com.typelib_file | "" | PHP_INI_SYSTEM
crack.default_dictionary | NULL | PHP_INI_SYSTEM
exif.encode_unicode | "ISO-8859-15" | PHP_INI_ALL
exif.decode_unicode_motorola | "UCS-2BE" | PHP_INI_ALL
exif.decode_unicode_intel | "UCS-2LE" | PHP_INI_ALL
exif.encode_jis | "" | PHP_INI_ALL
exif.decode_jis_motorola | "JIS" | PHP_INI_ALL
exif.decode_jis_intel | "JIS" | PHP_INI_ALL
fbsql.allow_persistent | "1" | PHP_INI_SYSTEM
fbsql.generate_warnings | "0" | PHP_INI_SYSTEM
fbsql.autocommit | "1" | PHP_INI_SYSTEM
fbsql.max_persistent | "-1" | PHP_INI_SYSTEM
fbsql.max_links | "128" | PHP_INI_SYSTEM
fbsql.max_connections | "128" | PHP_INI_SYSTEM
fbsql.max_results | "128" | PHP_INI_SYSTEM
fbsql.batchSize | "1000" | PHP_INI_SYSTEM
fbsql.default_host | NULL | PHP_INI_SYSTEM
fbsql.default_user | "_SYSTEM" | PHP_INI_SYSTEM
fbsql.default_password | "" | PHP_INI_SYSTEM
fbsql.default_database | "" | PHP_INI_SYSTEM
fbsql.default_database_password | "" | PHP_INI_SYSTEM
hwapi.allow_persistent | "0" | PHP_INI_SYSTEM
hyerwave.allow_persistent | "0" | PHP_INI_SYSTEM
hyperwave.default_port | "418" | PHP_INI_ALL
iconv.input_encoding | ICONV_INPUT_ENCODING | PHP_INI_ALL
iconv.output_encoding | ICONV_OUTPUT_ENCODING | PHP_INI_ALL
iconv.internal_encoding | ICONV_INTERNAL_ENCODING | PHP_INI_ALL
ifx.allow_persistent | "1" | PHP_INI_SYSTEM
ifx.max_persistent | "-1" | PHP_INI_SYSTEM
ifx.max_links | "-1" | PHP_INI_SYSTEM
ifx.default_host | NULL | PHP_INI_SYSTEM
ifx.default_user | NULL | PHP_INI_SYSTEM
ifx.default_password | NULL | PHP_INI_SYSTEM
ifx.blobinfile | "1" | PHP_INI_ALL
ifx.textasvarchar | "0" | PHP_INI_ALL
ifx.byteasvarchar | "0" | PHP_INI_ALL
ifx.charasvarchar | "0" | PHP_INI_ALL
ifx.nullformat | "0" | PHP_INI_ALL
ingres.allow_persistent | "1" | PHP_INI_SYSTEM
ingres.max_persistent | "-1" | PHP_INI_SYSTEM
ingres.max_links | "-1" | PHP_INI_SYSTEM
ingres.default_database | NULL | PHP_INI_ALL
ingres.default_user | NULL | PHP_INI_ALL
ingres.default_password | NULL | PHP_INI_ALL
ibase.allow_persistent | "1" | PHP_INI_SYSTEM
ibase.max_persistent | "-1" | PHP_INI_SYSTEM
ibase.max_links | "-1" | PHP_INI_SYSTEM
ibase.default_user | NULL | PHP_INI_ALL
ibase.default_password | NULL | PHP_INI_ALL
ibase.timestampformat | "%m/%d/%Y%H:%M:%S" | PHP_INI_ALL
ibase.dateformat | "%m/%d/%Y" | PHP_INI_ALL
ibase.timeformat | "%H:%M:%S" | PHP_INI_ALL
java.class.path | NULL | PHP_INI_ALL
java.home | NULL | PHP_INI_ALL
java.library.path | NULL | PHP_INI_ALL
java.library | JAVALIB | PHP_INI_ALL
java.library | NULL | PHP_INI_ALL
ldap.max_links | "-1" | PHP_INI_SYSTEM
mbstring.detect_order | NULL | PHP_INI_ALL
mbstring.http_input | NULL | PHP_INI_ALL
mbstring.http_output | NULL | PHP_INI_ALL
mbstring.internal_encoding | NULL | PHP_INI_ALL
mbstring.substitute_character | NULL | PHP_INI_ALL
mbstring.func_overload | "0" | PHP_INI_SYSTEM
mcrypt.algorithms_dir | NULL | PHP_INI_ALL
mcrypt.modes_dir | NULL | PHP_INI_ALL
mime_magic.magicfile | "/usr/share/misc/magic.mime" | PHP_INI_SYSTEM
mssql.allow_persistent | "1" | PHP_INI_SYSTEM
mssql.max_persistent | "-1" | PHP_INI_SYSTEM
mssql.max_links | "-1" | PHP_INI_SYSTEM
mssql.max_procs | "25" | PHP_INI_ALL
mssql.min_error_severity | "10" | PHP_INI_ALL
mssql.min_message_severity | "10" | PHP_INI_ALL
mssql.compatability_mode | "0" | PHP_INI_ALL
mssql.connect_timeout | "5" | PHP_INI_ALL
mssql.timeout | "60" | PHP_INI_ALL
mssql.textsize | "-1" | PHP_INI_ALL
mssql.textlimit | "-1" | PHP_INI_ALL
mssql.batchsize | "0" | PHP_INI_ALL
mssql.datetimeconvert | "1" | PHP_INI_ALL
mysql.allow_persistent | "1" | PHP_INI_SYSTEM
mysql.max_persistent | "-1" | PHP_INI_SYSTEM
mysql.max_links | "-1" | PHP_INI_SYSTEM
mysql.default_host | NULL | PHP_INI_ALL
mysql.default_user | NULL | PHP_INI_ALL
mysql.default_password | NULL | PHP_INI_ALL
mysql.default_port | NULL | PHP_INI_ALL
mysql.default_socket | NULL | PHP_INI_ALL
ncurses.value | "42" | PHP_INI_ALL
ncurses.string | "foobar" | PHP_INI_ALL
odbc.allow_persistent | "1" | PHP_INI_SYSTEM
odbc.max_persistent | "-1" | PHP_INI_SYSTEM
odbc.max_links | "-1" | PHP_INI_SYSTEM
odbc.default_db | NULL | PHP_INI_ALL
odbc.default_user | NULL | PHP_INI_ALL
odbc.default_pw | NULL | PHP_INI_ALL
odbc.defaultlrl | "4096" | PHP_INI_ALL
odbc.defaultbinmode | "1" | PHP_INI_ALL
odbc.check_persistent | "1" | PHP_INI_SYSTEM
pfpro.defaulthost | "test.signio.com" |
pfpro.defaulthost | "test-payflow.verisign.com" |
pfpro.defaultport | "443" | PHP_INI_ALL
pfpro.defaulttimeout | "30" | PHP_INI_ALL
pfpro.proxyaddress | "" | PHP_INI_ALL
pfpro.proxyport | "" | PHP_INI_ALL
pfpro.proxylogon | "" | PHP_INI_ALL
pfpro.proxypassword | "" | PHP_INI_ALL
pgsql.allow_persistent | "1" | PHP_INI_SYSTEM
pgsql.max_persistent | "-1" | PHP_INI_SYSTEM
pgsql.max_links | "-1" | PHP_INI_SYSTEM
pgsql.auto_reset_persistent | "0" | PHP_INI_SYSTEM
pgsql.ignore_notice | "0" | PHP_INI_ALL
pgsql.log_notice | "0" | PHP_INI_ALL
session.save_path | "/tmp" | PHP_INI_ALL
session.name | "PHPSESSID" | PHP_INI_ALL
session.save_handler | "files" | PHP_INI_ALL
session.auto_start | "0" | PHP_INI_ALL
session.gc_probability | "1" | PHP_INI_ALL
session.gc_maxlifetime | "1440" | PHP_INI_ALL
session.serialize_handler | "php" | PHP_INI_ALL
session.cookie_lifetime | "0" | PHP_INI_ALL
session.cookie_path | "/" | PHP_INI_ALL
session.cookie_domain | "" | PHP_INI_ALL
session.cookie_secure | "" | PHP_INI_ALL
session.use_cookies | "1" | PHP_INI_ALL
session.use_only_cookies | "0" | PHP_INI_ALL
session.referer_check | "" | PHP_INI_ALL
session.entropy_file | "" | PHP_INI_ALL
session.entropy_length | "0" | PHP_INI_ALL
session.cache_limiter | "nocache" | PHP_INI_ALL
session.cache_expire | "180" | PHP_INI_ALL
session.use_trans_sid | "1" | PHP_INI_ALL
session.encode_sources | "globals | track"
extname.global_value | "42" | PHP_INI_ALL
extname.global_string | "foobar" | PHP_INI_ALL
assert.active | "1" | PHP_INI_ALL
assert.bail | "0" | PHP_INI_ALL
assert.warning | "1" | PHP_INI_ALL
assert.callback | NULL | PHP_INI_ALL
assert.quiet_eval | "0" | PHP_INI_ALL
safe_mode_protected_env_vars | SAFE_MODE_PROTECTED_ENV_VARS | PHP_INI_SYSTEM
safe_mode_allowed_env_vars | SAFE_MODE_ALLOWED_ENV_VARS | PHP_INI_SYSTEM
url_rewriter.tags | "a=href,area=href,frame=src,form=fakeentry" | PHP_INI_ALL
sybct.allow_persistent | "1" | PHP_INI_SYSTEM
sybct.max_persistent | "-1" | PHP_INI_SYSTEM
sybct.max_links | "-1" | PHP_INI_SYSTEM
sybct.min_server_severity | "10" | PHP_INI_ALL
sybct.min_client_severity | "10" | PHP_INI_ALL
sybct.hostname | NULL | PHP_INI_ALL
tokenizer.global_value | "42" | PHP_INI_ALL
tokenizer.global_string | "foobar" | PHP_INI_ALL
vpopmail.directory | "" | PHP_INI_ALL
zlib.output_compression | "0" | PHP_INI_SYSTEM|PHP_INI_PERDIR
zlib.output_compression_level | "-1" | PHP_INI_ALL
define_syslog_variables | "0" | PHP_INI_ALL
highlight.bg | HL_BG_COLOR | PHP_INI_ALL
highlight.comment | HL_COMMENT_COLOR | PHP_INI_ALL
highlight.default | HL_DEFAULT_COLOR | PHP_INI_ALL
highlight.html | HL_HTML_COLOR | PHP_INI_ALL
highlight.keyword | HL_KEYWORD_COLOR | PHP_INI_ALL
highlight.string | HL_STRING_COLOR | PHP_INI_ALL
allow_call_time_pass_reference | "1" | PHP_INI_SYSTEM|PHP_INI_PERDIR
asp_tags | "0" | PHP_INI_SYSTEM|PHP_INI_PERDIR
display_errors | "1" | PHP_INI_ALL
display_startup_errors | "0" | PHP_INI_ALL
enable_dl | "1" | PHP_INI_SYSTEM
expose_php | "1" | PHP_INI_SYSTEM
html_errors | "1" | PHP_INI_SYSTEM
xmlrpc_errors | "0" | PHP_INI_SYSTEM
xmlrpc_error_number | "0" | PHP_INI_ALL
ignore_user_abort | "0" | PHP_INI_ALL
implicit_flush | "0" | PHP_INI_PERDIR|PHP_INI_SYSTEM
log_errors | "0" | PHP_INI_ALL
log_errors_max_len | "1024" | PHP_INI_ALL
ignore_repeated_errors | "0" | PHP_INI_ALL
ignore_repeated_source | "0" | PHP_INI_ALL
magic_quotes_gpc | "1" | PHP_INI_PERDIR|PHP_INI_SYSTEM
magic_quotes_runtime | "0" | PHP_INI_ALL
magic_quotes_sybase | "0" | PHP_INI_ALL
output_buffering | "0" | PHP_INI_PERDIR|PHP_INI_SYSTEM
output_handler | NULL | PHP_INI_PERDIR|PHP_INI_SYSTEM
register_argc_argv | "1" | PHP_INI_ALL
register_globals | "0" | PHP_INI_PERDIR|PHP_INI_SYSTEM
safe_mode | "1" | PHP_INI_SYSTEM
safe_mode | "0" | PHP_INI_SYSTEM
safe_mode_include_dir | NULL | PHP_INI_SYSTEM
safe_mode_gid | "0" | PHP_INI_SYSTEM
short_open_tag | DEFAULT_SHORT_OPEN_TAG | PHP_INI_SYSTEM|PHP_INI_PERDIR
sql.safe_mode | "0" | PHP_INI_SYSTEM
track_errors | "0" | PHP_INI_ALL
y2k_compliance | "0" | PHP_INI_ALL
unserialize_callback_func | NULL | PHP_INI_ALL
arg_separator.output | "&" | PHP_INI_ALL
arg_separator.input | "&" | PHP_INI_SYSTEM|PHP_INI_PERDIR
auto_append_file | NULL | PHP_INI_SYSTEM|PHP_INI_PERDIR
auto_prepend_file | NULL | PHP_INI_SYSTEM|PHP_INI_PERDIR
doc_root | NULL | PHP_INI_SYSTEM
default_charset | SAPI_DEFAULT_CHARSET | PHP_INI_ALL
default_mimetype | SAPI_DEFAULT_MIMETYPE | PHP_INI_ALL
error_log | NULL | PHP_INI_ALL
extension_dir | PHP_EXTENSION_DIR | PHP_INI_SYSTEM
gpc_order | "GPC" | PHP_INI_ALL
include_path | PHP_INCLUDE_PATH | PHP_INI_ALL
max_execution_time | "30" | PHP_INI_ALL
open_basedir | NULL | PHP_INI_SYSTEM
safe_mode_exec_dir | "1" | PHP_INI_SYSTEM
upload_max_filesize | "2M" | PHP_INI_SYSTEM
file_uploads | "1" | PHP_INI_ALL
post_max_size | "8M" | PHP_INI_SYSTEM
upload_tmp_dir | NULL | PHP_INI_SYSTEM
user_dir | NULL | PHP_INI_SYSTEM
variables_order | NULL | PHP_INI_ALL
error_append_string | NULL | PHP_INI_ALL
error_prepend_string | NULL | PHP_INI_ALL
SMTP | "localhost" | PHP_INI_ALL
smtp_port | 25 | PHP_INI_ALL
browscap | NULL | PHP_INI_SYSTEM
error_reporting | NULL | PHP_INI_ALL
memory_limit | "8M" | PHP_INI_ALL
precision | "14" | PHP_INI_ALL
sendmail_from | NULL | PHP_INI_ALL
sendmail_path | DEFAULT_SENDMAIL_PATH | PHP_INI_SYSTEM
disable_functions | "" | PHP_INI_SYSTEM
allow_url_fopen | "1" | PHP_INI_ALL
always_populate_raw_post_data | "0" | PHP_INI_ALL
xbithack | "0" | PHP_INI_ALL
engine | "1" | PHP_INI_ALL
last_modified | "0" | PHP_INI_ALL
child_terminate | "0" | PHP_INI_ALL
async_send | "0" | PHP_INI_ALL

表格 2. Definition of PHP_INI_* constants

Constant | Value | Meaning
PHP_INI_USER | 1 | Entry can be set in user scripts
PHP_INI_PERDIR | 2 | Entry can be set in .htaccess and VHost directives in httpd.conf.
PHP_INI_SYSTEM | 4 | Entry can be set in php.ini or httpd.conf (but not in VHost blocks in httpd.conf).
PHP_INI_ALL | 7 | Entry can be set anywhere

See also: ini_alter(),
ini_get(), and
ini_restore()

后退 | 起点 | 前进
ini_restore | 上一级 | php_logo_guid


php_logo_guid

(PHP 4 )

php_logo_guid -- Gets the logo guid

Description

string php_logo_guid ( void)

注: This functionality was added in PHP 4.0.0.

See also: phpinfo(),
phpversion(), and
phpcredits().

后退 | 起点 | 前进
ini_set | 上一级 | php_sapi_name


php_sapi_name

(PHP 4 >= 4.0.1)

php_sapi_name -- Returns the type of interface between web server and PHP

Description

string php_sapi_name ( void)

php_sapi_name() returns a lowercase string which describes the type of interface between web server and PHP (Server API, SAPI). In CGI PHP, this string is "cgi", in mod_php for Apache, this string is "apache" and so on.

例子 1. php_sapi_name() Example

$sapi_type = php_sapi_name();
if ($sapi_type == "cgi")
    print "You are using CGI PHP\n";
else
    print "You are not using CGI PHP\n";

后退 | 起点 | 前进
php_logo_guid | 上一级 | php_uname


php_uname

(PHP 4 >= 4.0.2)

php_uname -- Returns information about the operating system PHP was built on

Description

string php_uname ( void)

php_uname() returns a string with a description of the operating system PHP is built on.

例子 1. php_uname() Example

if (substr(php_uname(), 0, 7) == "Windows") {
   die ("Sorry, this script doesn't run on Windows.\n");
}

后退 | 起点 | 前进
php_sapi_name | 上一级 | phpcredits


phpcredits

(PHP 4 )

phpcredits -- Prints out the credits for PHP

Description

void phpcredits ( [int flag])

This function prints out the credits listing the PHP developers, modules, etc. It generates the appropriate HTML codes to insert the information in a page. flag is optional, and it defaults to CREDITS_ALL. To generate a custom credits page, you may want to use the flag parameter. For example to print the general credits, you will use somewhere in your code:

...
phpcredits(CREDITS_GENERAL);
...

And if you want to print the core developers and the documentation group, in a page of its own, you will use:

<?php
phpcredits(CREDITS_GROUP + CREDITS_DOCS + CREDITS_FULLPAGE);
?>

And if you feel like embedding all the credits in your page, then code like the one below will do it:

<html>
 <head>
  <title>My credits page</title>
 </head>
 <body>
  <?php
 // some code of your own
 phpcredits(CREDITS_ALL);
 // some more code
 ?>
 </body>
</html>

表格 1. Pre-defined phpcredits() flags

name | description
CREDITS_ALL | All the credits, equivalent to using: CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES + CREDITS_FULLPAGE. It generates a complete stand-alone HTML page with the appropriate tags.
CREDITS_DOCS | The credits for the documentation team
CREDITS_FULLPAGE | Usually used in combination with the other flags. Indicates that the a complete stand-alone HTML page needs to be printed including the information indicated by the other flags.
CREDITS_GENERAL | General credits: Language design and concept, PHP 4.0 authors and SAPI module.
CREDITS_GROUP | A list of the core developers
CREDITS_MODULES | A list of the extension modules for PHP, and their authors
CREDITS_SAPI | A list of the server API modules for PHP, and their authors

See also: phpinfo(),
phpversion(), and
php_logo_guid().

后退 | 起点 | 前进
php_uname | 上一级 | phpinfo


phpinfo

(PHP 3, PHP 4 )

phpinfo -- Outputs lots of PHP information

Description

int phpinfo ( [int what])

Outputs a large amount of information about the current state of PHP. This includes information about PHP compilation options and extensions, the PHP version, server information and environment (if compiled as a module), the PHP environment, OS version information, paths, master and local values of configuration options, HTTP headers, and the PHP License.

Because every system is setup differently, phpinfo() is commonly used to check configuration settings and for available predefined variables on a given system. Also, phpinfo() is a valuable debugging tool as it contains all EGPCS (Environment, GET, POST, Cookie, Server) data.

The output may be customized by passing one or more of the following constants bitwise values summed together in the optional what parameter. One can also combine the respective constants or bitwise values together with the or operator.

表格 1. phpinfo() options

Name (constant) | Value | Description
INFO_GENERAL | 1 | The configuration line, php.ini location, build date, Web Server, System and more.
INFO_CREDITS | 2 | PHP 4 Credits. See also phpcredits().
INFO_CONFIGURATION | 4 | Current Local and Master values for php directives. See also ini_get().
INFO_MODULES | 8 | Loaded modules and their respective settings.
INFO_ENVIRONMENT | 16 | Environment Variable information that's also available in $_ENV.
INFO_VARIABLES | 32 | Shows all predefined variables from EGPCS (Environment, GET, POST, Cookie, Server).
INFO_LICENSE | 64 | PHP License information. See also the license faq.
INFO_ALL | -1 | Shows all of the above. This is the default value.

例子 1. phpinfo() examples

<?php

// Show all information, defaults to INFO_ALL
phpinfo();

// Show just the module information.
// phpinfo(8) yields identical results.
phpinfo(INFO_MODULES);

?>

注: Parts of the information displayed are disabled when the expose_php configuration setting is set to off. This includes the PHP and Zend logos, and the credits.

See also: phpversion(),
phpcredits(),
php_logo_guid(), ini_get(),
ini_set(), and the section on Predefined
Variables.

后退 | 起点 | 前进
phpcredits | 上一级 | phpversion


phpversion

(PHP 3, PHP 4 )

phpversion -- Gets the current PHP version

Description

string phpversion ( void)

Returns a string containing the version of the currently running PHP parser.

注: This information is also available in the predefined constant PHP_VERSION.

例子 1. phpversion() Example

<?php
// prints e.g. 'Current PHP version: 4.1.1'
echo 'Current PHP version: ' . phpversion();
?>

See also version_compare(),
phpinfo(), phpcredits(),
php_logo_guid(), and
zend_version().

后退 | 起点 | 前进
phpinfo | 上一级 | putenv


putenv

(PHP 3, PHP 4 )

putenv -- Sets the value of an environment variable

Description

void putenv ( string setting)

Adds setting to the server environment. The environment variable will only exist for the duration of the current request. At the end of the request the environment is restored to its original state.

Setting certain environment variables may be a potential security breach. The safe_mode_allowed_env_vars directive contains a comma-delimited list of prefixes. In Safe Mode, the user may only alter environment variables whose names begin with the prefixes supplied by this directive. By default, users will only be able to set environment variables that begin with PHP_ (e.g. PHP_FOO=BAR). Note: if this directive is empty, PHP will let the user modify ANY environment variable!

The safe_mode_protected_env_vars directive contains a comma-delimited list of environment variables, that the end user won't be able to change using putenv(). These variables will be protected even if safe_mode_allowed_env_vars is set to allow to change them.

警告

These directives have only effect when safe-mode itself is enabled!

例子 1. Setting an Environment Variable

putenv ("UNIQID=$uniqid");

See also getenv().

后退 | 起点 | 前进
phpversion | 上一级 | set_magic_quotes_runtime


set_magic_quotes_runtime

(PHP 3>= 3.0.6, PHP 4 )

set_magic_quotes_runtime -- Sets the current active configuration setting of magic_quotes_runtime

Description

long set_magic_quotes_runtime ( int new_setting)

Set the current active configuration setting of magic_quotes_runtime (0 for off, 1 for on).

See also: get_magic_quotes_gpc() and get_magic_quotes_runtime().

后退 | 起点 | 前进
putenv | 上一级 | set_time_limit


set_time_limit

(PHP 3, PHP 4 )

set_time_limit -- Limits the maximum execution time

Description

void set_time_limit ( int seconds)

Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the configuration file. If seconds is set to zero, no time limit is imposed.

When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.

set_time_limit() has no effect when PHP is running in safe mode. There is no workaround other than turning off safe mode or changing the time limit in the configuration file.

注: The set_time_limit() function and the configuration directive max_execution_time only affect the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), the sleep() function, database queries, etc. is not included when determining the maximum time that the script has been running.

后退 | 起点 | 前进
set_magic_quotes_runtime | 上一级 | version_compare


version_compare

(PHP 4 >= 4.1.0)

version_compare -- Compares two "PHP-standardized" version number strings

Description

int version_compare ( string version1, string version2 [, string operator])

version_compare() compares two "PHP-standardized" version number strings. This is useful if you would like to write programs working only on some versions of PHP.

version_compare() returns -1 if the first version is lower than the second, 0 if they are equal, and +1 if the second is lower.

If you specify the third optional operator argument, you can test for a particular relationship. The possible operators are: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne respectively. Using this argument, the function will return 1 if the relationship is the one specified by the operator, 0 otherwise.

例子 1. version_compare() Example

// prints -1
echo version_compare("4.0.4", "4.0.6");

// these all print 1
echo version_compare("4.0.4", "4.0.6", "<");
echo version_compare("4.0.6", "4.0.6", "eq");

后退 | 起点 | 前进
set_time_limit | 上一级 | zend_logo_guid


zend_logo_guid

(PHP 4 )

zend_logo_guid -- Gets the zend guid

Description

string zend_logo_guid ( void)

注: This functionality was added in PHP 4.0.0.

后退 | 起点 | 前进
version_compare | 上一级 | zend_version


zend_version

(PHP 4 )

zend_version -- Gets the version of the current Zend engine

Description

string zend_version ( void)

Returns a string containing the version of the currently running PHP parser.

例子 1. zend_version() Example

// prints e.g. 'Zend engine version: 1.0.4'
echo "Zend engine version: " . zend_version();

See also phpinfo(),
phpcredits(),
php_logo_guid(), and
phpversion().

后退 | 起点 | 前进
zend_logo_guid | 上一级 | POSIX functions


POSIX functions

PHP 手册
后退 前进

LXXIX. POSIX functions

介绍

This module contains an interface to those functions defined in the IEEE 1003.1 (POSIX.1) standards document which are not accessible through other means. POSIX.1 for example defined the open(), read(), write() and close() functions, too, which traditionally have been part of PHP 3 for a long time. Some more system specific functions have not been available before, though, and this module tries to remedy this by providing easy access to these functions.

警告

Sensitive data can be retrieved with the POSIX functions, e.g. posix_getpwnam() and friends. None of the POSIX function perform any kind of access checking when safe mode is enabled. It's therefore strongly advised to disable the POSIX extension at all (use --disable-posix in your configure line) if you're operating in such an environment.

注: The POSIX extension is not available on the Windows platform.

相关参考

The section about Process Control Functions maybe of interest for you.

目录
posix_ctermid — Get path name of controlling terminal
posix_getcwd — Pathname of current directory
posix_getegid — Return the effective group ID of the current process
posix_geteuid — Return the effective user ID of the current process
posix_getgid — Return the real group ID of the current process
posix_getgrgid — Return info about a group by group id
posix_getgrnam — Return info about a group by name
posix_getgroups — Return the group set of the current process
posix_getlogin — Return login name
posix_getpgid — Get process group id for job control
posix_getpgrp — Return the current process group identifier
posix_getpid — Return the current process identifier
posix_getppid — Return the parent process identifier
posix_getpwnam — Return info about a user by username
posix_getpwuid — Return info about a user by user id
posix_getrlimit — Return info about system ressource limits
posix_getsid — Get the current sid of the process
posix_getuid — Return the real user ID of the current process
posix_isatty — Determine if a file descriptor is an interactive terminal
posix_kill — Send a signal to a process
posix_mkfifo — Create a fifo special file (a named pipe)
posix_setegid — Set the effective GID of the current process
posix_seteuid — Set the effective UID of the current process
posix_setgid — Set the GID of the current process
posix_setpgid — set process group id for job control
posix_setsid — Make the current process a session leader
posix_setuid — Set the UID of the current process
posix_times — Get process times
posix_ttyname — Determine terminal device name
posix_uname — Get system name

后退 | 起点 | 前进
zend_version | 上一级 | posix_ctermid


posix_ctermid

(PHP 3>= 3.0.13, PHP 4 )

posix_ctermid -- Get path name of controlling terminal

Description

string posix_ctermid ( void)

Needs to be written.

后退 | 起点 | 前进
POSIX functions | 上一级 | posix_getcwd


posix_getcwd

(PHP 3>= 3.0.13, PHP 4 )

posix_getcwd -- Pathname of current directory

Description

string posix_getcwd ( void)

Needs to be written ASAP.

后退 | 起点 | 前进
posix_ctermid | 上一级 | posix_getegid


posix_getegid

(PHP 3>= 3.0.10, PHP 4 )

posix_getegid -- Return the effective group ID of the current process

Description

int posix_getegid ( void)

Return the numeric effective group ID of the current process. See also posix_getgrgid() for information on how to convert this into a useable group name.

后退 | 起点 | 前进
posix_getcwd | 上一级 | posix_geteuid


posix_geteuid

(PHP 3>= 3.0.10, PHP 4 )

posix_geteuid -- Return the effective user ID of the current process

Description

int posix_geteuid ( void)

Return the numeric effective user ID of the current process. See also posix_getpwuid() for information on how to convert this into a useable username.

后退 | 起点 | 前进
posix_getegid | 上一级 | posix_getgid


posix_getgid

(PHP 3>= 3.0.10, PHP 4 )

posix_getgid -- Return the real group ID of the current process

Description

int posix_getgid ( void)

Return the numeric real group ID of the current process. See also posix_getgrgid() for information on how to convert this into a useable group name.

后退 | 起点 | 前进
posix_geteuid | 上一级 | posix_getgrgid


posix_getgrgid

(PHP 3>= 3.0.13, PHP 4 )

posix_getgrgid -- Return info about a group by group id

Description

array posix_getgrgid ( int gid)

Needs to be written.

后退 | 起点 | 前进
posix_getgid | 上一级 | posix_getgrnam


posix_getgrnam

(PHP 3>= 3.0.13, PHP 4 )

posix_getgrnam -- Return info about a group by name

Description

array posix_getgrnam ( string name)

Needs to be written.

后退 | 起点 | 前进
posix_getgrgid | 上一级 | posix_getgroups


posix_getgroups

(PHP 3>= 3.0.10, PHP 4 )

posix_getgroups -- Return the group set of the current process

Description

array posix_getgroups ( void)

Returns an array of integers containing the numeric group ids of the group set of the current process. See also posix_getgrgid() for information on how to convert this into useable group names.

后退 | 起点 | 前进
posix_getgrnam | 上一级 | posix_getlogin


posix_getlogin

(PHP 3>= 3.0.13, PHP 4 )

posix_getlogin -- Return login name

Description

string posix_getlogin ( void)

Returns the login name of the user owning the current process. See posix_getpwnam() for information how to get more information about this user.

后退 | 起点 | 前进
posix_getgroups | 上一级 | posix_getpgid


posix_getpgid

(PHP 3>= 3.0.10, PHP 4 )

posix_getpgid -- Get process group id for job control

Description

int posix_getpgid ( int pid)

Returns the process group identifier of the process pid.

This is not a POSIX function, but is common on BSD and System V systems. If your system does not support this function at system level, this PHP function will always return FALSE.

后退 | 起点 | 前进
posix_getlogin | 上一级 | posix_getpgrp


posix_getpgrp

(PHP 3>= 3.0.10, PHP 4 )

posix_getpgrp -- Return the current process group identifier

Description

int posix_getpgrp ( void)

Return the process group identifier of the current process. See POSIX.1 and the getpgrp(2) manual page on your POSIX system for more information on process groups.

后退 | 起点 | 前进
posix_getpgid | 上一级 | posix_getpid


posix_getpid

(PHP 3>= 3.0.10, PHP 4 )

posix_getpid -- Return the current process identifier

Description

int posix_getpid ( void)

Return the process identifier of the current process.

后退 | 起点 | 前进
posix_getpgrp | 上一级 | posix_getppid


posix_getppid

(PHP 3>= 3.0.10, PHP 4 )

posix_getppid -- Return the parent process identifier

Description

int posix_getppid ( void)

Return the process identifier of the parent process of the current process.

后退 | 起点 | 前进
posix_getpid | 上一级 | posix_getpwnam


posix_getpwnam

(PHP 3>= 3.0.13, PHP 4 )

posix_getpwnam -- Return info about a user by username

Description

array posix_getpwnam ( string username)

Returns an associative array containing information about a user referenced by an alphanumeric username, passed in the username parameter.

The array elements returned are:

表格 1. The user information array

Element | Description
name | The name element contains the username of the user. This is a short, usually less than 16 character "handle" of the user, not her real, full name. This should be the same as the username parameter used when calling the function, and hence redundant.
passwd | The passwd element contains the user's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead.
uid | User ID of the user in numeric form.
gid | The group ID of the user. Use the function posix_getgrgid() to resolve the group name and a list of its members.
gecos | GECOS is an obsolete term that refers to the finger information field on a Honeywell batch processing system. The field, however, lives on, and its contents have been formalized by POSIX. The field contains a comma separated list containing the user's full name, office phone, office number, and home phone number. On most systems, only the user's full name is available.
dir | This element contains the absolute path to the home directory of the user.
shell | The shell element contains the absolute path to the executable of the user's default shell.

后退 | 起点 | 前进
posix_getppid | 上一级 | posix_getpwuid


posix_getpwuid

(PHP 3>= 3.0.13, PHP 4 )

posix_getpwuid -- Return info about a user by user id

Description

array posix_getpwuid ( int uid)

Returns an associative array containing information about a user referenced by a numeric user ID, passed in the uid parameter.

The array elements returned are:

表格 1. The user information array

Element | Description
name | The name element contains the username of the user. This is a short, usually less than 16 character "handle" of the user, not her real, full name.
passwd | The passwd element contains the user's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead.
uid | User ID, should be the same as the uid parameter used when calling the function, and hence redundant.
gid | The group ID of the user. Use the function posix_getgrgid() to resolve the group name and a list of its members.
gecos | GECOS is an obsolete term that refers to the finger information field on a Honeywell batch processing system. The field, however, lives on, and its contents have been formalized by POSIX. The field contains a comma separated list containing the user's full name, office phone, office number, and home phone number. On most systems, only the user's full name is available.
dir | This element contains the absolute path to the home directory of the user.
shell | The shell element contains the absolute path to the executable of the user's default shell.

后退 | 起点 | 前进
posix_getpwnam | 上一级 | posix_getrlimit


posix_getrlimit

(PHP 3>= 3.0.10, PHP 4 )

posix_getrlimit -- Return info about system ressource limits

Description

array posix_getrlimit ( void)

Needs to be written ASAP.

后退 | 起点 | 前进
posix_getpwuid | 上一级 | posix_getsid


posix_getsid

(PHP 3>= 3.0.10, PHP 4 )

posix_getsid -- Get the current sid of the process

Description

int posix_getsid ( int pid)

Return the sid of the process pid. If pid is 0, the sid of the current process is returned.

This is not a POSIX function, but is common on System V systems. If your system does not support this function at system level, this PHP function will always return FALSE.

后退 | 起点 | 前进
posix_getrlimit | 上一级 | posix_getuid


posix_getuid

(PHP 3>= 3.0.10, PHP 4 )

posix_getuid -- Return the real user ID of the current process

Description

int posix_getuid ( void)

Return the numeric real user ID of the current process. See also posix_getpwuid() for information on how to convert this into a useable username.

后退 | 起点 | 前进
posix_getsid | 上一级 | posix_isatty


posix_isatty

(PHP 3>= 3.0.13, PHP 4 )

posix_isatty -- Determine if a file descriptor is an interactive terminal

Description

bool posix_isatty ( int fd)

Needs to be written.

后退 | 起点 | 前进
posix_getuid | 上一级 | posix_kill


posix_kill

(PHP 3>= 3.0.13, PHP 4 )

posix_kill -- Send a signal to a process

Description

bool posix_kill ( int pid, int sig)

Send the signal sig to the process with the process identifier pid. Returns FALSE, if unable to send the signal, TRUE otherwise.

See also the kill(2) manual page of your POSIX system, which contains additional information about negative process identifiers, the special pid 0, the special pid -1, and the signal number 0.

后退 | 起点 | 前进
posix_isatty | 上一级 | posix_mkfifo


posix_mkfifo

(PHP 3>= 3.0.13, PHP 4 )

posix_mkfifo -- Create a fifo special file (a named pipe)

Description

bool posix_mkfifo ( string pathname, int mode)

posix_mkfifo() creates a special FIFO file which exists in the file system and acts as a bidirectional communication endpoint for processes.

The second parameter mode has to be given in octal notation (e.g. 0644). The permission of the newly created FIFO also depends on the setting of the current umask(). The permissions of the created file are (mode & ~umask).

注: W当 安全模式（safe mode） 被激活，PHP 将检查您将要操作的目录和正在执行的脚本是否有相同的 UID。

后退 | 起点 | 前进
posix_kill | 上一级 | posix_setegid


posix_setegid

(PHP 4 >= 4.0.2)

posix_setegid -- Set the effective GID of the current process

Description

bool posix_setegid ( int gid)

Set the effective group ID of the current process. This is a privileged function and you need appropriate privileges (usually root) on your system to be able to perform this function.

Returns TRUE on success, FALSE otherwise.

后退 | 起点 | 前进
posix_mkfifo | 上一级 | posix_seteuid


posix_seteuid

(PHP 4 >= 4.0.2)

posix_seteuid -- Set the effective UID of the current process

Description

bool posix_seteuid ( int uid)

Set the real user ID of the current process. This is a privileged function and you need appropriate privileges (usually root) on your system to be able to perform this function.

Returns TRUE on success, FALSE otherwise. See also posix_setgid().

后退 | 起点 | 前进
posix_setegid | 上一级 | posix_setgid


posix_setgid

(PHP 3>= 3.0.13, PHP 4 )

posix_setgid -- Set the GID of the current process

Description

bool posix_setgid ( int gid)

Set the real group ID of the current process. This is a privileged function and you need appropriate privileges (usually root) on your system to be able to perform this function. The appropriate order of function calls is posix_setgid() first, posix_setuid() last.

Returns TRUE on success, FALSE otherwise.

后退 | 起点 | 前进
posix_seteuid | 上一级 | posix_setpgid


posix_setpgid

(PHP 3>= 3.0.13, PHP 4 )

posix_setpgid -- set process group id for job control

Description

int posix_setpgid ( int pid, int pgid)

Let the process pid join the process group pgid. See POSIX.1 and the setsid(2) manual page on your POSIX system for more informations on process groups and job control. Returns TRUE on success, FALSE otherwise.

后退 | 起点 | 前进
posix_setgid | 上一级 | posix_setsid


posix_setsid

(PHP 3>= 3.0.13, PHP 4 )

posix_setsid -- Make the current process a session leader

Description

int posix_setsid ( void)

Make the current process a session leader. See POSIX.1 and the setsid(2) manual page on your POSIX system for more informations on process groups and job control. Returns the session id.

后退 | 起点 | 前进
posix_setpgid | 上一级 | posix_setuid


posix_setuid

(PHP 3>= 3.0.13, PHP 4 )

posix_setuid -- Set the UID of the current process

Description

bool posix_setuid ( int uid)

Set the real user ID of the current process. This is a privileged function and you need appropriate privileges (usually root) on your system to be able to perform this function.

Returns TRUE on success, FALSE otherwise. See also posix_setgid().

后退 | 起点 | 前进
posix_setsid | 上一级 | posix_times


posix_times

(PHP 3>= 3.0.13, PHP 4 )

posix_times -- Get process times

Description

array posix_times ( void)

Returns a hash of strings with information about the current process CPU usage. The indices of the hash are

  • ticks - the number of clock ticks that have elapsed since reboot.

  • utime - user time used by the current process.

  • stime - system time used by the current process.

  • cutime - user time used by current process and children.

  • cstime - system time used by current process and children.

后退 | 起点 | 前进
posix_setuid | 上一级 | posix_ttyname


posix_ttyname

(PHP 3>= 3.0.13, PHP 4 )

posix_ttyname -- Determine terminal device name

Description

string posix_ttyname ( int fd)

Needs to be written.

后退 | 起点 | 前进
posix_times | 上一级 | posix_uname


posix_uname

(PHP 3>= 3.0.10, PHP 4 )

posix_uname -- Get system name

Description

array posix_uname ( void)

Returns a hash of strings with information about the system. The indices of the hash are

  • sysname - operating system name (e.g. Linux)

  • nodename - system name (e.g. valiant)

  • release - operating system release (e.g. 2.2.10)

  • version - operating system version (e.g. #4 Tue Jul 20 17:01:36 MEST 1999)

  • machine - system architecture (e.g. i586)

  • domainname - DNS domainname (e.g. php.net)

domainname is a GNU extension and not part of POSIX.1, so this field is only available on GNU systems or when using the GNU libc.

Posix requires that you must not make any assumptions about the format of the values, e.g. you cannot rely on three digit version numbers or anything else returned by this function.

后退 | 起点 | 前进
posix_ttyname | 上一级 | PostgreSQL 数据库函数库


PostgreSQL 数据库函数库

PHP 手册
后退 前进

LXXX. PostgreSQL 数据库函数库

介绍

PostgreSQL 是一个开放源码的免费数据库系统。Postgres 最初由加州大学伯克利分校计算机科学系开发，倡导了很多关系对象的观念，这些观念现在已经用在一些商业数据库系统中。它提供了 SQL92/SQL99 语言支持，事务集成以及类型扩展。PostgreSQL 则是 Postgres 的一个开放代码的后代。

需求

要使用 PostgreSQL 支持，需要 PostgreSQL 6.5 或更新版本，PostgreSQL 7.0 或更新版本来使用所有的 PostgreSQL 模块。PostgreSQL支持多种字符编码包括多字节字符编码。关于 PostgreSQL 的当前版本以及更多信息见：http://www.postgresql.org/。

安装

为添加 PostgreSQL 支持，在编译 PHP 时需要 --with-pgsql[=DIR] 选项。如果可以用共享模块方式，PostgreSQL 模块可以在 php.ini 用 extension 指令或者 dl() 函数加载。

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. PostgreSQL 配置选项

名称 | 默认值 | 可变范围
pgsql.allow_persistent | "1" | PHP_INI_SYSTEM
pgsql.max_persistent | "-1" | PHP_INI_SYSTEM
pgsql.max_links | "-1" | PHP_INI_SYSTEM
pgsql.auto_reset_persistent | "0" | PHP_INI_SYSTEM
pgsql.ignore_notice | "0" | PHP_INI_ALL
pgsql.log_notice | "0" | PHP_INI_ALL
PHP_INI_* 常量的更多细节和定义参见 ini_set()。

下面是配置指令的简短说明。

pgsql.allow_persistent boolean

是否允许持久的 Postgres 连接。

pgsql.max_persistent integer

每个进程所能有的持久 Postgres 连接数目。

pgsql.max_links integer

每个进程所能有的 Postgres 连接数目，包括持久连接。

使用方法及提示

警告

由于 notice message handling 代码中的 bug，不推荐在 PHP 4.0.6 中使用 PostgreSQL 模块。使用 4.1.0 或更新版本。

警告

为符合当前编码标准，PostgreSQL 函数名称将在 4.2.0 版本中改变。大多数新名称将多出一个下划线，例如 pg_lo_open()。一部分函数则改变了名称以保持一致性。例如 pg_exec() 改为 pg_query()。老的函数名依然可以在 4.2.0 和以后的少数几个版本中使用，但以后可能会删除。

表格 2. 已改变的函数名

旧名称 | 新名称
pg_exec() | pg_query()
pg_getlastoid() | pg_last_oid()
pg_cmdtuples() | pg_affected_rows()
pg_numrows() | pg_num_rows()
pg_numfields() | pg_num_fields()
pg_fieldname() | pg_field_name()
pg_fieldsize() | pg_field_size()
pg_fieldnum() | pg_field_num()
pg_fieldprtlen() | pg_field_prtlen()
pg_fieldisnull() | pg_field_is_null()
pg_freeresult() | pg_free_result()
pg_result() | pg_fetch_result()
pg_loreadall() | pg_lo_read_all()
pg_locreate() | pg_lo_create()
pg_lounlink() | pg_lo_unlink()
pg_loopen() | pg_lo_open()
pg_loclose() | pg_lo_close()
pg_loread() | pg_lo_read()
pg_lowrite() | pg_lo_write()
pg_loimport() | pg_lo_import()
pg_loexport() | pg_lo_export()

为以后支持异步连接，将不再提倡用旧语法使用函数 pg_connect()/pg_pconnect()。请用连接字符串作为参数来使用函数 pg_connect() 和 pg_pconnect()。

不是所有的版本都支持所有的函数，这和 libpq 的版本和编译方法有关。如果编译源代码时少了一个函数，那么 libpq 就不支持需要该函数的功能。

用比 PostgreSQL 服务器所接受的连接更新的 libpq 版本也很重要。如果你用的 libpq 版本比 PostgreSQL 服务器预期的低就可能出现问题。

PostgreSQL 在 6.3 (03/02/1998) 版之后默认使用 unix domain sockets，默认状态下不会打开 TCP 端口。下面这张表说明了各种新建连接的可能性。TCP/IP socket 放在 /tmp/.s.PGSQL.5432。该选项可用 postmaster 中的 '-i' 参数打开，它表示“监视 TCP/IP 端口以及 Unix domain socket”。

表格 3. Postmaster 和 PHP

Postmaster | PHP | 状态
postmaster & | pg_connect("dbname=MyDbName"); | OK
postmaster -i & | pg_connect("dbname=MyDbName"); | OK
postmaster & | pg_connect("host=localhost dbname=MyDbName"); | Unable to connect to PostgreSQL server: connectDB() failed: Is the postmaster running and accepting TCP/IP (with -i) connection at 'localhost' on port '5432'? in /path/to/file.php on line 20.
postmaster -i & | pg_connect("host=localhost dbname=MyDbName"); | OK

到 PostgreSQL 服务器的连接可以通过以下命令串中的参数对建立：$conn = pg_connect("host=myHost port=myPort tty=myTTY options=myOptions dbname=myDB user=myUser password=myPassword");

以前的语法： $conn = pg_connect ("host", "port", "options", "tty", "dbname") 已经不再提倡使用。

环境变量会影响 PostgreSQL 服务器／客户机的行为。例如如果连接串中省略了主机名，PostgreSQL 模块将会查找环境变量 PGHOST。 不同版本所支持的环境变量不同，详情参考 PostgreSQL Programmers's Manual (libpq - Environment Variables)。

确认已经给适当的用户设置了环境变量。用 $_ENV 或 getenv() 来检查当前进程可以使用哪些环境变量。

例子 1. 设定默认参数

PGHOST=pgsql.example.com
PGPORT=7890
PGDATABASE=web-system
PGUSER=web-user
PGPASSWORD=secret
PGDATESTYLE=ISO
PGTZ=JST
PGCLIENTENCODING=EUC-JP

export PGHOST PGPORT PGDATABASE PGUSER PGPASSWORD PGDATESTYLE PGTZ PGCLIENTENCODING

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

PGSQL_ASSOC (integer)

PGSQL_NUM (integer)

PGSQL_BOTH (integer)

PGSQL_CONNECTION_BAD (integer)

PGSQL_CONNECTION_OK (integer)

PGSQL_SEEK_SET (integer)

PGSQL_SEEK_CUR (integer)

PGSQL_SEEK_END (integer)

PGSQL_ESCAPE_STRING (integer)

PGSQL_ESCAPE_BYTEA (integer)

PGSQL_EMPTY_QUERY (integer)

PGSQL_COMMAND_OK (integer)

PGSQL_TUPLES_OK (integer)

PGSQL_COPY_OUT (integer)

PGSQL_COPY_IN (integer)

PGSQL_BAD_RESPONSE (integer)

PGSQL_NONFATAL_ERROR (integer)

PGSQL_FATAL_ERROR (integer)

范例

从 PostgreSQL 7.1.0 开始，在一个 text 类型字段中最多可以储存 1GB 的数据。在老版本中则限制为一个块的大小（默认 8KB，最大 32KB，编译时指定）。

要使用 large object (lo) 接口，需要把 large object 函数放在一个事务段中。事务段以 SQL 语句 BEGIN 开始，如果该事务合法，以 COMMIT 或者 END结束，如果该事务失败，则以 ROLLBACK 或者 ABORT结束。

例子 2. 使用 Large Object

<?php
    $database = pg_connect ("dbname=jacarta");
    pg_query ($database, "begin");
    $oid = pg_lo_create ($database);
    echo "$oid\n";
    $handle = pg_lo_open ($database, $oid, "w");
    echo "$handle\n";
    pg_lo_write ($handle, "large object data");
    pg_lo_close ($handle);
    pg_query ($database, "commit");
?>
在关闭 large object 之前不应关闭到 PostgreSQL 服务器的连接。

目录
pg_affected_rows — 返回受影响的记录数目
pg_cancel_query — 取消异步查询
pg_client_encoding — 取得客户端编码方式
pg_close — 关闭一个 PostgreSQL 连接
pg_connect — 打开一个 PostgreSQL 连接
pg_connection_busy — 获知连接是否为忙
pg_connection_reset — 重置连接（再次连接）
pg_connection_status — 获得连接状态
pg_convert — 将关联的数组值转换为适合 SQL 语句的格式。
pg_copy_from — 根据数组将记录插入表中
pg_copy_to — 将一个表拷贝到数组中
pg_dbname — 获得数据库名
pg_delete — 删除记录
pg_end_copy — 与 PostgreSQL 后端同步
pg_escape_bytea — 转义 bytea 类型的二进制数据
pg_escape_string — 转义 text/char 类型的字符串
pg_fetch_array — 提取一行作为数组
pg_fetch_object — 提取一行作为对象
pg_fetch_result — 从结果资源中返回值
pg_fetch_row — 提取一行作为枚举数组
pg_field_is_null — 测试字段是否为 NULL
pg_field_name — 返回字段的名字
pg_field_num — 返回字段的编号
pg_field_prtlen — 返回打印出来的长度
pg_field_size — 返回指定字段占用内部存储空间的大小
pg_field_type — 返回相应字段的类型名称
pg_free_result — 释放查询结果占用的内存
pg_get_result — 取得异步查询结果
pg_host — 返回和某连接关联的主机名
pg_insert — 将数组插入到表中
pg_last_error — 得到某连接的最后一条错误信息
pg_last_notice — 返回 PostgreSQL 服务器最新一条公告信息
pg_last_oid — 返回上一个对象的 oid
pg_lo_close — 关闭一个大型对象
pg_lo_create — 新建一个大型对象
pg_lo_export — 将大型对象导出到文件
pg_lo_import — 将文件导入为大型对象
pg_lo_open — 打开一个大型对象
pg_lo_read_all — 读入整个大型对象并直接发送给浏览器
pg_lo_read — 从大型对象中读入数据
pg_lo_seek — 移动大型对象中的指针
pg_lo_tell — 返回大型对象的当前指针位置
pg_lo_unlink — 删除一个大型对象
pg_lo_write — 向大型对象写入数据
pg_metadata — 获得表的元数据
pg_num_fields — 返回字段的数目
pg_num_rows — 返回行的数目
pg_options — 获得和连接有关的选项
pg_pconnect — 打开一个持久的 PostgreSQL 连接
pg_port — 返回该连接的端口号
pg_put_line — 向 PostgreSQL 后端发送以 NULL 结尾的字符串
pg_query — 执行查询
pg_result_error — 获得查询结果的错误信息
pg_result_status — 获得查询结果的状态
pg_select — 选择记录
pg_send_query — 发送异步查询
pg_set_client_encoding — 设定客户端编码
pg_trace — 启动一个 PostgreSQL 连接的追踪功能
pg_tty — 返回该连接的 tty 号
pg_untrace — 关闭 PostgreSQL 连接的追踪功能
pg_update — 更新表

后退 | 起点 | 前进
posix_uname | 上一级 | pg_affected_rows


pg_affected_rows

(PHP 4 >= 4.2.0)

pg_affected_rows -- 返回受影响的记录数目

描述

int pg_affected_rows ( resource result)

pg_affected_rows() 返回在 pg_query() 中执行 INSERT，UPDATE 和 DELETE 查询后受到影响的记录数目（包括实例／记录／行）。如果本函数没有影响到任何记录，则返回 0。

例子 1. pg_affected_rows()

<?php
     $result = pg_query ($conn, "INSERT INTO publisher VALUES ('Author')");
     $cmdtuples = pg_affected_rows ($result);
     echo $cmdtuples . " tuples are affected.";
?>

注: 本函数以前被称为 pg_cmdtuples()。

参见 pg_query() 和 pg_num_rows()。

后退 | 起点 | 前进
PostgreSQL 数据库函数库 | 上一级 | pg_cancel_query


pg_cancel_query

(PHP 4 >= 4.2.0)

pg_cancel_query -- 取消异步查询

描述

bool pg_cancel_query ( resource connection)

pg_cancel_query() 取消由 pg_send_query() 发送的异步查询。不能取消由 pg_query() 执行的查询。

参见 pg_send_query() 和 pg_connection_busy()。

后退 | 起点 | 前进
pg_affected_rows | 上一级 | pg_client_encoding


pg_client_encoding

(PHP 3 CVS only, PHP 4 >= 4.0.3)

pg_client_encoding -- 取得客户端编码方式

Description

string pg_client_encoding ( [resource connection])

pg_client_encoding() 以字符串形式返回客户端编码。所返回的字符串为以下之一：SQL_ASCII，EUC_JP，EUC_CN，EUC_KR，EUC_TW，UNICODE，MULE_INTERNAL，LATINX (X=1...9)，KOI8，WIN，ALT，SJIS，BIG5，WIN1250。

注: 本函数需要 PHP-4.0.3 或以上版本以及 PostgreSQL-7.0 或以上版本。如果在编译 libpq 时没有加入多字节编码支持，则 pg_set_client_encoding() 总是返回 "SQL_ASCII"。所支持的编码方式取决于 PostgreSQL 的版本。详情参见 PostgreSQL 手册如何加入多字节支持以及所支持的编码方式。

本函数以前被称为 pg_clientencoding()。

参见 pg_set_client_encoding()。

后退 | 起点 | 前进
pg_cancel_query | 上一级 | pg_close


pg_close

(PHP 3, PHP 4 )

pg_close -- 关闭一个 PostgreSQL 连接

描述

bool pg_close ( resource connection)

pg_close() 关闭由所给资源 connection 指定的到 PostgreSQL 数据库的非持久连接。如果成功则返回 TRUE，失败则返回 FALSE。

注: 使用 pg_close() 并不很必要，因为非持久连接在本脚本执行结束后会自动关闭。

如果在此连接中打开了 large object 资源，则在关闭所有 large object 资源之前不要关闭连接。

后退 | 起点 | 前进
pg_client_encoding | 上一级 | pg_connect


pg_connect

(PHP 3, PHP 4 )

pg_connect -- 打开一个 PostgreSQL 连接

Description

resource pg_connect ( string connection_string)

pg_connect() 返回其它 PostgreSQL 函数所需要的资源。

pg_connect() 打开一个由 connection_string 所指定的 PostgreSQL 数据库的连接。如果成功则返回连接资源，如果不能连接则返回 FALSE。connection_string 应该是用引号引起来的字符串。

例子 1. 使用 pg_connect

<?php
$dbconn = pg_connect ("dbname=mary");
//connect to a database named "mary"
$dbconn2 = pg_connect ("host=localhost port=5432 dbname=mary");
// connect to a database named "mary" on "localhost" at port "5432"
$dbconn3 = pg_connect ("host=sheep port=5432 dbname=mary user=lamb password=foo");
//connect to a database named "mary" on the host "sheep" with a username and password
$conn_string = "host=sheep port=5432 dbname=test user=lamb password=bar";
$dbconn4 = pg_connect ($conn_string);
//connect to a database named "test" on the host "sheep" with a username and password
?>
connection_string 所包括的参数有 host，port，tty, options，dbname, user 和 password。

如果用同样的 connection_string 再次调用 pg_connect()，不会建立新连接，而是返回前面已经打开的连接资源。如果使用不同的连接字符串，则可以和同一个数据库建立多个连接。

旧的多参数语法 $conn = pg_connect ("host", "port", "options", "tty", "dbname") 已经不提倡使用。

参见 pg_pconnect()，pg_close()，pg_host()，pg_port(), pg_tty()，pg_options() and pg_dbname()。

后退 | 起点 | 前进
pg_close | 上一级 | pg_connection_busy


pg_connection_busy

(PHP 4 >= 4.2.0)

pg_connection_busy -- 获知连接是否为忙

Description

bool pg_connection_busy ( resource connection)

pg_connection_busy() 在此连接状态为忙的时候返回 TRUE。如果连接状态为忙，说明前一个查询仍然在执行。如果调用 pg_get_result() 函数的话，则会被锁死。

参见 pg_connection_status() 和 pg_get_result()。

后退 | 起点 | 前进
pg_connect | 上一级 | pg_connection_reset


pg_connection_reset

(PHP 4 >= 4.2.0)

pg_connection_reset -- 重置连接（再次连接）

描述

bool pg_connection_reset ( resource connection)

pg_connection_reset() 重置一个连接，用于错误恢复。如果成功则返回 TRUE，失败则返回 FALSE。

参见 pg_connect()，pg_pconnect() 和 pg_connection_status()。

后退 | 起点 | 前进
pg_connection_busy | 上一级 | pg_connection_status


pg_connection_status

(PHP 4 >= 4.2.0)

pg_connection_status -- 获得连接状态

描述

int pg_connection_status ( resource connection)

pg_connection_status() 返回一个连接的状态。可能的状态为 PGSQL_CONNECTION_OK 和 PGSQL_CONNECTION_BAD。

参见 pg_connection_busy()。

后退 | 起点 | 前进
pg_connection_reset | 上一级 | pg_convert


pg_convert

(PHP 4 CVS only)

pg_convert -- 将关联的数组值转换为适合 SQL 语句的格式。

描述

array pg_convert ( resource connection, string table_name, array assoc_array [, int options])

pg_convert() 检查并转换 assoc_array 为适合 SQL 语句的格式。

注: 本函数是试验性质的。

参见 pg_metadata()。

后退 | 起点 | 前进
pg_connection_status | 上一级 | pg_copy_from


pg_copy_from

(PHP 4 >= 4.2.0)

pg_copy_from -- 根据数组将记录插入表中

描述

int pg_copy_from ( int connection, string table_name, array rows [, string delimiter [, string null_as]])

pg_copy_from() 将数组 rows 的内容作为记录插入表中。它在内部使用了 COPY 命令来插入记录。如果成功则返回 TRUE，失败则返回 FALSE。

参见 pg_copy_to()。

后退 | 起点 | 前进
pg_convert | 上一级 | pg_copy_to


pg_copy_to

(PHP 4 >= 4.2.0)

pg_copy_to -- 将一个表拷贝到数组中

描述

int pg_copy_to ( int connection, string table_name [, string delimiter [, string null_as]])

pg_copy_to() 将一个表拷贝到数组中，该数组作为结果返回。如果失败则返回 FALSE。

参见 pg_copy_from()。

后退 | 起点 | 前进
pg_copy_from | 上一级 | pg_dbname


pg_dbname

(PHP 3, PHP 4 )

pg_dbname -- 获得数据库名

描述

string pg_dbname ( resource connection)

pg_dbname() 返回给定 PostgreSQL connection 资源的数据库名称。如果 connection 不是有效的 PostgreSQL 连接资源则返回 FALSE。

后退 | 起点 | 前进
pg_copy_to | 上一级 | pg_delete


pg_delete

(PHP 4 CVS only)

pg_delete -- 删除记录

描述

long pg_delete ( resource connection, string table_name, array assoc_array [, int options])

pg_delete() 删除符合条件的记录，条件在 assoc_array 中以 field=>value 格式给出。如果指定了 option，则 pg_convert() 按照该选项作用于 assoc_array 之上。

例子 1. pg_delete

<?php
    $db = pg_connect ('dbname=foo');
    // This is safe, since $_POST is converted automatically
    $res = pg_delete($db, 'post_log', $_POST);
    if ($res) {
        echo "POST data is deleted: $res\n";
    }
    else {
        echo "User must have sent wrong inputs\n";
    }
?>

注: 本函数为试验性质。

参见 pg_convert()。

后退 | 起点 | 前进
pg_dbname | 上一级 | pg_end_copy


pg_end_copy

(PHP 4 >= 4.0.3)

pg_end_copy -- 与 PostgreSQL 后端同步

描述

bool pg_end_copy ( [resource connection])

pg_end_copy() 在处理完 pg_put_line() 所执行的拷贝操作之后将 PostgreSQL 前端（通常为 web server 进程）与 PostgreSQL 服务器进行同步。pg_end_copy() 必须被调用，否则 PostgreSQL 服务器可能会和前端失去同步并报错。如果成功则返回 TRUE，失败则返回 FALSE。

更多细节和例子参见 pg_put_line()。

后退 | 起点 | 前进
pg_delete | 上一级 | pg_escape_bytea


pg_escape_bytea

(PHP 4 >= 4.2.0)

pg_escape_bytea -- 转义 bytea 类型的二进制数据

Description

string pg_escape_bytea ( string data)

pg_escape_bytea() 转义 bytea 数据类型的二进制字符串，返回转义后的字符串。

注: 当对 bytea 类型字段进行 SELECT 操作时，PostgreSQL 返回前导 \ 的八进制字节值（例如 \032）。用户需要自己将结果转换为二进制格式。

本函数需要 PostgreSQL 7.2 或以上版本。在 PostgreSQL 7.2.0 和 7.2.1 版中，如果使用了多字节支持，bytea 类型必须被强制转换。例如 INSERT INTO test_table (image) VALUES ('$image_escaped'::bytea);。PostgreSQL 7.2.2 或以上版本不需要强制转换。异常情况是当客户端和后端字符编码不匹配时，可能会有多字节流错误。用户必须强制转换 bytea 以避免此错误。

新版的 PostgreSQL 将支持未转义的函数。到时就会加入内置的未转义函数支持。

参见 pg_escape_string()。

后退 | 起点 | 前进
pg_end_copy | 上一级 | pg_escape_string


pg_escape_string

(PHP 4 >= 4.2.0)

pg_escape_string -- 转义 text/char 类型的字符串

描述

string pg_escape_string ( string data)

pg_escape_string() 转义 text/char 数据类型的字符串，返回转义后的字符串。建议用此函数替代 addslashes()。

注: 本函数需要 PostgreSQL 7.2 或以上版本。

参见 pg_escape_bytea()。

后退 | 起点 | 前进
pg_escape_bytea | 上一级 | pg_fetch_array


pg_fetch_array

(PHP 3>= 3.0.1, PHP 4 )

pg_fetch_array -- 提取一行作为数组

描述

array pg_fetch_array ( resource result [, int row [, int result_type]])

pg_fetch_array() 返回一个与所提取的行（tuples/records）相一致的数组。如果如果没有更多行可供提取，则返回 FALSE。

pg_fetch_array() 是 pg_fetch_row() 的扩展版本。在返回的数组中不仅以数字索引方式存放数据（字段编号），默认情况下还用字段名做索引存放数据（字段名）。

row 是想要取得的行（记录）的编号。第一行为 0。

result_type 是可选参数，控制着怎样初始化返回值。result_type 是一个常量，可以有以下取值：PGSQL_ASSOC，PGSQL_NUM 和 PGSQL_BOTH。取值为 PGSQL_ASSOC 时 pg_fetch_array() 返回用字段名作为键值索引的关联数组，取值为 PGSQL_NUM 时用字段编号作为键值，取值为 PGSQL_BOTH 时则同时用两者作为键值。默认值是 PGSQL_BOTH。

注: result_type 是在 PHP 4.0 中才加入的参数。

pg_fetch_array() 并不明显比使用 pg_fetch_row() 慢，而且在使用中提供了更大的方便。

参见 pg_fetch_row() 和 pg_fetch_object() 以及 pg_fetch_result()。

例子 1. PostgreSQL fetch array

<?php
$conn = pg_pconnect ("dbname=publisher");
if (!$conn) {
    echo "An error occured.\n";
    exit;
}

$result = pg_query ($conn, "SELECT * FROM authors");
if (!$result) {
    echo "An error occured.\n";
    exit;
}

$arr = pg_fetch_array ($result, 0, PGSQL_NUM);
echo $arr[0] . " <- array\n";

$arr = pg_fetch_array ($result, 1, PGSQL_ASSOC);
echo $arr["author"] . " <- array\n";
?>

注: 从 4.1.0 开始，row 成为可选参数。每次调用 pg_fetch_array()，内部的行计数器都会加一。

后退 | 起点 | 前进
pg_escape_string | 上一级 | pg_fetch_object


pg_fetch_object

(PHP 3>= 3.0.1, PHP 4 )

pg_fetch_object -- 提取一行作为对象

描述

object pg_fetch_object ( resource result, int row [, int result_type])

pg_fetch_object() 返回与所提取行的属性相一致的一个对象。如果出错或者没有更多行可供提取时则返回 FALSE。

pg_fetch_object() 和 pg_fetch_array() 相似，只有一点区别 － 返回一个对象而不是数组。间接的，这意味着只能通过字段名来访问数据而不能通过偏移量来访问（数字是非法的属性名）。

row 是想要取得的行（记录）的编号。第一行为 0。

除了速度之外，本函数和 pg_fetch_array() 完全一样，而且几乎和 pg_fetch_row() 一样快（速度上的差别很小）。

注: 从 4.3.0 开始，result_type 默认值为 PGSQL_ASSOC，而旧版本的默认值是 PGSQL_BOTH。数字属性在这里没有用处，因为在 PHP 中对象的属性不能是数字。

result_type 参数在以后的版本中可能会删除。

参见 pg_query()，pg_fetch_array()，pg_fetch_row() 和 pg_fetch_result()。

例子 1. Postgres fetch object

<?php
$database = "verlag";
$db_conn = pg_connect ("host=localhost port=5432 dbname=$database");
if (!$db_conn): ?>
    <H1>Failed connecting to postgres database <?php echo $database ?></H1> <?php
    exit;
endif;

$qu = pg_query ($db_conn, "SELECT * FROM verlag ORDER BY autor");
$row = 0; // postgres needs a row counter other dbs might not

while ($data = pg_fetch_object ($qu, $row)) {
    echo $data->autor." (";
    echo $data->jahr ."): ";
    echo $data->titel."<BR>";
    $row++;
}
?>
<PRE>
<?php
$fields[] = Array ("autor", "Author");
$fields[] = Array ("jahr",  "  Year");
$fields[] = Array ("titel", " Title");

$row= 0; // postgres needs a row counter other dbs might not
while ($data = pg_fetch_object ($qu, $row)) {
    echo "----------\n";
    reset ($fields);
    while (list (,$item) = each ($fields)):
        echo $item[1].": ".$data->$item[0]."\n";
    endwhile;
    $row++;
}
echo "----------\n";
?>
</PRE>
<?php
pg_free_result ($qu);
pg_close ($db_conn);
?>

注: 从 4.1.0 开始，row 成为可选参数。每次调用 pg_fetch_object()，内部的行计数器都会加一。

后退 | 起点 | 前进
pg_fetch_array | 上一级 | pg_fetch_result


pg_fetch_result

(PHP 4 >= 4.2.0)

pg_fetch_result -- 从结果资源中返回值

描述

mixed pg_fetch_result ( resource result, int row, mixed field)

pg_fetch_result() 根据由 pg_query() 返回的 result 资源返回相应的值。row 为整型数。field 为字段名（字符串）或字段索引（整数）。row 和 field 指明了查询结果中的哪个单元被返回。行编号从 0 开始。除了用字段名之外，还可以用不带引号的数字作为字段索引。字段索引从 0 开始。

PostgreSQL 有很多内置的类型，这里只直接支持基本类型。所有形式的 integer，boolean 和 void 类型都被返回为 integer 值。所有形式的 float 和 real 类型都被返回为 float 值。Boolean 类型被返回为 "t" 或者 "f"。所有其它类型包括数组都被返回为字符串，该字符串的格式和默认的 PostgreSQL 风格一样，可以在 psql 程序中看到。

后退 | 起点 | 前进
pg_fetch_object | 上一级 | pg_fetch_row


pg_fetch_row

(PHP 3>= 3.0.1, PHP 4 )

pg_fetch_row -- 提取一行作为枚举数组

描述

array pg_fetch_row ( resource result, int row)

pg_fetch_row() 根据指定的 result 资源提取一行数据（记录）作为数组返回。每个得到的列依次存放在数组中，从偏移量 0 开始。

返回的数组和提取的行相一致。如果没有更多行可提取，则返回 FALSE。

参见 pg_query()，pg_fetch_array()，pg_fetch_object() 和 pg_fetch_result()。

例子 1. Postgres fetch row

<?php
$conn = pg_pconnect ("dbname=publisher");
if (!$conn) {
    echo "An error occured.\n";
    exit;
}

$result = pg_query ($conn, "SELECT * FROM authors");
if (!$result) {
    echo "An error occured.\n";
    exit;
}

$num = pg_num_rows($result);

for ($i=0; $i < $num; $i++) {
  $r = pg_fetch_row($result, $i);

  for ($j=0; $j < count($r); $j++) {
    echo "$r[$j]&nbsp;";
  }

  echo "<BR>";

}

?>

注: 从 4.1.0 开始，row 成为可选参数。每次调用 pg_fetch_row()，内部的行计数器都会加一。

后退 | 起点 | 前进
pg_fetch_result | 上一级 | pg_field_is_null


pg_field_is_null

(PHP 4 >= 4.2.0)

pg_field_is_null -- 测试字段是否为 NULL

描述

int pg_field_is_null ( resource result, int row, mixed field)

pg_field_is_null() 测试字段是否为 NULL。如果字段在给出的行中为 NULL 则返回 1，如果字段在给出的行中不是 NULL 则返回 0。字段可以以列的索引号（数字）方式给出，也可以以字段名（字符串）方式给出。行的编号从 0 开始。

注: 本函数以前的名字为 pg_fieldisnull()。

后退 | 起点 | 前进
pg_fetch_row | 上一级 | pg_field_name


pg_field_name

(PHP 4 >= 4.2.0)

pg_field_name -- 返回字段的名字

Description

string pg_field_name ( resource result, int field_number)

pg_field_name() 返回给定 PostgreSQL result 资源中的 field_number 所代表的字段名。字段编号从 0 开始。

注: 本函数以前的名字为 pg_fieldname()。

参见 pg_field_num()。

后退 | 起点 | 前进
pg_field_is_null | 上一级 | pg_field_num


pg_field_num

(PHP 4 >= 4.2.0)

pg_field_num -- 返回字段的编号

Description

int pg_field_num ( resource result, string field_name)

pg_field_num() 返回给定 PostgreSQL result 资源中的 field_name 所代表的列（字段）的编号。字段编号从 0 开始。如果出错本函数返回 -1。

注: 本函数以前的名字为 pg_fieldnum()。

参见 pg_field_name()。

后退 | 起点 | 前进
pg_field_name | 上一级 | pg_field_prtlen


pg_field_prtlen

(PHP 4 >= 4.2.0)

pg_field_prtlen -- 返回打印出来的长度

描述

int pg_field_prtlen ( resource result, int row_number, string field_name)

pg_field_prtlen() 返回 PostgreSQL result 中得到的值实际上打印出来的长度（字符数）。行编号从 0 开始。如果出错本函数返回 -1。

注: 本函数以前的名字为 pg_field_prtlen()。

参见 pg_field_size()。

后退 | 起点 | 前进
pg_field_num | 上一级 | pg_field_size


pg_field_size

(PHP 4 >= 4.2.0)

pg_field_size -- 返回指定字段占用内部存储空间的大小

Description

int pg_field_size ( resource result, int field_number)

pg_field_size() 返回 PostgreSQL result 中指定字段占用内部存储空间的大小（字节数）。字段编号从 0 开始。字段大小为 -1 表示可变长度字段。如果出错本函数返回 FALSE。

注: 本函数以前的名字为 pg_fieldsize()。

参见 pg_field_prtlen() 和 pg_field_type()。

后退 | 起点 | 前进
pg_field_prtlen | 上一级 | pg_field_type


pg_field_type

(PHP 4 >= 4.2.0)

pg_field_type -- 返回相应字段的类型名称

描述

string pg_field_type ( resource result, int field_number)

pg_field_type() 以字符串返回 PostgreSQL result 资源中指定 field_number 字段的类型。字段编号从 0 开始。

注: 本函数以前的名字为 pg_fieldtype()。

参见 pg_field_len() 和 pg_field_name()。

后退 | 起点 | 前进
pg_field_size | 上一级 | pg_free_result


pg_free_result

(PHP 4 >= 4.2.0)

pg_free_result -- 释放查询结果占用的内存

描述

bool pg_free_result ( resource result)

pg_free_result() 仅在当你担心脚本执行时占用了过多内存时调用。脚本执行完毕后所有的查询结果占用的内存都会被自动释放。不过如果你确认在脚本中不会再用到查询结果了，你可以用 result 作为参数调用 pg_free_result() 来释放有关的内存。如果成功则返回 TRUE，失败则返回 FALSE。

注: 本函数以前的名字为 pg_freeresult()。

参见 pg_query()。

后退 | 起点 | 前进
pg_field_type | 上一级 | pg_get_result


pg_get_result

(PHP 4 >= 4.2.0)

pg_get_result -- 取得异步查询结果

描述

resource pg_get_result ( [resource connection])

pg_get_result() 取得执行 pg_send_query() 而得到的查询结果资源。pg_send_query() 可以向 PostgreSQL 发送多个查询， pg_get_result() 则用来逐个得到查询结果。返回值为查询结果资源号。如果没有更多查询结果，则返回 FALSE。

后退 | 起点 | 前进
pg_free_result | 上一级 | pg_host


pg_host

(PHP 3, PHP 4 )

pg_host -- 返回和某连接关联的主机名

描述

string pg_host ( resource connection)

pg_host() 返回指定的 PostgreSQL connection 资源号所连接到的主机名称。

参见 pg_connect() 和 pg_pconnect()。

后退 | 起点 | 前进
pg_get_result | 上一级 | pg_insert


pg_insert

(PHP 4 CVS only)

pg_insert -- 将数组插入到表中

描述

bool pg_insert ( resource connection, string table_name, array assoc_array [, int options])

pg_insert() 将具有 field=>value 结构的数组 assoc_array 插入到由 table_name 指定的表中。如果给出了参数 options ，则函数 pg_convert() 会按照给定选项被作用到 assoc_array 上。

例子 1. pg_insert

<?php
    $db = pg_connect ('dbname=foo');
    // This is safe, since $_POST is converted automatically
    $res = pg_insert($db, 'post_log', $_POST);
    if ($res) {
        echo "POST data is succesfully logged\n";
    }
    else {
        echo "User must have sent wrong inputs\n";
    }
?>

注: 本函数为试验性质。

参见 pg_convert()。

后退 | 起点 | 前进
pg_host | 上一级 | pg_last_error


pg_last_error

(PHP 4 >= 4.2.0)

pg_last_error -- 得到某连接的最后一条错误信息

描述

string pg_last_error ( [resource connection])

pg_last_error() 返回指定连接 connection 的最后一条错误信息。

错误信息可能会被 PostgreSQL(libpq) 的内部函数调用所覆盖。如果 PostgreSQL 的内部模块函数产生了多个错误，则可能不能返回适当的错误信息。

使用 pg_result_error()，pg_result_status() 和 pg_connection_status() 来取得更好的错误处理。

注: 本函数以前的名字为 pg_errormessage()。

参见 pg_result_error()。

后退 | 起点 | 前进
pg_insert | 上一级 | pg_last_notice


pg_last_notice

(PHP 4 >= 4.0.6)

pg_last_notice -- 返回 PostgreSQL 服务器最新一条公告信息

描述

string pg_last_notice ( resource connection)

pg_last_notice() 返回由 connection 指定的 PostgreSQL 服务器最新的一条公告信息。PostgreSQL 服务器在某些情况下会发送公告信息，例如如果不能继续进行某事务时。有了 pg_last_notice()，只要检查公告是否和该事务有关，就可以避免提交无用的查询。

警告

本函数为试验性质，并且还没有完全实现。pg_last_notice() 是 PHP 4.0.6 新增的，但是 PHP 4.0.6 本身在公告信息处理上有问题。即使不使用 pg_last_notice() 函数，也不推荐在 PHP 4.0.6 中使用 PostgreSQL 模块。

本函数在 PHP 4.3.0 中完全实现。低于 PHP 4.3.0 的版本中都忽略了数据库连接参数。

在 PHP 4.3.0 中可以通过在 php.ini 中把 pgsql.ignore_notice 置为 1 来使公告信息追踪成为可选项。

在 PHP 4.3.0 中可以通过在 php.ini 中把 pgsql.log_notice 置为 0 来使公告信息日志成为可选项。除非 pgsql.ignore_notice 为 0，否则公告信息不能被日志记录。

参见 pg_query() 和 pg_last_error()。

后退 | 起点 | 前进
pg_last_error | 上一级 | pg_last_oid


pg_last_oid

(PHP 4 >= 4.2.0)

pg_last_oid -- 返回上一个对象的 oid

描述

int pg_last_oid ( resource result)

pg_last_oid() 在上一条通过 pg_query() 发送的命令是 SQL INSERT 的情况下用来取得分配给所插入记录的 oid。如果存在有效的 oid 则返回一个正整数，如果出错或者上一条通过 pg_query() 发送的命令不是 INSERT 或者该 INSERT 失败则返回 FALSE。

从 PostgreSQL 7.2 版开始 OID 字段成为可选项。如果一个表中没有定义 OID 字段，程序员必须用 pg_result_status() 函数来检查记录是否被成功插入。

注: 本函数以前的名字为 pg_getlastoid()。

参见 pg_query() 和 pg_result_status()。

后退 | 起点 | 前进
pg_last_notice | 上一级 | pg_lo_close


pg_lo_close

(PHP 4 >= 4.2.0)

pg_lo_close -- 关闭一个大型对象

描述

bool pg_lo_close ( resource large_object)

pg_lo_close() 关闭一个大型对象。参数 large_object 是 pg_lo_open() 函数所返回的资源号。

要使用大型对象（lo）接口，需要将其放置在事务块中。

注: 本函数以前的名字为 pg_loclose()。

参见 pg_lo_open()，pg_lo_create() 和 pg_lo_import()。

后退 | 起点 | 前进
pg_last_oid | 上一级 | pg_lo_create


pg_lo_create

(PHP 4 >= 4.2.0)

pg_lo_create -- 新建一个大型对象

描述

int pg_lo_create ( resource connection)

pg_lo_create() 新建一个大型对象并返回该大型对象的 oid。connection 指定了由 pg_connect() 或 pg_pconnect() 打开的有效的数据库连接号。不支持 PostgreSQL 访问模式 INV_READ，INV_WRITE 和 INV_ARCHIVE，该对象总是以读写方式访问。INV_ARCHIVE 已经从 PostgreSQL 中删除了（6.3 及以上版本）。本函数返回大型对象的 oid，如果出错则返回 FALSE。

要使用大型对象（lo）接口，需要将其放置在事务块中。

注: 本函数以前的名字为 pg_locreate()。

后退 | 起点 | 前进
pg_lo_close | 上一级 | pg_lo_export


pg_lo_export

(PHP 4 >= 4.2.0)

pg_lo_export -- 将大型对象导出到文件

描述

bool pg_lo_export ( int oid, string pathname [, resource connection])

oid 参数指定了要导出的大型对象的 oid，pathname 参数则指明了文件名。如果成功则返回 TRUE，失败则返回 FALSE。

要使用大型对象（lo）接口，需要将其放置在事务块中。

注: 本函数以前的名字为 pg_loexport()。

参见 pg_lo_import()。

后退 | 起点 | 前进
pg_lo_create | 上一级 | pg_lo_import


pg_lo_import

(PHP 4 >= 4.2.0)

pg_lo_import -- 将文件导入为大型对象

描述

int pg_lo_import ( [resource connection, string pathname])

在 PHP 4.2.0 版本之前，本函数语法不一样，见如下定义：

int pg_lo_import ( string pathname [, resource connection])

pathname 变量指明了要导入为大型对象的文件名。导入成功则返回新建的大型对象的 oid，如果出错则返回 FALSE。

要使用大型对象（lo）接口，需要将其放置在事务块中。

注: 当 安全模式（safe mode） 被激活，PHP 将检查您将要操作的文件或者目录与正在执行的脚本是否有相同的 UID。

注: 本函数以前的名字为 pg_loimport()。

参见 pg_lo_export() 和 pg_lo_open()。

后退 | 起点 | 前进
pg_lo_export | 上一级 | pg_lo_open


pg_lo_open

(PHP 4 >= 4.2.0)

pg_lo_open -- 打开一个大型对象

描述

resource pg_lo_open ( resource connection, int oid, string mode)

pg_lo_open() 打开一个大型对象并返回大型对象资源号。该资源号内封装了连接号。oid 指定了有效的大型对象的 oid，mode 可以为 "r"，"w" 或者 "rw"。如果失败则返回 FALSE。

警告

在关闭大型对象资源之前不要关闭数据库连接。

要使用大型对象（lo）接口，需要将其放置在事务块中。

注: 本函数以前的名字为 pg_loopen()。

参见 pg_lo_close() 和 pg_lo_create()。

后退 | 起点 | 前进
pg_lo_import | 上一级 | pg_lo_read_all


pg_lo_read_all

(PHP 4 >= 4.2.0)

pg_lo_read_all -- 读入整个大型对象并直接发送给浏览器

描述

int pg_lo_read_all ( resource large_object)

pg_lo_read_all() 读入一个大型对象并在（PHP）发送完所有待发的 header 之后将其直接发送给浏览器。主要目的是发送图片或声音等二进制数据。返回值为读入的字节数，如果出错则返回 FALSE。

要使用大型对象（lo）接口，需要将其放置在事务块中。

注: 本函数以前的名字为 pg_loreadall()。

参见 pg_lo_read()。

后退 | 起点 | 前进
pg_lo_open | 上一级 | pg_lo_read


pg_lo_read

(PHP 4 >= 4.2.0)

pg_lo_read -- 从大型对象中读入数据

描述

string pg_lo_read ( resource large_object, int len)

pg_lo_read() 从大型对象中读入最多 len 字节的数据并以字符串返回。large_object 指定了有效的大型对象的资源号，len 则指定了大型对象的段所允许的最大长度。如果出错则返回 FALSE。

要使用大型对象（lo）接口，需要将其放置在事务块中。

注: 本函数以前的名字为 pg_loread()。

参见 pg_lo_read_all()。

后退 | 起点 | 前进
pg_lo_read_all | 上一级 | pg_lo_seek


pg_lo_seek

(PHP 4 >= 4.2.0)

pg_lo_seek -- 移动大型对象中的指针

描述

bool pg_lo_seek ( resource large_object, int offset [, int whence])

pg_lo_seek() 在大型对象资源中移动指针位置。whence 参数为 PGSQL_SEEK_SET，PGSQL_SEEK_CUR 或 PGSQL_SEEK_END。

参见 pg_lo_tell()。

后退 | 起点 | 前进
pg_lo_read | 上一级 | pg_lo_tell


pg_lo_tell

(PHP 4 >= 4.2.0)

pg_lo_tell -- 返回大型对象的当前指针位置

描述

int pg_lo_tell ( resource large_object)

pg_lo_tell() 返回当前指针位置（大型对象中从头开始的偏移量）。

参见 pg_lo_seek()。

后退 | 起点 | 前进
pg_lo_seek | 上一级 | pg_lo_unlink


pg_lo_unlink

(PHP 4 >= 4.2.0)

pg_lo_unlink -- 删除一个大型对象

描述

bool pg_lo_unlink ( resource connection, int oid)

pg_lo_unlink() 删除由 oid 指定的大型对象。如果成功则返回 TRUE，失败则返回 FALSE。

要使用大型对象（lo）接口，需要将其放置在事务块中。

注: 本函数以前的名字为 pg_lo_unlink()。

参见 pg_lo_create() 和 pg_lo_import()。

后退 | 起点 | 前进
pg_lo_tell | 上一级 | pg_lo_write


pg_lo_write

(PHP 4 >= 4.2.0)

pg_lo_write -- 向大型对象写入数据

描述

int pg_lo_write ( resource large_object, string data)

pg_lo_write() 把 data 参数中的数据尽可能多地写入大型对象并返回实际写入的字节数。如果出错则返回 FALSE。large_object 参数是 pg_lo_open() 函数所返回的大型对象资源号。

要使用大型对象（lo）接口，需要将其放置在事务块中。

注: 本函数以前的名字为 pg_lo_write()。

参见 pg_lo_create() 和 pg_lo_open()。

后退 | 起点 | 前进
pg_lo_unlink | 上一级 | pg_metadata


pg_metadata

(PHP 4 CVS only)

pg_metadata -- 获得表的元数据

描述

array pg_metadata ( resource connection, string table_name)

pg_metadata() 以数组形式返回 table_name 表的定义。如果出错则返回 FALSE。

注: 本函数为试验性质。

参见 pg_convert()。

后退 | 起点 | 前进
pg_lo_write | 上一级 | pg_num_fields


pg_num_fields

(PHP 4 >= 4.2.0)

pg_num_fields -- 返回字段的数目

描述

int pg_num_fields ( resource result)

pg_num_fields() 返回 PostgreSQL result 中的字段（列）数目。参数是由 pg_query() 函数返回的查询结果资源号。如果出错则返回 -1。

注: 本函数以前的名字为 pg_numfields()。

参见 pg_num_rows() 和 pg_affected_rows()。

后退 | 起点 | 前进
pg_metadata | 上一级 | pg_num_rows


pg_num_rows

(PHP 4 >= 4.2.0)

pg_num_rows -- 返回行的数目

描述

int pg_num_rows ( resource result)

pg_num_rows() 返回 PostgreSQL result 中的行的数目。result 参数是由 pg_query() 函数返回的查询结果资源号。如果出错则返回 -1。

注: 用 pg_affected_rows() 函数获得被 INSERT，UPDATE 和 DELETE 命令影响到的行的数目。

注: 本函数以前的名字为 pg_numrows()。

参见 pg_num_fields() 和 pg_affected_rows()。

后退 | 起点 | 前进
pg_num_fields | 上一级 | pg_options


pg_options

(PHP 3, PHP 4 )

pg_options -- 获得和连接有关的选项

描述

string pg_options ( resource connection)

pg_options() 以字符串形式返回指定 PostgreSQL connection 资源的连接选项。

后退 | 起点 | 前进
pg_num_rows | 上一级 | pg_pconnect


pg_pconnect

(PHP 3, PHP 4 )

pg_pconnect -- 打开一个持久的 PostgreSQL 连接

描述

int pg_pconnect ( string connection_string)

pg_pconnect() 打开一个到 PostgreSQL 数据库的持久连接。返回其它 PostgreSQL 函数所需要的连接资源号。

connection_string 参数的定义见 pg_connect()。

要打开持久连接功能，php.ini 中的 pgsql.allow_persistent 参数必须为 "On"（也是默认值）。 最大持久连接数目由 php.ini 中的 pgsql.max_persistent 参数定义（默认为 -1 表示没有限制）。所有连接的数目可由 php.ini 中的 pgsql.max_links 参数设置。

pg_close() 不能关闭由 pg_pconnect() 打开的持久连接。

参见 pg_connect()。

后退 | 起点 | 前进
pg_options | 上一级 | pg_port


pg_port

(PHP 3, PHP 4 )

pg_port -- 返回该连接的端口号

描述

int pg_port ( resource connection)

pg_port() 返回给定的 PostgreSQL connection 资源所连接的端口号。

后退 | 起点 | 前进
pg_pconnect | 上一级 | pg_put_line


pg_put_line

(PHP 4 >= 4.0.3)

pg_put_line -- 向 PostgreSQL 后端发送以 NULL 结尾的字符串

描述

bool pg_put_line ( [resource connection, string data])

pg_put_line() 向 PostgreSQL 后端服务器发送以 NULL 结尾的字符串。例如可以通过 PostgreSQL 的 copy 操作来向表中高速插入数据。结尾的 NULL 字符会自动加入。如果成功则返回 TRUE，失败则返回 FALSE。

注: 应用程序必须明确地在最后一行发送两个字符 "\." 来向后端指明发送数据结束。

参见 pg_end_copy().

例子 1. 向表中高速插入数据

<?php
    $conn = pg_pconnect ("dbname=foo");
    pg_query($conn, "create table bar (a int4, b char(16), d float8)");
    pg_query($conn, "copy bar from stdin");
    pg_put_line($conn, "3\thello world\t4.5\n");
    pg_put_line($conn, "4\tgoodbye world\t7.11\n");
    pg_put_line($conn, "\\.\n");
    pg_end_copy($conn);
?>

后退 | 起点 | 前进
pg_port | 上一级 | pg_query


pg_query

(PHP 4 >= 4.2.0)

pg_query -- 执行查询

描述

resource pg_query ( resource connection, string query)

pg_query() 在查询可以执行时返回查询结果资源号。如果查询失败或者提供的连接号无效则返回 FALSE。如果连接号有效，则可以用 pg_last_error() 函数来提取详细的错误信息。pg_last_error() 发送一条 SQL 语句到 connection 资源指定的 PostgreSQL 数据库。connection 必须是由 pg_connect() 或 pg_pconnect() 返回的合法连接号。本函数返回值是一个其它 PostgreSQL 函数例如 pg_fetch_array() 可以用来访问查询结果的查询结果资源号。

注: connection 是 pg_query() 中的可选参数。如果没有指定 connection，则使用默认连接。默认连接是 pg_connect() 或 pg_pconnect() 所打开的最后一个连接。

尽管 connection 参数可以省略，但不推荐这样做。因为这样可能会导致很难发现脚本中的错误。

注: 本函数以前的名字为 pg_exec()。pg_exec() 函数为了兼容性的原因仍然可以使用，但是鼓励用户使用新的名字。

参见 pg_connect()，pg_pconnect()，pg_fetch_array()，pg_fetch_object()，pg_num_rows() 和 pg_affected_rows()。

后退 | 起点 | 前进
pg_put_line | 上一级 | pg_result_error


pg_result_error

(PHP 4 >= 4.2.0)

pg_result_error -- 获得查询结果的错误信息

描述

string pg_result_error ( resource result)

pg_result_error() 返回和 result 资源关联的错误信息。因此用户更有机会可以得到比 pg_last_error() 更好的错误信息。

参见 pg_query()，pg_send_query()，pg_get_result()，pg_last_error() 和 pg_last_notice()。

后退 | 起点 | 前进
pg_query | 上一级 | pg_result_status


pg_result_status

(PHP 4 >= 4.2.0)

pg_result_status -- 获得查询结果的状态

描述

int pg_result_status ( resource result)

pg_result_status() 返回该查询结果资源的状态。可能的返回值有 PGSQL_EMPTY_QUERY，PGSQL_COMMAND_OK，PGSQL_TUPLES_OK，PGSQL_COPY_TO，PGSQL_COPY_FROM，PGSQL_BAD_RESPONSE，PGSQL_NONFATAL_ERROR 和 PGSQL_FATAL_ERROR。

参见 pg_connection_status()。

后退 | 起点 | 前进
pg_result_error | 上一级 | pg_select


pg_select

(PHP 4 CVS only)

pg_select -- 选择记录

描述

array pg_select ( resource connection, string table_name, array assoc_array [, int options])

pg_select() 根据 assoc_array 数组中的 field=>value 值来选择记录。成功的查询返回和 assoc_array 指定的条件相匹配的包括记录和字段的数组。如果指定了 options，pg_convert() 会按照指定选项作用于 assoc_array 之上。

例子 1. pg_select

<?php
    $db = pg_connect ('dbname=foo');
    // This is safe, since $_POST is converted automatically
    $rec = pg_select($db, 'post_log', $_POST);
    if ($rec) {
        echo "Records selected\n";
        var_dump($rec);
    }
    else {
        echo "User must have sent wrong inputs\n";
    }
?>

注: 本函数为试验性质。

参见 pg_convert()。

后退 | 起点 | 前进
pg_result_status | 上一级 | pg_send_query


pg_send_query

(PHP 4 >= 4.2.0)

pg_send_query -- 发送异步查询

描述

bool pg_send_query ( resource connection, string query)

bool pg_send_query ( string query)

pg_send_query() 向 connection 连接发送异步查询。和 pg_query() 不同，它可以向 PostgreSQL 发送多个查询并用 pg_get_result() 依次得到结果。当执行查询时脚本的执行不会被锁定。用 pg_connection_busy() 来检查连接连接是否为忙（例如查询正在执行中）。调用 pg_cancel_query() 则有可能取消查询。

尽管用户可以一次发送多个查询，但用户不能通过正忙的连接发送多个查询。如果向正忙的连接发送了查询，则会等待上一条查询结束并丢弃所有结果。

参见 pg_query()，pg_cancel_query()，pg_get_result() 和 pg_connection_busy()。

后退 | 起点 | 前进
pg_select | 上一级 | pg_set_client_encoding


pg_set_client_encoding

(PHP 3 CVS only, PHP 4 >= 4.0.3)

pg_set_client_encoding -- 设定客户端编码

描述

int pg_set_client_encoding ( [resource connection, string encoding])

pg_set_client_encoding() 设定客户端编码方式，成功返回 0，出错返回 -1。

encoding 是客户端的编码方式，可以为：SQL_ASCII，EUC_JP，EUC_CN，EUC_KR，EUC_TW，UNICODE，MULE_INTERNAL，LATINX (X=1...9)，KOI8，WIN，ALT，SJIS，BIG5，WIN1250。可用的编码取决于 PostgreSQL 和 libpq 的版本。参考 PostgreSQL 手册查看你的 PostgreSQL 所支持的编码方式。

注: 本函数需要 PHP 4.0.3 或以上版本以及 PostgreSQL 7.0 或以上版本。所支持的编码方式取决于 PostgreSQL 的版本，详情参考 PostgreSQL 手册。

本函数以前的名字为 pg_setclientencoding()。

参见 pg_client_encoding()。

后退 | 起点 | 前进
pg_send_query | 上一级 | pg_trace


pg_trace

(PHP 4 >= 4.0.1)

pg_trace -- 启动一个 PostgreSQL 连接的追踪功能

描述

bool pg_trace ( string pathname [, string mode [, resource connection]])

pg_trace() 启动 PostgreSQL 前端／后端通讯的追踪并记录到 pathname 指定的文件中。要完全理解结果，用户需要熟悉 PostgreSQL 通讯协议的本质。对不熟悉的用户来说，追踪发送到服务器的查询错误依然有用，例如可以用 grep '^To backend' trace.log 来查看哪些查询实际上被发送到了 PostgreSQL 服务器。更多信息参考 PostgreSQL 手册。

参数 pathname 和 mode 和 fopen()(mode 默认为 'w') 中的一样。connection 指定了要追踪的连接，默认为上一个打开的连接。

如果 pathname 可以作为日志文件打开，则返回 TRUE，否则返回 FALSE。

参见 fopen() 和 pg_untrace()。

后退 | 起点 | 前进
pg_set_client_encoding | 上一级 | pg_tty


pg_tty

(PHP 3, PHP 4 )

pg_tty -- 返回该连接的 tty 号

描述

string pg_tty ( resource connection)

pg_tty() 返回指定 PostgreSQL connection 资源在服务器端输出调试信息的 tty 号。

后退 | 起点 | 前进
pg_trace | 上一级 | pg_untrace


pg_untrace

(PHP 4 >= 4.0.1)

pg_untrace -- 关闭 PostgreSQL 连接的追踪功能

描述

bool pg_untrace ( [resource connection])

停止由 pg_trace() 启动的追踪功能。connection 指定了被追踪的连接号，默认为上一个打开的连接。

本函数总是返回 TRUE。

参见 pg_trace()。

后退 | 起点 | 前进
pg_tty | 上一级 | pg_update


pg_update

(PHP 4 CVS only)

pg_update -- 更新表

描述

long pg_update ( resource connection, string table_name, array condition, array data [, int options])

pg_update() 用 condition 作为条件查询数据库，用 data 中的数据更新符合条件的记录。如果指定了 options，则 pg_convert() 会按照指定选项作用到 data 上。

例子 1. pg_update

<?php
    $db = pg_connect ('dbname=foo');
    $data = array('field1'=>'AA', 'field2'=>'BB');
    // This is safe, since $_POST is converted automatically
    $res = pg_update($db, 'post_log', $_POST, $data);
    if ($res) {
        echo "Data is updated: $res\n";
    }
    else {
        echo "User must have sent wrong inputs\n";
    }
?>

注: 本函数为试验性质。

参见 pg_convert()。

后退 | 起点 | 前进
pg_untrace | 上一级 | Process Control Functions


Process Control Functions

PHP 手册
后退 前进

LXXXI. Process Control Functions

介绍

Process Control support in PHP implements the Unix style of process creation, program execution, signal handling and process termination. Process Control should not be enabled within a webserver environment and unexpected results may happen if any Process Control functions are used within a webserver environment.

This documentation is intended to explain the general usage of each of the Process Control functions. For detailed information about Unix process control you are encouraged to consult your systems documentation including fork(2), waitpid(2) and signal(2) or a comprehensive reference such as Advanced Programming in the UNIX Environment by W. Richard Stevens (Addison-Wesley).

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

Process Control support in PHP is not enabled by default. You will need to use the --enable-pcntl configuration option when compiling PHP to enable Process Control support.

注: Currently, this module will not function on non-Unix platforms (Windows).

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

The following list of signals are supported by the Process Control functions. Please see your systems signal(7) man page for details of the default behavior of these signals.

WNOHANG (integer)

WUNTRACED (integer)

SIG_IGN (integer)

SIG_DFL (integer)

SIG_ERR (integer)

SIGHUP (integer)

SIGINT (integer)

SIGQUIT (integer)

SIGILL (integer)

SIGTRAP (integer)

SIGABRT (integer)

SIGIOT (integer)

SIGBUS (integer)

SIGFPE (integer)

SIGKILL (integer)

SIGUSR1 (integer)

SIGSEGV (integer)

SIGUSR2 (integer)

SIGPIPE (integer)

SIGALRM (integer)

SIGTERM (integer)

SIGSTKFLT (integer)

SIGCLD (integer)

SIGCHLD (integer)

SIGCONT (integer)

SIGSTOP (integer)

SIGTSTP (integer)

SIGTTIN (integer)

SIGTTOU (integer)

SIGURG (integer)

SIGXCPU (integer)

SIGXFSZ (integer)

SIGVTALRM (integer)

SIGPROF (integer)

SIGWINCH (integer)

SIGPOLL (integer)

SIGIO (integer)

SIGPWR (integer)

SIGSYS (integer)

SIGBABY (integer)

范例

This example forks off a daemon process with a signal handler.

例子 1. Process Control Example

<?php

$pid = pcntl_fork();
if ($pid == -1) {
     die("could not fork");
} else if ($pid) {
     exit(); // we are the parent
} else {
     // we are the child
}

// detatch from the controlling terminal
if (!posix_setsid()) {
    die("could not detach from terminal");
}

// setup signal handlers
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");

// loop forever performing tasks
while(1) {

    // do something interesting here

}

function sig_handler($signo) {

     switch($signo) {
         case SIGTERM:
             // handle shutdown tasks
             exit;
             break;
         case SIGHUP:
             // handle restart tasks
             break;
         default:
             // handle all other signals
     }

}

?>

相关参考

A look at the section about POSIX functions may be useful.

目录
pcntl_exec — Executes specified program in current process space
pcntl_fork — Forks the currently running process
pcntl_signal — Installs a signal handler
pcntl_waitpid — Waits on or returns the status of a forked child
pcntl_wexitstatus — Returns the return code of a terminated child
pcntl_wifexited — Returns TRUE if status code represents a successful exit
pcntl_wifsignaled — Returns TRUE if status code represents a termination due to a signal
pcntl_wifstopped — Returns TRUE if child process is currently stopped
pcntl_wstopsig — Returns the signal which caused the child to stop
pcntl_wtermsig — Returns the signal which caused the child to terminate

后退 | 起点 | 前进
pg_update | 上一级 | pcntl_exec


pcntl_exec

(PHP 4 >= 4.2.0)

pcntl_exec -- Executes specified program in current process space

Description

bool pcntl_exec ( string path [, array args [, array envs]])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
Process Control Functions | 上一级 | pcntl_fork


pcntl_fork

(PHP 4 >= 4.1.0)

pcntl_fork -- Forks the currently running process

Description

int pcntl_fork ( void)

The pcntl_fork() function creates a child process that differs from the parent process only in it's PID and PPID. Please see your system's fork(2) man page for specific details as to how fork works on your system.

On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of execution. On failure, a -1 will be returned in the parent's context, no child process will be created, and a PHP error is raised.

例子 1. pcntl_fork() Example

<?php

$pid = pcntl_fork();
if ($pid == -1) {
     die("could not fork");
} else if ($pid) {
     // we are the parent
} else {
     // we are the child
}

?>

See also pcntl_waitpid() and pcntl_signal().

后退 | 起点 | 前进
pcntl_exec | 上一级 | pcntl_signal


pcntl_signal

(PHP 4 >= 4.1.0)

pcntl_signal -- Installs a signal handler

Description

bool pcntl_signal ( int signo, mixed handle)

The pcntl_signal() function installs a new signal handler for the signal indicated by signo. The signal handler is set to handler which may be the name of a user created function, or either of the two global constants SIG_IGN or SIG_DFL.

pcntl_signal() returns TRUE on success or FALSE on failure.

例子 1. pcntl_signal() Example

<?php

// signal handler function
function sig_handler($signo) {

     switch($signo) {
         case SIGTERM:
             // handle shutdown tasks
             exit;
             break;
         case SIGHUP:
             // handle restart tasks
             break;
         case SIGUSR1:
             print "Caught SIGUSR1...\n";
             break;
         default:
             // handle all other signals
     }

}

print "Installing signal handler...\n";

// setup signal handlers
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");
pcntl_signal(SIGUSR1, "sig_handler");

print "Generating signal SIGTERM to self...\n";

// send SIGUSR1 to current process id
posix_kill(posix_getpid(), SIGUSR1);

print "Done\n"

?>

See also pcntl_fork() and pcntl_waitpid().

后退 | 起点 | 前进
pcntl_fork | 上一级 | pcntl_waitpid


pcntl_waitpid

(PHP 4 >= 4.1.0)

pcntl_waitpid -- Waits on or returns the status of a forked child

Description

int pcntl_waitpid ( int pid, int status, int options)

The pcntl_waitpid() function suspends execution of the current process until a child as specified by the pid argument has exited, or until a signal is delivered whose action is to terminate the current process or to call a signal handling function. If a child as requested by pid has already exited by the time of the call (a so-called "zombie" process), the function returns immediately. Any system resources used by the child are freed. Please see your system's waitpid(2) man page for specific details as to how waitpid works on your system.

pcntl_waitpid() returns the process ID of the child which exited, -1 on error or zero if WNOHANG was used and no child was available

The value of pid can be one of the following:

表格 1. possible values for pid

< -1 | wait for any child process whose process group ID is equal to the absolute value of pid.
-1 | wait for any child process; this is the same behaviour that the wait function exhibits.
0 | wait for any child process whose process group ID is equal to that of the calling process.
> 0 | wait for the child whose process ID is equal to the value of pid.

pcntl_waitpid() will store status information
in the status parameter which can be
evaluated using the following functions:
pcntl_wifexited(),
pcntl_wifstopped(),
pcntl_wifsignaled(),
pcntl_wexitstatus(),
pcntl_wtermsig() and
pcntl_wstopsig().

The value of options is the value of zero or more of the following two global constants OR'ed together:

表格 2. possible values for options

WNOHANG | return immediately if no child has exited.
WUNTRACED | return for children which are stopped, and whose status has not been reported.

See also pcntl_fork(),
pcntl_signal(),
pcntl_wifexited(),
pcntl_wifstopped(),
pcntl_wifsignaled(),
pcntl_wexitstatus(),
pcntl_wtermsig() and
pcntl_wstopsig().

后退 | 起点 | 前进
pcntl_signal | 上一级 | pcntl_wexitstatus


pcntl_wexitstatus

(PHP 4 >= 4.1.0)

pcntl_wexitstatus -- Returns the return code of a terminated child

Description

int pcntl_wexitstatus ( int status)

Returns the return code of a terminated child. This function is only useful if pcntl_wifexited() returned TRUE.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid() and pcntl_wifexited().

后退 | 起点 | 前进
pcntl_waitpid | 上一级 | pcntl_wifexited


pcntl_wifexited

(PHP 4 >= 4.1.0)

pcntl_wifexited -- Returns TRUE if status code represents a successful exit

Description

int pcntl_wifexited ( int status)

Returns TRUE if the child status code represents a successful exit.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid() and pcntl_wexitstatus().

后退 | 起点 | 前进
pcntl_wexitstatus | 上一级 | pcntl_wifsignaled


pcntl_wifsignaled

(PHP 4 >= 4.1.0)

pcntl_wifsignaled -- Returns TRUE if status code represents a termination due to a signal

Description

int pcntl_wifsignaled ( int status)

Returns TRUE if the child process exited because of a signal which was not caught.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid() and pcntl_signal().

后退 | 起点 | 前进
pcntl_wifexited | 上一级 | pcntl_wifstopped


pcntl_wifstopped

(PHP 4 >= 4.1.0)

pcntl_wifstopped -- Returns TRUE if child process is currently stopped

Description

int pcntl_wifstopped ( int status)

Returns TRUE if the child process which caused the return is currently stopped; this is only possible if the call to pcntl_waitpid() was done using the option WUNTRACED.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid().

后退 | 起点 | 前进
pcntl_wifsignaled | 上一级 | pcntl_wstopsig


pcntl_wstopsig

(PHP 4 >= 4.1.0)

pcntl_wstopsig -- Returns the signal which caused the child to stop

Description

int pcntl_wstopsig ( int status)

Returns the number of the signal which caused the child to stop. This function is only useful if pcntl_wifstopped() returned TRUE.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid() and pcntl_wifstopped().

后退 | 起点 | 前进
pcntl_wifstopped | 上一级 | pcntl_wtermsig


pcntl_wtermsig

(PHP 4 >= 4.1.0)

pcntl_wtermsig -- Returns the signal which caused the child to terminate

Description

int pcntl_wtermsig ( int status)

Returns the number of the signal that caused the child process to terminate. This function is only useful if pcntl_wifsignaled() returned TRUE.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid(),
pcntl_signal() and
pcntl_wifsignaled().

后退 | 起点 | 前进
pcntl_wstopsig | 上一级 | Program Execution functions


Program Execution functions

PHP 手册
后退 前进

LXXXII. Program Execution functions

介绍

Those functions provides means to executes commands on the system itself, and means secure such commands.

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

这些函数作为 PHP 核心的一部分，无需被安装即可使用。

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

相关参考

Those functions are also closely related to the backtick operator.

目录
escapeshellarg — escape a string to be used as a shell argument
escapeshellcmd — escape shell metacharacters
exec — Execute an external program
passthru — Execute an external program and display raw output
proc_close — Close a process opened by proc_open and return the exit code of that process.
proc_open — Execute a command and open file pointers for input/output
shell_exec — Execute command via shell and return complete output as string
system — Execute an external program and display output

后退 | 起点 | 前进
pcntl_wtermsig | 上一级 | escapeshellarg


escapeshellarg

(PHP 4 >= 4.0.3)

escapeshellarg -- escape a string to be used as a shell argument

Description

string escapeshellarg ( string arg)

escapeshellarg() adds single quotes around a string and quotes/escapes any existing single quotes allowing you to pass a string directly to a shell function and having it be treated as a single safe argument. This function should be used to escape individual arguments to shell functions coming from user input. The shell functions include exec(), system() and the backtick operator. A standard use would be:

system("ls ".escapeshellarg($dir));

See also exec(), popen(), system(), and the backtick operator.

后退 | 起点 | 前进
Program Execution functions | 上一级 | escapeshellcmd


escapeshellcmd

(PHP 3, PHP 4 )

escapeshellcmd -- escape shell metacharacters

Description

string escapeshellcmd ( string command)

escapeshellcmd() escapes any characters in a string that might be used to trick a shell command into executing arbitrary commands. This function should be used to make sure that any data coming from user input is escaped before this data is passed to the exec() or system() functions, or to the backtick operator. A standard use would be:

$e = escapeshellcmd($userinput);
system("echo $e"); // here we don't care if $e has spaces
$f = escapeshellcmd($filename);
system("touch \"/tmp/$f\"; ls -l \"/tmp/$f\""); // and here we do, so we use quotes

See also escapeshellarg(), exec(), popen(), system(), and the backtick operator.

后退 | 起点 | 前进
escapeshellarg | 上一级 | exec


exec

(PHP 3, PHP 4 )

exec -- Execute an external program

Description

string exec ( string command [, array output [, int return_var]])

exec() executes the given command, however it does not output anything. It simply returns the last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

If the array argument is present, then the specified array will be filled with every line of output from the command. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec().

If the return_var argument is present along with the array argument, then the return status of the executed command will be written to this variable.

警告

If you are going to allow data coming from user input to be passed to this function, then you should be using escapeshellarg() or escapeshellcmd() to make sure that users cannot trick the system into executing arbitrary commands.

注: If you start a program using this function and want to leave it running in the background, you have to make sure that the output of that program is redirected to a file or some other output stream or else PHP will hang until the execution of the program ends.

See also system(),
passthru(), popen(),
escapeshellcmd(), and the backtick operator.

后退 | 起点 | 前进
escapeshellcmd | 上一级 | passthru


passthru

(PHP 3, PHP 4 )

passthru -- Execute an external program and display raw output

Description

void passthru ( string command [, int return_var])

The passthru() function is similar to the exec() function in that it executes a command. If the return_var argument is present, the return status of the Unix command will be placed here. This function should be used in place of exec() or system() when the output from the Unix command is binary data which needs to be passed directly back to the browser. A common use for this is to execute something like the pbmplus utilities that can output an image stream directly. By setting the Content-type to image/gif and then calling a pbmplus program to output a gif, you can create PHP scripts that output images directly.

警告

If you are going to allow data coming from user input to be passed to this function, then you should be using escapeshellarg() or escapeshellcmd() to make sure that users cannot trick the system into executing arbitrary commands.

注: If you start a program using this function and want to leave it running in the background, you have to make sure that the output of that program is redirected to a file or some other output stream or else PHP will hang until the execution of the program ends.

See also exec(), system(), popen(), escapeshellcmd(), and the backtick operator.

后退 | 起点 | 前进
exec | 上一级 | proc_close


proc_close

(PHP 4 CVS only)

proc_close -- Close a process opened by proc_open and return the exit code of that process.

Description

int proc_close ( resource process)

proc_close() is similar to pclose() except that it only works on processes opened by proc_open(). proc_close() waits for the process to terminate, and returns it's exit code. If you have open pipes to that process, you should fclose() them prior to calling this function in order to avoid a deadlock - the child process may not be able to exit while the pipes are open.

后退 | 起点 | 前进
passthru | 上一级 | proc_open


proc_open

(PHP 4 CVS only)

proc_open -- Execute a command and open file pointers for input/output

Description

resource proc_open ( string cmd, array descriptorspec, array pipes)

proc_open() is similar to popen() but provides a much greater degree of control over the program execution. cmd is the command to be executed by the shell. descriptorspec is an indexed array where the key represents the descriptor number and the value represents how PHP will pass that descriptor to the child process. pipes will be set to an indexed array of file pointers that correspond to PHP's end of any pipes that are created. The return value is a resource representing the process; you should free it using proc_close() when you are finished with it.

$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
   2 => array("file", "/tmp/error-output.txt", "a"), // stderr is a file to write to
);
$process = proc_open("php", $descriptorspec, $pipes);
if (is_resource($process)) {
    // $pipes now looks like this:
    // 0 => writeable handle connected to child stdin
    // 1 => readable handle connected to child stdout
    // Any error output will be appended to /tmp/error-output.txt

    fwrite($pipes[0], "<?php echo \"Hello World!\"; ?>");
    fclose($pipes[0]);

    while(!feof($pipes[1])) {
        echo fgets($pipes[1], 1024);
    }
    fclose($pipes[1]);
    // It is important that you close any pipes before calling
    // proc_close in order to avoid a deadlock
    $return_value = proc_close($process);

    echo "command returned $return_value\n";
}

The file descriptor numbers in descriptorspec are not limited to 0, 1 and 2 - you may specify any valid file descriptor number and it will be passed to the child process. This allows your script to interoperate with other scripts that run as "co-processes". In particular, this is useful for passing passphrases to programs like PGP, GPG and openssl in a more secure manner. It is also useful for reading status information provided by those programs on auxillary file descriptors.

注: Windows compatibility: Descriptors beyond 2 (stderr) are made available to the child process as inheritable handles, but since the Windows architecture does not associate file descriptor numbers with low-level handles, the child process does not (yet) have a means of accessing those handles. Stdin, stdout and stderr work as expected.

注: This function was introduced in PHP 4.3.0.

注: If you only need a uni-directional (one-way) process pipe, use popen() instead, as it is much easier to use.

See also exec(), system(),
passthru(), popen(),
escapeshellcmd(), and the backtick operator.

后退 | 起点 | 前进
proc_close | 上一级 | shell_exec


shell_exec

(PHP 4 )

shell_exec -- Execute command via shell and return complete output as string

Description

string shell_exec ( string cmd)

This function is identical to the backtick operator.

后退 | 起点 | 前进
proc_open | 上一级 | system


system

(PHP 3, PHP 4 )

system -- Execute an external program and display output

Description

string system ( string command [, int return_var])

system() is just like the C version of the function in that it executes the given command and outputs the result. If a variable is provided as the second argument, then the return status code of the executed command will be written to this variable.

警告

If you are going to allow data coming from user input to be passed to this function, then you should be using escapeshellarg() or escapeshellcmd() to make sure that users cannot trick the system into executing arbitrary commands.

注: If you start a program using this function and want to leave it running in the background, you have to make sure that the output of that program is redirected to a file or some other output stream or else PHP will hang until the execution of the program ends.

The system() call also tries to automatically flush the web server's output buffer after each line of output if PHP is running as a server module.

Returns the last line of the command output on success, and FALSE on failure.

If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

See also exec(),
passthru(), popen(),
escapeshellcmd(), and the backtick operator.

后退 | 起点 | 前进
shell_exec | 上一级 | Printer functions


Printer functions

PHP 手册
后退 前进

LXXXIII. Printer functions

介绍

These functions are only available under Windows 9.x, ME, NT4 and 2000. They have been added in PHP 4 (4.0.4).

安装

Add the line extension=php_printer.dll to your php.ini file.

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. Printer configuration options

Name | Default | Changeable
printer.default_printer | "" | PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

目录
printer_abort — Deletes the printer's spool file
printer_close — Close an open printer connection
printer_create_brush — Create a new brush
printer_create_dc — Create a new device context
printer_create_font — Create a new font
printer_create_pen — Create a new pen
printer_delete_brush — Delete a brush
printer_delete_dc — Delete a device context
printer_delete_font — Delete a font
printer_delete_pen — Delete a pen
printer_draw_bmp — Draw a bmp
printer_draw_chord — Draw a chord
printer_draw_elipse — Draw an ellipse
printer_draw_line — Draw a line
printer_draw_pie — Draw a pie
printer_draw_rectangle — Draw a rectangle
printer_draw_roundrect — Draw a rectangle with rounded corners
printer_draw_text — Draw text
printer_end_doc — Close document
printer_end_page — Close active page
printer_get_option — Retrieve printer configuration data
printer_list — Return an array of printers attached to the server
printer_logical_fontheight — Get logical font height
printer_open — Open connection to a printer
printer_select_brush — Select a brush
printer_select_font — Select a font
printer_select_pen — Select a pen
printer_set_option — Configure the printer connection
printer_start_doc — Start a new document
printer_start_page — Start a new page
printer_write — Write data to the printer

后退 | 起点 | 前进
system | 上一级 | printer_abort


printer_abort

(no version information, might be only in CVS)

printer_abort -- Deletes the printer's spool file

Description

void printer_abort ( resource handle)

This function deletes the printers spool file.

handle must be a valid handle to a printer.

例子 1. printer_abort() example

$handle = printer_open();
printer_abort($handle);
printer_close($handle);

后退 | 起点 | 前进
Printer functions | 上一级 | printer_close


printer_close

(no version information, might be only in CVS)

printer_close -- Close an open printer connection

Description

void printer_close ( resource handle)

This function closes the printer connection. printer_close() also closes the active device context.

handle must be a valid handle to a printer.

例子 1. printer_close() example

$handle = printer_open();
printer_close($handle);

后退 | 起点 | 前进
printer_abort | 上一级 | printer_create_brush


printer_create_brush

(no version information, might be only in CVS)

printer_create_brush -- Create a new brush

Description

mixed printer_create_brush ( int style, string color)

The function creates a new brush and returns a handle to it. A brush is used to fill shapes. For an example see printer_select_brush(). color must be a color in RGB hex format, i.e. "000000" for black, style must be one of the following constants:

  • PRINTER_BRUSH_SOLID: creates a brush with a solid color.

  • PRINTER_BRUSH_DIAGONAL: creates a brush with a 45-degree upward left-to-right hatch ( / ).

  • PRINTER_BRUSH_CROSS: creates a brush with a cross hatch ( + ).

  • PRINTER_BRUSH_DIAGCROSS: creates a brush with a 45 cross hatch ( x ).

  • PRINTER_BRUSH_FDIAGONAL: creates a brush with a 45-degree downward left-to-right hatch ( \ ).

  • PRINTER_BRUSH_HORIZONTAL: creates a brush with a horizontal hatch ( - ).

  • PRINTER_BRUSH_VERTICAL: creates a brush with a vertical hatch ( | ).

  • PRINTER_BRUSH_CUSTOM: creates a custom brush from an BMP file. The second parameter is used to specify the BMP instead of the RGB color code.

后退 | 起点 | 前进
printer_close | 上一级 | printer_create_dc


printer_create_dc

(no version information, might be only in CVS)

printer_create_dc -- Create a new device context

Description

void printer_create_dc ( resource handle)

The function creates a new device context. A device context is used to customize the graphic objects of the document. handle must be a valid handle to a printer.

例子 1. printer_create_dc() example

$handle = printer_open();
printer_start_doc($handle);
printer_start_page($handle);

printer_create_dc($handle);
/* do some stuff with the dc */
printer_set_option($handle, PRINTER_TEXT_COLOR, "333333");
printer_draw_text($handle, 1, 1, "text");
printer_delete_dc($handle);

/* create another dc */
printer_create_dc($handle);
printer_set_option($handle, PRINTER_TEXT_COLOR, "000000");
printer_draw_text($handle, 1, 1, "text");
/* do some stuff with the dc */

printer_delete_dc($handle);

printer_endpage($handle);
printer_end_doc($handle);
printer_close($handle);

后退 | 起点 | 前进
printer_create_brush | 上一级 | printer_create_font


printer_create_font

(no version information, might be only in CVS)

printer_create_font -- Create a new font

Description

mixed printer_create_font ( string face, int height, int width, int font_weight, bool italic, bool underline, bool strikeout, int orientaton)

The function creates a new font and returns a handle to it. A font is used to draw text. For an example see printer_select_font(). face must be a string specifying the font face. height specifies the font height, and width the font width. The font_weight specifies the font weight (400 is normal), and can be one of the following predefined constants.

  • PRINTER_FW_THIN: sets the font weight to thin (100).

  • PRINTER_FW_ULTRALIGHT: sets the font weight to ultra light (200).

  • PRINTER_FW_LIGHT: sets the font weight to light (300).

  • PRINTER_FW_NORMAL: sets the font weight to normal (400).

  • PRINTER_FW_MEDIUM: sets the font weight to medium (500).

  • PRINTER_FW_BOLD: sets the font weight to bold (700).

  • PRINTER_FW_ULTRABOLD: sets the font weight to ultra bold (800).

  • PRINTER_FW_HEAVY: sets the font weight to heavy (900).

italic can be TRUE or FALSE, and sets whether the font should be italic.

underline can be TRUE or FALSE, and sets whether the font should be underlined.

strikeout can be TRUE or FALSE, and sets whether the font should be striked out.

orientation specifies a rotation. For an example see printer_select_font().

后退 | 起点 | 前进
printer_create_dc | 上一级 | printer_create_pen


printer_create_pen

(no version information, might be only in CVS)

printer_create_pen -- Create a new pen

Description

mixed printer_create_pen ( int style, int width, string color)

The function creates a new pen and returns a handle to it. A pen is used to draw lines and curves. For an example see printer_select_pen(). color must be a color in RGB hex format, i.e. "000000" for black, width specifies the width of the pen whereas style must be one of the following constants:

  • PRINTER_PEN_SOLID: creates a solid pen.

  • PRINTER_PEN_DASH: creates a dashed pen.

  • PRINTER_PEN_DOT: creates a dotted pen.

  • PRINTER_PEN_DASHDOT: creates a pen with dashes and dots.

  • PRINTER_PEN_DASHDOTDOT: creates a pen with dashes and double dots.

  • PRINTER_PEN_INVISIBLE: creates an invisible pen.

后退 | 起点 | 前进
printer_create_font | 上一级 | printer_delete_brush


printer_delete_brush

(no version information, might be only in CVS)

printer_delete_brush -- Delete a brush

Description

bool printer_delete_brush ( resource handle)

The function deletes the selected brush. For an example see printer_select_brush(). It returns TRUE on success, or FALSE otherwise. handle must be a valid handle to a brush.

后退 | 起点 | 前进
printer_create_pen | 上一级 | printer_delete_dc


printer_delete_dc

(no version information, might be only in CVS)

printer_delete_dc -- Delete a device context

Description

bool printer_delete_dc ( resource handle)

The function deletes the device context and returns TRUE on success, or FALSE if an error occurred. For an example see printer_create_dc(). handle must be a valid handle to a printer.

后退 | 起点 | 前进
printer_delete_brush | 上一级 | printer_delete_font


printer_delete_font

(no version information, might be only in CVS)

printer_delete_font -- Delete a font

Description

bool printer_delete_font ( resource handle)

The function deletes the selected font. For an example see printer_select_font(). It returns TRUE on success, or FALSE otherwise. handle must be a valid handle to a font.

后退 | 起点 | 前进
printer_delete_dc | 上一级 | printer_delete_pen


printer_delete_pen

(no version information, might be only in CVS)

printer_delete_pen -- Delete a pen

Description

bool printer_delete_pen ( resource handle)

The function deletes the selected pen. For an example see printer_select_pen(). It returns TRUE on success, or FALSE otherwise. handle must be a valid handle to a pen.

后退 | 起点 | 前进
printer_delete_font | 上一级 | printer_draw_bmp


printer_draw_bmp

(no version information, might be only in CVS)

printer_draw_bmp -- Draw a bmp

Description

void printer_draw_bmp ( resource handle, string filename, int x, int y)

The function simply draws an bmp the bitmap filename at position x, y. handle must be a valid handle to a printer.

The function returns TRUE on success, or otherwise FALSE.

例子 1. printer_draw_bmp() example

$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

printer_draw_bmp($handle, "c:\\image.bmp", 1, 1);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);

后退 | 起点 | 前进
printer_delete_pen | 上一级 | printer_draw_chord


printer_draw_chord

(no version information, might be only in CVS)

printer_draw_chord -- Draw a chord

Description

void printer_draw_chord ( resource handle, int rec_x, int rec_y, int rec_x1, int rec_y1, int rad_x, int rad_y, int rad_x1, int rad_y1)

The function simply draws an chord. handle must be a valid handle to a printer.

rec_x is the upper left x coordinate of the bounding rectangle.

rec_y is the upper left y coordinate of the bounding rectangle.

rec_x1 is the lower right x coordinate of the bounding rectangle.

rec_y1 is the lower right y coordinate of the bounding rectangle.

rad_x is x coordinate of the radial defining the beginning of the chord.

rad_y is y coordinate of the radial defining the beginning of the chord.

rad_x1 is x coordinate of the radial defining the end of the chord.

rad_y1 is y coordinate of the radial defining the end of the chord.

例子 1. printer_draw_chord() example

$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_chord($handle, 1, 1, 500, 500, 1, 1, 500, 1);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);

后退 | 起点 | 前进
printer_draw_bmp | 上一级 | printer_draw_elipse


printer_draw_elipse

(no version information, might be only in CVS)

printer_draw_elipse -- Draw an ellipse

Description

void printer_draw_elipse ( resource handle, int ul_x, int ul_y, int lr_x, int lr_y)

The function simply draws an ellipse. handle must be a valid handle to a printer.

ul_x is the upper left x coordinate of the ellipse.

ul_y is the upper left y coordinate of the ellipse.

lr_x is the lower right x coordinate of the ellipse.

lr_y is the lower right y coordinate of the ellipse.

例子 1. printer_draw_elipse() example

$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_elipse($handle, 1, 1, 500, 500);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);

后退 | 起点 | 前进
printer_draw_chord | 上一级 | printer_draw_line


printer_draw_line

(no version information, might be only in CVS)

printer_draw_line -- Draw a line

Description

void printer_draw_line ( resource printer_handle, int from_x, int from_y, int to_x, int to_y)

The function simply draws a line from position from_x, from_y to position to_x, to_y using the selected pen. printer_handle must be a valid handle to a printer.

例子 1. printer_draw_line() example

$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 30, "000000");
printer_select_pen($handle, $pen);

printer_draw_line($handle, 1, 10, 1000, 10);
printer_draw_line($handle, 1, 60, 500, 60);

printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);

后退 | 起点 | 前进
printer_draw_elipse | 上一级 | printer_draw_pie


printer_draw_pie

(no version information, might be only in CVS)

printer_draw_pie -- Draw a pie

Description

void printer_draw_pie ( resource handle, int rec_x, int rec_y, int rec_x1, int rec_y1, int rad1_x, int rad1_y, int rad2_x, int rad2_y)

The function simply draws an pie. handle must be a valid handle to a printer.

rec_x is the upper left x coordinate of the bounding rectangle.

rec_y is the upper left y coordinate of the bounding rectangle.

rec_x1 is the lower right x coordinate of the bounding rectangle.

rec_y1 is the lower right y coordinate of the bounding rectangle.

rad1_x is x coordinate of the first radial's ending.

rad1_y is y coordinate of the first radial's ending.

rad2_x is x coordinate of the second radial's ending.

rad2_y is y coordinate of the second radial's ending.

例子 1. printer_draw_pie() example

$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_pie($handle, 1, 1, 500, 500, 1, 1, 500, 1);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);

后退 | 起点 | 前进
printer_draw_line | 上一级 | printer_draw_rectangle


printer_draw_rectangle

(no version information, might be only in CVS)

printer_draw_rectangle -- Draw a rectangle

Description

void printer_draw_rectangle ( resource handle, int ul_x, int ul_y, int lr_x, int lr_y)

The function simply draws a rectangle.

handle must be a valid handle to a printer.

ul_x is the upper left x coordinate of the rectangle.

ul_y is the upper left y coordinate of the rectangle.

lr_x is the lower right x coordinate of the rectangle.

lr_y is the lower right y coordinate of the rectangle.

例子 1. printer_draw_rectangle() example

$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_rectangle($handle, 1, 1, 500, 500);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);

后退 | 起点 | 前进
printer_draw_pie | 上一级 | printer_draw_roundrect


printer_draw_roundrect

(no version information, might be only in CVS)

printer_draw_roundrect -- Draw a rectangle with rounded corners

Description

void printer_draw_roundrect ( resource handle, int ul_x, int ul_y, int lr_x, int lr_y, int width, int height)

The function simply draws a rectangle with rounded corners.

handle must be a valid handle to a printer.

ul_x is the upper left x coordinate of the rectangle.

ul_y is the upper left y coordinate of the rectangle.

lr_x is the lower right x coordinate of the rectangle.

lr_y is the lower right y coordinate of the rectangle.

width is the width of the ellipse.

height is the height of the ellipse.

例子 1. printer_draw_roundrect() example

$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_roundrect($handle, 1, 1, 500, 500, 200, 200);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);

后退 | 起点 | 前进
printer_draw_rectangle | 上一级 | printer_draw_text


printer_draw_text

(no version information, might be only in CVS)

printer_draw_text -- Draw text

Description

void printer_draw_text ( resource printer_handle, string text, int x, int y)

The function simply draws text at position x, y using the selected font. printer_handle must be a valid handle to a printer.

例子 1. printer_draw_text() example

$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$font = printer_create_font("Arial",72,48,400,false,false,false,0);
printer_select_font($handle, $font);
printer_draw_text($handle, "test", 10, 10);
printer_delete_font($font);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);

后退 | 起点 | 前进
printer_draw_roundrect | 上一级 | printer_end_doc


printer_end_doc

(no version information, might be only in CVS)

printer_end_doc -- Close document

Description

bool printer_end_doc ( resource handle)

Closes a new document in the printer spooler. The document is now ready for printing. For an example see printer_start_doc(). handle must be a valid handle to a printer.

后退 | 起点 | 前进
printer_draw_text | 上一级 | printer_end_page


printer_end_page

(no version information, might be only in CVS)

printer_end_page -- Close active page

Description

bool printer_end_page ( resource handle)

The function closes the active page in the active document. For an example see printer_start_doc(). handle must be a valid handle to a printer.

后退 | 起点 | 前进
printer_end_doc | 上一级 | printer_get_option


printer_get_option

(no version information, might be only in CVS)

printer_get_option -- Retrieve printer configuration data

Description

mixed printer_get_option ( resource handle, string option)

The function retrieves the configuration setting of option. handle must be a valid handle to a printer. Take a look at printer_set_option() for the settings that can be retrieved, additionally the following settings can be retrieved:

  • PRINTER_DEVICENAME returns the devicename of the printer.

  • PRINTER_DRIVERVERSION returns the printer driver version.

例子 1. printer_get_option() example

$handle = printer_open();
print printer_get_option($handle, PRINTER_DRIVERVERSION);
printer_close($handle);

后退 | 起点 | 前进
printer_end_page | 上一级 | printer_list


printer_list

(no version information, might be only in CVS)

printer_list -- Return an array of printers attached to the server

Description

array printer_list ( int enumtype [, string name [, int level]])

The function enumerates available printers and their capabilities. level sets the level of information request. Can be 1,2,4 or 5. enumtype must be one of the following predefined constants:

  • PRINTER_ENUM_LOCAL: enumerates the locally installed printers.

  • PRINTER_ENUM_NAME: enumerates the printer of name, can be a server, domain or print provider.

  • PRINTER_ENUM_SHARED: this parameter can't be used alone, it has to be OR'ed with other parameters, i.e. PRINTER_ENUM_LOCAL to detect the locally shared printers.

  • PRINTER_ENUM_DEFAULT: (Win9.x only) enumerates the default printer.

  • PRINTER_ENUM_CONNECTIONS: (WinNT/2000 only) enumerates the printers to which the user has made connections.

  • PRINTER_ENUM_NETWORK: (WinNT/2000 only) enumerates network printers in the computer's domain. Only valid if level is 1.

  • PRINTER_ENUM_REMOTE: (WinNT/2000 only) enumerates network printers and print servers in the computer's domain. Only valid if level is 1.

例子 1. printer_list() example

/* detect locally shared printer */
var_dump( printer_list(PRINTER_ENUM_LOCAL | PRINTER_ENUM_SHARED) );

后退 | 起点 | 前进
printer_get_option | 上一级 | printer_logical_fontheight


printer_logical_fontheight

(no version information, might be only in CVS)

printer_logical_fontheight -- Get logical font height

Description

int printer_logical_fontheight ( resource handle, int height)

The function calculates the logical font height of height. handle must be a valid handle to a printer.

例子 1. printer_logical_fontheight() example

$handle = printer_open();
print printer_logical_fontheight($handle, 72);
printer_close($handle);

后退 | 起点 | 前进
printer_list | 上一级 | printer_open


printer_open

(no version information, might be only in CVS)

printer_open -- Open connection to a printer

Description

mixed printer_open ( [string devicename])

This function tries to open a connection to the printer devicename, and returns a handle on success or FALSE on failure.

If no parameter was given it tries to open a connection to the default printer (if not specified in php.ini as printer.default_printer, php tries to detect it).

printer_open() also starts a device context.

例子 1. printer_open() example

$handle = printer_open("HP Deskjet 930c");
$handle = printer_open();

后退 | 起点 | 前进
printer_logical_fontheight | 上一级 | printer_select_brush


printer_select_brush

(no version information, might be only in CVS)

printer_select_brush -- Select a brush

Description

void printer_select_brush ( resource printer_handle, resource brush_handle)

The function selects a brush as the active drawing object of the actual device context. A brush is used to fill shapes. If you draw an rectangle the brush is used to draw the shapes, while the pen is used to draw the border. If you haven't selected a brush before drawing shapes, the shape won't be filled. printer_handle must be a valid handle to a printer. brush_handle must be a valid handle to a brush.

例子 1. printer_select_brush() example

$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);
$brush = printer_create_brush(PRINTER_BRUSH_CUSTOM, "c:\\brush.bmp");
printer_select_brush($handle, $brush);

printer_draw_rectangle($handle, 1,1,500,500);

printer_delete_brush($brush);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "000000");
printer_select_brush($handle, $brush);
printer_draw_rectangle($handle, 1,501,500,1001);
printer_delete_brush($brush);

printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);

后退 | 起点 | 前进
printer_open | 上一级 | printer_select_font


printer_select_font

(no version information, might be only in CVS)

printer_select_font -- Select a font

Description

void printer_select_font ( resource printer_handle, resource font_handle)

The function selects a font to draw text. printer_handle must be a valid handle to a printer. font_handle must be a valid handle to a font.

例子 1. printer_select_font() example

$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$font = printer_create_font("Arial", 148, 76, PRINTER_FW_MEDIUM, false, false, false, -50);
printer_select_font($handle, $font);
printer_draw_text($handle, "PHP is simply cool", 40, 40);
printer_delete_font($font);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);

后退 | 起点 | 前进
printer_select_brush | 上一级 | printer_select_pen


printer_select_pen

(no version information, might be only in CVS)

printer_select_pen -- Select a pen

Description

void printer_select_pen ( resource printer_handle, resource pen_handle)

The function selects a pen as the active drawing object of the actual device context. A pen is used to draw lines and curves. I.e. if you draw a single line the pen is used. If you draw an rectangle the pen is used to draw the borders, while the brush is used to fill the shape. If you haven't selected a pen before drawing shapes, the shape won't be outlined. printer_handle must be a valid handle to a printer. pen_handle must be a valid handle to a pen.

例子 1. printer_select_pen() example

$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 30, "2222FF");
printer_select_pen($handle, $pen);

printer_draw_line($handle, 1, 60, 500, 60);

printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);

后退 | 起点 | 前进
printer_select_font | 上一级 | printer_set_option


printer_set_option

(no version information, might be only in CVS)

printer_set_option -- Configure the printer connection

Description

bool printer_set_option ( resource handle, int option, mixed value)

The function sets the following options for the current connection. handle must be a valid handle to a printer. For option can be one of the following constants:

  • PRINTER_COPIES: sets how many copies should be printed, value must be an integer.

  • PRINTER_MODE: specifies the type of data (text, raw or emf), value must be a string.

  • PRINTER_TITLE: specifies the name of the document, value must be a string.

  • PRINTER_ORIENTATION: specifies the orientation of the paper, value can be either PRINTER_ORIENTATION_PORTRAIT or PRINTER_ORIENTATION_LANDSCAPE

  • PRINTER_RESOLUTION_Y: specifies the y-resolution in DPI, value must be an integer.

  • PRINTER_RESOLUTION_X: specifies the x-resolution in DPI, value must be an integer.

  • PRINTER_PAPER_FORMAT: specifies the a predefined paper format, set value to PRINTER_FORMAT_CUSTOM if you want to specify a custom format with PRINTER_PAPER_WIDTH and PRINTER_PAPER_LENGTH. value can be one of the following constants.

    • PRINTER_FORMAT_CUSTOM: let's you specify a custom paper format.

    • PRINTER_FORMAT_LETTER: specifies standard letter format (8 1/2- by 11-inches).

    • PRINTER_FORMAT_LETTER: specifies standard legal format (8 1/2- by 14-inches).

    • PRINTER_FORMAT_A3: specifies standard A3 format (297- by 420-millimeters).

    • PRINTER_FORMAT_A4: specifies standard A4 format (210- by 297-millimeters).

    • PRINTER_FORMAT_A5: specifies standard A5 format (148- by 210-millimeters).

    • PRINTER_FORMAT_B4: specifies standard B4 format (250- by 354-millimeters).

    • PRINTER_FORMAT_B5: specifies standard B5 format (182- by 257-millimeter).

    • PRINTER_FORMAT_FOLIO: specifies standard FOLIO format (8 1/2- by 13-inch).

  • PRINTER_PAPER_LENGTH: if PRINTER_PAPER_FORMAT is set to PRINTER_FORMAT_CUSTOM, PRINTER_PAPER_LENGTH specifies a custom paper length in mm, value must be an integer.

  • PRINTER_PAPER_WIDTH: if PRINTER_PAPER_FORMAT is set to PRINTER_FORMAT_CUSTOM, PRINTER_PAPER_WIDTH specifies a custom paper width in mm, value must be an integer.

  • PRINTER_SCALE: specifies the factor by which the printed output is to be scaled. the page size is scaled from the physical page size by a factor of scale/100. for example if you set the scale to 50, the output would be half of it's original size. value must be an integer.

  • PRINTER_BACKGROUND_COLOR: specifies the background color for the actual device context, value must be a string containing the rgb information in hex format i.e. "005533".

  • PRINTER_TEXT_COLOR: specifies the text color for the actual device context, value must be a string containing the rgb information in hex format i.e. "005533".

  • PRINTER_TEXT_ALIGN: specifies the text alignment for the actual device context, value can be combined through OR'ing the following constants:

    • PRINTER_TA_BASELINE: text will be aligned at the base line.

    • PRINTER_TA_BOTTOM: text will be aligned at the bottom.

    • PRINTER_TA_TOP: text will be aligned at the top.

    • PRINTER_TA_CENTER: text will be aligned at the center.

    • PRINTER_TA_LEFT: text will be aligned at the left.

    • PRINTER_TA_RIGHT: text will be aligned at the right.

例子 1. printer_set_option() example

$handle = printer_open();
printer_set_option($handle, PRINTER_SCALE, 75);
printer_set_option($handle, PRINTER_TEXT_ALIGN, PRINTER_TA_LEFT);
printer_close($handle);

后退 | 起点 | 前进
printer_select_pen | 上一级 | printer_start_doc


printer_start_doc

(no version information, might be only in CVS)

printer_start_doc -- Start a new document

Description

bool printer_start_doc ( resource handle [, string document])

The function creates a new document in the printer spooler. A document can contain multiple pages, it's used to schedule the print job in the spooler. handle must be a valid handle to a printer. The optional parameter document can be used to set an alternative document name.

例子 1. printer_start_doc() example

$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);

后退 | 起点 | 前进
printer_set_option | 上一级 | printer_start_page


printer_start_page

(no version information, might be only in CVS)

printer_start_page -- Start a new page

Description

bool printer_start_page ( resource handle)

The function creates a new page in the active document. For an example see printer_start_doc(). handle must be a valid handle to a printer.

后退 | 起点 | 前进
printer_start_doc | 上一级 | printer_write


printer_write

(no version information, might be only in CVS)

printer_write -- Write data to the printer

Description

bool printer_write ( resource handle, string content)

Writes content directly to the printer, and returns TRUE on success or FALSE if it failed.

handle must be a valid handle to a printer.

例子 1. printer_write() example

$handle = printer_open();
printer_write($handle, "Text to print");
printer_close($handle);

后退 | 起点 | 前进
printer_start_page | 上一级 | Pspell Functions


Pspell Functions

PHP 手册
后退 前进

LXXXIV. Pspell Functions

介绍

These functions allow you to check the spelling of a word and offer suggestions.

需求

To compile PHP with pspell support, you need the aspell and pspell libraries, available from http://aspell.sourceforge.net/ and http://aspell.net/ respectively.

安装

If you have the libraries needed add the --with-pspell[=dir] option when compiling PHP.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

PSPELL_FAST (integer)

PSPELL_NORMAL (integer)

PSPELL_BAD_SPELLERS (integer)

PSPELL_RUN_TOGETHER (integer)

目录
pspell_add_to_personal — Add the word to a personal wordlist
pspell_add_to_session — Add the word to the wordlist in the current session
pspell_check — Check a word
pspell_clear_session — Clear the current session
pspell_config_create — Create a config used to open a dictionary
pspell_config_ignore — Ignore words less than N characters long
pspell_config_mode — Change the mode number of suggestions returned
pspell_config_personal — Set a file that contains personal wordlist
pspell_config_repl — Set a file that contains replacement pairs
pspell_config_runtogether — Consider run-together words as valid compounds
pspell_config_save_repl — Determine whether to save a replacement pairs list along with the wordlist
pspell_new_config — Load a new dictionary with settings based on a given config
pspell_new_personal — Load a new dictionary with personal wordlist
pspell_new — Load a new dictionary
pspell_save_wordlist — Save the personal wordlist to a file
pspell_store_replacement — Store a replacement pair for a word
pspell_suggest — Suggest spellings of a word

后退 | 起点 | 前进
printer_write | 上一级 | pspell_add_to_personal


pspell_add_to_personal

(PHP 4 >= 4.0.2)

pspell_add_to_personal -- Add the word to a personal wordlist

Description

int pspell_add_to_personal ( int dictionary_link, string word)

pspell_add_to_personal() adds a word to the personal wordlist. If you used pspell_new_config() with pspell_config_personal() to open the dictionary, you can save the wordlist later with pspell_save_wordlist(). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

例子 1. pspell_add_to_personal()

$pspell_config = pspell_config_create ("en");
pspell_config_personal ($pspell_config, "/var/dictionaries/custom.pws");
$pspell_link = pspell_new_config ($pspell_config);

pspell_add_to_personal ($pspell_link, "Vlad");
pspell_save_wordlist ($pspell_link);

后退 | 起点 | 前进
Pspell Functions | 上一级 | pspell_add_to_session


pspell_add_to_session

(PHP 4 >= 4.0.2)

pspell_add_to_session -- Add the word to the wordlist in the current session

Description

int pspell_add_to_session ( int dictionary_link, string word)

pspell_add_to_session() adds a word to the wordlist associated with the current session. It is very similar to pspell_add_to_personal()

后退 | 起点 | 前进
pspell_add_to_personal | 上一级 | pspell_check


pspell_check

(PHP 4 >= 4.0.2)

pspell_check -- Check a word

Description

bool pspell_check ( int dictionary_link, string word)

pspell_check() checks the spelling of a word and returns TRUE if the spelling is correct, FALSE if not.

例子 1. pspell_check()

$pspell_link = pspell_new ("en");

if (pspell_check ($pspell_link, "testt")) {
    echo "This is a valid spelling";
} else {
    echo "Sorry, wrong spelling";
}

后退 | 起点 | 前进
pspell_add_to_session | 上一级 | pspell_clear_session


pspell_clear_session

(PHP 4 >= 4.0.2)

pspell_clear_session -- Clear the current session

Description

int pspell_clear_session ( int dictionary_link)

pspell_clear_session() clears the current session. The current wordlist becomes blank, and, for example, if you try to save it with pspell_save_wordlist(), nothing happens.

例子 1. pspell_add_to_personal()

$pspell_config = pspell_config_create ("en");
pspell_config_personal ($pspell_config, "/var/dictionaries/custom.pws");
$pspell_link = pspell_new_config ($pspell_config);

pspell_add_to_personal ($pspell_link, "Vlad");
pspell_clear_session ($pspell_link);
pspell_save_wordlist ($pspell_link);    //"Vlad" will not be saved

后退 | 起点 | 前进
pspell_check | 上一级 | pspell_config_create


pspell_config_create

(PHP 4 >= 4.0.2)

pspell_config_create -- Create a config used to open a dictionary

Description

int pspell_config_create ( string language [, string spelling [, string jargon [, string encoding]]])

pspell_config_create() has a very similar syntax to pspell_new(). In fact, using pspell_config_create() immediatelly followed by pspell_new_config() will produce the exact same result. However, after creating a new config, you can also use pspell_config_*() functions before calling pspell_new_config() to take advantage of some advanced functionality.

The language parameter is the language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.

The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.

The encoding parameter is the encoding that words are expected to be in. Valid values are 'utf-8', 'iso8859-*', 'koi8-r', 'viscii', 'cp1252', 'machine unsigned 16', 'machine unsigned 32'. This parameter is largely untested, so be careful when using.

The mode parameter is the mode in which spellchecker will work. There are several modes available:

  • PSPELL_FAST - Fast mode (least number of suggestions)

  • PSPELL_NORMAL - Normal mode (more suggestions)

  • PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)

For more information and examples, check out inline manual pspell website:http://aspell.net/.

例子 1. pspell_config_create()

$pspell_config = pspell_config_create ("en");
pspell_config_personal ($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl ($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_personal ($pspell_config, "en");

后退 | 起点 | 前进
pspell_clear_session | 上一级 | pspell_config_ignore


pspell_config_ignore

(PHP 4 >= 4.0.2)

pspell_config_ignore -- Ignore words less than N characters long

Description

int pspell_config_ignore ( int dictionary_link, int n)

pspell_config_ignore() should be used on a config before calling pspell_new_config(). This function allows short words to be skipped by the spellchecker. Words less then n characters will be skipped.

例子 1. pspell_config_ignore()

$pspell_config = pspell_config_create ("en");
pspell_config_ignore($pspell_config, 5);
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "abcd");    //will not result in an error

后退 | 起点 | 前进
pspell_config_create | 上一级 | pspell_config_mode


pspell_config_mode

(PHP 4 >= 4.0.2)

pspell_config_mode -- Change the mode number of suggestions returned

Description

int pspell_config_mode ( int dictionary_link, int mode)

pspell_config_mode() should be used on a config before calling pspell_new_config(). This function determines how many suggestions will be returned by pspell_suggest().

The mode parameter is the mode in which spellchecker will work. There are several modes available:

  • PSPELL_FAST - Fast mode (least number of suggestions)

  • PSPELL_NORMAL - Normal mode (more suggestions)

  • PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)

例子 1. pspell_config_mode()

$pspell_config = pspell_config_create ("en");
pspell_config_mode($pspell_config, PSPELL_FAST);
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "thecat");

后退 | 起点 | 前进
pspell_config_ignore | 上一级 | pspell_config_personal


pspell_config_personal

(PHP 4 >= 4.0.2)

pspell_config_personal -- Set a file that contains personal wordlist

Description

int pspell_config_personal ( int dictionary_link, string file)

pspell_config_personal() should be used on a config before calling pspell_new_config(). The personal wordlist will be loaded and used in addition to the standard one after you call pspell_new_config(). If the file does not exist, it will be created. The file is also the file where pspell_save_wordlist() will save personal wordlist to. The file should be writable by whoever php runs as (e.g. nobody). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

例子 1. pspell_config_personal()

$pspell_config = pspell_config_create ("en");
pspell_config_personal ($pspell_config, "/var/dictionaries/custom.pws");
$pspell_link = pspell_new_config ($pspell_config);
pspell_check ($pspell_link, "thecat");

后退 | 起点 | 前进
pspell_config_mode | 上一级 | pspell_config_repl


pspell_config_repl

(PHP 4 >= 4.0.2)

pspell_config_repl -- Set a file that contains replacement pairs

Description

int pspell_config_repl ( int dictionary_link, string file)

pspell_config_repl() should be used on a config before calling pspell_new_config(). The replacement pairs improve the quality of the spellchecker. When a word is misspelled, and a proper suggestion was not found in the list, pspell_store_replacement() can be used to store a replacement pair and then pspell_save_wordlist() to save the wordlist along with the replacement pairs. The file should be writable by whoever php runs as (e.g. nobody). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

例子 1. pspell_config_repl()

$pspell_config = pspell_config_create ("en");
pspell_config_personal ($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl ($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_config ($pspell_config);
pspell_check ($pspell_link, "thecat");

后退 | 起点 | 前进
pspell_config_personal | 上一级 | pspell_config_runtogether


pspell_config_runtogether

(PHP 4 >= 4.0.2)

pspell_config_runtogether -- Consider run-together words as valid compounds

Description

int pspell_config_runtogether ( int dictionary_link, bool flag)

pspell_config_runtogether() should be used on a config before calling pspell_new_config(). This function determines whether run-together words will be treated as legal compounds. That is, "thecat" will be a legal compound, athough there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.

例子 1. pspell_config_runtogether()

$pspell_config = pspell_config_create ("en");
pspell_config_runtogether ($pspell_config, true);
$pspell_link = pspell_new_config ($pspell_config);
pspell_check ($pspell_link, "thecat");

后退 | 起点 | 前进
pspell_config_repl | 上一级 | pspell_config_save_repl


pspell_config_save_repl

(PHP 4 >= 4.0.2)

pspell_config_save_repl -- Determine whether to save a replacement pairs list along with the wordlist

Description

int pspell_config_save_repl ( int dictionary_link, bool flag)

pspell_config_save_repl() should be used on a config before calling pspell_new_config(). It determines whether pspell_save_wordlist() will save the replacement pairs along with the wordlist. Usually there is no need to use this function because if pspell_config_repl() is used, the replacement pairs will be saved by pspell_save_wordlist() anyway, and if it is not, the replacement pairs will not be saved. Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

后退 | 起点 | 前进
pspell_config_runtogether | 上一级 | pspell_new_config


pspell_new_config

(PHP 4 >= 4.0.2)

pspell_new_config -- Load a new dictionary with settings based on a given config

Description

int pspell_new_config ( int config)

pspell_new_config() opens up a new dictionary with settings specified in a config, created with with pspell_config_create() and modified with pspell_config_*() functions. This method provides you with the most flexibility and has all the functionality provided by pspell_new() and pspell_new_personal().

The config parameter is the one returned by pspell_config_create() when the config was created.

例子 1. pspell_new_config()

$pspell_config = pspell_config_create ("en");
pspell_config_personal ($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl ($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_config ($pspell_config);

后退 | 起点 | 前进
pspell_config_save_repl | 上一级 | pspell_new_personal


pspell_new_personal

(PHP 4 >= 4.0.2)

pspell_new_personal -- Load a new dictionary with personal wordlist

Description

int pspell_new_personal ( string personal, string language [, string spelling [, string jargon [, string encoding [, int mode]]]])

pspell_new_personal() opens up a new dictionary with a personal wordlist and returns the dictionary link identifier for use in other pspell functions. The wordlist can be modified and saved with pspell_save_wordlist(), if desired. However, the replacement pairs are not saved. In order to save replacement pairs, you should create a config using pspell_config_create(), set the personal wordlist file with pspell_config_personal(), set the file for replacement pairs with pspell_config_repl(), and open a new dictionary with pspell_new_config().

The personal parameter specifies the file where words added to the personal list will be stored. It should be an absolute filename beginning with '/' because otherwise it will be relative to $HOME, which is "/root" for most systems, and is probably not what you want.

The language parameter is the language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.

The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.

The encoding parameter is the encoding that words are expected to be in. Valid values are 'utf-8', 'iso8859-*', 'koi8-r', 'viscii', 'cp1252', 'machine unsigned 16', 'machine unsigned 32'. This parameter is largely untested, so be careful when using.

The mode parameter is the mode in which spellchecker will work. There are several modes available:

  • PSPELL_FAST - Fast mode (least number of suggestions)

  • PSPELL_NORMAL - Normal mode (more suggestions)

  • PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)

  • PSPELL_RUN_TOGETHER - Consider run-together words as legal compounds. That is, "thecat" will be a legal compound, athough there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.

Mode is a bitmask constructed from different constants listed above. However, PSPELL_FAST, PSPELL_NORMAL and PSPELL_BAD_SPELLERS are mutually exclusive, so you should select only one of them.

For more information and examples, check out inline manual pspell website:http://aspell.net/.

例子 1. pspell_new_personal()

$pspell_link = pspell_new_personal ("/var/dictionaries/custom.pws",
        "en", "", "", "", PSPELL_FAST|PSPELL_RUN_TOGETHER));

后退 | 起点 | 前进
pspell_new_config | 上一级 | pspell_new


pspell_new

(PHP 4 >= 4.0.2)

pspell_new -- Load a new dictionary

Description

int pspell_new ( string language [, string spelling [, string jargon [, string encoding [, int mode]]]])

pspell_new() opens up a new dictionary and returns the dictionary link identifier for use in other pspell functions.

The language parameter is the language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.

The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.

The encoding parameter is the encoding that words are expected to be in. Valid values are 'utf-8', 'iso8859-*', 'koi8-r', 'viscii', 'cp1252', 'machine unsigned 16', 'machine unsigned 32'. This parameter is largely untested, so be careful when using.

The mode parameter is the mode in which spellchecker will work. There are several modes available:

  • PSPELL_FAST - Fast mode (least number of suggestions)

  • PSPELL_NORMAL - Normal mode (more suggestions)

  • PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)

  • PSPELL_RUN_TOGETHER - Consider run-together words as legal compounds. That is, "thecat" will be a legal compound, athough there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.

Mode is a bitmask constructed from different constants listed above. However, PSPELL_FAST, PSPELL_NORMAL and PSPELL_BAD_SPELLERS are mutually exclusive, so you should select only one of them.

For more information and examples, check out inline manual pspell website:http://aspell.net/.

例子 1. pspell_new()

$pspell_link = pspell_new ("en", "", "", "",
                           (PSPELL_FAST|PSPELL_RUN_TOGETHER));

后退 | 起点 | 前进
pspell_new_personal | 上一级 | pspell_save_wordlist


pspell_save_wordlist

(PHP 4 >= 4.0.2)

pspell_save_wordlist -- Save the personal wordlist to a file

Description

int pspell_save_wordlist ( int dictionary_link)

pspell_save_wordlist() saves the personal wordlist from the current session. The dictionary has to be open with pspell_new_personal(), and the location of files to be saved specified with pspell_config_personal() and (optionally) pspell_config_repl(). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

例子 1. pspell_add_to_personal()

$pspell_config = pspell_config_create ("en");
pspell_config_personal ($pspell_config, "/tmp/dicts/newdict");
$pspell_link = pspell_new_config ($pspell_config);

pspell_add_to_personal ($pspell_link, "Vlad");
pspell_save_wordlist ($pspell_link);

后退 | 起点 | 前进
pspell_new | 上一级 | pspell_store_replacement


pspell_store_replacement

(PHP 4 >= 4.0.2)

pspell_store_replacement -- Store a replacement pair for a word

Description

int pspell_store_replacement ( int dictionary_link, string misspelled, string correct)

pspell_store_replacement() stores a replacement pair for a word, so that replacement can be returned by pspell_suggest() later. In order to be able to take advantage of this function, you have to use pspell_new_personal() to open the dictionary. In order to permanently save the replacement pair, you have to use pspell_config_personal() and pspell_config_repl() to set the path where to save your custom wordlists, and then use pspell_save_wordlist() for the changes to be written to disk. Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

例子 1. pspell_store_replacement()

$pspell_config = pspell_config_create ("en");
pspell_config_personal ($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl ($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_config ($pspell_config);

pspell_store_replacement ($pspell_link, $misspelled, $correct);
pspell_save_wordlist ($pspell_link);

后退 | 起点 | 前进
pspell_save_wordlist | 上一级 | pspell_suggest


pspell_suggest

(PHP 4 >= 4.0.2)

pspell_suggest -- Suggest spellings of a word

Description

array pspell_suggest ( int dictionary_link, string word)

pspell_suggest() returns an array of possible spellings for the given word.

例子 1. pspell_suggest()

$pspell_link = pspell_new ("en");

if (!pspell_check ($pspell_link, "testt")) {
    $suggestions = pspell_suggest ($pspell_link, "testt");

    foreach ($suggestions as $suggestion) {
        echo "Possible spelling: $suggestion<br>";
    }
}

后退 | 起点 | 前进
pspell_store_replacement | 上一级 | GNU Readline


GNU Readline

PHP 手册
后退 前进

LXXXV. GNU Readline

介绍

The readline() functions implement an interface to the GNU Readline library. These are functions that provide editable command lines. An example being the way Bash allows you to use the arrow keys to insert characters or scroll through command history. Because of the interactive nature of this library, it will be of little use for writing Web applications, but may be useful when writing scripts meant to be run from a shell.

需求

To use the readline functions, you need to install libreadline. You can find libreadline on the home page of the GNU Readline project, at http://cnswww.cns.cwru.edu/~chet/readline/rltop.html. It's maintained by Chet Ramey, who's also the author of Bash.

安装

To use this functions you must compile PHP with readline support. You need to configure PHP --with-readline.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

目录
readline_add_history — Adds a line to the history
readline_clear_history — Clears the history
readline_completion_function — Registers a completion function
readline_info — Gets/sets various internal readline variables
readline_list_history — Lists the history
readline_read_history — Reads the history
readline_write_history — Writes the history
readline — Reads a line

后退 | 起点 | 前进
pspell_suggest | 上一级 | readline_add_history


readline_add_history

(PHP 4 )

readline_add_history -- Adds a line to the history

Description

void readline_add_history ( string line)

This function adds a line to the command line history.

后退 | 起点 | 前进
GNU Readline | 上一级 | readline_clear_history


readline_clear_history

(PHP 4 )

readline_clear_history -- Clears the history

Description

bool readline_clear_history ( void)

This function clears the entire command line history.

后退 | 起点 | 前进
readline_add_history | 上一级 | readline_completion_function


readline_completion_function

(PHP 4 )

readline_completion_function -- Registers a completion function

Description

bool readline_completion_function ( string line)

This function registers a completion function. You must supply the name of an existing function which accepts a partial command line and returns an array of possible matches. This is the same kind of functionality you'd get if you hit your tab key while using Bash.

后退 | 起点 | 前进
readline_clear_history | 上一级 | readline_info


readline_info

(PHP 4 )

readline_info -- Gets/sets various internal readline variables

Description

mixed readline_info ( [string varname [, string newvalue]])

If called with no parameters, this function returns an array of values for all the setting readline uses. The elements will be indexed by the following values: done, end, erase_empty_line, library_version, line_buffer, mark, pending_input, point, prompt, readline_name, and terminal_name.

If called with one parameter, the value of that setting is returned. If called with two parameters, the setting will be changed to the given value.

后退 | 起点 | 前进
readline_completion_function | 上一级 | readline_list_history


readline_list_history

(PHP 4 )

readline_list_history -- Lists the history

Description

array readline_list_history ( void)

This function returns an array of the entire command line history. The elements are indexed by integers starting at zero.

后退 | 起点 | 前进
readline_info | 上一级 | readline_read_history


readline_read_history

(PHP 4 )

readline_read_history -- Reads the history

Description

bool readline_read_history ( string filename)

This function reads a command history from a file.

后退 | 起点 | 前进
readline_list_history | 上一级 | readline_write_history


readline_write_history

(PHP 4 )

readline_write_history -- Writes the history

Description

bool readline_write_history ( string filename)

This function writes the command history to a file.

后退 | 起点 | 前进
readline_read_history | 上一级 | readline


readline

(PHP 4 )

readline -- Reads a line

Description

string readline ( [string prompt])

This function returns a single string from the user. You may specify a string with which to prompt the user. The line returned has the ending newline removed. You must add this line to the history yourself using readline_add_history().

例子 1. readline()

//get 3 commands from user
for ($i=0; $i < 3; $i++) {
        $line = readline ("Command: ");
        readline_add_history ($line);
}

//dump history
print_r (readline_list_history());

//dump variables
print_r (readline_info());

后退 | 起点 | 前进
readline_write_history | 上一级 | GNU Recode functions


GNU Recode functions

PHP 手册
后退 前进

LXXXVI. GNU Recode functions

介绍

This module contains an interface to the GNU Recode library, version 3.5. The GNU Recode library converts files between various coded character sets and surface encodings. When this cannot be achieved exactly, it may get rid of the offending characters or fall back on approximations. The library recognises or produces nearly 150 different character sets and is able to convert files between almost any pair. Most RFC 1345 character sets are supported.

需求

You must have GNU Recode 3.5 or higher installed on your system. You can download the package from here.

安装

To be able to use the functions defined in this module you must compile your PHP interpreter using the --with-recode[=DIR] option.

警告

Crashes and startup problems of PHP may be encountered when loading the recode as extension after loading any extension of mysql or imap. Loading the recode before those extension has proven to fix the problem. This is due a technical problem that both the c-client library used by imap and recode have their own hash_lookup() function and both mysql and recode have their own hash_insert function.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

目录
recode_file — Recode from file to file according to recode request
recode_string — Recode a string according to a recode request
recode — Recode a string according to a recode request

后退 | 起点 | 前进
readline | 上一级 | recode_file


recode_file

(PHP 3>= 3.0.13, PHP 4 )

recode_file -- Recode from file to file according to recode request

Description

bool recode_file ( string request, resource input, resource output)

Recode the file referenced by file handle input into the file referenced by file handle output according to the recode request. Returns FALSE, if unable to comply, TRUE otherwise.

This function does not currently process filehandles referencing remote files (URLs). Both filehandles must refer to local files.

例子 1. Basic recode_file() example

$input = fopen ('input.txt', 'r');
$output = fopen ('output.txt', 'w');
recode_file ("us..flat", $input, $output);

后退 | 起点 | 前进
GNU Recode functions | 上一级 | recode_string


recode_string

(PHP 3>= 3.0.13, PHP 4 )

recode_string -- Recode a string according to a recode request

Description

string recode_string ( string request, string string)

Recode the string string according to the recode request request. Returns the recoded string or FALSE, if unable to perform the recode request.

A simple recode request may be "lat1..iso646-de". See also the GNU Recode documentation of your installation for detailed instructions about recode requests.

例子 1. Basic recode_string() example:

print recode_string ("us..flat", "The following character has a diacritical mark: &aacute;");

后退 | 起点 | 前进
recode_file | 上一级 | recode


recode

(PHP 4 )

recode -- Recode a string according to a recode request

Description

string recode ( string request, string string)

注: This is an alias for recode_string(). It has been added in PHP 4.

后退 | 起点 | 前进
recode_string | 上一级 | Regular Expression Functions (Perl-Compatible)


Regular Expression Functions (Perl-Compatible)

PHP 手册
后退 前进

LXXXVII. Regular Expression Functions (Perl-Compatible)

介绍

The syntax for patterns used in these functions closely resembles Perl. The expression should be enclosed in the delimiters, a forward slash (/), for example. Any character can be used for delimiter as long as it's not alphanumeric or backslash (\). If the delimiter character has to be used in the expression itself, it needs to be escaped by backslash. Since PHP 4.0.4, you can also use Perl-style (), {}, [], and <> matching delimiters.

The ending delimiter may be followed by various modifiers that affect the matching. See Pattern Modifiers.

PHP also supports regular expressions using a POSIX-extended syntax using the POSIX-extended regex functions..

需求

Regular expression support is provided by the PCRE library package, which is open source software, written by Philip Hazel, and copyright by the University of Cambridge, England. It is available at ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/.

安装

Beginning with PHP 4.2.0 this function are enabled by default. For older versions you have to configure and compile PHP with --with-pcre-regex[=DIR] in order to use these functions. You can disable the pcre functions with --without-pcre-regex.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

表格 1. PREG constants

constant | description
PREG_PATTERN_ORDER | Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on. This flag is only used with preg_match_all().
PREG_SET_ORDER | Orders results so that $matches[0] is an array of first set of matches, $matches[1] is an array of second set of matches, and so on. This flag is only used with preg_match_all().
PREG_OFFSET_CAPTURE | See the description of PREG_SPLIT_OFFSET_CAPTURE. This flag is available since PHP 4.3.0 .
PREG_SPLIT_NO_EMPTY | This flag tells preg_split() to only return only non-empty pieces.
PREG_SPLIT_DELIM_CAPTURE | This flag tells preg_split() to capture parenthesized expression in the delimiter pattern as well. This flag is available since PHP 4.0.5 .
PREG_SPLIT_OFFSET_CAPTURE | If this flag is set, for every occuring match the appendant string offset will also be returned. Note that this changes the return value in an array where very element is an array consisting of the matched string at offset 0 and it's string offset into subject at offset 1. This flag is available since PHP 4.3.0 and is only used for preg_split().

范例

例子 1. Examples of valid patterns

  • /<\/\w+>/

  • |(\d{3})-\d+|Sm

  • /^(?i)php[34]/

  • {^\s+(\s+)?$}

例子 2. Examples of invalid patterns

  • /href='(.*)' - missing ending delimiter

  • /\w+\s*\w+/J - unknown modifier 'J'

  • 1-\d3-\d3-\d4| - missing starting delimiter

目录
Pattern Modifiers — Describes possible modifiers in regex patterns
Pattern Syntax — Describes PCRE regex syntax
preg_grep — Return array entries that match the pattern
preg_match_all — Perform a global regular expression match
preg_match — Perform a regular expression match
preg_quote — Quote regular expression characters
preg_replace_callback — Perform a regular expression search and replace using a callback
preg_replace — Perform a regular expression search and replace
preg_split — Split string by a regular expression

后退 | 起点 | 前进
recode | 上一级 | Pattern Modifiers


Pattern Modifiers

Pattern Modifiers -- Describes possible modifiers in regex patterns

Description

The current possible PCRE modifiers are listed below. The names in parentheses refer to internal PCRE names for these modifiers.

i (PCRE_CASELESS)

If this modifier is set, letters in the pattern match both upper and lower case letters.

m (PCRE_MULTILINE)

By default, PCRE treats the subject string as consisting of a single "line" of characters (even if it actually contains several newlines). The "start of line" metacharacter (^) matches only at the start of the string, while the "end of line" metacharacter ($) matches only at the end of the string, or before a terminating newline (unless D modifier is set). This is the same as Perl.

When this modifier is set, the "start of line" and "end of line" constructs match immediately following or immediately before any newline in the subject string, respectively, as well as at the very start and end. This is equivalent to Perl's /m modifier. If there are no "\n" characters in a subject string, or no occurrences of ^ or $ in a pattern, setting this modifier has no effect.

s (PCRE_DOTALL)

If this modifier is set, a dot metacharacter in the pattern matches all characters, including newlines. Without it, newlines are excluded. This modifier is equivalent to Perl's /s modifier. A negative class such as [^a] always matches a newline character, independent of the setting of this modifier.

x (PCRE_EXTENDED)

If this modifier is set, whitespace data characters in the pattern are totally ignored except when escaped or inside a character class, and characters between an unescaped # outside a character class and the next newline character, inclusive, are also ignored. This is equivalent to Perl's /x modifier, and makes it possible to include comments inside complicated patterns. Note, however, that this applies only to data characters. Whitespace characters may never appear within special character sequences in a pattern, for example within the sequence (?( which introduces a conditional subpattern.

e

If this modifier is set, preg_replace() does normal substitution of backreferences in the replacement string, evaluates it as PHP code, and uses the result for replacing the search string.

Only preg_replace() uses this modifier; it is ignored by other PCRE functions.

注: This modifier was not available in PHP3.

A (PCRE_ANCHORED)

If this modifier is set, the pattern is forced to be "anchored", that is, it is constrained to match only at the start of the string which is being searched (the "subject string"). This effect can also be achieved by appropriate constructs in the pattern itself, which is the only way to do it in Perl.

D (PCRE_DOLLAR_ENDONLY)

If this modifier is set, a dollar metacharacter in the pattern matches only at the end of the subject string. Without this modifier, a dollar also matches immediately before the final character if it is a newline (but not before any other newlines). This modifier is ignored if m modifier is set. There is no equivalent to this modifier in Perl.

S

When a pattern is going to be used several times, it is worth spending more time analyzing it in order to speed up the time taken for matching. If this modifier is set, then this extra analysis is performed. At present, studying a pattern is useful only for non-anchored patterns that do not have a single fixed starting character.

U (PCRE_UNGREEDY)

This modifier inverts the "greediness" of the quantifiers so that they are not greedy by default, but become greedy if followed by "?". It is not compatible with Perl. It can also be set by a (?U) modifier setting within the pattern.

X (PCRE_EXTRA)

This modifier turns on additional functionality of PCRE that is incompatible with Perl. Any backslash in a pattern that is followed by a letter that has no special meaning causes an error, thus reserving these combinations for future expansion. By default, as in Perl, a backslash followed by a letter with no special meaning is treated as a literal. There are at present no other features controlled by this modifier.

u (PCRE_UTF8)

This modifier turns on additional functionality of PCRE that is incompatible with Perl. Pattern strings are treated as UTF-8. This modifier is available from PHP 4.1.0 or greater on Unix and from PHP 4.2.3 on win32.

后退 | 起点 | 前进
Regular Expression Functions (Perl-Compatible) | 上一级 | Pattern Syntax


Pattern Syntax

Pattern Syntax -- Describes PCRE regex syntax

Description

The PCRE library is a set of functions that implement regular expression pattern matching using the same syntax and semantics as Perl 5, with just a few differences (see below). The current implementation corresponds to Perl 5.005.

Differences From Perl

The differences described here are with respect to Perl 5.005.

  1. By default, a whitespace character is any character that the C library function isspace() recognizes, though it is possible to compile PCRE with alternative character type tables. Normally isspace() matches space, formfeed, newline, carriage return, horizontal tab, and vertical tab. Perl 5 no longer includes vertical tab in its set of whitespace characters. The \v escape that was in the Perl documentation for a long time was never in fact recognized. However, the character itself was treated as whitespace at least up to 5.002. In 5.004 and 5.005 it does not match \s.

  2. PCRE does not allow repeat quantifiers on lookahead assertions. Perl permits them, but they do not mean what you might think. For example, (?!a){3} does not assert that the next three characters are not "a". It just asserts that the next character is not "a" three times.

  3. Capturing subpatterns that occur inside negative looka- head assertions are counted, but their entries in the offsets vector are never set. Perl sets its numerical vari- ables from any such patterns that are matched before the assertion fails to match something (thereby succeeding), but only if the negative lookahead assertion contains just one branch.

  4. Though binary zero characters are supported in the subject string, they are not allowed in a pattern string because it is passed as a normal C string, terminated by zero. The escape sequence "\\x00" can be used in the pattern to represent a binary zero.

  5. The following Perl escape sequences are not supported: \l, \u, \L, \U, \E, \Q. In fact these are implemented by Perl's general string-handling and are not part of its pat- tern matching engine.

  6. The Perl \G assertion is not supported as it is not relevant to single pattern matches.

  7. Fairly obviously, PCRE does not support the (?{code}) construction.

  8. There are at the time of writing some oddities in Perl 5.005_02 concerned with the settings of captured strings when part of a pattern is repeated. For example, matching "aba" against the pattern /^(a(b)?)+$/ sets $2 to the value "b", but matching "aabbaa" against /^(aa(bb)?)+$/ leaves $2 unset. However, if the pattern is changed to /^(aa(b(b))?)+$/ then $2 (and $3) get set. In Perl 5.004 $2 is set in both cases, and that is also TRUE of PCRE. If in the future Perl changes to a consistent state that is different, PCRE may change to follow.

  9. Another as yet unresolved discrepancy is that in Perl 5.005_02 the pattern /^(a)?(?(1)a|b)+$/ matches the string "a", whereas in PCRE it does not. However, in both Perl and PCRE /^(a)?a/ matched against "a" leaves $1 unset.

  10. PCRE provides some extensions to the Perl regular expression facilities:

    1. Although lookbehind assertions must match fixed length strings, each alternative branch of a lookbehind assertion can match a different length of string. Perl 5.005 requires them all to have the same length.

    2. If PCRE_DOLLAR_ENDONLY is set and PCRE_MULTILINE is not set, the $ meta- character matches only at the very end of the string.

    3. If PCRE_EXTRA is set, a backslash followed by a letter with no special meaning is faulted.

    4. If PCRE_UNGREEDY is set, the greediness of the repeti- tion quantifiers is inverted, that is, by default they are not greedy, but if followed by a question mark they are.

Regular Expression Details

Introduction

The syntax and semantics of the regular expressions sup- ported by PCRE are described below. Regular expressions are also described in the Perl documentation and in a number of other books, some of which have copious examples. Jeffrey Friedl's "Mastering Regular Expressions", published by O'Reilly (ISBN 1-56592-257-3), covers them in great detail. The description here is intended as reference documentation. A regular expression is a pattern that is matched against a subject string from left to right. Most characters stand for themselves in a pattern, and match the corresponding charac- ters in the subject. As a trivial example, the pattern The quick brown fox matches a portion of a subject string that is identical to itself.

Meta-characters

The power of regular expressions comes from the ability to include alternatives and repetitions in the pat- tern. These are encoded in the pattern by the use of meta- characters, which do not stand for themselves but instead are interpreted in some special way.

There are two different sets of meta-characters: those that are recognized anywhere in the pattern except within square brackets, and those that are recognized in square brackets. Outside square brackets, the meta-characters are as follows:

\

general escape character with several uses

^

assert start of subject (or line, in multiline mode)

$

assert end of subject (or line, in multiline mode)

.

match any character except newline (by default)

[

start character class definition

]

end character class definition

|

start of alternative branch

(

start subpattern

)

end subpattern

?

extends the meaning of (, also 0 or 1 quantifier, also quantifier minimizer

*

0 or more quantifier

+

1 or more quantifier

{

start min/max quantifier

}

end min/max quantifier

Part of a pattern that is in square brackets is called a "character class". In a character class the only meta- characters are:

\

general escape character

^

negate the class, but only if the first character

-

indicates character range

]

terminates the character class

The following sections describe the use of each of the meta-characters.

backslash

The backslash character has several uses. Firstly, if it is followed by a non-alphanumeric character, it takes away any special meaning that character may have. This use of backslash as an escape character applies both inside and outside character classes.

For example, if you want to match a "*" character, you write "\*" in the pattern. This applies whether or not the follow- ing character would otherwise be interpreted as a meta- character, so it is always safe to precede a non-alphanumeric with "\" to specify that it stands for itself. In particu- lar, if you want to match a backslash, you write "\\".

If a pattern is compiled with the PCRE_EXTENDED option, whi- tespace in the pattern (other than in a character class) and characters between a "#" outside a character class and the next newline character are ignored. An escaping backslash can be used to include a whitespace or "#" character as part of the pattern.

A second use of backslash provides a way of encoding non- printing characters in patterns in a visible manner. There is no restriction on the appearance of non-printing characters, apart from the binary zero that terminates a pattern, but when a pattern is being prepared by text editing, it is usually easier to use one of the following escape sequences than the binary character it represents:

\a

alarm, that is, the BEL character (hex 07)

\cx

"control-x", where x is any character

\e

escape (hex 1B)

\f

formfeed (hex 0C)

\n

newline (hex 0A)

\r

carriage return (hex 0D)

\t

tab (hex 09)

\xhh

character with hex code hh

\ddd

character with octal code ddd, or backreference

The precise effect of "\cx" is as follows: if "x" is a lower case letter, it is converted to upper case. Then bit 6 of the character (hex 40) is inverted. Thus "\cz" becomes hex 1A, but "\c{" becomes hex 3B, while "\c;" becomes hex 7B.

After "\x", up to two hexadecimal digits are read (letters can be in upper or lower case).

After "\0" up to two further octal digits are read. In both cases, if there are fewer than two digits, just those that are present are used. Thus the sequence "\0\x\07" specifies two binary zeros followed by a BEL character. Make sure you supply two digits after the initial zero if the character that follows is itself an octal digit.

The handling of a backslash followed by a digit other than 0 is complicated. Outside a character class, PCRE reads it and any following digits as a decimal number. If the number is less than 10, or if there have been at least that many previous capturing left parentheses in the expression, the entire sequence is taken as a back reference. A description of how this works is given later, following the discussion of parenthesized subpatterns.

Inside a character class, or if the decimal number is greater than 9 and there have not been that many capturing subpatterns, PCRE re-reads up to three octal digits following the backslash, and generates a single byte from the least significant 8 bits of the value. Any subsequent digits stand for themselves. For example:

\040

is another way of writing a space

\40

is the same, provided there are fewer than 40 previous capturing subpatterns

\7

is always a back reference

\11

might be a back reference, or another way of writing a tab

\011

is always a tab

\0113

is a tab followed by the character "3"

\113

is the character with octal code 113 (since there can be no more than 99 back references)

\377

is a byte consisting entirely of 1 bits

\81

is either a back reference, or a binary zero followed by the two characters "8" and "1"

Note that octal values of 100 or greater must not be intro- duced by a leading zero, because no more than three octal digits are ever read.

All the sequences that define a single byte value can be used both inside and outside character classes. In addition, inside a character class, the sequence "\b" is interpreted as the backspace character (hex 08). Outside a character class it has a different meaning (see below).

The third use of backslash is for specifying generic charac- ter types:

\d

any decimal digit

\D

any character that is not a decimal digit

\s

any whitespace character

\S

any character that is not a whitespace character

\w

any "word" character

\W

any "non-word" character

Each pair of escape sequences partitions the complete set of characters into two disjoint sets. Any given character matches one, and only one, of each pair.

A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a Perl "word". The definition of letters and digits is controlled by PCRE's character tables, and may vary if locale-specific matching is taking place (see "Locale support" above). For example, in the "fr" (French) locale, some char- acter codes greater than 128 are used for accented letters, and these are matched by \w.

These character type sequences can appear both inside and outside character classes. They each match one character of the appropriate type. If the current matching point is at the end of the subject string, all of them fail, since there is no character to match.

The fourth use of backslash is for certain simple asser- tions. An assertion specifies a condition that has to be met at a particular point in a match, without consuming any characters from the subject string. The use of subpatterns for more complicated assertions is described below. The backslashed assertions are

\b

word boundary

\B

not a word boundary

\A

start of subject (independent of multiline mode)

\Z

end of subject or newline at end (independent of multiline mode)

\z

end of subject(independent of multiline mode)

These assertions may not appear in character classes (but note that "\b" has a different meaning, namely the backspace character, inside a character class).

A word boundary is a position in the subject string where the current character and the previous character do not both match \w or \W (i.e. one matches \w and the other matches \W), or the start or end of the string if the first or last character matches \w, respectively.

The \A, \Z, and \z assertions differ from the traditional circumflex and dollar (described below) in that they only ever match at the very start and end of the subject string, whatever options are set. They are not affected by the PCRE_NOTBOL or PCRE_NOTEOL options. The difference between \Z and \z is that \Z matches before a newline that is the last character of the string as well as at the end of the string, whereas \z matches only at the end.

Circumflex and dollar

Outside a character class, in the default matching mode, the
circumflex character is an assertion which is true only if
the current matching point is at the start of the subject
string. Inside a character class, circumflex has an entirely
different meaning (see below).

Circumflex need not be the first character of the pattern if
a number of alternatives are involved, but it should be the
first thing in each alternative in which it appears if the
pattern is ever to match that branch. If all possible alter-
natives start with a circumflex, that is, if the pattern is
constrained to match only at the start of the subject, it is
said to be an "anchored" pattern. (There are also other con-
structs that can cause a pattern to be anchored.)

A dollar character is an assertion which is TRUE only if the
current matching point is at the end of the subject string,
or immediately before a newline character that is the last
character in the string (by default). Dollar need not be the
last character of the pattern if a number of alternatives
are involved, but it should be the last item in any branch
in which it appears. Dollar has no special meaning in a
character class.

The meaning of dollar can be changed so that it matches only
at the very end of the string, by setting the
PCRE_DOLLAR_ENDONLY
option at compile or matching time. This
does not affect the \Z assertion.

The meanings of the circumflex and dollar characters are
changed if the PCRE_MULTILINE option is set. When this is
the case, they match immediately after and immediately
before an internal "\n" character, respectively, in addition
to matching at the start and end of the subject string. For
example, the pattern /^abc$/ matches the subject string
"def\nabc" in multiline mode, but not otherwise. Conse-
quently, patterns that are anchored in single line mode
because all branches start with "^" are not anchored in mul-
tiline mode. The PCRE_DOLLAR_ENDONLY option is ignored if
PCRE_MULTILINE is set.

Note that the sequences \A, \Z, and \z can be used to match
the start and end of the subject in both modes, and if all
branches of a pattern start with \A is it always anchored,
whether PCRE_MULTILINE is set or not.

FULL STOP

Outside a character class, a dot in the pattern matches any
one character in the subject, including a non-printing
character, but not (by default) newline. If the PCRE_DOTALL
option is set, then dots match newlines as well. The han-
dling of dot is entirely independent of the handling of cir-
cumflex and dollar, the only relationship being that they
both involve newline characters. Dot has no special meaning
in a character class.

Square brackets

An opening square bracket introduces a character class, ter-
minated by a closing square bracket. A closing square
bracket on its own is not special. If a closing square
bracket is required as a member of the class, it should be
the first data character in the class (after an initial cir-
cumflex, if present) or escaped with a backslash.

A character class matches a single character in the subject;
the character must be in the set of characters defined by
the class, unless the first character in the class is a cir-
cumflex, in which case the subject character must not be in
the set defined by the class. If a circumflex is actually
required as a member of the class, ensure it is not the
first character, or escape it with a backslash.

For example, the character class [aeiou] matches any lower
case vowel, while [^aeiou] matches any character that is not
a lower case vowel. Note that a circumflex is just a con-
venient notation for specifying the characters which are in
the class by enumerating those that are not. It is not an
assertion: it still consumes a character from the subject
string, and fails if the current pointer is at the end of
the string.

When caseless matching is set, any letters in a class
represent both their upper case and lower case versions, so
for example, a caseless [aeiou] matches "A" as well as "a",
and a caseless [^aeiou] does not match "A", whereas a case-
ful version would.

The newline character is never treated in any special way in
character classes, whatever the setting of the PCRE_DOTALL
or PCRE_MULTILINE options is. A class such as [^a] will
always match a newline.

The minus (hyphen) character can be used to specify a range
of characters in a character class. For example, [d-m]
matches any letter between d and m, inclusive. If a minus
character is required in a class, it must be escaped with a
backslash or appear in a position where it cannot be inter-
preted as indicating a range, typically as the first or last
character in the class.

It is not possible to have the literal character "]" as the
end character of a range. A pattern such as [W-]46] is
interpreted as a class of two characters ("W" and "-") fol-
lowed by a literal string "46]", so it would match "W46]" or
"-46]". However, if the "]" is escaped with a backslash it
is interpreted as the end of range, so [W-\]46] is inter-
preted as a single class containing a range followed by two
separate characters. The octal or hexadecimal representation
of "]" can also be used to end a range.

Ranges operate in ASCII collating sequence. They can also be
used for characters specified numerically, for example
[\000-\037]. If a range that includes letters is used when
caseless matching is set, it matches the letters in either
case. For example, [W-c] is equivalent to [][\^_`wxyzabc],
matched caselessly, and if character tables for the "fr"
locale are in use, [\xc8-\xcb] matches accented E characters
in both cases.

The character types \d, \D, \s, \S, \w, and \W may also
appear in a character class, and add the characters that
they match to the class. For example, [\dABCDEF] matches any
hexadecimal digit. A circumflex can conveniently be used
with the upper case character types to specify a more res-
tricted set of characters than the matching lower case type.
For example, the class [^\W_] matches any letter or digit,
but not underscore.

All non-alphanumeric characters other than \, -, ^ (at the
start) and the terminating ] are non-special in character
classes, but it does no harm if they are escaped.

Vertical bar

Vertical bar characters are used to separate alternative
patterns. For example, the pattern

gilbert|sullivan

matches either "gilbert" or "sullivan". Any number of alternatives
may appear, and an empty alternative is permitted
(matching the empty string). The matching process tries
each alternative in turn, from left to right, and the first
one that succeeds is used. If the alternatives are within a
subpattern (defined below), "succeeds" means matching the
rest of the main pattern as well as the alternative in the
subpattern.

Internal option setting

The settings of PCRE_CASELESS ,
PCRE_MULTILINE ,
PCRE_DOTALL ,
and PCRE_EXTENDED can be changed from within the pattern by
a sequence of Perl option letters enclosed between "(?" and
")". The option letters are

i for PCRE_CASELESS
m for PCRE_MULTILINE
s for PCRE_DOTALL
x for PCRE_EXTENDED

For example, (?im) sets caseless, multiline matching. It is
also possible to unset these options by preceding the letter
with a hyphen, and a combined setting and unsetting such as
(?im-sx), which sets PCRE_CASELESS and PCRE_MULTILINE while
unsetting PCRE_DOTALL and PCRE_EXTENDED , is also permitted.
If a letter appears both before and after the hyphen, the
option is unset.

The scope of these option changes depends on where in the
pattern the setting occurs. For settings that are outside
any subpattern (defined below), the effect is the same as if
the options were set or unset at the start of matching. The
following patterns all behave in exactly the same way:

(?i)abc
a(?i)bc
ab(?i)c
abc(?i)

which in turn is the same as compiling the pattern abc with
PCRE_CASELESS set.
In other words, such "top level" settings apply to the whole
pattern (unless there are other changes inside subpatterns).
If there is more than one setting of the same option at top level,
the rightmost setting is used.

If an option change occurs inside a subpattern, the effect
is different. This is a change of behaviour in Perl 5.005.
An option change inside a subpattern affects only that part
of the subpattern that follows it, so

(a(?i)b)c

matches abc and aBc and no other strings (assuming
PCRE_CASELESS is not used). By this means, options can be
made to have different settings in different parts of the
pattern. Any changes made in one alternative do carry on
into subsequent branches within the same subpattern. For
example,

(a(?i)b|c)

matches "ab", "aB", "c", and "C", even though when matching
"C" the first branch is abandoned before the option setting.
This is because the effects of option settings happen at
compile time. There would be some very weird behaviour otherwise.

The PCRE-specific options PCRE_UNGREEDY and
PCRE_EXTRA can
be changed in the same way as the Perl-compatible options by
using the characters U and X respectively. The (?X) flag
setting is special in that it must always occur earlier in
the pattern than any of the additional features it turns on,
even when it is at top level. It is best put at the start.

subpatterns

Subpatterns are delimited by parentheses (round brackets),
which can be nested. Marking part of a pattern as a subpattern
does two things:

1. It localizes a set of alternatives. For example, the pat-
tern

cat(aract|erpillar|)

matches one of the words "cat", "cataract", or "caterpillar".
Without the parentheses, it would match "cataract",
"erpillar" or the empty string.

2. It sets up the subpattern as a capturing subpattern (as
defined above). When the whole pattern matches, that portion
of the subject string that matched the subpattern is
passed back to the caller via the ovector
argument of
pcre_exec(). Opening parentheses are counted
from left to right (starting from 1) to obtain the numbers of the
capturing subpatterns.

For example, if the string "the red king" is matched against
the pattern

the ((red|white) (king|queen))

the captured substrings are "red king", "red", and "king",
and are numbered 1, 2, and 3.

The fact that plain parentheses fulfil two functions is not
always helpful. There are often times when a grouping subpattern
is required without a capturing requirement. If an
opening parenthesis is followed by "?:", the subpattern does
not do any capturing, and is not counted when computing the
number of any subsequent capturing subpatterns. For example,
if the string "the white queen" is matched against the
pattern

the ((?:red|white) (king|queen))

the captured substrings are "white queen" and "queen", and
are numbered 1 and 2. The maximum number of captured substrings
is 99, and the maximum number of all subpatterns,
both capturing and non-capturing, is 200.

As a convenient shorthand, if any option settings are
required at the start of a non-capturing subpattern, the
option letters may appear between the "?" and the ":". Thus
the two patterns

(?i:saturday|sunday)
(?:(?i)saturday|sunday)

match exactly the same set of strings. Because alternative
branches are tried from left to right, and options are not
reset until the end of the subpattern is reached, an option
setting in one branch does affect subsequent branches, so
the above patterns match "SUNDAY" as well as "Saturday".

Repetition

Repetition is specified by quantifiers, which can follow any
of the following items:

a single character, possibly escaped
the . metacharacter
a character class
a back reference (see next section)
a parenthesized subpattern (unless it is an assertion -
see below)

The general repetition quantifier specifies a minimum and
maximum number of permitted matches, by giving the two
numbers in curly brackets (braces), separated by a comma.
The numbers must be less than 65536, and the first must be
less than or equal to the second. For example:

z{2,4}

matches "zz", "zzz", or "zzzz". A closing brace on its own
is not a special character. If the second number is omitted,
but the comma is present, there is no upper limit; if the
second number and the comma are both omitted, the quantifier
specifies an exact number of required matches. Thus

[aeiou]{3,}

matches at least 3 successive vowels, but may match many
more, while

\d{8}

matches exactly 8 digits. An opening curly bracket that
appears in a position where a quantifier is not allowed, or
one that does not match the syntax of a quantifier, is taken
as a literal character. For example, {,6} is not a quantifier,
but a literal string of four characters.

The quantifier {0} is permitted, causing the expression to
behave as if the previous item and the quantifier were not
present.

For convenience (and historical compatibility) the three
most common quantifiers have single-character abbreviations:

* is equivalent to {0,}
+ is equivalent to {1,}
? is equivalent to {0,1}

It is possible to construct infinite loops by following a
subpattern that can match no characters with a quantifier
that has no upper limit, for example:

(a?)*

Earlier versions of Perl and PCRE used to give an error at
compile time for such patterns. However, because there are
cases where this can be useful, such patterns are now
accepted, but if any repetition of the subpattern does in
fact match no characters, the loop is forcibly broken.

By default, the quantifiers are "greedy", that is, they
match as much as possible (up to the maximum number of permitted
times), without causing the rest of the pattern to
fail. The classic example of where this gives problems is in
trying to match comments in C programs. These appear between
the sequences /* and */ and within the sequence, individual
* and / characters may appear. An attempt to match C comments
by applying the pattern

/\*.*\*/

to the string

/* first command */ not comment /* second comment */

fails, because it matches the entire string due to the
greediness of the .* item.

However, if a quantifier is followed by a question mark,
then it ceases to be greedy, and instead matches the minimum
number of times possible, so the pattern

/\*.*?\*/

does the right thing with the C comments. The meaning of the
various quantifiers is not otherwise changed, just the preferred
number of matches. Do not confuse this use of ques-
tion mark with its use as a quantifier in its own right.
Because it has two uses, it can sometimes appear doubled, as
in

\d??\d

which matches one digit by preference, but can match two if
that is the only way the rest of the pattern matches.

If the PCRE_UNGREEDY option is set (an option which is not
available in Perl) then the quantifiers are not greedy by
default, but individual ones can be made greedy by following
them with a question mark. In other words, it inverts the
default behaviour.

When a parenthesized subpattern is quantified with a minimum
repeat count that is greater than 1 or with a limited maximum,
more store is required for the compiled pattern, in
proportion to the size of the minimum or maximum.

If a pattern starts with .* or .{0,} and the PCRE_DOTALL
option (equivalent to Perl's /s) is set, thus allowing the .
to match newlines, then the pattern is implicitly anchored,
because whatever follows will be tried against every character
position in the subject string, so there is no point in
retrying the overall match at any position after the first.
PCRE treats such a pattern as though it were preceded by \A.
In cases where it is known that the subject string contains
no newlines, it is worth setting PCRE_DOTALL when the pattern begins with .* in order to
obtain this optimization, or
alternatively using ^ to indicate anchoring explicitly.

When a capturing subpattern is repeated, the value captured
is the substring that matched the final iteration. For example, after

(tweedle[dume]{3}\s*)+

has matched "tweedledum tweedledee" the value of the captured
substring is "tweedledee". However, if there are
nested capturing subpatterns, the corresponding captured
values may have been set in previous iterations. For example,
after

/(a|(b))+/

matches "aba" the value of the second captured substring is
"b".

BACK REFERENCES

Outside a character class, a backslash followed by a digit
greater than 0 (and possibly further digits) is a back
reference to a capturing subpattern earlier (i.e. to its
left) in the pattern, provided there have been that many
previous capturing left parentheses.

However, if the decimal number following the backslash is
less than 10, it is always taken as a back reference, and
causes an error only if there are not that many capturing
left parentheses in the entire pattern. In other words, the
parentheses that are referenced need not be to the left of
the reference for numbers less than 10. See the section
entitled "Backslash" above for further details of the handling
of digits following a backslash.

A back reference matches whatever actually matched the capturing
subpattern in the current subject string, rather than
anything matching the subpattern itself. So the pattern

(sens|respons)e and \1ibility

matches "sense and sensibility" and "response and responsibility",
but not "sense and responsibility". If caseful
matching is in force at the time of the back reference, then
the case of letters is relevant. For example,

((?i)rah)\s+\1

matches "rah rah" and "RAH RAH", but not "RAH rah", even
though the original capturing subpattern is matched caselessly.

There may be more than one back reference to the same subpattern.
If a subpattern has not actually been used in a
particular match, then any back references to it always
fail. For example, the pattern

(a|(bc))\2

always fails if it starts to match "a" rather than "bc".
Because there may be up to 99 back references, all digits
following the backslash are taken as part of a potential
back reference number. If the pattern continues with a digit
character, then some delimiter must be used to terminate the
back reference. If the PCRE_EXTENDED option is set, this can
be whitespace. Otherwise an empty comment can be used.

A back reference that occurs inside the parentheses to which
it refers fails when the subpattern is first used, so, for
example, (a\1) never matches. However, such references can
be useful inside repeated subpatterns. For example, the pattern

(a|b\1)+

matches any number of "a"s and also "aba", "ababaa" etc. At
each iteration of the subpattern, the back reference matches
the character string corresponding to the previous iteration.
In order for this to work, the pattern must be such
that the first iteration does not need to match the back
reference. This can be done using alternation, as in the
example above, or by a quantifier with a minimum of zero.

Assertions

An assertion is a test on the characters following or
preceding the current matching point that does not actually
consume any characters. The simple assertions coded as \b,
\B, \A, \Z, \z, ^ and $ are described above. More complicated
assertions are coded as subpatterns. There are two
kinds: those that look ahead of the current position in the
subject string, and those that look behind it.

An assertion subpattern is matched in the normal way, except
that it does not cause the current matching position to be
changed. Lookahead assertions start with (?= for positive
assertions and (?! for negative assertions. For example,

\w+(?=;)

matches a word followed by a semicolon, but does not include
the semicolon in the match, and

foo(?!bar)

matches any occurrence of "foo" that is not followed by
"bar". Note that the apparently similar pattern

(?!foo)bar

does not find an occurrence of "bar" that is preceded by
something other than "foo"; it finds any occurrence of "bar"
whatsoever, because the assertion (?!foo) is always TRUE
when the next three characters are "bar". A lookbehind
assertion is needed to achieve this effect.

Lookbehind assertions start with (?<= for positive assertions
and (?<! for negative assertions. For example,

(?<!foo)bar

does find an occurrence of "bar" that is not preceded by
"foo". The contents of a lookbehind assertion are restricted
such that all the strings it matches must have a fixed
length. However, if there are several alternatives, they do
not all have to have the same fixed length. Thus

(?<=bullock|donkey)

is permitted, but

(?<!dogs?|cats?)

causes an error at compile time. Branches that match different
length strings are permitted only at the top level of
a lookbehind assertion. This is an extension compared with
Perl 5.005, which requires all branches to match the same
length of string. An assertion such as

(?<=ab(c|de))

is not permitted, because its single top-level branch can
match two different lengths, but it is acceptable if rewritten
to use two top-level branches:

(?<=abc|abde)

The implementation of lookbehind assertions is, for each
alternative, to temporarily move the current position back
by the fixed width and then try to match. If there are
insufficient characters before the current position, the
match is deemed to fail. Lookbehinds in conjunction with
once-only subpatterns can be particularly useful for matching
at the ends of strings; an example is given at the end
of the section on once-only subpatterns.

Several assertions (of any sort) may occur in succession.
For example,

(?<=\d{3})(?<!999)foo

matches "foo" preceded by three digits that are not "999".
Notice that each of the assertions is applied independently
at the same point in the subject string. First there is a
check that the previous three characters are all digits,
then there is a check that the same three characters are not
"999". This pattern does not match "foo" preceded by six
characters, the first of which are digits and the last three
of which are not "999". For example, it doesn't match
"123abcfoo". A pattern to do that is

(?<=\d{3}...)(?<!999)foo

This time the first assertion looks at the preceding six
characters, checking that the first three are digits, and
then the second assertion checks that the preceding three
characters are not "999".

Assertions can be nested in any combination. For example,

(?<=(?<!foo)bar)baz

matches an occurrence of "baz" that is preceded by "bar"
which in turn is not preceded by "foo", while

(?<=\d{3}(?!999)...)foo

is another pattern which matches "foo" preceded by three
digits and any three characters that are not "999".

Assertion subpatterns are not capturing subpatterns, and may
not be repeated, because it makes no sense to assert the
same thing several times. If any kind of assertion contains
capturing subpatterns within it, these are counted for the
purposes of numbering the capturing subpatterns in the whole
pattern. However, substring capturing is carried out only
for positive assertions, because it does not make sense for
negative assertions.

Assertions count towards the maximum of 200 parenthesized
subpatterns.

Once-only subpatterns

With both maximizing and minimizing repetition, failure of
what follows normally causes the repeated item to be re-
evaluated to see if a different number of repeats allows the
rest of the pattern to match. Sometimes it is useful to
prevent this, either to change the nature of the match, or
to cause it fail earlier than it otherwise might, when the
author of the pattern knows there is no point in carrying
on.

Consider, for example, the pattern \d+foo when applied to
the subject line

123456bar

After matching all 6 digits and then failing to match "foo",
the normal action of the matcher is to try again with only 5
digits matching the \d+ item, and then with 4, and so on,
before ultimately failing. Once-only subpatterns provide the
means for specifying that once a portion of the pattern has
matched, it is not to be re-evaluated in this way, so the
matcher would give up immediately on failing to match "foo"
the first time. The notation is another kind of special
parenthesis, starting with (?> as in this example:

(?>\d+)bar

This kind of parenthesis "locks up" the part of the pattern
it contains once it has matched, and a failure further into
the pattern is prevented from backtracking into it. Back-
tracking past it to previous items, however, works as normal.

An alternative description is that a subpattern of this type
matches the string of characters that an identical standalone
pattern would match, if anchored at the current point
in the subject string.

Once-only subpatterns are not capturing subpatterns. Simple
cases such as the above example can be thought of as a maximizing
repeat that must swallow everything it can. So,
while both \d+ and \d+? are prepared to adjust the number of
digits they match in order to make the rest of the pattern
match, (?>\d+) can only match an entire sequence of digits.

This construction can of course contain arbitrarily complicated
subpatterns, and it can be nested.

Once-only subpatterns can be used in conjunction with look-
behind assertions to specify efficient matching at the end
of the subject string. Consider a simple pattern such as

abcd$

when applied to a long string which does not match. Because
matching proceeds from left to right, PCRE will look for
each "a" in the subject and then see if what follows matches
the rest of the pattern. If the pattern is specified as

^.*abcd$

then the initial .* matches the entire string at first, but
when this fails (because there is no following "a"), it
backtracks to match all but the last character, then all but
the last two characters, and so on. Once again the search
for "a" covers the entire string, from right to left, so we
are no better off. However, if the pattern is written as

^(?>.*)(?<=abcd)

then there can be no backtracking for the .* item; it can
match only the entire string. The subsequent lookbehind
assertion does a single test on the last four characters. If
it fails, the match fails immediately. For long strings,
this approach makes a significant difference to the processing time.

When a pattern contains an unlimited repeat inside a subpattern
that can itself be repeated an unlimited number of
times, the use of a once-only subpattern is the only way to
avoid some failing matches taking a very long time indeed.
The pattern

(\D+|<\d+>)*[!?]

matches an unlimited number of substrings that either consist
of non-digits, or digits enclosed in <>, followed by
either ! or ?. When it matches, it runs quickly. However, if
it is applied to

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

it takes a long time before reporting failure. This is
because the string can be divided between the two repeats in
a large number of ways, and all have to be tried. (The example
used [!?] rather than a single character at the end,
because both PCRE and Perl have an optimization that allows
for fast failure when a single character is used. They
remember the last single character that is required for a
match, and fail early if it is not present in the string.)
If the pattern is changed to

((?>\D+)|<\d+>)*[!?]

sequences of non-digits cannot be broken, and failure happens quickly.

Conditional subpatterns

It is possible to cause the matching process to obey a subpattern
conditionally or to choose between two alternative
subpatterns, depending on the result of an assertion, or
whether a previous capturing subpattern matched or not. The
two possible forms of conditional subpattern are

(?(condition)yes-pattern)
(?(condition)yes-pattern|no-pattern)

If the condition is satisfied, the yes-pattern is used; otherwise
the no-pattern (if present) is used. If there are
more than two alternatives in the subpattern, a compile-time
error occurs.

There are two kinds of condition. If the text between the
parentheses consists of a sequence of digits, then the
condition is satisfied if the capturing subpattern of that
number has previously matched. Consider the following pattern,
which contains non-significant white space to make it
more readable (assume the PCRE_EXTENDED option) and to
divide it into three parts for ease of discussion:

( \( )? [^()]+ (?(1) \) )

The first part matches an optional opening parenthesis, and
if that character is present, sets it as the first captured
substring. The second part matches one or more characters
that are not parentheses. The third part is a conditional
subpattern that tests whether the first set of parentheses
matched or not. If they did, that is, if subject started
with an opening parenthesis, the condition is TRUE, and so
the yes-pattern is executed and a closing parenthesis is
required. Otherwise, since no-pattern is not present, the
subpattern matches nothing. In other words, this pattern
matches a sequence of non-parentheses, optionally enclosed
in parentheses.

If the condition is not a sequence of digits, it must be an
assertion. This may be a positive or negative lookahead or
lookbehind assertion. Consider this pattern, again containing
non-significant white space, and with the two alternatives on
the second line:

(?(?=[^a-z]*[a-z])
\d{2}-[a-z]{3}-\d{2} | \d{2}-\d{2}-\d{2} )

The condition is a positive lookahead assertion that matches
an optional sequence of non-letters followed by a letter. In
other words, it tests for the presence of at least one
letter in the subject. If a letter is found, the subject is
matched against the first alternative; otherwise it is
matched against the second. This pattern matches strings in
one of the two forms dd-aaa-dd or dd-dd-dd, where aaa are
letters and dd are digits.

Comments

The sequence (?# marks the start of a comment which
continues up to the next closing parenthesis. Nested
parentheses are not permitted. The characters that make up a
comment play no part in the pattern matching at all.

If the PCRE_EXTENDED option is set, an unescaped # character
outside a character class introduces a comment that contin-
ues up to the next newline character in the pattern.

Recursive patterns

Consider the problem of matching a string in parentheses,
allowing for unlimited nested parentheses. Without the use
of recursion, the best that can be done is to use a pattern
that matches up to some fixed depth of nesting. It is not
possible to handle an arbitrary nesting depth. Perl 5.6 has
provided an experimental facility that allows regular
expressions to recurse (amongst other things). The special
item (?R) is provided for the specific case of recursion.
This PCRE pattern solves the parentheses problem (assume
the PCRE_EXTENDED
option is set so that white space is
ignored):

\( ( (?>[^()]+) | (?R) )* \)

First it matches an opening parenthesis. Then it matches any
number of substrings which can either be a sequence of non-
parentheses, or a recursive match of the pattern itself
(i.e. a correctly parenthesized substring). Finally there is
a closing parenthesis.

This particular example pattern contains nested unlimited
repeats, and so the use of a once-only subpattern for matching
strings of non-parentheses is important when applying
the pattern to strings that do not match. For example, when
it is applied to

(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()

it yields "no match" quickly. However, if a once-only subpattern
is not used, the match runs for a very long time
indeed because there are so many different ways the + and *
repeats can carve up the subject, and all have to be tested
before failure can be reported.

The values set for any capturing subpatterns are those from
the outermost level of the recursion at which the subpattern
value is set. If the pattern above is matched against

(ab(cd)ef)

the value for the capturing parentheses is "ef", which is
the last value taken on at the top level. If additional
parentheses are added, giving

\( ( ( (?>[^()]+) | (?R) )* ) \)
^ ^
^ ^ then the string they capture
is "ab(cd)ef", the contents of the top level parentheses. If
there are more than 15 capturing parentheses in a pattern,
PCRE has to obtain extra memory to store data during a
recursion, which it does by using pcre_malloc, freeing it
via pcre_free afterwards. If no memory can be obtained, it
saves data for the first 15 capturing parentheses only, as
there is no way to give an out-of-memory error from within a
recursion.

Performances

Certain items that may appear in patterns are more efficient
than others. It is more efficient to use a character class
like [aeiou] than a set of alternatives such as (a|e|i|o|u).
In general, the simplest construction that provides the
required behaviour is usually the most efficient. Jeffrey
Friedl's book contains a lot of discussion about optimizing
regular expressions for efficient performance.

When a pattern begins with .* and the PCRE_DOTALL option is
set, the pattern is implicitly anchored by PCRE, since it
can match only at the start of a subject string. However, if
PCRE_DOTALL is not set, PCRE cannot make this optimization,
because the . metacharacter does not then match a newline,
and if the subject string contains newlines, the pattern may
match from the character immediately following one of them
instead of from the very start. For example, the pattern

(.*) second

matches the subject "first\nand second" (where \n stands for
a newline character) with the first captured substring being
"and". In order to do this, PCRE has to retry the match
starting after every newline in the subject.

If you are using such a pattern with subject strings that do
not contain newlines, the best performance is obtained by
setting PCRE_DOTALL , or starting the pattern with ^.* to
indicate explicit anchoring. That saves PCRE from having to
scan along the subject looking for a newline to restart at.

Beware of patterns that contain nested indefinite repeats.
These can take a long time to run when applied to a string
that does not match. Consider the pattern fragment

(a+)*

This can match "aaaa" in 33 different ways, and this number
increases very rapidly as the string gets longer. (The *
repeat can match 0, 1, 2, 3, or 4 times, and for each of
those cases other than 0, the + repeats can match different
numbers of times.) When the remainder of the pattern is such
that the entire match is going to fail, PCRE has in principle
to try every possible variation, and this can take an
extremely long time.

An optimization catches some of the more simple cases such
as

(a+)*b

where a literal character follows. Before embarking on the
standard matching procedure, PCRE checks that there is a "b"
later in the subject string, and if there is not, it fails
the match immediately. However, when there is no following
literal this optimization cannot be used. You can see the
difference by comparing the behaviour of

(a+)*\d

with the pattern above. The former gives a failure almost
instantly when applied to a whole line of "a" characters,
whereas the latter takes an appreciable time with strings
longer than about 20 characters.

后退 | 起点 | 前进
Pattern Modifiers | 上一级 | preg_grep


preg_grep

(PHP 4 )

preg_grep -- Return array entries that match the pattern

Description

array preg_grep ( string pattern, array input)

preg_grep() returns the array consisting of the elements of the input array that match the given pattern.

Since PHP 4.0.4, the results returned by preg_grep() are indexed using the keys from the input array. If this behavior is undesirable, use array_values() on the array returned by preg_grep() to reindex the values.

例子 1. preg_grep() example

// return all array elements
// containing floating point numbers
$fl_array = preg_grep ("/^(\d+)?\.\d+$/", $array);

后退 | 起点 | 前进
Pattern Syntax | 上一级 | preg_match_all


preg_match_all

(PHP 3>= 3.0.9, PHP 4 )

preg_match_all -- Perform a global regular expression match

Description

int preg_match_all ( string pattern, string subject, array matches [, int flags])

Searches subject for all matches to the regular expression given in pattern and puts them in matches in the order specified by order.

After the first match is found, the subsequent searches are continued on from end of the last match.

flags can be a combination of the following flags (note that it doesn't make sense to use PREG_PATTERN_ORDER together with PREG_SET_ORDER):

PREG_PATTERN_ORDER

Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on.

preg_match_all ("|<[^>]+>(.*)</[^>]+>|U",
    "<b>example: </b><div align=left>this is a test</div>",
    $out, PREG_PATTERN_ORDER);
print $out[0][0].", ".$out[0][1]."\n";
print $out[1][0].", ".$out[1][1]."\n";

This example will produce:
<b>example: </b>, <div align=left>this is a test</div>
example: , this is a test
So, $out[0] contains array of strings that matched full pattern, and $out[1] contains array of strings enclosed by tags.

PREG_SET_ORDER

Orders results so that $matches[0] is an array of first set of matches, $matches[1] is an array of second set of matches, and so on.

preg_match_all ("|<[^>]+>(.*)</[^>]+>|U",
    "<b>example: </b><div align=left>this is a test</div>",
    $out, PREG_SET_ORDER);
print $out[0][0].", ".$out[0][1]."\n";
print $out[1][0].", ".$out[1][1]."\n";

This example will produce:

<b>example: </b>, example:
<div align=left>this is a test</div>, this is a test

In this case, $matches[0] is the first set of matches, and $matches[0][0] has text matched by full pattern, $matches[0][1] has text matched by first subpattern and so on. Similarly, $matches[1] is the second set of matches, etc.

PREG_OFFSET_CAPTURE

If this flag is set, for every occuring match the appendant string offset will also be returned. Note that this changes the return value in an array where every element is an array consisting of the matched string at offset 0 and it's string offset into subject at offset 1. This flag is available since PHP 4.3.0 .

If no order flag is given, PREG_PATTERN_ORDER is assumed.

Returns the number of full pattern matches (which might be zero), or FALSE if an error occurred.

例子 1. Getting all phone numbers out of some text.

preg_match_all ("/\(?  (\d{3})?  \)?  (?(1)  [\-\s] ) \d{3}-\d{4}/x",
                "Call 555-1212 or 1-800-555-1212", $phones);

例子 2. Find matching HTML tags (greedy)

// The \\2 is an example of backreferencing. This tells pcre that
// it must match the second set of parentheses in the regular expression
// itself, which would be the ([\w]+) in this case. The extra backslash is
// required because the string is in double quotes.
$html = "<b>bold text</b><a href=howdy.html>click me</a>";

preg_match_all ("/(<([\w]+)[^>]*>)(.*)(<\/\\2>)/", $html, $matches);

for ($i=0; $i< count($matches[0]); $i++) {
  echo "matched: ".$matches[0][$i]."\n";
  echo "part 1: ".$matches[1][$i]."\n";
  echo "part 2: ".$matches[3][$i]."\n";
  echo "part 3: ".$matches[4][$i]."\n\n";
}
This example will produce:
matched: <b>bold text</b>
part 1: <b>
part 2: bold text
part 3: </b>

matched: <a href=howdy.html>click me</a>
part 1: <a href=howdy.html>
part 2: click me
part 3: </a>

See also preg_match(),
preg_replace(),
and preg_split().

后退 | 起点 | 前进
preg_grep | 上一级 | preg_match


preg_match

(PHP 3>= 3.0.9, PHP 4 )

preg_match -- Perform a regular expression match

Description

int preg_match ( string pattern, string subject [, array matches [, int flags]])

Searches subject for a match to the regular expression given in pattern.

If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.

flags can be the following flag:

PREG_OFFSET_CAPTURE

If this flag is set, for every occuring match the appendant string offset will also be returned. Note that this changes the return value in an array where every element is an array consisting of the matched string at offset 0 and it's string offset into subject at offset 1. This flag is available since PHP 4.3.0 .

The flags parameter is available since PHP 4.3.0 .

preg_match() returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match. preg_match_all() on the contrary will continue until it reaches the end of subject. preg_match() returns FALSE if an error occured.

例子 1. Find the string of text "php"

// the "i" after the pattern delimiter indicates a case-insensitive search
if (preg_match ("/php/i", "PHP is the web scripting language of choice.")) {
    print "A match was found.";
} else {
    print "A match was not found.";
}

例子 2. find the word "web"

// the \b in the pattern indicates a word boundary, so only the distinct
// word "web" is matched, and not a word partial like "webbing" or "cobweb"
if (preg_match ("/\bweb\b/i", "PHP is the web scripting language of choice.")) {
    print "A match was found.";
} else {
    print "A match was not found.";
}
if (preg_match ("/\bweb\b/i", "PHP is the website scripting language of choice.")) {
    print "A match was found.";
} else {
    print "A match was not found.";
}

例子 3. Getting the domain name out of a URL

// get host name from URL
preg_match("/^(http:\/\/)?([^\/]+)/i",
"http://www.php.net/index.html", $matches);
$host = $matches[2];
// get last two segments of host name
preg_match("/[^\.\/]+\.[^\.\/]+$/",$host,$matches);
echo "domain name is: ".$matches[0]."\n";

This example will produce:
domain name is: php.net

See also preg_match_all(), preg_replace(), and preg_split().

后退 | 起点 | 前进
preg_match_all | 上一级 | preg_quote


preg_quote

(PHP 3>= 3.0.9, PHP 4 )

preg_quote -- Quote regular expression characters

Description

string preg_quote ( string str [, string delimiter])

preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.

If the optional delimiter is specified, it will also be escaped. This is useful for escaping the delimiter that is required by the PCRE functions. The / is the most commonly used delimiter.

The special regular expression characters are:
. \\ + * ? [ ^ ] $ ( ) { } = ! < > | :

例子 1.

$keywords = "$40 for a g3/400";
$keywords = preg_quote ($keywords, "/");
echo $keywords; // returns \$40 for a g3\/400

例子 2. Italicizing a word within some text

// In this example, preg_quote($word) is used to keep the
// asterisks from having special meaning to the regular
// expression.

$textbody = "This book is *very* difficult to find.";
$word = "*very*";
$textbody = preg_replace ("/".preg_quote($word)."/",
                          "<i>".$word."</i>",
                          $textbody);

后退 | 起点 | 前进
preg_match | 上一级 | preg_replace_callback


preg_replace_callback

(PHP 4 >= 4.0.5)

preg_replace_callback -- Perform a regular expression search and replace using a callback

Description

mixed preg_replace_callback ( mixed pattern, mixed callback, mixed subject [, int limit])

The behavior of this function is almost identical to preg_replace(), except for the fact that instead of replacement parameter, one should specify a callback that will be called and passed an array of matched elements in the subject string. The callback should return the replacement string. This function was added in PHP 4.0.5.

See also preg_replace().

后退 | 起点 | 前进
preg_quote | 上一级 | preg_replace


preg_replace

(PHP 3>= 3.0.9, PHP 4 )

preg_replace -- Perform a regular expression search and replace

Description

mixed preg_replace ( mixed pattern, mixed replacement, mixed subject [, int limit])

Searches subject for matches to pattern and replaces them with replacement. If limit is specified, then only limit matches will be replaced; if limit is omitted or is -1, then all matches are replaced.

Replacement may contain references of the form \\n or (since PHP 4.0.4) $n, with the latter form being the preferred one. Every such reference will be replaced by the text captured by the n'th parenthesized pattern. n can be from 0 to 99, and \\0 or $0 refers to the text matched by the whole pattern. Opening parentheses are counted from left to right (starting from 1) to obtain the number of the capturing subpattern.

If matches are found, the new subject will be returned, otherwise subject will be returned unchanged.

Every parameter to preg_replace() (except limit) can be an array.

If subject is an array, then the search and replace is performed on every entry of subject, and the return value is an array as well.

If pattern and replacement are arrays, then preg_replace() takes a value from each array and uses them to do search and replace on subject. If replacement has fewer values than pattern, then empty string is used for the rest of replacement values. If pattern is an array and replacement is a string, then this replacement string is used for every value of pattern. The converse would not make sense, though.

/e modifier makes preg_replace() treat the replacement parameter as PHP code after the appropriate references substitution is done. Tip: make sure that replacement constitutes a valid PHP code string, otherwise PHP will complain about a parse error at the line containing preg_replace().

例子 1. Replacing several values

$patterns = array ("/(19|20)(\d{2})-(\d{1,2})-(\d{1,2})/",
                   "/^\s*{(\w+)}\s*=/");
$replace = array ("\\3/\\4/\\1\\2", "$\\1 =");
print preg_replace ($patterns, $replace, "{startDate} = 1999-5-27");
This example will produce:
$startDate = 5/27/1999

例子 2. Using /e modifier

preg_replace ("/(<\/?)(\w+)([^>]*>)/e",
              "'\\1'.strtoupper('\\2').'\\3'",
              $html_body);

This would capitalize all HTML tags in the input text.

例子 3. Convert HTML to text

// $document should contain an HTML document.
// This will remove HTML tags, javascript sections
// and white space. It will also convert some
// common HTML entities to their text equivalent.

$search = array ("'<script[^>]*?>.*?</script>'si",  // Strip out javascript
                 "'<[\/\!]*?[^<>]*?>'si",           // Strip out html tags
                 "'([\r\n])[\s]+'",                 // Strip out white space
                 "'&(quot|#34);'i",                 // Replace html entities
                 "'&(amp|#38);'i",
                 "'&(lt|#60);'i",
                 "'&(gt|#62);'i",
                 "'&(nbsp|#160);'i",
                 "'&(iexcl|#161);'i",
                 "'&(cent|#162);'i",
                 "'&(pound|#163);'i",
                 "'&(copy|#169);'i",
                 "'&#(\d+);'e");                    // evaluate as php

$replace = array ("",
                  "",
                  "\\1",
                  "\"",
                  "&",
                  "<",
                  ">",
                  " ",
                  chr(161),
                  chr(162),
                  chr(163),
                  chr(169),
                  "chr(\\1)");

$text = preg_replace ($search, $replace, $document);

注: Parameter limit was added after PHP 4.0.1pl2.

See also preg_match(),
preg_match_all(), and
preg_split().

后退 | 起点 | 前进
preg_replace_callback | 上一级 | preg_split


preg_split

(PHP 3>= 3.0.9, PHP 4 )

preg_split -- Split string by a regular expression

Description

array preg_split ( string pattern, string subject [, int limit [, int flags]])

注: Parameter flags was added in PHP 4 Beta 3.

Returns an array containing substrings of subject split along boundaries matched by pattern.

If limit is specified, then only substrings up to limit are returned, and if limit is -1, it actually means "no limit", which is useful for specifying the flags.

flags can be any combination of the following flags (combined with bitwise | operator):

PREG_SPLIT_NO_EMPTY

If this flag is set, only non-empty pieces will be returned by preg_split().

PREG_SPLIT_DELIM_CAPTURE

If this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well. This flag was added for 4.0.5.

PREG_SPLIT_OFFSET_CAPTURE

If this flag is set, for every occuring match the appendant string offset will also be returned. Note that this changes the return value in an array where every element is an array consisting of the matched string at offset 0 and it's string offset into subject at offset 1. This flag is available since PHP 4.3.0 .

例子 1. preg_split() example : Get the parts of a search string.

// split the phrase by any number of commas or space characters,
// which include " ", \r, \t, \n and \f
$keywords = preg_split ("/[\s,]+/", "hypertext language, programming");

例子 2. Splitting a string into component characters.

$str = 'string';
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);

例子 3. Splitting a string into matches and their offsets.

$str = 'hypertext language programming';
$chars = preg_split('/ /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE);
print_r($chars);

will yield

Array
(
    [0] => Array
        (
            [0] => hypertext
            [1] => 0
        )

    [1] => Array
        (
            [0] => language
            [1] => 10
        )

    [2] => Array
        (
            [0] => programming
            [1] => 19
        )

)

See also
spliti(),
split(),
implode(),
 preg_match(),
preg_match_all(), and
preg_replace().

后退 | 起点 | 前进
preg_replace | 上一级 | qtdom functions


qtdom functions

PHP 手册
后退 前进

LXXXVIII. qtdom functions

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

目录
qdom_error — Returns the error string from the last QDOM operation or FALSE if no errors occured
qdom_tree — creates a tree of an xml string

后退 | 起点 | 前进
preg_split | 上一级 | qdom_error


qdom_error

(PHP 4 >= 4.0.5)

qdom_error -- Returns the error string from the last QDOM operation or FALSE if no errors occured

Description

string qdom_error ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
qtdom functions | 上一级 | qdom_tree


qdom_tree

(PHP 4 >= 4.0.4)

qdom_tree -- creates a tree of an xml string

Description

object qdom_tree ( string )

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
qdom_error | 上一级 | Regular Expression Functions (POSIX Extended)


Regular Expression Functions (POSIX Extended)

PHP 手册
后退 前进

LXXXIX. Regular Expression Functions (POSIX Extended)

介绍

注: PHP also supports regular expressions using a Perl-compatible syntax using the PCRE functions. Those functions support non-greedy matching, assertions, conditional subpatterns, and a number of other features not supported by the POSIX-extended regular expression syntax.

警告

These regular expression functions are not binary-safe. The PCRE functions are.

Regular expressions are used for complex string manipulation in PHP. The functions that support regular expressions are:

  • ereg()

  • ereg_replace()

  • eregi()

  • eregi_replace()

  • split()

  • spliti()

These functions all take a regular expression string as their first argument. PHP uses the POSIX extended regular expressions as defined by POSIX 1003.2. For a full description of POSIX regular expressions see the regex man pages included in the regex directory in the PHP distribution. It's in manpage format, so you'll want to do something along the lines of man /usr/local/src/regex/regex.7 in order to read it.

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

这些函数作为 PHP 核心的一部分，无需被安装即可使用。

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

范例

例子 1. Regular Expression Examples

ereg ("abc", $string);
/* Returns true if"abc"
   is found anywhere in $string. */

ereg ("^abc", $string);
/* Returns true if "abc";
   is found at the beginning of $string. */

ereg ("abc$", $string);
/* Returns true if "abc"
   is found at the end of $string. */

eregi ("(ozilla.[23]|MSIE.3)", $HTTP_USER_AGENT);
/* Returns true if client browser
   is Netscape 2, 3 or MSIE 3. */

ereg ("([[:alnum:]]+) ([[:alnum:]]+) ([[:alnum:]]+)", $string,$regs);
/* Places three space separated words
   into $regs[1], $regs[2] and $regs[3]. */

$string = ereg_replace ("^", "<br />", $string);
/* Put a <br /> tag at the beginning of $string. */

$string = ereg_replace ("$", "<br />", $string);
/* Put a <br />; tag at the end of $string. */

$string = ereg_replace ("\n", "", $string);
/* Get rid of any newline
   characters in $string. */

相关参考

For regular expressions in Perl-compatible syntax have a look at the PCRE functions.

目录
ereg_replace — Replace regular expression
ereg — Regular expression match
eregi_replace — replace regular expression case insensitive
eregi — case insensitive regular expression match
split — split string into array by regular expression
spliti — Split string into array by regular expression case insensitive
sql_regcase — Make regular expression for case insensitive match

后退 | 起点 | 前进
qdom_tree | 上一级 | ereg_replace


ereg_replace

(PHP 3, PHP 4 )

ereg_replace -- Replace regular expression

Description

string ereg_replace ( string pattern, string replacement, string string)

注: preg_replace(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to ereg_replace().

This function scans string for matches to pattern, then replaces the matched text with replacement.

The modified string is returned. (Which may mean that the original string is returned if there are no matches to be replaced.)

If pattern contains parenthesized substrings, replacement may contain substrings of the form \\digit, which will be replaced by the text matching the digit'th parenthesized substring; \\0 will produce the entire contents of string. Up to nine substrings may be used. Parentheses may be nested, in which case they are counted by the opening parenthesis.

If no matches are found in string, then string will be returned unchanged.

For example, the following code snippet prints "This was a test" three times:

例子 1. ereg_replace() Example

$string = "This is a test";
echo ereg_replace (" is", " was", $string);
echo ereg_replace ("( )is", "\\1was", $string);
echo ereg_replace ("(( )is)", "\\2was", $string);

One thing to take note of is that if you use an integer value as the replacement parameter, you may not get the results you expect. This is because ereg_replace() will interpret the number as the ordinal value of a character, and apply that. For instance:

例子 2. ereg_replace() Example

<?php
/* This will not work as expected. */
$num = 4;
$string = "This string has four words.";
$string = ereg_replace('four', $num, $string);
echo $string;   /* Output: 'This string has   words.' */

/* This will work. */
$num = '4';
$string = "This string has four words.";
$string = ereg_replace('four', $num, $string);
echo $string;   /* Output: 'This string has 4 words.' */
?>

例子 3. Replace URLs with links

$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]",
                     "<a href=\"\\0\">\\0</a>", $text);

See also ereg(), eregi(),
eregi_replace(), str_replace(),
and preg_match().

后退 | 起点 | 前进
Regular Expression Functions (POSIX Extended) | 上一级 | ereg


ereg

(PHP 3, PHP 4 )

ereg -- Regular expression match

Description

int ereg ( string pattern, string string [, array regs])

注: preg_match(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to ereg().

Searches a string for matches to the regular expression given in pattern.

If matches are found for parenthesized substrings of pattern and the function is called with the third argument regs, the matches will be stored in the elements of the array regs. $regs[1] will contain the substring which starts at the first left parenthesis; $regs[2] will contain the substring starting at the second, and so on. $regs[0] will contain a copy of the complete string matched.

注: Up to (and including) PHP 4.1.0 $regs will be filled with exactly ten elements, even though more or fewer than ten parenthesized substrings may actually have matched. This has no effect on ereg()'s ability to match more substrings. If no matches are found, $regs will not be altered by ereg().

Searching is case sensitive.

Returns TRUE if a match for pattern was found in string, or FALSE if no matches were found or an error occurred.

The following code snippet takes a date in ISO format (YYYY-MM-DD) and prints it in DD.MM.YYYY format:

例子 1. ereg() Example

if (ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $date, $regs)) {
    echo "$regs[3].$regs[2].$regs[1]";
} else {
    echo "Invalid date format: $date";
}

See also eregi(),
ereg_replace(),
eregi_replace(), and
preg_match().

后退 | 起点 | 前进
ereg_replace | 上一级 | eregi_replace


eregi_replace

(PHP 3, PHP 4 )

eregi_replace -- replace regular expression case insensitive

Description

string eregi_replace ( string pattern, string replacement, string string)

This function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters.

See also ereg(), eregi(), and ereg_replace().

后退 | 起点 | 前进
ereg | 上一级 | eregi


eregi

(PHP 3, PHP 4 )

eregi -- case insensitive regular expression match

Description

int eregi ( string pattern, string string [, array regs])

This function is identical to ereg() except that this ignores case distinction when matching alphabetic characters.

例子 1. eregi() example

if (eregi("z", $string)) {
    echo "'$string' contains a 'z' or 'Z'!";
}

See also ereg(),
ereg_replace(), and
eregi_replace().

后退 | 起点 | 前进
eregi_replace | 上一级 | split


split

(PHP 3, PHP 4 )

split -- split string into array by regular expression

Description

array split ( string pattern, string string [, int limit])

注: preg_split(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to split().

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the regular expression pattern. If limit is set, the returned array will contain a maximum of limit elements with the last element containing the whole rest of string. If an error occurs, split() returns FALSE.

To split off the first four fields from a line from /etc/passwd:

例子 1. split() Example

list($user,$pass,$uid,$gid,$extra)= split (":", $passwd_line, 5);

注: If there are n occurrences of pattern, the returned array will contain n+1 items. For example, if there is no occurrence of pattern, an array with only one element will be returned. Of course, this is also true if string is empty.

To parse a date which may be delimited with slashes, dots, or hyphens:

例子 2. split() Example

$date = "04/30/1973";  // Delimiters may be slash, dot, or hyphen
list ($month, $day, $year) = split ('[/.-]', $date);
echo "Month: $month; Day: $day; Year: $year<br>\n";

Note that pattern is case-sensitive.

Note that if you don't require the power of regular expressions, it is faster to use explode(), which doesn't incur the overhead of the regular expression engine.

For users looking for a way to emulate Perl's @chars = split('', $str) behaviour, please see the examples for preg_split().

Please note that pattern is a regular expression. If you want to split on any of the characters which are considered special by regular expressions, you'll need to escape them first. If you think split() (or any other regex function, for that matter) is doing something weird, please read the file regex.7, included in the regex/ subdirectory of the PHP distribution. It's in manpage format, so you'll want to do something along the lines of man /usr/local/src/regex/regex.7 in order to read it.

See also:
preg_split(),
 spliti(),
explode(),
implode(),
chunk_split(), and
wordwrap().

后退 | 起点 | 前进
eregi | 上一级 | spliti


spliti

(PHP 4 >= 4.0.1)

spliti -- Split string into array by regular expression case insensitive

Description

array spliti ( string pattern, string string [, int limit])

This function is identical to split() except that this ignores case distinction when matching alphabetic characters.

See also
preg_spliti(),
 split(),
explode(),
and implode().

后退 | 起点 | 前进
split | 上一级 | sql_regcase


sql_regcase

(PHP 3, PHP 4 )

sql_regcase -- Make regular expression for case insensitive match

Description

string sql_regcase ( string string)

Returns a valid regular expression which will match string, ignoring case. This expression is string with each character converted to a bracket expression; this bracket expression contains that character's uppercase and lowercase form if applicable, otherwise it contains the original character twice.

例子 1. sql_regcase() Example

echo sql_regcase ("Foo bar");
prints
[Ff][Oo][Oo] [Bb][Aa][Rr]
.

This can be used to achieve case insensitive pattern matching in products which support only case sensitive regular expressions.

后退 | 起点 | 前进
spliti | 上一级 | Semaphore, Shared Memory and IPC Functions


Semaphore, Shared Memory and IPC Functions

PHP 手册
后退 前进

XC. Semaphore, Shared Memory and IPC Functions

介绍

This module provides wrappers for the System V IPC family of functions. It includes semaphores, shared memory and inter-process messaging (IPC).

Semaphores may be used to provide exclusive access to resources on the current machine, or to limit the number of processes that may simultaneously use a resource.

This module provides also shared memory functions using System V shared memory. Shared memory may be used to provide access to global variables. Different httpd-daemons and even other programs (such as Perl, C, ...) are able to access this data to provide a global data-exchange. Remember, that shared memory is NOT safe against simultaneous access. Use semaphores for synchronization.

表格 1. Limits of Shared Memory by the Unix OS

SHMMAX | max size of shared memory, normally 131072 bytes
SHMMIN | minimum size of shared memory, normally 1 byte
SHMMNI | max amount of shared memory segments on a system, normally 100
SHMSEG | max amount of shared memory segments per process, normally 6

The messaging functions may be used to send and receive messages to/from other processes. They provide a simple and effective means of exchanging data between processes, without the need for setting up an alternative using unix domain sockets.

注: These functions do not work on Windows systems.

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

Support for this functions are not enabled by default. To ennable System V semaphore support compile PHP with the option --enable-sysvsem. To enable the System V shared memory support compile PHP with the option --enable-sysvshm. To enable the System V messages support compile PHP with the option --enable-sysvmsg.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

预定义常量

该扩展模块未定义任何常量。

目录
ftok — Convert a pathname and a project identifier to a System V IPC key
msg_get_queue — Create or attach to a message queue
msg_receive — Receive a message from a message queue
msg_remove_queue — Destroy a message queue
msg_send — Send a message to a message queue
msg_set_queue — Set information in the message queue data structure
msg_stat_queue — Returns information from the message queue data structure
sem_acquire — Acquire a semaphore
sem_get — Get a semaphore id
sem_release — Release a semaphore
sem_remove — Remove a semaphore
shm_attach — Creates or open a shared memory segment
shm_detach — Disconnects from shared memory segment
shm_get_var — Returns a variable from shared memory
shm_put_var — Inserts or updates a variable in shared memory
shm_remove_var — Removes a variable from shared memory
shm_remove — Removes shared memory from Unix systems

后退 | 起点 | 前进
sql_regcase | 上一级 | ftok


ftok

(PHP 4 >= 4.2.0)

ftok -- Convert a pathname and a project identifier to a System V IPC key

Description

int ftok ( string pathname, string proj)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
Semaphore, Shared Memory and IPC Functions | 上一级 | msg_get_queue


msg_get_queue

(PHP 4 CVS only)

msg_get_queue -- Create or attach to a message queue

Description

int msg_get_queue ( int key [, int perms])

msg_get_queue() returns an id that can be used to access the System V message queue with the given key. The first call creates the message queue with the optional perms (default: 0666). A second call to msg_get_queue() for the same key will return a different message queue identifier, but both identifiers access the same underlying message queue. If the message queue already exists, the perms will be ignored.

See also: msg_remove_queue(),
msg_receive(), msg_send(),
msg_stat_queue() and
msg_set_queue().

This function was introduced in PHP 4.3.0 (not yet released).

后退 | 起点 | 前进
ftok | 上一级 | msg_receive


msg_receive

(PHP 4 CVS only)

msg_receive -- Receive a message from a message queue

Description

bool msg_receive ( int queue, int desiredmsgtype, int msgtype, int maxsize, mixed message [, bool unserialize [, int flags [, int errorcode]]])

msg_receive() will receive the first message from the specified queue of the type specified by desiredmsgtype. The type of the message that was received will be stored in msgtype. The maximum size of message to be accepted is specified by the maxsize; if the message in the queue is larger than this size the function will fail (unless you set flags as described below). The received message will be stored in message, unless there were errors receiving the message, in which case the optional errorcode will be set to the value of the system errno variable to help you identify the cause.

If desiredmsgtype is 0, the message from the front of the queue is returned. If desiredmsgtype is greater than 0, then the first message of that type is returned. If desiredmsgtype is less than 0, the first message on the queue with the lowest type less than or equal to the absolute value of desiredmsgtype will be read. If no messages match the criteria, your script will wait until a suitable message arrives on the queue. You can prevent the script from blocking by specifying MSG_IPC_NOWAIT in the flags parameter.

unserialize defaults to TRUE; if it is set to TRUE, the message is treated as though it was serialized using the same mechanism as the session module. The message will be unserialized and then returned to your script. This allows you to easily receive arrays or complex object structures from other PHP scripts, or if you are using the WDDX serializer, from any WDDX compatible source. If unserialize is FALSE, the message will be returned as a binary-safe string.

The optional flags allows you to pass flags to the low-level msgrcv system call. It defaults to 0, but you may specify one or more of the following values (by adding or ORing them together).

表格 1. Flag values for msg_receive

MSG_IPC_NOWAIT | If there are no messages of the desiredmsgtype, return immediately and do not wait. The function will fail and return an integer value corresponding to ENOMSG.
MSG_EXCEPT | Using this flag in combination with a desiredmsgtype greater than 0 will cause the function to receive the first message that is not equal to desiredmsgtype.
MSG_NOERROR | If the message is longer than maxsize, setting this flag will truncate the message to maxsize and will not signal an error.

Upon successful completion the message queue data structure is updated as follows: msg_lrpid is set to the process-ID of the calling process, msg_qnum is decremented by 1 and msg_rtime is set to the current time.

msg_receive() returns TRUE on success or FALSE on failure. If the function fails, the optional errorcode will be set to the value of the system errno variable.

See also: msg_remove_queue(),
msg_send(),
msg_stat_queue() and
msg_set_queue().

This function was introduced in PHP 4.3.0 (not yet released).

后退 | 起点 | 前进
msg_get_queue | 上一级 | msg_remove_queue


msg_remove_queue

(PHP 4 CVS only)

msg_remove_queue -- Destroy a message queue

Description

bool msg_remove_queue ( int queue)

msg_remove_queue() destroys the message queue specified by the queue. Only use this function when all processes have finished working with the message queue and you need to release the system resources held by it.

See also: msg_remove_queue(),
msg_receive(),
msg_stat_queue() and
msg_set_queue().

This function was introduced in PHP 4.3.0 (not yet released).

后退 | 起点 | 前进
msg_receive | 上一级 | msg_send


msg_send

(PHP 4 CVS only)

msg_send -- Send a message to a message queue

Description

bool msg_send ( int queue, int msgtype, mixed message [, bool serialize [, bool blocking [, int errorcode]]])

msg_send() sends a message of type msgtype (which MUST be greater than 0) to a the message queue specified by queue.

If the message is too large to fit in the queue, your script will wait until another process reads messages from the queue and frees enough space for your message to be sent. This is called blocking; you can prevent blocking by setting the optional blocking parameter to FALSE, in which case msg_send() will immediately return FALSE if the message is too big for the queue, and set the optional errorcode to EAGAIN, indicating that you should try to send your message again a little later on.

The optional serialize controls how the message is sent. serialize defaults to TRUE which means that the message is serialized using the same mechanism as the session module before being sent to the queue. This allows complex arrays and objects to be sent to other PHP scripts, or if you are using the WDDX serializer, to any WDDX compatible client.

Upon successful completion the message queue data structure is updated as follows: msg_lspid is set to the process-ID of the calling process, msg_qnum is incremented by 1 and msg_stime is set to the current time.

See also: msg_remove_queue(),
msg_receive(),
msg_stat_queue() and
msg_set_queue().

This function was introduced in PHP 4.3.0 (not yet released).

后退 | 起点 | 前进
msg_remove_queue | 上一级 | msg_set_queue


msg_set_queue

(PHP 4 CVS only)

msg_set_queue -- Set information in the message queue data structure

Description

bool msg_set_queue ( int queue, array data)

msg_set_queue() allows you to change the values of the msg_perm.uid, msg_perm.gid, msg_perm.mode and msg_qbytes fields of the underlying message queue data structure. You specify the values you require by setting the value of the keys that you require in the data array.

Changing the data structure will require that PHP be running as the same user that created the the queue, owns the queue (as determined by the existing msg_perm.xxx fields), or be running with root privileges. root privileges are required to raise the msg_qbytes values above the system defined limit.

See also: msg_remove_queue(),
msg_receive(),
msg_stat_queue() and
msg_set_queue().

This function was introduced in PHP 4.3.0 (not yet released).

后退 | 起点 | 前进
msg_send | 上一级 | msg_stat_queue


msg_stat_queue

(PHP 4 CVS only)

msg_stat_queue -- Returns information from the message queue data structure

Description

array msg_stat_queue ( int queue)

msg_stat_queue() returns the message queue meta data for the message queue specified by the queue. This is useful, for example, to determine which process sent the message that was just received.

The return value is an array whose keys and values have the following meanings:

表格 1. Array structure for msg_stat_queue

msg_perm.uid | The uid of the owner of the queue.
msg_perm.gid | The gid of the owner of the queue.
msg_perm.mode | The file access mode of the queue.
msg_stime | The time that the last message was sent to the queue.
msg_rtime | The time that the last message was received from the queue.
msg_ctime | The time that the queue was last changed.
msg_qnum | The number of messages waiting to be read from the queue.
msg_qbytes | The number of bytes of space currently available in the queue to hold sent messages until they are received.
msg_lspid | The pid of the process that sent the last message to the queue.
msg_lrpid | The pid of the process that received the last message from the queue.

See also: msg_remove_queue(),
msg_receive(),
msg_stat_queue() and
msg_set_queue().

This function was introduced in PHP 4.3.0 (not yet released).

后退 | 起点 | 前进
msg_set_queue | 上一级 | sem_acquire


sem_acquire

(PHP 3>= 3.0.6, PHP 4 )

sem_acquire -- Acquire a semaphore

Description

bool sem_acquire ( int sem_identifier)

Returns: TRUE on success, FALSE on error.

sem_acquire() blocks (if necessary) until the semaphore can be acquired. A process attempting to acquire a semaphore which it has already acquired will block forever if acquiring the semaphore would cause its max_acquire value to be exceeded.

After processing a request, any semaphores acquired by the process but not explicitly released will be released automatically and a warning will be generated.

See also: sem_get() and sem_release().

后退 | 起点 | 前进
msg_stat_queue | 上一级 | sem_get


sem_get

(PHP 3>= 3.0.6, PHP 4 )

sem_get -- Get a semaphore id

Description

int sem_get ( int key [, int max_acquire [, int perm]])

Returns: A positive semaphore identifier on success, or FALSE on error.

sem_get() returns an id that can be used to access the System V semaphore with the given key. The semaphore is created if necessary using the permission bits specified in perm (defaults to 0666). The number of processes that can acquire the semaphore simultaneously is set to max_acquire (defaults to 1). Actually this value is set only if the process finds it is the only process currently attached to the semaphore.

A second call to sem_get() for the same key will return a different semaphore identifier, but both identifiers access the same underlying semaphore.

See also: sem_acquire(), sem_release() and ftok().

注: This function does not work on Windows systems.

后退 | 起点 | 前进
sem_acquire | 上一级 | sem_release


sem_release

(PHP 3>= 3.0.6, PHP 4 )

sem_release -- Release a semaphore

Description

bool sem_release ( int sem_identifier)

Returns: TRUE on success, FALSE on error.

sem_release() releases the semaphore if it is currently acquired by the calling process, otherwise a warning is generated.

After releasing the semaphore, sem_acquire() may be called to re-acquire it.

See also: sem_get() and sem_acquire().

注: This function does not work on Windows systems.

后退 | 起点 | 前进
sem_get | 上一级 | sem_remove


sem_remove

(PHP 4 >= 4.1.0)

sem_remove -- Remove a semaphore

Description

bool sem_remove ( int sem_identifier)

Returns: TRUE on success, FALSE on error.

sem_remove() removes the semaphore sem_identifier if it has been created by sem_get(), otherwise generates a warning.

After removing the semaphore, it is no more accessible.

See also: sem_get(),
sem_release() and
sem_acquire().

注: This function does not work on Windows systems. It was added on PHP 4.1.0.

后退 | 起点 | 前进
sem_release | 上一级 | shm_attach


shm_attach

(PHP 3>= 3.0.6, PHP 4 )

shm_attach -- Creates or open a shared memory segment

Description

int shm_attach ( int key [, int memsize [, int perm]])

shm_attach() returns an id that that can be used to access the System V shared memory with the given key, the first call creates the shared memory segment with mem_size (default: sysvshm.init_mem in the configuration file, otherwise 10000 bytes) and the optional perm-bits (default: 0666).

A second call to shm_attach() for the same key will return a different shared memory identifier, but both identifiers access the same underlying shared memory. Memsize and perm will be ignored.

See also: ftok().

注: This function does not work on Windows systems.

后退 | 起点 | 前进
sem_remove | 上一级 | shm_detach


shm_detach

(PHP 3>= 3.0.6, PHP 4 )

shm_detach -- Disconnects from shared memory segment

Description

int shm_detach ( int shm_identifier)

shm_detach() disconnects from the shared memory given by the shm_identifier created by shm_attach(). Remember, that shared memory still exist in the Unix system and the data is still present.

后退 | 起点 | 前进
shm_attach | 上一级 | shm_get_var


shm_get_var

(PHP 3>= 3.0.6, PHP 4 )

shm_get_var -- Returns a variable from shared memory

Description

mixed shm_get_var ( int id, int variable_key)

shm_get_var() returns the variable with a given variable_key. The variable is still present in the shared memory.

注: This function does not work on Windows systems.

后退 | 起点 | 前进
shm_detach | 上一级 | shm_put_var


shm_put_var

(PHP 3>= 3.0.6, PHP 4 )

shm_put_var -- Inserts or updates a variable in shared memory

Description

int shm_put_var ( int shm_identifier, int variable_key, mixed variable)

Inserts or updates a variable with a given variable_key. All variable-types are supported.

注: This function does not work on Windows systems.

后退 | 起点 | 前进
shm_get_var | 上一级 | shm_remove_var


shm_remove_var

(PHP 3>= 3.0.6, PHP 4 )

shm_remove_var -- Removes a variable from shared memory

Description

int shm_remove_var ( int id, int variable_key)

Removes a variable with a given variable_key and frees the occupied memory.

注: This function does not work on Windows systems.

后退 | 起点 | 前进
shm_put_var | 上一级 | shm_remove


shm_remove

(PHP 3>= 3.0.6, PHP 4 )

shm_remove -- Removes shared memory from Unix systems

Description

int shm_remove ( int shm_identifier)

Removes shared memory from Unix systems. All data will be destroyed.

注: This function does not work on Windows systems.

后退 | 起点 | 前进
shm_remove_var | 上一级 | SESAM database functions


SESAM database functions

PHP 手册
后退 前进

XCI. SESAM database functions

SESAM/SQL-Server is a mainframe database system, developed by Fujitsu Siemens Computers, Germany. It runs on high-end mainframe servers using the operating system BS2000/OSD.

In numerous productive BS2000 installations, SESAM/SQL-Server has proven ...

  • the ease of use of Java-, Web- and client/server connectivity,

  • the capability to work with an availability of more than 99.99%,

  • the ability to manage tens and even hundreds of thousands of users.

Now there is a PHP3 SESAM interface available which allows database operations via PHP-scripts.

Configuration notes: There is no standalone support for the PHP SESAM interface, it works only as an integrated Apache module. In the Apache PHP module, this SESAM interface is configured using Apache directives.

表格 1. SESAM Configuration directives

Directive Meaning
php3_sesam_oml Name of BS2000 PLAM library containing the loadable SESAM driver modules. Required for using SESAM functions.

Example:

php3_sesam_oml $.SYSLNK.SESAM-SQL.030

php3_sesam_configfile Name of SESAM application configuration file. Required for using SESAM functions.

Example:

php3_sesam_configfile $SESAM.SESAM.CONF.AW

It will usually contain a configuration like (see SESAM reference manual):

CNF=B
NAM=K
NOTYPE

php3_sesam_messagecatalog Name of SESAM message catalog file. In most cases, this directive is not neccessary. Only if the SESAM message file is not installed in the system's BS2000 message file table, it can be set with this directive.

Example:

php3_sesam_messagecatalog $.SYSMES.SESAM-SQL.030

In addition to the configuration of the PHP/SESAM interface, you have to configure the SESAM-Database server itself on your mainframe as usual. That means:

  • starting the SESAM database handler (DBH), and

  • connecting the databases with the SESAM database handler

To get a connection between a PHP script and the database handler, the CNF and NAM parameters of the selected SESAM configuration file must match the id of the started database handler.

In case of distributed databases you have to start a SESAM/SQL-DCN agent with the distribution table including the host and database names.

The communication between PHP (running in the POSIX subsystem) and the database handler (running outside the POSIX subsystem) is realized by a special driver module called SQLSCI and SESAM connection modules using common memory. Because of the common memory access, and because PHP is a static part of the web server, database accesses are very fast, as they do not require remote accesses via ODBC, JDBC or UTM.

Only a small stub loader (SESMOD) is linked with PHP, and the SESAM connection modules are pulled in from SESAM's OML PLAM library. In the configuration, you must tell PHP the name of this PLAM library, and the file link to use for the SESAM configuration file (As of SESAM V3.0, SQLSCI is available in the SESAM Tool Library, which is part of the standard distribution).

Because the SQL command quoting for single quotes uses duplicated single quotes (as opposed to a single quote preceded by a backslash, used in some other databases), it is advisable to set the PHP configuration directives php3_magic_quotes_gpc and php3_magic_quotes_sybase to On for all PHP scripts using the SESAM interface.

Runtime considerations: Because of limitations of the BS2000 process model, the driver can be loaded only after the Apache server has forked off its server child processes. This will slightly slow down the initial SESAM request of each child, but subsequent accesses will respond at full speed.

When explicitly defining a Message Catalog for SESAM, that catalog will be loaded each time the driver is loaded (i.e., at the initial SESAM request). The BS2000 operating system prints a message after successful load of the message catalog, which will be sent to Apache's error_log file. BS2000 currently does not allow suppression of this message, it will slowly fill up the log.

Make sure that the SESAM OML PLAM library and SESAM configuration file are readable by the user id running the web server. Otherwise, the server will be unable to load the driver, and will not allow to call any SESAM functions. Also, access to the database must be granted to the user id under which the Apache server is running. Otherwise, connections to the SESAM database handler will fail.

Cursor Types: The result cursors which are allocated for SQL "select type" queries can be either "sequential" or "scrollable". Because of the larger memory overhead needed by "scrollable" cursors, the default is "sequential".

When using "scrollable" cursors, the cursor can be freely positioned on the result set. For each "scrollable" query, there are global default values for the scrolling type (initialized to: SESAM_SEEK_NEXT) and the scrolling offset which can either be set once by sesam_seek_row() or each time when fetching a row using sesam_fetch_row(). When fetching a row using a "scrollable" cursor, the following post-processing is done for the global default values for the scrolling type and scrolling offset:

表格 2. Scrolled Cursor Post-Processing

Scroll Type | Action
SESAM_SEEK_NEXT | none
SESAM_SEEK_PRIOR | none
SESAM_SEEK_FIRST | set scroll type to SESAM_SEEK_NEXT
SESAM_SEEK_LAST | set scroll type to SESAM_SEEK_PRIOR
SESAM_SEEK_ABSOLUTE | Auto-Increment internal offset value
SESAM_SEEK_RELATIVE | none. (maintain global default offset value, which allows for, e.g., fetching each 10th row backwards)

Porting note: Because in the PHP world it is natural to start indexes at zero (rather than 1), some adaptions have been made to the SESAM interface: whenever an indexed array is starting with index 1 in the native SESAM interface, the PHP interface uses index 0 as a starting point. E.g., when retrieving columns with sesam_fetch_row(), the first column has the index 0, and the subsequent columns have indexes up to (but not including) the column count ($array["count"]). When porting SESAM applications from other high level languages to PHP, be aware of this changed interface. Where appropriate, the description of the respective php sesam functions include a note that the index is zero based.

Security concerns: When allowing access to the SESAM databases, the web server user should only have as little privileges as possible. For most databases, only read access privilege should be granted. Depending on your usage scenario, add more access rights as you see fit. Never allow full control to any database for any user from the 'net! Restrict access to php scripts which must administer the database by using password control and/or SSL security.

Migration from other SQL databases: No two SQL dialects are ever 100% compatible. When porting SQL applications from other database interfaces to SESAM, some adaption may be required. The following typical differences should be noted:

  • Vendor specific data types

    Some vendor specific data types may have to be replaced by standard SQL data types (e.g., TEXT could be replaced by VARCHAR(max. size)).

  • Keywords as SQL identifiers

    In SESAM (as in standard SQL), such identifiers must be enclosed in double quotes (or renamed).

  • Display length in data types

    SESAM data types have a precision, not a display length. Instead of int(4) (intended use: integers up to '9999'), SESAM requires simply int for an implied size of 31 bits. Also, the only datetime data types available in SESAM are: DATE, TIME(3) and TIMESTAMP(3).

  • SQL types with vendor-specific unsigned, zerofill, or auto_increment attributes

    Unsigned and zerofill are not supported. Auto_increment is automatic (use "INSERT ... VALUES(*, ...)" instead of "... VALUES(0, ...)" to take advantage of SESAM-implied auto-increment.

  • int ... DEFAULT '0000'

    Numeric variables must not be initialized with string constants. Use DEFAULT 0 instead. To initialize variables of the datetime SQL data types, the initialization string must be prefixed with the respective type keyword, as in: CREATE TABLE exmpl ( xtime timestamp(3) DEFAULT TIMESTAMP '1970-01-01 00:00:00.000' NOT NULL );

  • $count = xxxx_num_rows();

    Some databases promise to guess/estimate the number of the rows in a query result, even though the returned value is grossly incorrect. SESAM does not know the number of rows in a query result before actually fetching them. If you REALLY need the count, try SELECT COUNT(...) WHERE ..., it will tell you the number of hits. A second query will (hopefully) return the results.

  • DROP TABLE thename;

    In SESAM, in the DROP TABLE command, the table name must be either followed by the keyword RESTRICT or CASCADE. When specifying RESTRICT, an error is returned if there are dependent objects (e.g., VIEWs), while with CASCADE, dependent objects will be deleted along with the specified table.

Notes on the use of various SQL types: SESAM does not currently support the BLOB type. A future version of SESAM will have support for BLOB.

At the PHP interface, the following type conversions are automatically applied when retrieving SQL fields:

表格 3. SQL to PHP Type Conversions

SQL Type | PHP Type
SMALLINT, INTEGER | integer
NUMERIC, DECIMAL, FLOAT, REAL, DOUBLE | float
DATE, TIME, TIMESTAMP | string
VARCHAR, CHARACTER | string
When retrieving a complete row, the result is returned as an array. Empty fields are not filled in, so you will have to check for the existence of the individual fields yourself (use isset() or empty() to test for empty fields). That allows more user control over the appearance of empty fields (than in the case of an empty string as the representation of an empty field).

Support of SESAM's "multiple fields" feature: The special "multiple fields" feature of SESAM allows a column to consist of an array of fields. Such a "multiple field" column can be created like this:

例子 1. Creating a "multiple field" column

CREATE TABLE multi_field_test (
    pkey CHAR(20) PRIMARY KEY,
    multi(3) CHAR(12)
)
and can be filled in using:

例子 2. Filling a "multiple field" column

INSERT INTO multi_field_test (pkey, multi(2..3) )
    VALUES ('Second', <'first_val', 'second_val'>)
Note that (like in this case) leading empty sub-fields are ignored, and the filled-in values are collapsed, so that in the above example the result will appear as multi(1..2) instead of multi(2..3).

When retrieving a result row, "multiple columns" are accessed like "inlined" additional columns. In the example above, "pkey" will have the index 0, and the three "multi(1..3)" columns will be accessible as indices 1 through 3.

For specific SESAM details, please refer to the SESAM/SQL-Server documentation (english) or the SESAM/SQL-Server documentation (german), both available online, or use the respective manuals.

目录
sesam_affected_rows — Get number of rows affected by an immediate query
sesam_commit — Commit pending updates to the SESAM database
sesam_connect — Open SESAM database connection
sesam_diagnostic — Return status information for last SESAM call
sesam_disconnect — Detach from SESAM connection
sesam_errormsg — Returns error message of last SESAM call
sesam_execimm — Execute an "immediate" SQL-statement
sesam_fetch_array — Fetch one row as an associative array
sesam_fetch_result — Return all or part of a query result
sesam_fetch_row — Fetch one row as an array
sesam_field_array — Return meta information about individual columns in a result
sesam_field_name — Return one column name of the result set
sesam_free_result — Releases resources for the query
sesam_num_fields — Return the number of fields/columns in a result set
sesam_query — Perform a SESAM SQL query and prepare the result
sesam_rollback — Discard any pending updates to the SESAM database
sesam_seek_row — Set scrollable cursor mode for subsequent fetches
sesam_settransaction — Set SESAM transaction parameters

后退 | 起点 | 前进
shm_remove | 上一级 | sesam_affected_rows


sesam_affected_rows

(PHP 3 CVS only)

sesam_affected_rows -- Get number of rows affected by an immediate query

Description

int sesam_affected_rows ( string result_id)

result_id is a valid result id returned by sesam_query().

Returns the number of rows affected by a query associated with result_id.

The sesam_affected_rows() function can only return useful values when used in combination with "immediate" SQL statements (updating operations like INSERT, UPDATE and DELETE) because SESAM does not deliver any "affected rows" information for "select type" queries. The number returned is the number of affected rows.

See also: sesam_query() and sesam_execimm()

$result = sesam_execimm ("DELETE FROM PHONE WHERE LASTNAME = '".strtoupper ($name)."'");
if (!$result) {
    ... error ...
}
print sesam_affected_rows ($result).
    " entries with last name ".$name." deleted.\n"

后退 | 起点 | 前进
SESAM database functions | 上一级 | sesam_commit


sesam_commit

(PHP 3 CVS only)

sesam_commit -- Commit pending updates to the SESAM database

Description

bool sesam_commit ( void)

Returns: TRUE on success, FALSE on errors

sesam_commit() commits any pending updates to the database.

Note that there is no "auto-commit" feature as in other databases, as it could lead to accidental data loss. Uncommitted data at the end of the current script (or when calling sesam_disconnect()) will be discarded by an implied sesam_rollback() call.

See also: sesam_rollback().

例子 1. Committing an update to the SESAM database

<?php
if (sesam_connect ("mycatalog", "myschema", "otto")) {
    if (!sesam_execimm ("INSERT INTO mytable VALUES (*, 'Small Test', <0, 8, 15>)"))
        die("insert failed");
    if (!sesam_commit())
        die("commit failed");
}
?>

后退 | 起点 | 前进
sesam_affected_rows | 上一级 | sesam_connect


sesam_connect

(PHP 3 CVS only)

sesam_connect -- Open SESAM database connection

Description

bool sesam_connect ( string catalog, string schema, string user)

Returns TRUE if a connection to the SESAM database was made, or FALSE on error.

sesam_connect() establishes a connection to an SESAM database handler task. The connection is always "persistent" in the sense that only the very first invocation will actually load the driver from the configured SESAM OML PLAM library. Subsequent calls will reuse the driver and will immediately use the given catalog, schema, and user.

When creating a database, the "catalog" name is specified in the SESAM configuration directive //ADD-SQL-DATABASE-CATALOG-LIST ENTRY-1 = *CATALOG(CATALOG-NAME = catalogname,...)

The "schema" references the desired database schema (see SESAM handbook).

The "user" argument references one of the users which are allowed to access this "catalog" / "schema" combination. Note that "user" is completely independent from both the system's user id's and from HTTP user/password protection. It appears in the SESAM configuration only.

See also sesam_disconnect().

例子 1. Connect to a SESAM database

<?php
if (!sesam_connect ("mycatalog", "myschema", "otto")
    die("Unable to connect to SESAM");
?>

后退 | 起点 | 前进
sesam_commit | 上一级 | sesam_diagnostic


sesam_diagnostic

(PHP 3 CVS only)

sesam_diagnostic -- Return status information for last SESAM call

Description

array sesam_diagnostic ( void)

Returns an associative array of status and return codes for the last SQL query/statement/command. Elements of the array are:

表格 1. Status information returned by sesam_diagnostic()

Element | Contents
$array["sqlstate"] | 5 digit SQL return code (see the SESAM manual for the description of the possible values of SQLSTATE)
$array["rowcount"] | number of affected rows in last update/insert/delete (set after "immediate" statements only)
$array["errmsg"] | "human readable" error message string (set after errors only)
$array["errcol"] | error column number of previous error (0-based; or -1 if undefined. Set after errors only)
$array["errlin"] | error line number of previous error (0-based; or -1 if undefined. Set after errors only)

In the following example, a syntax error (E SEW42AE ILLEGAL CHARACTER) is displayed by including the offending SQL statement and pointing to the error location:

例子 1. Displaying SESAM error messages with error position

<?php
// Function which prints a formatted error message,
// displaying a pointer to the syntax error in the
// SQL statement
function PrintReturncode ($exec_str) {
    $err = Sesam_Diagnostic();
    $colspan=4; // 4 cols for: sqlstate, errlin, errcol, rowcount
    if ($err["errlin"] == -1)
        --$colspan;
    if ($err["errcol"] == -1)
        --$colspan;
    if ($err["rowcount"] == 0)
        --$colspan;
    echo "<TABLE BORDER>\n";
    echo "<TR><TH COLSPAN=".$colspan."><FONT COLOR=red>ERROR:</FONT> ".
          htmlspecialchars($err["errmsg"])."</TH></TR>\n";
    if ($err["errcol"] >= 0) {
        echo "<TR><TD COLSPAN=".$colspan."><PRE>\n";
        $errstmt = $exec_str."\n";
        for ($lin=0; $errstmt != ""; ++$lin) {
            if ($lin != $err["errlin"]) { // $lin is less or greater than errlin
                if (!($i = strchr ($errstmt, "\n")))
                    $i = "";
                $line = substr ($errstmt, 0, strlen($errstmt)-strlen($i)+1);
                $errstmt = substr($i, 1);
                if ($line != "\n")
                    print htmlspecialchars ($line);
            } else {
                if (! ($i = strchr ($errstmt, "\n")))
                    $i = "";
                $line = substr ($errstmt, 0, strlen ($errstmt)-strlen($i)+1);
                $errstmt = substr($i, 1);
                for ($col=0; $col < $err["errcol"]; ++$col)
                    echo (substr($line, $col, 1) == "\t") ? "\t" : ".";
                echo "<FONT COLOR=RED><BLINK>\\</BLINK></FONT>\n";
                print "<FONT COLOR=\"#880000\">".htmlspecialchars($line)."</FONT>";
                for ($col=0; $col < $err["errcol"]; ++$col)
                    echo (substr ($line, $col, 1) == "\t") ? "\t" : ".";
                echo "<FONT COLOR=RED><BLINK>/</BLINK></FONT>\n";
            }
        }
        echo "</PRE></TD></TR>\n";
    }
    echo "<TR>\n";
    echo " <TD>sqlstate=" . $err["sqlstate"] . "</TD>\n";
    if ($err["errlin"] != -1)
        echo " <TD>errlin=" . $err["errlin"] . "</TD>\n";
    if ($err["errcol"] != -1)
        echo " <TD>errcol=" . $err["errcol"] . "</TD>\n";
    if ($err["rowcount"] != 0)
         echo " <TD>rowcount=" . $err["rowcount"] . "</TD>\n";
    echo "</TR>\n";
    echo "</TABLE>\n";
}

if (!sesam_connect ("mycatalog", "phoneno", "otto"))
  die ("cannot connect");

$stmt = "SELECT * FROM phone\n".
        " WHERE@ LASTNAME='KRAEMER'\n".
        " ORDER BY FIRSTNAME";
if (!($result = sesam_query ($stmt)))
    PrintReturncode ($stmt);
?>

See also: sesam_errormsg() for simple access to the error string only

后退 | 起点 | 前进
sesam_connect | 上一级 | sesam_disconnect


sesam_disconnect

(PHP 3 CVS only)

sesam_disconnect -- Detach from SESAM connection

Description

bool sesam_disconnect ( void)

Returns: always TRUE.

sesam_disconnect() closes the logical link to a SESAM database (without actually disconnecting and unloading the driver).

Note that this isn't usually necessary, as the open connection is automatically closed at the end of the script's execution. Uncommitted data will be discarded, because an implicit sesam_rollback() is executed.

sesam_disconnect() will not close the persistent link, it will only invalidate the currently defined "catalog", "schema" and "user" triple, so that any sesam function called after sesam_disconnect() will fail.

See also: sesam_connect().

例子 1. Closing a SESAM connection

if (sesam_connect ("mycatalog", "myschema", "otto")) {
    ... some queries and stuff ...
    sesam_disconnect();
}

后退 | 起点 | 前进
sesam_diagnostic | 上一级 | sesam_errormsg


sesam_errormsg

(PHP 3 CVS only)

sesam_errormsg -- Returns error message of last SESAM call

Description

string sesam_errormsg ( void)

Returns the SESAM error message associated with the most recent SESAM error.

if (!sesam_execimm ($stmt))
  printf ("%s<br>\n", sesam_errormsg());

See also: sesam_diagnostic() for the full set of SESAM SQL status information

后退 | 起点 | 前进
sesam_disconnect | 上一级 | sesam_execimm


sesam_execimm

(PHP 3 CVS only)

sesam_execimm -- Execute an "immediate" SQL-statement

Description

string sesam_execimm ( string query)

Returns: A SESAM "result identifier" on success, or FALSE on error.

sesam_execimm() executes an "immediate" statement (i.e., a statement like UPDATE, INSERT or DELETE which returns no result, and has no INPUT or OUTPUT variables). "select type" queries can not be used with sesam_execimm(). Sets the affected_rows value for retrieval by the sesam_affected_rows() function.

Note that sesam_query() can handle both "immediate" and "select-type" queries. Use sesam_execimm() only if you know beforehand what type of statement will be executed. An attempt to use SELECT type queries with sesam_execimm() will return $err["sqlstate"] == "42SBW".

The returned "result identifier" can not be used for retrieving anything but the sesam_affected_rows(); it is only returned for symmetry with the sesam_query() function.

$stmt = "INSERT INTO mytable VALUES ('one', 'two')";
$result = sesam_execimm ($stmt);
$err = sesam_diagnostic();
print ("sqlstate = ".$err["sqlstate"]."\n".
       "Affected rows = ".$err["rowcount"]." == ".
       sesam_affected_rows($result)."\n");

See also: sesam_query() and sesam_affected_rows().

后退 | 起点 | 前进
sesam_errormsg | 上一级 | sesam_fetch_array


sesam_fetch_array

(PHP 3 CVS only)

sesam_fetch_array -- Fetch one row as an associative array

Description

array sesam_fetch_array ( string result_id [, int whence [, int offset]])

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

sesam_fetch_array() is an alternative version of sesam_fetch_row(). Instead of storing the data in the numeric indices of the result array, it stores the data in associative indices, using the field names as keys.

result_id is a valid result id returned by sesam_query() (select type queries only!).

For the valid values of the optional whenceand offset parameters, see the sesam_fetch_row() function for details.

sesam_fetch_array() fetches one row of data from the result associated with the specified result identifier. The row is returned as an associative array. Each result column is stored with an associative index equal to its column (aka. field) name. The column names are converted to lower case.

Columns without a field name (e.g., results of arithmetic operations) and empty fields are not stored in the array. Also, if two or more columns of the result have the same column names, the later column will take precedence. In this situation, either call sesam_fetch_row() or make an alias for the column.

SELECT TBL1.COL AS FOO, TBL2.COL AS BAR FROM TBL1, TBL2

A special handling allows fetching "multiple field" columns (which would otherwise all have the same column names). For each column of a "multiple field", the index name is constructed by appending the string "(n)" where n is the sub-index of the multiple field column, ranging from 1 to its declared repetition factor. The indices are NOT zero based, in order to match the nomenclature used in the respective query syntax. For a column declared as:

CREATE TABLE ... ( ... MULTI(3) INT )

the associative indices used for the individual "multiple field" columns would be "multi(1)", "multi(2)", and "multi(3)" respectively.

Subsequent calls to sesam_fetch_array() would return the next (or prior, or n'th next/prior, depending on the scroll attributes) row in the result set, or FALSE if there are no more rows.

例子 1. SESAM fetch array

<?php
$result = sesam_query ("SELECT * FROM phone\n".
                       "  WHERE LASTNAME='".strtoupper($name)."'\n".
                       "  ORDER BY FIRSTNAME", 1);
if (!$result) {
    ... error ...
}
// print the table:
print "<TABLE BORDER>\n";
while (($row = sesam_fetch_array ($result)) && count ($row) > 0) {
    print " <TR>\n";
    print " <TD>".htmlspecialchars ($row["firstname"])."</TD>\n";
    print " <TD>".htmlspecialchars ($row["lastname"])."</TD>\n";
    print " <TD>".htmlspecialchars ($row["phoneno"])."</TD>\n";
    print " </TR>\n";
}
print "</TABLE>\n";
sesam_free_result ($result);
?>

See also: sesam_fetch_row() which returns an indexed array.

后退 | 起点 | 前进
sesam_execimm | 上一级 | sesam_fetch_result


sesam_fetch_result

(PHP 3 CVS only)

sesam_fetch_result -- Return all or part of a query result

Description

mixed sesam_fetch_result ( string result_id [, int max_rows])

Returns a mixed array with the query result entries, optionally limited to a maximum of max_rows rows. Note that both row and column indexes are zero-based.

表格 1. Mixed result set returned by sesam_fetch_result()

Array Element | Contents
int $arr["count"] | number of columns in result set (or zero if this was an "immediate" query)
int $arr["rows"] | number of rows in result set (between zero and max_rows)
bool $arr["truncated"] | TRUE if the number of rows was at least max_rows, FALSE otherwise. Note that even when this is TRUE, the next sesam_fetch_result() call may return zero rows because there are no more result entries.
mixed $arr[col][row] | result data for all the fields at row(row) and column(col), (where the integer index row is between 0 and $arr["rows"]-1, and col is between 0 and $arr["count"]-1). Fields may be empty, so you must check for the existence of a field by using the php isset() function. The type of the returned fields depend on the respective SQL type declared for its column (see SESAM overview for the conversions applied). SESAM "multiple fields" are "inlined" and treated like a sequence of columns.
Note that the amount of memory used up by a large query may be gigantic. Use the max_rows parameter to limit the maximum number of rows returned, unless you are absolutely sure that your result will not use up all available memory.

See also: sesam_fetch_row(), and sesam_field_array() to check for "multiple fields". See the description of the sesam_query() function for a complete example using sesam_fetch_result().

后退 | 起点 | 前进
sesam_fetch_array | 上一级 | sesam_fetch_row


sesam_fetch_row

(PHP 3 CVS only)

sesam_fetch_row -- Fetch one row as an array

Description

array sesam_fetch_row ( string result_id [, int whence [, int offset]])

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

The number of columns in the result set is returned in an associative array element $array["count"]. Because some of the result columns may be empty, the count() function can not be used on the result row returned by sesam_fetch_row().

result_id is a valid result id returned by sesam_query() (select type queries only!).

whence is an optional parameter for a fetch operation on "scrollable" cursors, which can be set to the following predefined constants:

表格 1. Valid values for "whence" parameter

Value | Constant | Meaning
0 | SESAM_SEEK_NEXT | read sequentially (after fetch, the internal default is set to SESAM_SEEK_NEXT)
1 | SESAM_SEEK_PRIOR | read sequentially backwards (after fetch, the internal default is set to SESAM_SEEK_PRIOR)
2 | SESAM_SEEK_FIRST | rewind to first row (after fetch, the default is set to SESAM_SEEK_NEXT)
3 | SESAM_SEEK_LAST | seek to last row (after fetch, the default is set to SESAM_SEEK_PRIOR)
4 | SESAM_SEEK_ABSOLUTE | seek to absolute row number given as offset (Zero-based. After fetch, the internal default is set to SESAM_SEEK_ABSOLUTE, and the internal offset value is auto-incremented)
5 | SESAM_SEEK_RELATIVE | seek relative to current scroll position, where offset can be a positive or negative offset value.
This parameter is only valid for "scrollable" cursors.

When using "scrollable" cursors, the cursor can be freely positioned on the result set. If the whence parameter is omitted, the global default values for the scrolling type (initialized to: SESAM_SEEK_NEXT, and settable by sesam_seek_row()) are used. If whence is supplied, its value replaces the global default.

offset is an optional parameter which is only evaluated (and required) if whence is either SESAM_SEEK_RELATIVE or SESAM_SEEK_ABSOLUTE. This parameter is only valid for "scrollable" cursors.

sesam_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array (indexed by values between 0 and $array["count"]-1). Fields may be empty, so you must check for the existence of a field by using the php isset() function. The type of the returned fields depend on the respective SQL type declared for its column (see SESAM overview for the conversions applied). SESAM "multiple fields" are "inlined" and treated like a sequence of columns.

Subsequent calls to sesam_fetch_row() would return the next (or prior, or n'th next/prior, depending on the scroll attributes) row in the result set, or FALSE if there are no more rows.

例子 1. SESAM fetch rows

<?php
$result = sesam_query ("SELECT * FROM phone\n".
                       "  WHERE LASTNAME='".strtoupper($name)."'\n".
                       "  ORDER BY FIRSTNAME", 1);
if (!$result) {
    ... error ...
}
// print the table in backward order
print "<TABLE BORDER>\n";
$row = sesam_fetch_row ($result, SESAM_SEEK_LAST);
while (is_array ($row)) {
    print " <TR>\n";
    for ($col = 0; $col < $row["count"]; ++$col) {
        print "  <TD>".htmlspecialchars ($row[$col])."</TD>\n";
    }
    print " </TR>\n";
    // use implied SESAM_SEEK_PRIOR
    $row = sesam_fetch_row ($result);
}
print "</TABLE>\n";
sesam_free_result ($result);
?>

See also: sesam_fetch_array() which returns an associative array, and sesam_fetch_result() which returns many rows per invocation.

后退 | 起点 | 前进
sesam_fetch_result | 上一级 | sesam_field_array


sesam_field_array

(PHP 3 CVS only)

sesam_field_array -- Return meta information about individual columns in a result

Description

array sesam_field_array ( string result_id)

result_id is a valid result id returned by sesam_query().

Returns a mixed associative/indexed array with meta information (column name, type, precision, ...) about individual columns of the result after the query associated with result_id.

表格 1. Mixed result set returned by sesam_field_array()

Array Element | Contents
int $arr["count"] | Total number of columns in result set (or zero if this was an "immediate" query). SESAM "multiple fields" are "inlined" and treated like the respective number of columns.
string $arr[col]["name"] | column name for column(col), where col is between 0 and $arr["count"]-1. The returned value can be the empty string (for dynamically computed columns). SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same column name.
string $arr[col]["count"] | The "count" attribute describes the repetition factor when the column has been declared as a "multiple field". Usually, the "count" attribute is 1. The first column of a "multiple field" column however contains the number of repetitions (the second and following column of the "multiple field" contain a "count" attribute of 1). This can be used to detect "multiple fields" in the result set. See the example shown in the sesam_query() description for a sample use of the "count" attribute.
string $arr[col]["type"] php variable type of the data for column(col), where col is between 0 and $arr["count"]-1. The returned value can be one of

  • integer

  • float

  • string

depending on the SQL type of the result. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same php type.
string $arr[col]["sqltype"] SQL variable type of the column data for column(col), where col is between 0 and $arr["count"]-1. The returned value can be one of

  • "CHARACTER"

  • "VARCHAR"

  • "NUMERIC"

  • "DECIMAL"

  • "INTEGER"

  • "SMALLINT"

  • "FLOAT"

  • "REAL"

  • "DOUBLE"

  • "DATE"

  • "TIME"

  • "TIMESTAMP"

describing the SQL type of the result. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same SQL type.
string $arr[col]["length"] | The SQL "length" attribute of the SQL variable in column(col), where col is between 0 and $arr["count"]-1. The "length" attribute is used with "CHARACTER" and "VARCHAR" SQL types to specify the (maximum) length of the string variable. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same length attribute.
string $arr[col]["precision"] | The "precision" attribute of the SQL variable in column(col), where col is between 0 and $arr["count"]-1. The "precision" attribute is used with numeric and time data types. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same precision attribute.
string $arr[col]["scale"] | The "scale" attribute of the SQL variable in column(col), where col is between 0 and $arr["count"]-1. The "scale" attribute is used with numeric data types. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same scale attribute.

See the sesam_query() function for an example of the sesam_field_array() use.

后退 | 起点 | 前进
sesam_fetch_row | 上一级 | sesam_field_name


sesam_field_name

(PHP 3 CVS only)

sesam_field_name -- Return one column name of the result set

Description

int sesam_field_name ( string result_id, int index)

Returns the name of a field (i.e., the column name) in the result set, or FALSE on error.

For "immediate" queries, or for dynamic columns, an empty string is returned.

注: The column index is zero-based, not one-based as in SESAM.

See also: sesam_field_array(). It provides an easier interface to access the column names and types, and allows for detection of "multiple fields".

后退 | 起点 | 前进
sesam_field_array | 上一级 | sesam_free_result


sesam_free_result

(PHP 3 CVS only)

sesam_free_result -- Releases resources for the query

Description

int sesam_free_result ( string result_id)

Releases resources for the query associated with result_id. Returns FALSE on error.

后退 | 起点 | 前进
sesam_field_name | 上一级 | sesam_num_fields


sesam_num_fields

(PHP 3 CVS only)

sesam_num_fields -- Return the number of fields/columns in a result set

Description

int sesam_num_fields ( string result_id)

After calling sesam_query() with a "select type" query, this function gives you the number of columns in the result. Returns an integer describing the total number of columns (aka. fields) in the current result_id result set or FALSE on error.

For "immediate" statements, the value zero is returned. The SESAM "multiple field" columns count as their respective dimension, i.e., a three-column "multiple field" counts as three columns.

See also: sesam_query() and sesam_field_array() for a way to distinguish between "multiple field" columns and regular columns.

后退 | 起点 | 前进
sesam_free_result | 上一级 | sesam_query


sesam_query

(PHP 3 CVS only)

sesam_query -- Perform a SESAM SQL query and prepare the result

Description

string sesam_query ( string query [, bool scrollable])

Returns: A SESAM "result identifier" on success, or FALSE on error.

A "result_id" resource is used by other functions to retrieve the query results.

sesam_query() sends a query to the currently active database on the server. It can execute both "immediate" SQL statements and "select type" queries. If an "immediate" statement is executed, then no cursor is allocated, and any subsequent sesam_fetch_row() or sesam_fetch_result() call will return an empty result (zero columns, indicating end-of-result). For "select type" statements, a result descriptor and a (scrollable or sequential, depending on the optional boolean scrollable parameter) cursor will be allocated. If scrollable is omitted, the cursor will be sequential.

When using "scrollable" cursors, the cursor can be freely positioned on the result set. For each "scrollable" query, there are global default values for the scrolling type (initialized to: SESAM_SEEK_NEXT) and the scrolling offset which can either be set once by sesam_seek_row() or each time when fetching a row using sesam_fetch_row().

For "immediate" statements, the number of affected rows is saved for retrieval by the sesam_affected_rows() function.

See also: sesam_fetch_row() and sesam_fetch_result().

例子 1. Show all rows of the "phone" table as a html table

<?php
if (!sesam_connect ("phonedb", "demo", "otto"))
    die ("cannot connect");
$result = sesam_query ("select * from phone");
if (!$result) {
    $err = sesam_diagnostic();
    die ($err["errmsg"]);
}
echo "<TABLE BORDER>\n";
// Add title header with column names above the result:
if ($cols = sesam_field_array ($result)) {
    echo " <TR><TH COLSPAN=".$cols["count"].">Result:</TH></TR>\n";
    echo " <TR>\n";
    for ($col = 0; $col < $cols["count"]; ++$col) {
        $colattr = $cols[$col];
        /* Span the table head over SESAM's "Multiple Fields": */
        if ($colattr["count"] > 1) {
            echo "  <TH COLSPAN=".$colattr["count"].">".$colattr["name"].
                "(1..".$colattr["count"].")</TH>\n";
            $col += $colattr["count"] - 1;
        } else
            echo "  <TH>" . $colattr["name"] . "</TH>\n";
    }
    echo " </TR>\n";
}

do {
    // Fetch the result in chunks of 100 rows max.
    $ok = sesam_fetch_result ($result, 100);
    for ($row=0; $row < $ok["rows"]; ++$row) {
        echo " <TR>\n";
        for ($col = 0; $col < $ok["cols"]; ++$col) {
            if (isset($ok[$col][$row]))
                echo "  <TD>" . $ok[$col][$row] . "</TD>\n";
            } else {
                echo "  <TD>-empty-</TD>\n";
            }
        }
        echo " </TR>\n";
    }
}
while ($ok["truncated"]) { // while there may be more data
    echo "</TABLE>\n";
}
// free result id
sesam_free_result($result);
?>

后退 | 起点 | 前进
sesam_num_fields | 上一级 | sesam_rollback


sesam_rollback

(PHP 3 CVS only)

sesam_rollback -- Discard any pending updates to the SESAM database

Description

bool sesam_rollback ( void)

Returns: TRUE on success, FALSE on errors

sesam_rollback() discards any pending updates to the database. Also affected are result cursors and result descriptors.

At the end of each script, and as part of the sesam_disconnect() function, an implied sesam_rollback() is executed, discarding any pending changes to the database.

See also: sesam_commit().

例子 1. Discarding an update to the SESAM database

<?php
if (sesam_connect ("mycatalog", "myschema", "otto")) {
    if (sesam_execimm ("INSERT INTO mytable VALUES (*, 'Small Test', <0, 8, 15>)")
        && sesam_execimm ("INSERT INTO othertable VALUES (*, 'Another Test', 1)"))
        sesam_commit();
    else
        sesam_rollback();
}
?>

后退 | 起点 | 前进
sesam_query | 上一级 | sesam_seek_row


sesam_seek_row

(PHP 3 CVS only)

sesam_seek_row -- Set scrollable cursor mode for subsequent fetches

Description

bool sesam_seek_row ( string result_id, int whence [, int offset])

result_id is a valid result id (select type queries only, and only if a "scrollable" cursor was requested when calling sesam_query()).

whence sets the global default value for the scrolling type, it specifies the scroll type to use in subsequent fetch operations on "scrollable" cursors, which can be set to the following predefined constants:

表格 1. Valid values for "whence" parameter

Value | Constant | Meaning
0 | SESAM_SEEK_NEXT | read sequentially
1 | SESAM_SEEK_PRIOR | read sequentially backwards
2 | SESAM_SEEK_FIRST | fetch first row (after fetch, the default is set to SESAM_SEEK_NEXT)
3 | SESAM_SEEK_LAST | fetch last row (after fetch, the default is set to SESAM_SEEK_PRIOR)
4 | SESAM_SEEK_ABSOLUTE | fetch absolute row number given as offset (Zero-based. After fetch, the default is set to SESAM_SEEK_ABSOLUTE, and the offset value is auto-incremented)
5 | SESAM_SEEK_RELATIVE | fetch relative to current scroll position, where offset can be a positive or negative offset value (this also sets the default "offset" value for subsequent fetches).

offset is an optional parameter which is only evaluated (and required) if whence is either SESAM_SEEK_RELATIVE or SESAM_SEEK_ABSOLUTE.

后退 | 起点 | 前进
sesam_rollback | 上一级 | sesam_settransaction


sesam_settransaction

(PHP 3 CVS only)

sesam_settransaction -- Set SESAM transaction parameters

Description

bool sesam_settransaction ( int isolation_level, int read_only)

Returns: TRUE if the values are valid, and the settransaction() operation was successful, FALSE otherwise.

sesam_settransaction() overrides the default values for the "isolation level" and "read-only" transaction parameters (which are set in the SESAM configuration file), in order to optimize subsequent queries and guarantee database consistency. The overridden values are used for the next transaction only.

sesam_settransaction() can only be called before starting a transaction, not after the transaction has been started already.

To simplify the use in php scripts, the following constants have been predefined in php (see SESAM handbook for detailed explanation of the semantics):

表格 1. Valid values for "Isolation_Level" parameter

Value | Constant | Meaning
1 | SESAM_TXISOL_READ_UNCOMMITTED | Read Uncommitted
2 | SESAM_TXISOL_READ_COMMITTED | Read Committed
3 | SESAM_TXISOL_REPEATABLE_READ | Repeatable Read
4 | SESAM_TXISOL_SERIALIZABLE | Serializable

表格 2. Valid values for "Read_Only" parameter

Value | Constant | Meaning
0 | SESAM_TXREAD_READWRITE | Read/Write
1 | SESAM_TXREAD_READONLY | Read-Only

The values set by sesam_settransaction() will override the default setting specified in the SESAM configuration file.

例子 1. Setting SESAM transaction parameters

<?php
sesam_settransaction (SESAM_TXISOL_REPEATABLE_READ,
                     SESAM_TXREAD_READONLY);
?>

后退 | 起点 | 前进
sesam_seek_row | 上一级 | Session handling functions


Session handling functions

PHP 手册
后退 前进

XCII. Session handling functions

介绍

Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site.

If you are familiar with the session management of PHPLIB, you will notice that some concepts are similar to PHP's session support.

A visitor accessing your web site is assigned an unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL.

The session support allows you to register arbitrary numbers of variables to be preserved across requests. When a visitor accesses your site, PHP will check automatically (if session.auto_start is set to 1) or on your request (explicitly through session_start() or implicitly through session_register()) whether a specific session id has been sent with the request. If this is the case, the prior saved environment is recreated.

All registered variables are serialized after the request finishes. Registered variables which are undefined are marked as being not defined. On subsequent accesses, these are not defined by the session module unless the user defines them later.

注: Session handling was added in PHP 4.0.

Sessions and security

Using sessions, does not mean, you can be absolutely sure, that the session data can only be viewed by that user. This is important to keep in mind, when storing and displaying sensitive information. When storing data into a session, one should always ask themselves, what the damage is, when somebody else views that information, or how your application is affected when this session is actually somebody else.

For instance, if somebody else takes a session, can he then post a message in a forum, as that user and how big of a problem is that? Or perhaps he can view what the original user was thinking of ordering, because he gets access to that user's shopping cart. Obviously for a flowershop, this is less dramatic, than for a pharmacy.

Therefore, when dealing with sensitive information, there should always be additional methods to decide whether it is a valid session. Sessions are not reliable as a secure authentication mechanism.

Sessions rely on the session ID, meaning one can 'steal' a session, by stealing the session ID. This can be made harder, by using a cookie specifically a session cookie, but does not in any way make it impossible and still relies on the user closing all browser windows, to expire the session cookie. Besides that, even session cookies can be sniffed on a network or logged by a proxyserver.

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

Session support is enabled in PHP by default. If you would not like to build your PHP with session support, you should specify the --disable-session option to configure.

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. Session configuration options

Name | Default | Changeable
session.save_path | "/tmp" | PHP_INI_ALL
session.name | "PHPSESSID" | PHP_INI_ALL
session.save_handler | "files" | PHP_INI_ALL
session.auto_start | "0" | PHP_INI_ALL
session.gc_probability | "1" | PHP_INI_ALL
session.gc_maxlifetime | "1440" | PHP_INI_ALL
session.serialize_handler | "php" | PHP_INI_ALL
session.cookie_lifetime | "0" | PHP_INI_ALL
session.cookie_path | "/" | PHP_INI_ALL
session.cookie_domain | "" | PHP_INI_ALL
session.cookie_secure | "" | PHP_INI_ALL
session.use_cookies | "1" | PHP_INI_ALL
session.use_only_cookies | "0" | PHP_INI_ALL
session.referer_check | "" | PHP_INI_ALL
session.entropy_file | "" | PHP_INI_ALL
session.entropy_length | "0" | PHP_INI_ALL
session.cache_limiter | "nocache" | PHP_INI_ALL
session.cache_expire | "180" | PHP_INI_ALL
session.use_trans_sid | "0" | PHP_INI_ALL
url_rewriter.tags | "a=href,area=href,frame=src,input=src,form=fakeentry" | PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

The session management system supports a number of configuration options which you can place in your php.ini file. We will give a short overview.

  • session.save_handler defines the name of the handler which is used for storing and retrieving data associated with a session. Defaults to files.

  • session.save_path defines the argument which is passed to the save handler. If you choose the default files handler, this is the path where the files are created. Defaults to /tmp. If session.save_path's path depth is more than 2, garbage collection will not be performed.

    警告

    If you leave this set to a world-readable directory, such as /tmp (the default), other users on the server may be able to hijack sessions by getting the list of files in that directory.

    注: Windows users have to change this variable in order to use PHP's session functions. Make sure to specify a valid path, e.g.: c:/temp.

  • session.name specifies the name of the session which is used as cookie name. It should only contain alphanumeric characters. Defaults to PHPSESSID.

  • session.auto_start specifies whether the session module starts a session automatically on request startup. Defaults to 0 (disabled).

  • session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser. The value 0 means "until the browser is closed." Defaults to 0.

  • session.serialize_handler defines the name of the handler which is used to serialize/deserialize data. Currently, a PHP internal format (name php) and WDDX is supported (name wddx). WDDX is only available, if PHP is compiled with WDDX support. Defaults to php.

  • session.gc_probability specifies the probability that the gc (garbage collection) routine is started on each request in percent. Defaults to 1.

  • session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and cleaned up.

    注: If you are using the default file-based session handler, your filesystem must keep track of access times (atime). Windows FAT does not so you will have to come up with another way to handle garbage collecting your session if you are stuck with a FAT filesystem or any other fs where atime tracking is not available.

  • session.referer_check contains the substring you want to check each HTTP Referer for. If the Referer was sent by the client and the substring was not found, the embedded session id will be marked as invalid. Defaults to the empty string.

  • session.entropy_file gives a path to an external resource (file) which will be used as an additional entropy source in the session id creation process. Examples are /dev/random or /dev/urandom which are available on many Unix systems.

  • session.entropy_length specifies the number of bytes which will be read from the file specified above. Defaults to 0 (disabled).

  • session.use_cookies specifies whether the module will use cookies to store the session id on the client side. Defaults to 1 (enabled).

  • session.use_only_cookies specifies whether the module will only use cookies to store the session id on the client side. Defaults to 0 (disabled, for backward compatibility). Enabling this setting prevents attacks involved passing session ids in URLs. This setting was added in PHP 4.3.0.

  • session.cookie_path specifies path to set in session_cookie. Defaults to /.

  • session.cookie_domain specifies domain to set in session_cookie. Default is none at all.

  • session.cache_limiter specifies cache control method to use for session pages (none/nocache/private/private_no_expire/public). Defaults to nocache.

  • session.cache_expire specifies time-to-live for cached session pages in minutes, this has no effect for nocache limiter. Defaults to 180.

  • session.use_trans_sid whether transparent sid support is enabled or not. Defaults to 0 (disabled).

    注: For PHP 4.1.2 or less, it is enabled by compiling with --enable-trans-sid. From PHP 4.2.0, trans-sid feature is always compiled.

    URL based session management has additional security risks compared to cookie based session management. Users may send an URL that contains an active session ID to their friends by email or users may save an URL that contains a session ID to their bookmarks and access your site with the same session ID always, for example.

  • url_rewriter.tags specifies which html tags are rewritten to include session id if transparent sid support is enabled. Defaults to a=href,area=href,frame=src,input=src,form=fakeentry

The track_vars and register_globals configuration settings influence how the session variables get stored and restored.

注: As of PHP 4.0.3, track_vars is always turned on.

资源类型

该扩展模块未定义任何资源类型。

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

SID (string)

Constant containing the session name and session ID in the form of "name=ID".

范例

注: As of PHP 4.1.0, $_SESSION is available as global variable just like $_POST, $_GET, $_REQUEST and so on. Not like $HTTP_SESSION_VARS, $_SESSION is always global. Therefore, global should not be used for $_SESSION.

If track_vars is enabled and register_globals is disabled, only members of the global associative array $HTTP_SESSION_VARS can be registered as session variables. The restored session variables will only be available in the array $HTTP_SESSION_VARS.

例子 1. Registering a variable with track_vars enabled

<?php
session_start();
if (isset($HTTP_SESSION_VARS['count'])) {
   $HTTP_SESSION_VARS['count']++;
}
else {
   $HTTP_SESSION_VARS['count'] = 0;
}
?>

Use of $_SESSION (or $HTTP_SESSION_VARS with PHP 4.0.6 or less) is recommended for security and code readablity. With $_SESSION or $HTTP_SESSION_VARS, there is no need to use session_register()/session_unregister()/session_is_registered() functions. Users can access session variable like a normal variable.

例子 2. Registering a variable with $_SESSION.

<?php
session_start();
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
if (!isset($_SESSION['count'])) {
    $_SESSION['count'] = 0;
} else {
    $_SESSION['count']++;
}
?>

例子 3. Unregistering a variable with $_SESSION.

<?php
session_start();
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
unset($_SESSION['count']);
?>

If register_globals is enabled, then all global variables can be registered as session variables and the session variables will be restored to corresponding global variables. Since PHP must know which global variables are registered as session variables, users must register variables with session_register() function while $HTTP_SESSION_VARS/$_SESSION does not need to use session_register().

注意

If you are using $HTTP_SESSION_VARS/$_SESSION and disable register_globals, do not use session_register(), session_is_registered() and session_unregister().

If you enable register_globals, session_unregister() should be used since session variables are registered as global variables when session data is deserialized. Disabling register_globals is recommended for both security and performance reason.

例子 4. Registering a variable with register_globals enabled

<?php
if (!session_is_registered('count')) {
    session_register("count");
    $count = 0;
}
else {
    $count++;
}
?>

If both track_vars and register_globals are enabled, then the globals variables and the $HTTP_SESSION_VARS/$_SESSION entries will reference the same value for already registered variables.

If user use session_register() to register session variable, $HTTP_SESSION_VARS/$_SESSION will not have these variable in array until it is loaded from session storage. (i.e. until next request)

Passing the Session ID

There are two methods to propagate a session id:

  • Cookies

  • URL parameter

The session module supports both methods. Cookies are optimal, but since they are not reliable (clients are not bound to accept them), we cannot rely on them. The second method embeds the session id directly into URLs.

PHP is capable of doing this transparently when compiled with --enable-trans-sid. If you enable this option, relative URIs will be changed to contain the session id automatically. Alternatively, you can use the constant SID which is defined, if the client did not send the appropriate cookie. SID is either of the form session_name=session_id or is an empty string.

注: The arg_separator.output php.ini directive allows to customize the argument seperator.

The following example demonstrates how to register a variable, and how to link correctly to another page using SID.

例子 5. Counting the number of hits of a single user

<?php
if (!session_is_registered('count')) {
    session_register('count');
    $count = 1;
}
else {
    $count++;
}
?>

Hello visitor, you have seen this page <?php echo $count; ?> times.<p>;

<?php
# the <?php echo SID?> (<?=SID?> can be used if short tag is enabled)
# is necessary to preserve the session id
# in the case that the user has disabled cookies
?>

To continue, <A HREF="nextpage.php?<?php echo SID?>">click here</A>

The <?=SID?> is not necessary, if --enable-trans-sid was used to compile PHP.

注: Non-relative URLs are assumed to point to external sites and hence don't append the SID, as it would be a security risk to leak the SID to a different server.

Custom Session Handlers

To implement database storage, or any other storage method, you will need to use session_set_save_handler() to create a set of user-level storage functions.

目录
session_cache_expire — Return current cache expire
session_cache_limiter — Get and/or set the current cache limiter
session_decode — Decodes session data from a string
session_destroy — Destroys all data registered to a session
session_encode — 将当前会话数据编码为一个字符串
session_get_cookie_params — Get the session cookie parameters
session_id — Get and/or set the current session id
session_is_registered — Find out if a variable is registered in a session
session_module_name — Get and/or set the current session module
session_name — Get and/or set the current session name
session_readonly — Begin session - reinitializes frozen variables, but no writeback on request end
session_register — Register one or more variables with the current session
session_save_path — Get and/or set the current session save path
session_set_cookie_params — Set the session cookie parameters
session_set_save_handler — Sets user-level session storage functions
session_start — Initialize session data
session_unregister — Unregister a variable from the current session
session_unset — Free all session variables
session_write_close — Write session data and end session

后退 | 起点 | 前进
sesam_settransaction | 上一级 | session_cache_expire


session_cache_expire

(PHP 4 >= 4.2.0)

session_cache_expire -- Return current cache expire

Description

int session_cache_expire ( [int new_cache_expire])

session_cache_expire() returns current cache expire. If new_cache_expire is given, the current cache expire is replaced with new_cache_expire.

后退 | 起点 | 前进
Session handling functions | 上一级 | session_cache_limiter


session_cache_limiter

(PHP 4 >= 4.0.3)

session_cache_limiter -- Get and/or set the current cache limiter

Description

string session_cache_limiter ( [string cache_limiter])

session_cache_limiter() returns the name of the current cache limiter. If cache_limiter is specified, the name of the current cache limiter is changed to the new value.

The cache limiter controls the cache control HTTP headers sent to the client. These headers determine the rules by which the page content may be cached. Setting the cache limiter to nocache, for example, would disallow any client-side caching. A value of public, however, would permit caching. It can also be set to private, which is slightly more restrictive than public.

In private mode, the Expire header sent to the client may cause confusion for some browsers, including Mozilla. You can avoid this problem by using private_no_expire mode. The expire header is never sent to the client in this mode.

注: private_no_expire was added in PHP 4.2.0dev.

The cache limiter is reset to the default value stored in session.cache_limiter at request startup time. Thus, you need to call session_cache_limiter() for every request (and before session_start() is called).

例子 1. session_cache_limiter() examples

<?php

# set the cache limiter to 'private'

session_cache_limiter('private');
$cache_limiter = session_cache_limiter();

echo "The cache limiter is now set to $cache_limiter<p>";
?>

后退 | 起点 | 前进
session_cache_expire | 上一级 | session_decode


session_decode

(PHP 4 )

session_decode -- Decodes session data from a string

Description

bool session_decode ( string data)

session_decode() decodes the session data in data, setting variables stored in the session.

后退 | 起点 | 前进
session_cache_limiter | 上一级 | session_destroy


session_destroy

(PHP 4 )

session_destroy -- Destroys all data registered to a session

Description

bool session_destroy ( void)

session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie.

This function returns TRUE on success and FALSE on failure to destroy the session data.

例子 1. Destroying a session

<?php

// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
session_unset();
// Finally, destroy the session.
session_destroy();

?>

例子 2. Destroying a session with $_SESSION

<?php

// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// Finally, destroy the session.
session_destroy();

?>

后退 | 起点 | 前进
session_decode | 上一级 | session_encode


session_encode

(PHP 4 )

session_encode -- 将当前会话数据编码为一个字符串

描述

string session_encode ( void)

session_encode()返回一个字符串,该字符串包含有被编码的当前会话数据.

后退 | 起点 | 前进
session_destroy | 上一级 | session_get_cookie_params


session_get_cookie_params

(PHP 4 )

session_get_cookie_params -- Get the session cookie parameters

Description

array session_get_cookie_params ( void)

The session_get_cookie_params() function returns an array with the current session cookie information, the array contains the following items:

  • "lifetime" - The lifetime of the cookie.

  • "path" - The path where information is stored.

  • "domain" - The domain of the cookie.

  • "secure" - The cookie should only be sent over secure connections. (This item was added in PHP 4.0.4.)

后退 | 起点 | 前进
session_encode | 上一级 | session_id


session_id

(PHP 4 )

session_id -- Get and/or set the current session id

Description

string session_id ( [string id])

session_id() returns the session id for the current session.

If id is specified, it will replace the current session id. session_id() needs to be called before session_start() for that purpose. Depending on the session handler, not all characters are allowed within the session id. For example, the file session handler only allows characters in the range a-z, A-Z and 0-9!

The constant SID can also be used to retrieve the current name and session id as a string suitable for adding to URLs. Note that SID is only defined if the client didn't sent the right cookie. See also Session handling.

See also session_start().

后退 | 起点 | 前进
session_get_cookie_params | 上一级 | session_is_registered


session_is_registered

(PHP 4 )

session_is_registered -- Find out if a variable is registered in a session

Description

bool session_is_registered ( string name)

session_is_registered() returns TRUE if there is a variable with the name name registered in the current session.

注: If $_SESSION (or $HTTP_SESSION_VARS for PHP 4.0.6 or less) is used, use isset() to check a variable is registered in $_SESSION.

注意

If you are using $_SESSION (or $HTTP_SESSION_VARS), do not use session_register(), session_is_registered() and session_unregister().

后退 | 起点 | 前进
session_id | 上一级 | session_module_name


session_module_name

(PHP 4 )

session_module_name -- Get and/or set the current session module

Description

string session_module_name ( [string module])

session_module_name() returns the name of the current session module. If module is specified, that module will be used instead.

后退 | 起点 | 前进
session_is_registered | 上一级 | session_name


session_name

(PHP 4 )

session_name -- Get and/or set the current session name

Description

string session_name ( [string name])

session_name() returns the name of the current session. If name is specified, the name of the current session is changed to its value.

The session name references the session id in cookies and URLs. It should contain only alphanumeric characters; it should be short and descriptive (i.e. for users with enabled cookie warnings). The session name is reset to the default value stored in session.name at request startup time. Thus, you need to call session_name() for every request (and before session_start() or session_register() are called).

例子 1. session_name() examples

<?php

// set the session name to WebsiteID

$previous_name = session_name("WebsiteID");

echo "The previous session name was $previous_name<p>";
?>

后退 | 起点 | 前进
session_module_name | 上一级 | session_readonly


session_readonly

(no version information, might be only in CVS)

session_readonly -- Begin session - reinitializes frozen variables, but no writeback on request end

Description

void session_readonly ( void)

Read in session data without locking the session data. Changing session data is not possible, but frameset performance will be improved.

后退 | 起点 | 前进
session_name | 上一级 | session_register


session_register

(PHP 4 )

session_register -- Register one or more variables with the current session

Description

bool session_register ( mixed name [, mixed ...])

session_register() accepts a variable number of arguments, any of which can be either a string holding the name of a variable or an array consisting of variable names or other arrays. For each name, session_register() registers the global variable with that name in the current session.

注意

This registers a global variable. If you want to register a session variable inside a function, you need to make sure to make it global using global() or use the session arrays as noted below.

注意

If you are using $_SESSION (or $HTTP_SESSION_VARS), do not use session_register(), session_is_registered() and session_unregister().

This function returns TRUE when all of the variables are successfully registered with the session.

If session_start() was not called before this function is called, an implicit call to session_start() with no parameters will be made.

You can also create a session variable by simply setting the appropriate member of the $_SESSION or $HTTP_SESSION_VARS (PHP < 4.1.0) array.

$barney = "A big purple dinosaur.";
session_register("barney");

$_SESSION["zim"] = "An invader from another planet.";

# The old way was to use $HTTP_SESSION_VARS
$HTTP_SESSION_VARS["spongebob"] = "He's got square pants.";

注: It is not currently possible to register resource variables in a session. For example, you can not create a connection to a database and store the connection id as a session variable and expect the connection to still be valid the next time the session is restored. PHP functions that return a resource are identified by having a return type of resource in their function definitions. A list of functions that return resources are available in the resource types appendix.

If $_SESSION (or $HTTP_SESSION_VARS for PHP 4.0.6 or less) is used, assign variable to $_SESSION. i.e. $_SESSION['var'] = 'ABC';

See also session_is_registered() and session_unregister().

后退 | 起点 | 前进
session_readonly | 上一级 | session_save_path


session_save_path

(PHP 4 )

session_save_path -- Get and/or set the current session save path

Description

string session_save_path ( [string path])

session_save_path() returns the path of the current directory used to save session data. If path is specified, the path to which data is saved will be changed.

注: On some operating systems, you may want to specify a path on a filesystem that handles lots of small files efficiently. For example, on Linux, reiserfs may provide better performance than ext2fs.

后退 | 起点 | 前进
session_register | 上一级 | session_set_cookie_params


session_set_cookie_params

(PHP 4 )

session_set_cookie_params -- Set the session cookie parameters

Description

void session_set_cookie_params ( int lifetime [, string path [, string domain [, bool secure]]])

Set cookie parameters defined in the php.ini file. The effect of this function only lasts for the duration of the script.

注: The secure parameter was added in PHP 4.0.4.

后退 | 起点 | 前进
session_save_path | 上一级 | session_set_save_handler


session_set_save_handler

(PHP 4 )

session_set_save_handler -- Sets user-level session storage functions

Description

bool session_set_save_handler ( string open, string close, string read, string write, string destroy, string gc)

session_set_save_handler() sets the user-level session storage functions which are used for storing and retrieving data associated with a session. This is most useful when a storage method other than those supplied by PHP sessions is preferred. i.e. Storing the session data in a local database. 如果成功则返回 TRUE，失败则返回 FALSE。

注: You must set the configuration option session.save_handler to user in your php.ini file for session_set_save_handler() to take effect.

注: The "write" handler is not executed until after the output stream is closed. Thus, output from debugging statements in the "write" handler will never be seen in the browser. If debugging output is necessary, it is suggested that the debug output be written to a file instead.

注: The write handler is not executed if the session contains no data; this applies even if empty session variables are registered. This differs to the default file-based session save handler, which creates empty session files.

The following example provides file based session storage similar to the PHP sessions default save handler files. This example could easily be extended to cover database storage using your favorite PHP supported database engine.

Read function must return string value always to make save handler work as expected. Return empty string if there is no data to read. Return values from other handlers are converted to boolean expression. TRUE for success, FALSE for failure.

例子 1. session_set_save_handler() example

<?php
function open ($save_path, $session_name) {
  global $sess_save_path, $sess_session_name;

  $sess_save_path = $save_path;
  $sess_session_name = $session_name;
  return(true);
}

function close() {
  return(true);
}

function read ($id) {
  global $sess_save_path, $sess_session_name;

  $sess_file = "$sess_save_path/sess_$id";
  if ($fp = @fopen($sess_file, "r")) {
    $sess_data = fread($fp, filesize($sess_file));
    return($sess_data);
  } else {
    return(""); // Must return "" here.
  }

}

function write ($id, $sess_data) {
  global $sess_save_path, $sess_session_name;

  $sess_file = "$sess_save_path/sess_$id";
  if ($fp = @fopen($sess_file, "w")) {
    return(fwrite($fp, $sess_data));
  } else {
    return(false);
  }

}

function destroy ($id) {
  global $sess_save_path, $sess_session_name;

  $sess_file = "$sess_save_path/sess_$id";
  return(@unlink($sess_file));
}

/*********************************************
 * WARNING - You will need to implement some *
 * sort of garbage collection routine here.  *
 *********************************************/
function gc ($maxlifetime) {
  return true;
}

session_set_save_handler ("open", "close", "read", "write", "destroy", "gc");

session_start();

// proceed to use sessions normally

?>

后退 | 起点 | 前进
session_set_cookie_params | 上一级 | session_start


session_start

(PHP 4 )

session_start -- Initialize session data

Description

bool session_start ( void)

session_start() creates a session (or resumes the current one based on the session id being passed via a GET variable or a cookie).

If you want to use a named session, you must call session_name() before calling session_start().

This function always returns TRUE.

注: If you are using cookie-based sessions, you must call session_start() before anything is output to the browser.

session_start() will register internal output handler for URL rewriting when trans-sid is enabled. If a user uses ob_gzhandler or like with ob_start(), the order of output handler is important for proper output. For example, user must register ob_gzhandler before session start.

注: Use of zlib.output_compression is recommended rather than ob_gzhandler()

后退 | 起点 | 前进
session_set_save_handler | 上一级 | session_unregister


session_unregister

(PHP 4 )

session_unregister -- Unregister a variable from the current session

Description

bool session_unregister ( string name)

session_unregister() unregisters (forgets) the global variable named name from the current session.

This function returns TRUE when the variable is successfully unregistered from the session.

注: If $_SESSION (or $HTTP_SESSION_VARS for PHP 4.0.6 or less) is used, use unset() to unregister a session variable.

注意

This function doesn't unset the corresponding global variable for name, it only prevents the variable from being saved as part of the session. You must call unset() to remove the corresponding global variable.

注意

If you are using $_SESSION (or $HTTP_SESSION_VARS), do not use session_register(), session_is_registered() and session_unregister().

后退 | 起点 | 前进
session_start | 上一级 | session_unset


session_unset

(PHP 4 )

session_unset -- Free all session variables

Description

void session_unset ( void)

The session_unset() function frees all session variables currently registered.

注: If $_SESSION (or $HTTP_SESSION_VARS for PHP 4.0.6 or less) is used, use unset() to unregister session variable. i.e. $_SESSION = array();

后退 | 起点 | 前进
session_unregister | 上一级 | session_write_close


session_write_close

(PHP 4 >= 4.0.4)

session_write_close -- Write session data and end session

Description

void session_write_close ( void)

End the current session and store session data.

Session data is usually stored after your script terminated without the need to call session_write_close(), but as session data is locked to prevent concurrent writes only one script may operate on a session at any time. When using framesets together with sessions you will experience the frames loading one by one due to this locking. You can reduce the time needed to load all the frames by ending the session as soon as all changes to session variables are done.

后退 | 起点 | 前进
session_unset | 上一级 | Shared Memory Functions


Shared Memory Functions

PHP 手册
后退 前进

XCIII. Shared Memory Functions

介绍

Shmop is an easy to use set of functions that allows PHP to read, write, create and delete UNIX shared memory segments. These functions will not typically work on Windows, as it does not support shared memory. As of Windows 2000 though, enabling the php_shmop.dll in your php.ini will enable this functionality though.

注: In PHP 4.0.3, these functions were prefixed by shm rather than shmop.

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

To use shmop you will need to compile php with the --enable-shmop parameter in your configure line.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

预定义常量

该扩展模块未定义任何常量。

范例

例子 1. Shared Memory Operations Overview

<?php

// Create 100 byte shared memory block with system id if 0xff3
$shm_id = shmop_open(0xff3, "c", 0644, 100);
if(!$shm_id) {
    echo "Couldn't create shared memory segment\n";
}

// Get shared memory block's size
$shm_size = shmop_size($shm_id);
echo "SHM Block Size: ".$shm_size. " has been created.\n";

// Lets write a test string into shared memory
$shm_bytes_written = shmop_write($shm_id, "my shared memory block", 0);
if($shm_bytes_written != strlen("my shared memory block")) {
    echo "Couldn't write the entire length of data\n";
}

// Now lets read the string back
$my_string = shmop_read($shm_id, 0, $shm_size);
if(!$my_string) {
    echo "Couldn't read from shared memory block\n";
}
echo "The data inside shared memory was: ".$my_string."\n";

//Now lets delete the block and close the shared memory segment
if(!shmop_delete($shm_id)) {
    echo "Couldn't mark shared memory block for deletion.";
}
shmop_close($shm_id);

?>

目录
shmop_close — Close shared memory block
shmop_delete — Delete shared memory block
shmop_open — Create or open shared memory block
shmop_read — Read data from shared memory block
shmop_size — Get size of shared memory block
shmop_write — Write data into shared memory block

后退 | 起点 | 前进
session_write_close | 上一级 | shmop_close


shmop_close

(PHP 4 >= 4.0.4)

shmop_close -- Close shared memory block

Description

int shmop_close ( int shmid)

shmop_close() is used to close a shared memory block.

shmop_close() takes the shmid, which is the shared memory block identifier created by shmop_open().

例子 1. Closing shared memory block

<?php
shmop_close($shm_id);
?>

This example will close shared memory block identified by $shm_id.

后退 | 起点 | 前进
Shared Memory Functions | 上一级 | shmop_delete


shmop_delete

(PHP 4 >= 4.0.4)

shmop_delete -- Delete shared memory block

Description

int shmop_delete ( int shmid)

shmop_delete() is used to delete a shared memory block.

shmop_delete() takes the shmid, which is the shared memory block identifier created by shmop_open(). On success 1 is returned, on failure 0 is returned.

例子 1. Deleting shared memory block

<?php
shmop_delete($shm_id);
?>

This example will delete shared memory block identified by $shm_id.

后退 | 起点 | 前进
shmop_close | 上一级 | shmop_open


shmop_open

(PHP 4 >= 4.0.4)

shmop_open -- Create or open shared memory block

Description

int shmop_open ( int key, string flags, int mode, int size)

shmop_open() can create or open a shared memory block.

shmop_open() takes 4 parameters: key, which is the system's id for the shared memory block, this parameter can be passed as a decimal or hex. The second parameter are the flags that you can use:

  • "a" for access (sets SHM_RDONLY for shmat) use this flag when you need to open an existing shared memory segment for read only

  • "c" for create (sets IPC_CREATE) use this flag when you need to create a new shared memory segment or if a segment with the same key exists, try to open it for read and write

  • "w" for read & write access use this flag when you need to read and write to a shared memory segment, use this flag in most cases.

  • "n" create a new memory segment (sets IPC_CREATE|IPC_EXCL) use this flag when you want to create a new shared memory segment but if one already exists with the same flag, fail. This is useful for security purposes, using this you can prevent race condition exploits.

The third parameter is the mode, which are the permissions that you wish to assign to your memory segment, those are the same as permission for a file. Permissions need to be passed in octal form ex. 0644. The last parameter is size of the shared memory block you wish to create in bytes.

注: Note: the 3rd and 4th should be entered as 0 if you are opening an existing memory segment. On success shmop_open() will return an id that you can use to access the shared memory segment you've created.

例子 1. Create a new shared memory block

<?php
$shm_id = shmop_open(0x0fff, "c", 0644, 100);
?>

This example opened a shared memory block with a system id of 0x0fff.

后退 | 起点 | 前进
shmop_delete | 上一级 | shmop_read


shmop_read

(PHP 4 >= 4.0.4)

shmop_read -- Read data from shared memory block

Description

string shmop_read ( int shmid, int start, int count)

shmop_read() will read a string from shared memory block.

shmop_read() takes 3 parameters: shmid, which is the shared memory block identifier created by shmop_open(), offset from which to start reading and count on the number of bytes to read.

例子 1. Reading shared memory block

<?php
$shm_data = shmop_read($shm_id, 0, 50);
?>

This example will read 50 bytes from shared memory block and place the data inside $shm_data.

后退 | 起点 | 前进
shmop_open | 上一级 | shmop_size


shmop_size

(PHP 4 >= 4.0.4)

shmop_size -- Get size of shared memory block

Description

int shmop_size ( int shmid)

shmop_size() is used to get the size, in bytes of the shared memory block.

shmop_size() takes the shmid, which is the shared memory block identifier created by shmop_open(), the function will return and int, which represents the number of bytes the shared memory block occupies.

例子 1. Getting the size of the shared memory block

<?php
$shm_size = shmop_size($shm_id);
?>

This example will put the size of shared memory block identified by $shm_id into $shm_size.

后退 | 起点 | 前进
shmop_read | 上一级 | shmop_write


shmop_write

(PHP 4 >= 4.0.4)

shmop_write -- Write data into shared memory block

Description

int shmop_write ( int shmid, string data, int offset)

shmop_write() will write a string into shared memory block.

shmop_write() takes 3 parameters: shmid, which is the shared memory block identifier created by shmop_open(), data, a string that you want to write into shared memory block and offset, which specifies where to start writing data inside the shared memory segment.

例子 1. Writing to shared memory block

<?php
$shm_bytes_written = shmop_write($shm_id, $my_string, 0);
?>

This example will write data inside $my_string into shared memory block, $shm_bytes_written will contain the number of bytes written.

后退 | 起点 | 前进
shmop_size | 上一级 | Shockwave Flash functions


Shockwave Flash functions

PHP 手册
后退 前进

XCIV. Shockwave Flash functions

介绍

PHP offers the ability to create Shockwave Flash files via Paul Haeberli's libswf module.

注: SWF support was added in PHP 4 RC2.

The libswf does not have support for Windows. The development of that library has been stopped, and the source is not available to port it to another systems.

For up to date SWF support take a look at the MING functions.

需求

You need the libswf library to compile PHP with support for this extension. You can download libswf at ftp://ftp.sgi.com/sgi/graphics/grafica/flash.

安装

Once you have libswf all you need to do is to configure --with-swf[=DIR] where DIR is a location containing the directories include and lib. The include directory has to contain the swf.h file and the lib directory has to contain the libswf.a file. If you unpack the libswf distribution the two files will be in one directory. Consequently you will have to copy the files to the proper location manually.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

MOD_COLOR (integer)

MOD_MATRIX (integer)

TYPE_PUSHBUTTON (integer)

TYPE_MENUBUTTON (integer)

BSHitTest (float)

BSDown (float)

BSOver (float)

BSUp (float)

OverDowntoIdle (integer)

IdletoOverDown (integer)

OutDowntoIdle (integer)

OutDowntoOverDown (integer)

OverDowntoOutDown (integer)

OverUptoOverDown (integer)

OverUptoIdle (integer)

IdletoOverUp (integer)

ButtonEnter (integer)

ButtonExit (integer)

MenuEnter (integer)

MenuExit (integer)

范例

Once you've successfully installed PHP with Shockwave Flash support you can then go about creating Shockwave files from PHP. You would be surprised at what you can do, take the following code:

例子 1. SWF example

<?php
swf_openfile ("test.swf", 256, 256, 30, 1, 1, 1);
swf_ortho2 (-100, 100, -100, 100);
swf_defineline (1, -70, 0, 70, 0, .2);
swf_definerect (4, 60, -10, 70, 0, 0);
swf_definerect (5, -60, 0, -70, 10, 0);
swf_addcolor (0, 0, 0, 0);

swf_definefont (10, "Mod");
swf_fontsize (5);
swf_fontslant (10);
swf_definetext (11, "This be Flash wit PHP!", 1);

swf_pushmatrix ();
swf_translate (-50, 80, 0);
swf_placeobject (11, 60);
swf_popmatrix ();

for ($i = 0; $i < 30; $i++) {
    $p = $i/(30-1);
    swf_pushmatrix ();
    swf_scale (1-($p*.9), 1, 1);
    swf_rotate (60*$p,  'z');
    swf_translate (20+20*$p, $p/1.5, 0);
    swf_rotate (270*$p,  'z');
    swf_addcolor ($p, 0, $p/1.2, -$p);
    swf_placeobject (1, 50);
    swf_placeobject (4, 50);
    swf_placeobject (5, 50);
    swf_popmatrix ();
    swf_showframe ();
}

for ($i = 0; $i < 30; $i++) {
    swf_removeobject (50);
    if (($i%4) == 0) {
        swf_showframe ();
    }
}

swf_startdoaction ();
swf_actionstop ();
swf_enddoaction ();

swf_closefile ();
?>

目录
swf_actiongeturl — Get a URL from a Shockwave Flash movie
swf_actiongotoframe — Play a frame and then stop
swf_actiongotolabel — Display a frame with the specified label
swf_actionnextframe — Go foward one frame
swf_actionplay — Start playing the flash movie from the current frame
swf_actionprevframe — Go backwards one frame
swf_actionsettarget — Set the context for actions
swf_actionstop — Stop playing the flash movie at the current frame
swf_actiontogglequality — Toggle between low and high quality
swf_actionwaitforframe — Skip actions if a frame has not been loaded
swf_addbuttonrecord — Controls location, appearance and active area of the current button
swf_addcolor — Set the global add color to the rgba value specified
swf_closefile — Close the current Shockwave Flash file
swf_definebitmap — Define a bitmap
swf_definefont — Defines a font
swf_defineline — Define a line
swf_definepoly — Define a polygon
swf_definerect — Define a rectangle
swf_definetext — Define a text string
swf_endbutton — End the definition of the current button
swf_enddoaction — End the current action
swf_endshape — Completes the definition of the current shape
swf_endsymbol — End the definition of a symbol
swf_fontsize — Change the font size
swf_fontslant — Set the font slant
swf_fonttracking — Set the current font tracking
swf_getbitmapinfo — Get information about a bitmap
swf_getfontinfo — The height in pixels of a capital A and a lowercase x
swf_getframe — Get the frame number of the current frame
swf_labelframe — Label the current frame
swf_lookat — Define a viewing transformation
swf_modifyobject — Modify an object
swf_mulcolor — Sets the global multiply color to the rgba value specified
swf_nextid — Returns the next free object id
swf_oncondition — Describe a transition used to trigger an action list
swf_openfile — Open a new Shockwave Flash file
swf_ortho2 — Defines 2D orthographic mapping of user coordinates onto the current viewport
swf_ortho — Defines an orthographic mapping of user coordinates onto the current viewport
swf_perspective — Define a perspective projection transformation
swf_placeobject — Place an object onto the screen
swf_polarview — Define the viewer's position with polar coordinates
swf_popmatrix — Restore a previous transformation matrix
swf_posround — Enables or Disables the rounding of the translation when objects are placed or moved
swf_pushmatrix — Push the current transformation matrix back unto the stack
swf_removeobject — Remove an object
swf_rotate — Rotate the current transformation
swf_scale — Scale the current transformation
swf_setfont — Change the current font
swf_setframe — Switch to a specified frame
swf_shapearc — Draw a circular arc
swf_shapecurveto3 — Draw a cubic bezier curve
swf_shapecurveto — Draw a quadratic bezier curve between two points
swf_shapefillbitmapclip — Set current fill mode to clipped bitmap
swf_shapefillbitmaptile — Set current fill mode to tiled bitmap
swf_shapefilloff — Turns off filling
swf_shapefillsolid — Set the current fill style to the specified color
swf_shapelinesolid — Set the current line style
swf_shapelineto — Draw a line
swf_shapemoveto — Move the current position
swf_showframe — Display the current frame
swf_startbutton — Start the definition of a button
swf_startdoaction — Start a description of an action list for the current frame
swf_startshape — Start a complex shape
swf_startsymbol — Define a symbol
swf_textwidth — Get the width of a string
swf_translate — Translate the current transformations
swf_viewport — Select an area for future drawing

后退 | 起点 | 前进
shmop_write | 上一级 | swf_actiongeturl


swf_actiongeturl

(PHP 4 )

swf_actiongeturl -- Get a URL from a Shockwave Flash movie

Description

void swf_actiongeturl ( string url, string target)

The swf_actionGetUrl() function gets the URL specified by the parameter url with the target target.

后退 | 起点 | 前进
Shockwave Flash functions | 上一级 | swf_actiongotoframe


swf_actiongotoframe

(PHP 4 )

swf_actiongotoframe -- Play a frame and then stop

Description

void swf_actiongotoframe ( int framenumber)

The swf_actionGotoFrame() function will go to the frame specified by framenumber, play it, and then stop.

后退 | 起点 | 前进
swf_actiongeturl | 上一级 | swf_actiongotolabel


swf_actiongotolabel

(PHP 4 )

swf_actiongotolabel -- Display a frame with the specified label

Description

void swf_actiongotolabel ( string label)

The swf_actionGotoLabel() function displays the frame with the label given by the label parameter and then stops.

后退 | 起点 | 前进
swf_actiongotoframe | 上一级 | swf_actionnextframe


swf_actionnextframe

(PHP 4 )

swf_actionnextframe -- Go foward one frame

Description

void swf_actionnextframe ( void)

Go foward one frame.

后退 | 起点 | 前进
swf_actiongotolabel | 上一级 | swf_actionplay


swf_actionplay

(PHP 4 )

swf_actionplay -- Start playing the flash movie from the current frame

Description

void swf_actionplay ( void)

Start playing the flash movie from the current frame.

后退 | 起点 | 前进
swf_actionnextframe | 上一级 | swf_actionprevframe


swf_actionprevframe

(PHP 4 )

swf_actionprevframe -- Go backwards one frame

Description

void swf_actionprevframe ( void)

后退 | 起点 | 前进
swf_actionplay | 上一级 | swf_actionsettarget


swf_actionsettarget

(PHP 4 )

swf_actionsettarget -- Set the context for actions

Description

void swf_actionsettarget ( string target)

The swf_actionSetTarget() function sets the context for all actions. You can use this to control other flash movies that are currently playing.

后退 | 起点 | 前进
swf_actionprevframe | 上一级 | swf_actionstop


swf_actionstop

(PHP 4 )

swf_actionstop -- Stop playing the flash movie at the current frame

Description

void swf_actionstop ( void)

Stop playing the flash movie at the current frame.

后退 | 起点 | 前进
swf_actionsettarget | 上一级 | swf_actiontogglequality


swf_actiontogglequality

(PHP 4 )

swf_actiontogglequality -- Toggle between low and high quality

Description

void swf_actiontogglequality ( void)

Toggle the flash movie between high and low quality.

后退 | 起点 | 前进
swf_actionstop | 上一级 | swf_actionwaitforframe


swf_actionwaitforframe

(PHP 4 )

swf_actionwaitforframe -- Skip actions if a frame has not been loaded

Description

void swf_actionwaitforframe ( int framenumber, int skipcount)

The swf_actionWaitForFrame() function will check to see if the frame, specified by the framenumber parameter has been loaded, if not it will skip the number of actions specified by the skipcount parameter. This can be useful for "Loading..." type animations.

后退 | 起点 | 前进
swf_actiontogglequality | 上一级 | swf_addbuttonrecord


swf_addbuttonrecord

(PHP 4 )

swf_addbuttonrecord -- Controls location, appearance and active area of the current button

Description

void swf_addbuttonrecord ( int states, int shapeid, int depth)

The swf_addbuttonrecord() function allows you to define the specifics of using a button. The first parameter, states, defines what states the button can have, these can be any or all of the following constants: BSHitTest, BSDown, BSOver or BSUp. The second parameter, the shapeid is the look of the button, this is usually the object id of the shape of the button. The depth parameter is the placement of the button in the current frame.

例子 1. swf_addbuttonrecord() function example

swf_startButton ($objid, TYPE_MENUBUTTON);
    swf_addButtonRecord (BSDown|BSOver, $buttonImageId, 340);
    swf_onCondition (MenuEnter);
        swf_actionGetUrl ("http://www.designmultimedia.com", "_level1");
    swf_onCondition (MenuExit);
        swf_actionGetUrl ("", "_level1");
swf_endButton ();

后退 | 起点 | 前进
swf_actionwaitforframe | 上一级 | swf_addcolor


swf_addcolor

(PHP 4 )

swf_addcolor -- Set the global add color to the rgba value specified

Description

void swf_addcolor ( float r, float g, float b, float a)

The swf_addcolor() function sets the global add color to the rgba color specified. This color is then used (implicitly) by the swf_placeobject(), swf_modifyobject() and the swf_addbuttonrecord() functions. The color of the object will be add by the rgba values when the object is written to the screen.

注: The rgba values can be either positive or negative.

后退 | 起点 | 前进
swf_addbuttonrecord | 上一级 | swf_closefile


swf_closefile

(PHP 4 )

swf_closefile -- Close the current Shockwave Flash file

Description

void swf_closefile ( [int return_file])

Close a file that was opened by the swf_openfile() function. If the return_file parameter is set then the contents of the SWF file are returned from the function.

例子 1. Creating a simple flash file based on user input and outputting it and saving it in a database

<?php

// The $text variable is submitted by the
// user

// Global variables for database
// access (used in the swf_savedata() function)
$DBHOST = "localhost";
$DBUSER = "sterling";
$DBPASS = "secret";

swf_openfile ("php://stdout", 256, 256, 30, 1, 1, 1);

    swf_definefont (10, "Ligon-Bold");
        swf_fontsize (12);
        swf_fontslant (10);

    swf_definetext (11, $text, 1);

    swf_pushmatrix ();
        swf_translate (-50, 80, 0);
        swf_placeobject (11, 60);
    swf_popmatrix ();

    swf_showframe ();

    swf_startdoaction ();
        swf_actionstop ();
    swf_enddoaction ();

$data = swf_closefile (1);

$data ?
  swf_savedata ($data) :
  die ("Error could not save SWF file");

// void swf_savedata (string data)
// Save the generated file a database
// for later retrieval
function swf_savedata ($data)
{
    global $DBHOST,
           $DBUSER,
           $DBPASS;

    $dbh = @mysql_connect ($DBHOST, $DBUSER, $DBPASS);

    if (!$dbh) {
        die (sprintf ("Error [%d]: %s",
                      mysql_errno (), mysql_error ()));
    }

    $stmt = "INSERT INTO swf_files (file) VALUES ('$data')";

    $sth = @mysql_query ($stmt, $dbh);

    if (!$sth) {
        die (sprintf ("Error [%d]: %s",
                      mysql_errno (), mysql_error ()));
    }

    @mysql_free_result ($sth);
    @mysql_close ($dbh);
}
?>

后退 | 起点 | 前进
swf_addcolor | 上一级 | swf_definebitmap


swf_definebitmap

(PHP 4 )

swf_definebitmap -- Define a bitmap

Description

void swf_definebitmap ( int objid, string image_name)

The swf_definebitmap() function defines a bitmap given a GIF, JPEG, RGB or FI image. The image will be converted into a Flash JPEG or Flash color map format.

后退 | 起点 | 前进
swf_closefile | 上一级 | swf_definefont


swf_definefont

(PHP 4 )

swf_definefont -- Defines a font

Description

void swf_definefont ( int fontid, string fontname)

The swf_definefont() function defines a font given by the fontname parameter and gives it the id specified by the fontid parameter. It then sets the font given by fontname to the current font.

后退 | 起点 | 前进
swf_definebitmap | 上一级 | swf_defineline


swf_defineline

(PHP 4 )

swf_defineline -- Define a line

Description

void swf_defineline ( int objid, float x1, float y1, float x2, float y2, float width)

The swf_defineline() defines a line starting from the x coordinate given by x1 and the y coordinate given by y1 parameter. Up to the x coordinate given by the x2 parameter and the y coordinate given by the y2 parameter. It will have a width defined by the width parameter.

后退 | 起点 | 前进
swf_definefont | 上一级 | swf_definepoly


swf_definepoly

(PHP 4 )

swf_definepoly -- Define a polygon

Description

void swf_definepoly ( int objid, array coords, int npoints, float width)

The swf_definepoly() function defines a polygon given an array of x, y coordinates (the coordinates are defined in the parameter coords). The parameter npoints is the number of overall points that are contained in the array given by coords. The width is the width of the polygon's border, if set to 0.0 the polygon is filled.

后退 | 起点 | 前进
swf_defineline | 上一级 | swf_definerect


swf_definerect

(PHP 4 )

swf_definerect -- Define a rectangle

Description

void swf_definerect ( int objid, float x1, float y1, float x2, float y2, float width)

The swf_definerect() defines a rectangle with an upper left hand coordinate given by the x, x1, and the y, y1. And a lower right hand coordinate given by the x coordinate, x2, and the y coordinate, y2 . Width of the rectangles border is given by the width parameter, if the width is 0.0 then the rectangle is filled.

后退 | 起点 | 前进
swf_definepoly | 上一级 | swf_definetext


swf_definetext

(PHP 4 )

swf_definetext -- Define a text string

Description

void swf_definetext ( int objid, string str, int docenter)

Define a text string (the str parameter) using the current font and font size. The docenter is where the word is centered, if docenter is 1, then the word is centered in x.

后退 | 起点 | 前进
swf_definerect | 上一级 | swf_endbutton


swf_endbutton

(PHP 4 )

swf_endbutton -- End the definition of the current button

Description

void swf_endbutton ( void)

The swf_endButton() function ends the definition of the current button.

后退 | 起点 | 前进
swf_definetext | 上一级 | swf_enddoaction


swf_enddoaction

(PHP 4 )

swf_enddoaction -- End the current action

Description

void swf_enddoaction ( void)

Ends the current action started by the swf_startdoaction() function.

后退 | 起点 | 前进
swf_endbutton | 上一级 | swf_endshape


swf_endshape

(PHP 4 )

swf_endshape -- Completes the definition of the current shape

Description

void swf_endshape ( void)

The swf_endshape() completes the definition of the current shape.

后退 | 起点 | 前进
swf_enddoaction | 上一级 | swf_endsymbol


swf_endsymbol

(PHP 4 )

swf_endsymbol -- End the definition of a symbol

Description

void swf_endsymbol ( void)

The swf_endsymbol() function ends the definition of a symbol that was started by the swf_startsymbol() function.

后退 | 起点 | 前进
swf_endshape | 上一级 | swf_fontsize


swf_fontsize

(PHP 4 )

swf_fontsize -- Change the font size

Description

void swf_fontsize ( float size)

The swf_fontsize() function changes the font size to the value given by the size parameter.

后退 | 起点 | 前进
swf_endsymbol | 上一级 | swf_fontslant


swf_fontslant

(PHP 4 )

swf_fontslant -- Set the font slant

Description

void swf_fontslant ( float slant)

Set the current font slant to the angle indicated by the slant parameter. Positive values create a foward slant, negative values create a negative slant.

后退 | 起点 | 前进
swf_fontsize | 上一级 | swf_fonttracking


swf_fonttracking

(PHP 4 )

swf_fonttracking -- Set the current font tracking

Description

void swf_fonttracking ( float tracking)

Set the font tracking to the value specified by the tracking parameter. This function is used to increase the spacing between letters and text, positive values increase the space and negative values decrease the space between letters.

后退 | 起点 | 前进
swf_fontslant | 上一级 | swf_getbitmapinfo


swf_getbitmapinfo

(PHP 4 )

swf_getbitmapinfo -- Get information about a bitmap

Description

array swf_getbitmapinfo ( int bitmapid)

The swf_getbitmapinfo() function returns an array of information about a bitmap given by the bitmapid parameter. The returned array has the following elements:

  • "size" - The size in bytes of the bitmap.

  • "width" - The width in pixels of the bitmap.

  • "height" - The height in pixels of the bitmap.

后退 | 起点 | 前进
swf_fonttracking | 上一级 | swf_getfontinfo


swf_getfontinfo

(PHP 4 )

swf_getfontinfo -- The height in pixels of a capital A and a lowercase x

Description

array swf_getfontinfo ( void)

The swf_getfontinfo() function returns an associative array with the following parameters:

  • Aheight - The height in pixels of a capital A.

  • xheight - The height in pixels of a lowercase x.

后退 | 起点 | 前进
swf_getbitmapinfo | 上一级 | swf_getframe


swf_getframe

(PHP 4 )

swf_getframe -- Get the frame number of the current frame

Description

int swf_getframe ( void)

The swf_getframe() function gets the number of the current frame.

后退 | 起点 | 前进
swf_getfontinfo | 上一级 | swf_labelframe


swf_labelframe

(PHP 4 )

swf_labelframe -- Label the current frame

Description

void swf_labelframe ( string name)

Label the current frame with the name given by the name parameter.

后退 | 起点 | 前进
swf_getframe | 上一级 | swf_lookat


swf_lookat

(PHP 4 )

swf_lookat -- Define a viewing transformation

Description

void swf_lookat ( float view_x, float view_y, float view_z, float reference_x, float reference_y, float reference_z, float twist)

The swf_lookat() function defines a viewing transformation by giving the viewing position (the parameters view_x, view_y, and view_z) and the coordinates of a reference point in the scene, the reference point is defined by the reference_x, reference_y , and reference_z parameters. The twist controls the rotation along with viewer's z axis.

后退 | 起点 | 前进
swf_labelframe | 上一级 | swf_modifyobject


swf_modifyobject

(PHP 4 )

swf_modifyobject -- Modify an object

Description

void swf_modifyobject ( int depth, int how)

Updates the position and/or color of the object at the specified depth, depth. The parameter how determines what is updated. how can either be the constant MOD_MATRIX or MOD_COLOR or it can be a combination of both (MOD_MATRIX|MOD_COLOR).

MOD_COLOR uses the current mulcolor (specified by the function swf_mulcolor()) and addcolor (specified by the function swf_addcolor()) to color the object. MOD_MATRIX uses the current matrix to position the object.

后退 | 起点 | 前进
swf_lookat | 上一级 | swf_mulcolor


swf_mulcolor

(PHP 4 )

swf_mulcolor -- Sets the global multiply color to the rgba value specified

Description

void swf_mulcolor ( float r, float g, float b, float a)

The swf_mulcolor() function sets the global multiply color to the rgba color specified. This color is then used (implicitly) by the swf_placeobject(), swf_modifyobject() and the swf_addbuttonrecord() functions. The color of the object will be multiplied by the rgba values when the object is written to the screen.

注: The rgba values can be either positive or negative.

后退 | 起点 | 前进
swf_modifyobject | 上一级 | swf_nextid


swf_nextid

(PHP 4 )

swf_nextid -- Returns the next free object id

Description

int swf_nextid ( void)

The swf_nextid() function returns the next available object id.

后退 | 起点 | 前进
swf_mulcolor | 上一级 | swf_oncondition


swf_oncondition

(PHP 4 )

swf_oncondition -- Describe a transition used to trigger an action list

Description

void swf_oncondition ( int transition)

The swf_onCondition() function describes a transition that will trigger an action list. There are several types of possible transitions, the following are for buttons defined as TYPE_MENUBUTTON:

  • IdletoOverUp

  • OverUptoIdle

  • OverUptoOverDown

  • OverDowntoOverUp

  • IdletoOverDown

  • OutDowntoIdle

  • MenuEnter (IdletoOverUp|IdletoOverDown)

  • MenuExit (OverUptoIdle|OverDowntoIdle)

For TYPE_PUSHBUTTON there are the following options:

  • IdletoOverUp

  • OverUptoIdle

  • OverUptoOverDown

  • OverDowntoOverUp

  • OverDowntoOutDown

  • OutDowntoOverDown

  • OutDowntoIdle

  • ButtonEnter (IdletoOverUp|OutDowntoOverDown)

  • ButtonExit (OverUptoIdle|OverDowntoOutDown)

后退 | 起点 | 前进
swf_nextid | 上一级 | swf_openfile


swf_openfile

(PHP 4 )

swf_openfile -- Open a new Shockwave Flash file

Description

void swf_openfile ( string filename, float width, float height, float framerate, float r, float g, float b)

The swf_openfile() function opens a new file named filename with a width of width and a height of height a frame rate of framerate and background with a red color of r a green color of g and a blue color of b.

The swf_openfile() must be the first function you call, otherwise your script will cause a segfault. If you want to send your output to the screen make the filename: "php://stdout" (support for this is in 4.0.1 and up).

后退 | 起点 | 前进
swf_oncondition | 上一级 | swf_ortho2


swf_ortho2

(PHP 4 )

swf_ortho2 -- Defines 2D orthographic mapping of user coordinates onto the current viewport

Description

void swf_ortho2 ( float xmin, float xmax, float ymin, float ymax)

The swf_ortho2() function defines a two dimensional orthographic mapping of user coordinates onto the current viewport, this defaults to one to one mapping of the area of the Flash movie. If a perspective transformation is desired, the swf_perspective () function can be used.

后退 | 起点 | 前进
swf_openfile | 上一级 | swf_ortho


swf_ortho

(PHP 4 >= 4.0.1)

swf_ortho -- Defines an orthographic mapping of user coordinates onto the current viewport

Description

void swf_ortho ( float xmin, float xmax, float ymin, float ymax, float zmin, float zmax)

The swf_ortho() function defines a orthographic mapping of user coordinates onto the current viewport.

后退 | 起点 | 前进
swf_ortho2 | 上一级 | swf_perspective


swf_perspective

(PHP 4 )

swf_perspective -- Define a perspective projection transformation

Description

void swf_perspective ( float fovy, float aspect, float near, float far)

The swf_perspective() function defines a perspective projection transformation. The fovy parameter is field-of-view angle in the y direction. The aspect parameter should be set to the aspect ratio of the viewport that is being drawn onto. The near parameter is the near clipping plane and the far parameter is the far clipping plane.

注: Various distortion artifacts may appear when performing a perspective projection, this is because Flash players only have a two dimensional matrix. Some are not to pretty.

后退 | 起点 | 前进
swf_ortho | 上一级 | swf_placeobject


swf_placeobject

(PHP 4 )

swf_placeobject -- Place an object onto the screen

Description

void swf_placeobject ( int objid, int depth)

Places the object specified by objid in the current frame at a depth of depth. The objid parameter and the depth must be between 1 and 65535.

This uses the current mulcolor (specified by swf_mulcolor()) and the current addcolor (specified by swf_addcolor()) to color the object and it uses the current matrix to position the object.

注: Full RGBA colors are supported.

后退 | 起点 | 前进
swf_perspective | 上一级 | swf_polarview


swf_polarview

(PHP 4 )

swf_polarview -- Define the viewer's position with polar coordinates

Description

void swf_polarview ( float dist, float azimuth, float incidence, float twist)

The swf_polarview() function defines the viewer's position in polar coordinates. The dist parameter gives the distance between the viewpoint to the world space origin. The azimuth parameter defines the azimuthal angle in the x,y coordinate plane, measured in distance from the y axis. The incidence parameter defines the angle of incidence in the y,z plane, measured in distance from the z axis. The incidence angle is defined as the angle of the viewport relative to the z axis. Finally the twist specifies the amount that the viewpoint is to be rotated about the line of sight using the right hand rule.

后退 | 起点 | 前进
swf_placeobject | 上一级 | swf_popmatrix


swf_popmatrix

(PHP 4 )

swf_popmatrix -- Restore a previous transformation matrix

Description

void swf_popmatrix ( void)

The swf_popmatrix() function pushes the current transformation matrix back onto the stack.

后退 | 起点 | 前进
swf_polarview | 上一级 | swf_posround


swf_posround

(PHP 4 )

swf_posround -- Enables or Disables the rounding of the translation when objects are placed or moved

Description

void swf_posround ( int round)

The swf_posround() function enables or disables the rounding of the translation when objects are placed or moved, there are times when text becomes more readable because rounding has been enabled. The round is whether to enable rounding or not, if set to the value of 1, then rounding is enabled, if set to 0 then rounding is disabled.

后退 | 起点 | 前进
swf_popmatrix | 上一级 | swf_pushmatrix


swf_pushmatrix

(PHP 4 )

swf_pushmatrix -- Push the current transformation matrix back unto the stack

Description

void swf_pushmatrix ( void)

The swf_pushmatrix() function pushes the current transformation matrix back onto the stack.

后退 | 起点 | 前进
swf_posround | 上一级 | swf_removeobject


swf_removeobject

(PHP 4 )

swf_removeobject -- Remove an object

Description

void swf_removeobject ( int depth)

Removes the object at the depth specified by depth.

后退 | 起点 | 前进
swf_pushmatrix | 上一级 | swf_rotate


swf_rotate

(PHP 4 )

swf_rotate -- Rotate the current transformation

Description

void swf_rotate ( float angle, string axis)

The swf_rotate() rotates the current transformation by the angle given by the angle parameter around the axis given by the axis parameter. Valid values for the axis are 'x' (the x axis), 'y' (the y axis) or 'z' (the z axis).

后退 | 起点 | 前进
swf_removeobject | 上一级 | swf_scale


swf_scale

(PHP 4 )

swf_scale -- Scale the current transformation

Description

void swf_scale ( float x, float y, float z)

The swf_scale() scales the x coordinate of the curve by the value of the x parameter, the y coordinate of the curve by the value of the y parameter, and the z coordinate of the curve by the value of the z parameter.

后退 | 起点 | 前进
swf_rotate | 上一级 | swf_setfont


swf_setfont

(PHP 4 )

swf_setfont -- Change the current font

Description

void swf_setfont ( int fontid)

The swf_setfont() sets the current font to the value given by the fontid parameter.

后退 | 起点 | 前进
swf_scale | 上一级 | swf_setframe


swf_setframe

(PHP 4 )

swf_setframe -- Switch to a specified frame

Description

void swf_setframe ( int framenumber)

The swf_setframe() changes the active frame to the frame specified by framenumber.

后退 | 起点 | 前进
swf_setfont | 上一级 | swf_shapearc


swf_shapearc

(PHP 4 )

swf_shapearc -- Draw a circular arc

Description

void swf_shapearc ( float x, float y, float r, float ang1, float ang2)

The swf_shapeArc() function draws a circular arc from angle A given by the ang1 parameter to angle B given by the ang2 parameter. The center of the circle has an x coordinate given by the x parameter and a y coordinate given by the y, the radius of the circle is given by the r parameter.

后退 | 起点 | 前进
swf_setframe | 上一级 | swf_shapecurveto3


swf_shapecurveto3

(PHP 4 )

swf_shapecurveto3 -- Draw a cubic bezier curve

Description

void swf_shapecurveto3 ( float x1, float y1, float x2, float y2, float x3, float y3)

Draw a cubic bezier curve using the x,y coordinate pairs x1, y1 and x2,y2 as off curve control points and the x,y coordinate x3, y3 as an endpoint. The current position is then set to the x,y coordinate pair given by x3,y3.

后退 | 起点 | 前进
swf_shapearc | 上一级 | swf_shapecurveto


swf_shapecurveto

(PHP 4 )

swf_shapecurveto -- Draw a quadratic bezier curve between two points

Description

void swf_shapecurveto ( float x1, float y1, float x2, float y2)

The swf_shapecurveto() function draws a quadratic bezier curve from the current location, though the x coordinate given by x1 and the y coordinate given by y1 to the x coordinate given by x2 and the y coordinate given by y2. The current position is then set to the x,y coordinates given by the x2 and y2 parameters

后退 | 起点 | 前进
swf_shapecurveto3 | 上一级 | swf_shapefillbitmapclip


swf_shapefillbitmapclip

(PHP 4 )

swf_shapefillbitmapclip -- Set current fill mode to clipped bitmap

Description

void swf_shapefillbitmapclip ( int bitmapid)

Sets the fill to bitmap clipped, empty spaces will be filled by the bitmap given by the bitmapid parameter.

后退 | 起点 | 前进
swf_shapecurveto | 上一级 | swf_shapefillbitmaptile


swf_shapefillbitmaptile

(PHP 4 )

swf_shapefillbitmaptile -- Set current fill mode to tiled bitmap

Description

void swf_shapefillbitmaptile ( int bitmapid)

Sets the fill to bitmap tile, empty spaces will be filled by the bitmap given by the bitmapid parameter (tiled).

后退 | 起点 | 前进
swf_shapefillbitmapclip | 上一级 | swf_shapefilloff


swf_shapefilloff

(PHP 4 )

swf_shapefilloff -- Turns off filling

Description

void swf_shapefilloff ( void)

The swf_shapeFillOff() function turns off filling for the current shape.

后退 | 起点 | 前进
swf_shapefillbitmaptile | 上一级 | swf_shapefillsolid


swf_shapefillsolid

(PHP 4 )

swf_shapefillsolid -- Set the current fill style to the specified color

Description

void swf_shapefillsolid ( float r, float g, float b, float a)

The swf_shapeFillSolid() function sets the current fill style to solid, and then sets the fill color to the values of the rgba parameters.

后退 | 起点 | 前进
swf_shapefilloff | 上一级 | swf_shapelinesolid


swf_shapelinesolid

(PHP 4 )

swf_shapelinesolid -- Set the current line style

Description

void swf_shapelinesolid ( float r, float g, float b, float a, float width)

The swf_shapeLineSolid() function sets the current line style to the color of the rgba parameters and width to the width parameter. If 0.0 is given as a width then no lines are drawn.

后退 | 起点 | 前进
swf_shapefillsolid | 上一级 | swf_shapelineto


swf_shapelineto

(PHP 4 )

swf_shapelineto -- Draw a line

Description

void swf_shapelineto ( float x, float y)

The swf_shapeLineTo() draws a line to the x,y coordinates given by the x parameter & the y parameter. The current position is then set to the x,y parameters.

后退 | 起点 | 前进
swf_shapelinesolid | 上一级 | swf_shapemoveto


swf_shapemoveto

(PHP 4 )

swf_shapemoveto -- Move the current position

Description

void swf_shapemoveto ( float x, float y)

The swf_shapeMoveTo() function moves the current position to the x coordinate given by the x parameter and the y position given by the y parameter.

后退 | 起点 | 前进
swf_shapelineto | 上一级 | swf_showframe


swf_showframe

(PHP 4 )

swf_showframe -- Display the current frame

Description

void swf_showframe ( void)

The swf_showframe function will output the current frame.

后退 | 起点 | 前进
swf_shapemoveto | 上一级 | swf_startbutton


swf_startbutton

(PHP 4 )

swf_startbutton -- Start the definition of a button

Description

void swf_startbutton ( int objid, int type)

The swf_startbutton() function starts off the definition of a button. The type parameter can either be TYPE_MENUBUTTON or TYPE_PUSHBUTTON. The TYPE_MENUBUTTON constant allows the focus to travel from the button when the mouse is down, TYPE_PUSHBUTTON does not allow the focus to travel when the mouse is down.

后退 | 起点 | 前进
swf_showframe | 上一级 | swf_startdoaction


swf_startdoaction

(PHP 4 )

swf_startdoaction -- Start a description of an action list for the current frame

Description

void swf_startdoaction ( void)

The swf_startdoaction() function starts the description of an action list for the current frame. This must be called before actions are defined for the current frame.

后退 | 起点 | 前进
swf_startbutton | 上一级 | swf_startshape


swf_startshape

(PHP 4 )

swf_startshape -- Start a complex shape

Description

void swf_startshape ( int objid)

The swf_startshape() function starts a complex shape, with an object id given by the objid parameter.

后退 | 起点 | 前进
swf_startdoaction | 上一级 | swf_startsymbol


swf_startsymbol

(PHP 4 )

swf_startsymbol -- Define a symbol

Description

void swf_startsymbol ( int objid)

Define an object id as a symbol. Symbols are tiny flash movies that can be played simultaneously. The objid parameter is the object id you want to define as a symbol.

后退 | 起点 | 前进
swf_startshape | 上一级 | swf_textwidth


swf_textwidth

(PHP 4 )

swf_textwidth -- Get the width of a string

Description

float swf_textwidth ( string str)

The swf_textwidth() function gives the width of the string, str, in pixels, using the current font and font size.

后退 | 起点 | 前进
swf_startsymbol | 上一级 | swf_translate


swf_translate

(PHP 4 )

swf_translate -- Translate the current transformations

Description

void swf_translate ( float x, float y, float z)

The swf_translate() function translates the current transformation by the x, y, and z values given.

后退 | 起点 | 前进
swf_textwidth | 上一级 | swf_viewport


swf_viewport

(PHP 4 )

swf_viewport -- Select an area for future drawing

Description

void swf_viewport ( float xmin, float xmax, float ymin, float ymax)

The swf_viewport() function selects an area for future drawing for xmin to xmax and ymin to ymax, if this function is not called the area defaults to the size of the screen.

后退 | 起点 | 前进
swf_translate | 上一级 | SNMP functions


SNMP functions

PHP 手册
后退 前进

XCV. SNMP functions

介绍

需求

In order to use the SNMP functions on Unix you need to install the UCD SNMP package. On Windows these functions are only available on NT and not on Win95/98.

安装

Important: In order to use the UCD SNMP package, you need to define NO_ZEROLENGTH_COMMUNITY to 1 before compiling it. After configuring UCD SNMP, edit config.h and search for NO_ZEROLENGTH_COMMUNITY. Uncomment the #define line. It should look like this afterwards:
#define NO_ZEROLENGTH_COMMUNITY 1
Now compile PHP --with-snmp[=DIR].

If you see strange segmentation faults in combination with SNMP commands, you did not follow the above instructions. If you do not want to recompile UCD SNMP, you can compile PHP with the --enable-ucd-snmp-hack switch which will work around the misfeature.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

预定义常量

该扩展模块未定义任何常量。

目录
snmp_get_quick_print — Fetch the current value of the UCD library's quick_print setting
snmp_set_quick_print — Set the value of quick_print within the UCD SNMP library
snmpget — Fetch an SNMP object
snmprealwalk — Return all objects including their respective object ID within the specified one
snmpset — Set an SNMP object
snmpwalk — Fetch all the SNMP objects from an agent
snmpwalkoid — Query for a tree of information about a network entity

后退 | 起点 | 前进
swf_viewport | 上一级 | snmp_get_quick_print


snmp_get_quick_print

(PHP 3>= 3.0.8, PHP 4 )

snmp_get_quick_print -- Fetch the current value of the UCD library's quick_print setting

Description

bool snmp_get_quick_print ( void)

Returns the current value stored in the UCD Library for quick_print. quick_print is off by default.

$quickprint = snmp_get_quick_print();

Above function call would return FALSE if quick_print is off, and TRUE if quick_print is on.

snmp_get_quick_print() is only available when using the UCD SNMP library. This function is not available when using the Windows SNMP library.

See: snmp_set_quick_print() for a full description of what quick_print does.

后退 | 起点 | 前进
SNMP functions | 上一级 | snmp_set_quick_print


snmp_set_quick_print

(PHP 3>= 3.0.8, PHP 4 )

snmp_set_quick_print -- Set the value of quick_print within the UCD SNMP library

Description

void snmp_set_quick_print ( bool quick_print)

Sets the value of quick_print within the UCD SNMP library. When this is set (1), the SNMP library will return 'quick printed' values. This means that just the value will be printed. When quick_print is not enabled (default) the UCD SNMP library prints extra information including the type of the value (i.e. IpAddress or OID). Additionally, if quick_print is not enabled, the library prints additional hex values for all strings of three characters or less.

Setting quick_print is often used when using the information returned rather then displaying it.

snmp_set_quick_print(0);
$a = snmpget("127.0.0.1", "public", ".1.3.6.1.2.1.2.2.1.9.1");
echo "$a<BR>\n";
snmp_set_quick_print(1);
$a = snmpget("127.0.0.1", "public", ".1.3.6.1.2.1.2.2.1.9.1");
echo "$a<BR>\n";

The first value printed might be: 'Timeticks: (0) 0:00:00.00', whereas with quick_print enabled, just '0:00:00.00' would be printed.

By default the UCD SNMP library returns verbose values, quick_print is used to return only the value.

Currently strings are still returned with extra quotes, this will be corrected in a later release.

snmp_set_quick_print() is only available when using the UCD SNMP library. This function is not available when using the Windows SNMP library.

后退 | 起点 | 前进
snmp_get_quick_print | 上一级 | snmpget


snmpget

(PHP 3, PHP 4 )

snmpget -- Fetch an SNMP object

Description

string snmpget ( string hostname, string community, string object_id [, int timeout [, int retries]])

Returns SNMP object value on success and FALSE on error.

The snmpget() function is used to read the value of an SNMP object specified by the object_id. SNMP agent is specified by the hostname and the read community is specified by the community parameter.

$syscontact = snmpget("127.0.0.1", "public", "system.SysContact.0");

后退 | 起点 | 前进
snmp_set_quick_print | 上一级 | snmprealwalk


snmprealwalk

(PHP 3>= 3.0.8, PHP 4 )

snmprealwalk -- Return all objects including their respective object ID within the specified one

Description

array snmprealwalk ( string host, string community, string object_id [, int timeout [, int retries]])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
snmpget | 上一级 | snmpset


snmpset

(PHP 3>= 3.0.12, PHP 4 )

snmpset -- Set an SNMP object

Description

bool snmpset ( string hostname, string community, string object_id, string type, mixed value [, int timeout [, int retries]])

Sets the specified SNMP object value, returning TRUE on success and FALSE on error.

The snmpset() function is used to set the value of an SNMP object specified by the object_id. SNMP agent is specified by the hostname and the read community is specified by the community parameter.

后退 | 起点 | 前进
snmprealwalk | 上一级 | snmpwalk


snmpwalk

(PHP 3, PHP 4 )

snmpwalk -- Fetch all the SNMP objects from an agent

Description

array snmpwalk ( string hostname, string community, string object_id [, int timeout [, int retries]])

Returns an array of SNMP object values starting from the object_id as root and FALSE on error.

snmpwalk() function is used to read all the values from an SNMP agent specified by the hostname. Community specifies the read community for that agent. A NULL object_id is taken as the root of the SNMP objects tree and all objects under that tree are returned as an array. If object_id is specified, all the SNMP objects below that object_id are returned.

$a = snmpwalk("127.0.0.1", "public", "");

Above function call would return all the SNMP objects from the SNMP agent running on localhost. One can step through the values with a loop

for ($i=0; $i < count($a); $i++) {
    echo $a[$i];
}

后退 | 起点 | 前进
snmpset | 上一级 | snmpwalkoid


snmpwalkoid

(PHP 3>= 3.0.8, PHP 4 )

snmpwalkoid -- Query for a tree of information about a network entity

Description

array snmpwalkoid ( string hostname, string community, string object_id [, int timeout [, int retries]])

Returns an associative array with object ids and their respective object value starting from the object_id as root and FALSE on error.

snmpwalkoid() function is used to read all object ids and their respective values from an SNMP agent specified by the hostname. Community specifies the read community for that agent. A NULL object_id is taken as the root of the SNMP objects tree and all objects under that tree are returned as an array. If object_id is specified, all the SNMP objects below that object_id are returned.

The existence of snmpwalkoid() and snmpwalk() has historical reasons. Both functions are provided for backward compatibility.

$a = snmpwalkoid("127.0.0.1", "public", "");

Above function call would return all the SNMP objects from the SNMP agent running on localhost. One can step through the values with a loop

for (reset($a); $i = key($a); next($a)) {
    echo "$i: $a[$i]<br>\n";
}

后退 | 起点 | 前进
snmpwalk | 上一级 | Socket functions


Socket functions

PHP 手册
后退 前进

XCVI. Socket functions

介绍

The socket extension implements a low-level interface to the socket communication functions based on the popular BSD sockets, providing the possibility to act as a socket server as well as a client.

For a more generic client-side socket interface, see fsockopen() and pfsockopen().

When using these functions, it is important to remember that while many of them have identical names to their C counterparts, they often have different declarations. Please be sure to read the descriptions to avoid confusion.

Those unfamiliar with socket programming can find a lot of useful material in the appropriate Unix man pages, and there is a great deal of tutorial information on socket programming in C on the web, much of which can be applied, with slight modifications, to socket programming in PHP. The UNIX Socket FAQ might be a good start.

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

The socket functions described here are part of an extension to PHP which must be enabled at compile time by giving the --enable-sockets option to configure.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

AF_UNIX (integer)

AF_INET (integer)

SOCK_STREAM (integer)

SOCK_DGRAM (integer)

SOCK_RAW (integer)

SOCK_SEQPACKET (integer)

SOCK_RDM (integer)

MSG_OOB (integer)

MSG_WAITALL (integer)

MSG_PEEK (integer)

MSG_DONTROUTE (integer)

SO_DEBUG (integer)

SO_REUSEADDR (integer)

SO_KEEPALIVE (integer)

SO_DONTROUTE (integer)

SO_LINGER (integer)

SO_BROADCAST (integer)

SO_OOBINLINE (integer)

SO_SNDBUF (integer)

SO_RCVBUF (integer)

SO_SNDLOWAT (integer)

SO_RCVLOWAT (integer)

SO_SNDTIMEO (integer)

SO_RCVTIMEO (integer)

SO_TYPE (integer)

SO_ERROR (integer)

SOL_SOCKET (integer)

PHP_NORMAL_READ (integer)

PHP_BINARY_READ (integer)

SOL_TCP (integer)

SOL_UDP (integer)

Socket Errors

The socket extension was written to provide a useable interface to the powerful BSD sockets. Care has been taken that the functions work equally well on Win32 and Unix implementations. Almost all of the sockets functions may fail under certain conditions and therefore emit an E_WARNING message describing the error. Sometimes this doesn't happen to the desire of the developer. For example the function socket_read() may suddenly emit an E_WARNING message because the connection broke unexpectedly. It's common to suppress the warning with the @-operator and catch the error code within the application with the socket_last_error() function. You may call the socket_strerror() function with this error code to retrieve a string describing the error. See their description for more information.

注: The E_WARNING messages generated by the socket extension are in english though the retrieved error message will appear depending on the current locale (LC_MESSAGES):
Warning - socket_bind() unable to bind address [98]: Die Adresse wird bereits verwendet

范例

例子 1. Socket example: Simple TCP/IP server

This example shows a simple talkback server. Change the address and port variables to suit your setup and execute. You may then connect to the server with a command similar to: telnet 192.168.1.53 10000 (where the address and port match your setup). Anything you type will then be output on the server side, and echoed back to you. To disconnect, enter 'quit'.

#!/usr/local/bin/php -q
<?php
error_reporting (E_ALL);

/* Allow the script to hang around waiting for connections. */
set_time_limit (0);

/* Turn on implicit output flushing so we see what we're getting
 * as it comes in. */
ob_implicit_flush ();

$address = '192.168.1.53';
$port = 10000;

if (($sock = socket_create (AF_INET, SOCK_STREAM, 0)) < 0) {
    echo "socket_create() failed: reason: " . socket_strerror ($sock) . "\n";
}

if (($ret = socket_bind ($sock, $address, $port)) < 0) {
    echo "socket_bind() failed: reason: " . socket_strerror ($ret) . "\n";
}

if (($ret = socket_listen ($sock, 5)) < 0) {
    echo "socket_listen() failed: reason: " . socket_strerror ($ret) . "\n";
}

do {
    if (($msgsock = socket_accept($sock)) < 0) {
        echo "socket_accept() failed: reason: " . socket_strerror ($msgsock) . "\n";
        break;
    }
    /* Send instructions. */
    $msg = "\nWelcome to the PHP Test Server. \n" .
        "To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
    socket_write($msgsock, $msg, strlen($msg));

    do {
        if (FALSE === ($buf = socket_read ($msgsock, 2048))) {
            echo "socket_read() failed: reason: " . socket_strerror ($ret) . "\n";
            break 2;
        }
        if (!$buf = trim ($buf)) {
            continue;
        }
        if ($buf == 'quit') {
            break;
        }
        if ($buf == 'shutdown') {
            socket_close ($msgsock);
            break 2;
        }
        $talkback = "PHP: You said '$buf'.\n";
        socket_write ($msgsock, $talkback, strlen ($talkback));
        echo "$buf\n";
    } while (true);
    socket_close ($msgsock);
} while (true);

socket_close ($sock);
?>

例子 2. Socket example: Simple TCP/IP client

This example shows a simple, one-shot HTTP client. It simply connects to a page, submits a HEAD request, echoes the reply, and exits.

<?php
error_reporting (E_ALL);

echo "<h2>TCP/IP Connection</h2>\n";

/* Get the port for the WWW service. */
$service_port = getservbyname ('www', 'tcp');

/* Get the IP address for the target host. */
$address = gethostbyname ('www.example.com');

/* Create a TCP/IP socket. */
$socket = socket_create (AF_INET, SOCK_STREAM, 0);
if ($socket < 0) {
    echo "socket_create() failed: reason: " . socket_strerror ($socket) . "\n";
} else {
    echo "OK.\n";
}

echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect ($socket, $address, $service_port);
if ($result < 0) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n";
} else {
    echo "OK.\n";
}

$in = "HEAD / HTTP/1.0\r\n\r\n";
$out = '';

echo "Sending HTTP HEAD request...";
socket_write ($socket, $in, strlen ($in));
echo "OK.\n";

echo "Reading response:\n\n";
while ($out = socket_read ($socket, 2048)) {
    echo $out;
}

echo "Closing socket...";
socket_close ($socket);
echo "OK.\n\n";
?>

目录
socket_accept — Accepts a connection on a socket
socket_bind — Binds a name to a socket
socket_clear_error — Clears the error on the socket or the last error code
socket_close — Closes a socket resource
socket_connect — Initiates a connection on a socket
socket_create_listen — Opens a socket on port to accept connections
socket_create_pair — Creates a pair of indistinguishable sockets and stores them in fds.
socket_create — Create a socket (endpoint for communication)
socket_get_option — Gets socket options for the socket
socket_getpeername — Queries the remote side of the given socket which may either result in host/port or in a UNIX filesystem path, dependent on its type.
socket_getsockname — Queries the local side of the given socket which may either result in host/port or in a UNIX filesystem path, dependent on its type.
socket_iovec_add — Adds a new vector to the scatter/gather array
socket_iovec_alloc — ...]) Builds a 'struct iovec' for use with sendmsg, recvmsg, writev, and readv
socket_iovec_delete — Deletes a vector from an array of vectors
socket_iovec_fetch — Returns the data held in the iovec specified by iovec_id[iovec_position]
socket_iovec_free — Frees the iovec specified by iovec_id
socket_iovec_set — Sets the data held in iovec_id[iovec_position] to new_val
socket_last_error — Returns the last error on the socket
socket_listen — Listens for a connection on a socket
socket_read — Reads a maximum of length bytes from a socket
socket_readv — Reads from an fd, using the scatter-gather array defined by iovec_id
socket_recv — Receives data from a connected socket
socket_recvfrom — Receives data from a socket, connected or not
socket_recvmsg — Used to receive messages on a socket, whether connection-oriented or not
socket_select — Runs the select() system call on the given arrays of sockets with a timeout specified by tv_sec and tv_usec
socket_send — Sends data to a connected socket
socket_sendmsg — Sends a message to a socket, regardless of whether it is connection-oriented or not
socket_sendto — Sends a message to a socket, whether it is connected or not
socket_set_nonblock — Sets nonblocking mode for file descriptor fd
socket_set_option — Sets socket options for the socket
socket_shutdown — Shuts down a socket for receiving, sending, or both.
socket_strerror — Return a string describing a socket error
socket_write — Write to a socket
socket_writev — Writes to a file descriptor, fd, using the scatter-gather array defined by iovec_id

后退 | 起点 | 前进
snmpwalkoid | 上一级 | socket_accept


socket_accept

(PHP 4 >= 4.1.0)

socket_accept -- Accepts a connection on a socket

Description

resource socket_accept ( resource socket)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

After the socket socket has been created using socket_create(), bound to a name with socket_bind(), and told to listen for connections with socket_listen(), this function will accept incoming connections on that socket. Once a successful connection is made, a new socket resource is returned, which may be used for communication. If there are multiple connections queued on the socket, the first will be used. If there are no pending connections, socket_accept() will block until a connection becomes present. If socket has been made non-blocking using socket_set_blocking() or socket_set_nonblock(), FALSE will be returned.

The socket resource returned by socket_accept() may not be used to accept new connections. The original listening socket socket, however, remains open and may be reused.

Returns a new socket resource on success, or FALSE on error. The actual error code can be retrieved by calling socket_last_error(). This error code may be passed to socket_strerror() to get a textual explanation of the error.

See also
socket_bind(),
socket_connect(),
socket_listen(),
socket_create(), and
socket_strerror().

后退 | 起点 | 前进
Socket functions | 上一级 | socket_bind


socket_bind

(PHP 4 >= 4.1.0)

socket_bind -- Binds a name to a socket

Description

bool socket_bind ( resource socket, string address [, int port])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

socket_bind() binds the name given in address to the socket described by socket, which must be a valid socket resource created with socket_create().

The address parameter is either an IP address in dotted-quad notation (e.g. 127.0.0.1), if the socket is of the AF_INET family; or the pathname of a Unix-domain socket, if the socket family is AF_UNIX.

The port parameter is only used when connecting to an AF_INET socket, and designates the port on the remote host to which a connection should be made.

如果成功则返回 TRUE，失败则返回 FALSE。 The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.

See also
socket_connect(),
socket_listen(),
socket_create(),
socket_last_error() and
socket_strerror().

后退 | 起点 | 前进
socket_accept | 上一级 | socket_clear_error


socket_clear_error

(PHP 4 >= 4.2.0)

socket_clear_error -- Clears the error on the socket or the last error code

Description

void socket_clear_error ( [resource socket])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

This function clears the error code on the given socket or the global last socket error.

This function allows explicitely resetting the error code value either of a socket or of the extension global last error code. This may be useful to detect within a part of the application if an error occured or not.

See also socket_last_error() and socket_strerror().

后退 | 起点 | 前进
socket_bind | 上一级 | socket_close


socket_close

(PHP 4 >= 4.1.0)

socket_close -- Closes a socket resource

Description

void socket_close ( resource socket)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

socket_close() closes the socket resource given by socket.

注: socket_close() can't be used on PHP file resources created with fopen(), popen(), fsockopen(), or pfsockopen(); it is meant for sockets created with socket_create() or socket_accept().

See also socket_bind(), socket_listen(),
socket_create() and
socket_strerror().

后退 | 起点 | 前进
socket_clear_error | 上一级 | socket_connect


socket_connect

(PHP 4 >= 4.1.0)

socket_connect -- Initiates a connection on a socket

Description

bool socket_connect ( resource socket, string address [, int port])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Initiates a connection using the socket resource socket, which must be a valid socket resource created with socket_create().

The address parameter is either an IP address in dotted-quad notation (e.g. 127.0.0.1), if the socket is of the AF_INET family; or the pathname of a Unix-domain socket, if the socket family is AF_UNIX.

The port parameter is only used when connecting to an AF_INET socket, and designates the port on the remote host to which a connection should be made.

如果成功则返回 TRUE，失败则返回 FALSE。 The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.

See also
socket_bind(),
socket_listen(),
socket_create(),
socket_last_error() and
socket_strerror().

后退 | 起点 | 前进
socket_close | 上一级 | socket_create_listen


socket_create_listen

(PHP 4 >= 4.1.0)

socket_create_listen -- Opens a socket on port to accept connections

Description

resource socket_create_listen ( int port [, int backlog])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

This function is meant to ease the task of creating a new socket which only listens to accept new connections.

socket_create_listen() create a new socket resource of type AF_INET listening on all local interfaces on the given port waiting for new connections.

The backlog parameter defines the maximum length the queue of pending connections may grow to. SOMAXCONN may be passed as backlog parameter, see socket_listen() for more information.

socket_create_listen() returns a new socket resource on success or FALSE on error. The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.

注: If you want to create a socket which only listens on a certain interfaces you need to use socket_create(), socket_bind() and socket_listen().

See also
socket_create(),
socket_bind(),
socket_listen(),
socket_last_error() and
socket_strerror().

后退 | 起点 | 前进
socket_connect | 上一级 | socket_create_pair


socket_create_pair

(PHP 4 >= 4.1.0)

socket_create_pair -- Creates a pair of indistinguishable sockets and stores them in fds.

Description

bool socket_create_pair ( int domain, int type, int protocol, array &fd)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
socket_create_listen | 上一级 | socket_create


socket_create

(PHP 4 >= 4.1.0)

socket_create -- Create a socket (endpoint for communication)

Description

resource socket_create ( int domain, int type, int protocol)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

Creates a communication endpoint (a socket), and returns a socket resource.

The domain parameter sets the domain (protocol family) to be used for communication. Currently, AF_INET and AF_UNIX are understood. AF_INET is typical used for internet based communication. AF_UNIX uses pathnames to identify sockets and can therefore only be used for local communication (which is faster, on the other hand).

The type parameter selects the socket type. This is one of SOCK_STREAM, SOCK_DGRAM, SOCK_SEQPACKET, SOCK_RAW, SOCK_RDM, or SOCK_PACKET. The two most common types are SOCK_DGRAM for UDP (connectionless) communication and SOCK_STREAM for TCP communication.

protocol sets the protocol which is either SOL_UDP or SOL_TCP.

Returns a socket resource on success, or FALSE on error. The actual error code can be retrieved by calling socket_last_error(). This error code may be passed to socket_strerror() to get a textual explanation of the error.

For more information on the usage of socket_create(), as well as on the meanings of the various parameters, see the Unix man page socket (2).

注: If an invalid domain or type is given, socket_create() defaults to AF_INET and SOCK_STREAM respectively and additionally emits an E_WARNING message.

See also
socket_accept(),
socket_bind(),
socket_connect(),
socket_listen(),
socket_last_error(), and
socket_strerror().

后退 | 起点 | 前进
socket_create_pair | 上一级 | socket_get_option


socket_get_option

(PHP 4 CVS only)

socket_get_option -- Gets socket options for the socket

Description

mixed socket_get_option ( resource socket, int level, int optname)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

注: This function used to be called socket_getopt() prior to PHP 4.3.0

后退 | 起点 | 前进
socket_create | 上一级 | socket_getpeername


socket_getpeername

(PHP 4 >= 4.1.0)

socket_getpeername -- Queries the remote side of the given socket which may either result in host/port or in a UNIX filesystem path, dependent on its type.

Description

bool socket_getpeername ( resource socket, string &addr [, int &port])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

If the given socket is of type AF_INET, socket_getpeername() will return the peers (remote) IP address in dotted-quad notation (e.g. 127.0.0.1) in the address parameter and, if the optional port parameter is present, also the associated port.

If the given socket is of type AF_UNIX, socket_getpeername() will return the UNIX filesystem path (e.g. /var/run/daemon.sock) in the address parameter.

如果成功则返回 TRUE，失败则返回 FALSE。 socket_getpeername() may also return FALSE if the socket type is not any of AF_INET or AF_UNIX, in which case the last socket error code is not updated.

See also
socket_getpeername(),
socket_last_error() and
socket_strerror().

后退 | 起点 | 前进
socket_get_option | 上一级 | socket_getsockname


socket_getsockname

(PHP 4 >= 4.1.0)

socket_getsockname -- Queries the local side of the given socket which may either result in host/port or in a UNIX filesystem path, dependent on its type.

Description

bool socket_getsockname ( resource socket, string &addr [, int &port])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

If the given socket is of type AF_INET, socket_getsockname() will return the local IP address in dotted-quad notation (e.g. 127.0.0.1) in the address parameter and, if the optional port parameter is present, also the associated port.

If the given socket is of type AF_UNIX, socket_getsockname() will return the UNIX filesystem path (e.g. /var/run/daemon.sock) in the address parameter.

如果成功则返回 TRUE，失败则返回 FALSE。 socket_getsockname() may also return FALSE if the socket type is not any of AF_INET or AF_UNIX, in which case the last socket error code is not updated.

See also
socket_getpeername(),
socket_last_error() and
socket_strerror().

后退 | 起点 | 前进
socket_getpeername | 上一级 | socket_iovec_add


socket_iovec_add

(PHP 4 >= 4.1.0)

socket_iovec_add -- Adds a new vector to the scatter/gather array

Description

bool socket_iovec_add ( resource iovec, int iov_len)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
socket_getsockname | 上一级 | socket_iovec_alloc


socket_iovec_alloc

(PHP 4 >= 4.1.0)

socket_iovec_alloc -- ...]) Builds a 'struct iovec' for use with sendmsg, recvmsg, writev, and readv

Description

resource socket_iovec_alloc ( int num_vectors [, int ])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
socket_iovec_add | 上一级 | socket_iovec_delete


socket_iovec_delete

(PHP 4 >= 4.1.0)

socket_iovec_delete -- Deletes a vector from an array of vectors

Description

bool socket_iovec_delete ( resource iovec, int iov_pos)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
socket_iovec_alloc | 上一级 | socket_iovec_fetch


socket_iovec_fetch

(PHP 4 >= 4.1.0)

socket_iovec_fetch -- Returns the data held in the iovec specified by iovec_id[iovec_position]

Description

string socket_iovec_fetch ( resource iovec, int iovec_position)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
socket_iovec_delete | 上一级 | socket_iovec_free


socket_iovec_free

(PHP 4 >= 4.1.0)

socket_iovec_free -- Frees the iovec specified by iovec_id

Description

bool socket_iovec_free ( resource iovec)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
socket_iovec_fetch | 上一级 | socket_iovec_set


socket_iovec_set

(PHP 4 >= 4.1.0)

socket_iovec_set -- Sets the data held in iovec_id[iovec_position] to new_val

Description

bool socket_iovec_set ( resource iovec, int iovec_position, string new_val)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
socket_iovec_free | 上一级 | socket_last_error


socket_last_error

(PHP 4 >= 4.1.0)

socket_last_error -- Returns the last error on the socket

Description

int socket_last_error ( [resource socket])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

This function returns a socket error code.

If a socket resource is passed to this function, the last error which occured on this particular socket is returned. If the socket resource is ommited, the error code of the last failed socket function is returned. The latter is in particular helpful for functions like socket_create() which don't return a socket on failure and socket_select() which can fail for reasons not directly tied to a particular socket. The error code is suitable to be fed to socket_strerror() which returns a string describing the given error code.
if (false == ($socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) {
    die("Couldn't create socket, error code is: " . socket_last_error() .
        ",error message is: " . socket_strerror(socket_last_error()));
}

注: socket_last_error() does not clear the error code, use socket_clear_error() for this purpose.

后退 | 起点 | 前进
socket_iovec_set | 上一级 | socket_listen


socket_listen

(PHP 4 >= 4.1.0)

socket_listen -- Listens for a connection on a socket

Description

bool socket_listen ( resource socket [, int backlog])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

After the socket socket has been created using socket_create() and bound to a name with socket_bind(), it may be told to listen for incoming connections on socket.

A maximum of backlog incoming connections will be queued for processing. If a connection request arrives with the queue full the client may receive an error with an indication of ECONNREFUSED, or, if the underlying protocol supports retransmission, the request may be ignored so that retries may succeed.

注: The maximum number passed to the backlog parameter highly depends on the underlying platform. On linux, it is silently truncated to SOMAXCONN. On win32, if passed SOMAXCONN, the underlying service provider responsible for the socket will set the backlog to a maximum reasonable value. There is no standard provision to find out the actual backlog value on this platform.

socket_listen() is applicable only to sockets of type SOCK_STREAM or SOCK_SEQPACKET.

如果成功则返回 TRUE，失败则返回 FALSE。 The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.

See also
socket_accept(),
socket_bind(),
socket_connect(),
socket_create() and
socket_strerror().

后退 | 起点 | 前进
socket_last_error | 上一级 | socket_read


socket_read

(PHP 4 >= 4.1.0)

socket_read -- Reads a maximum of length bytes from a socket

Description

string socket_read ( resource socket, int length [, int type])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

The function socket_read() reads from the socket resource socket created by the socket_create() or socket_accept() functions. The maximum number of bytes read is specified by the length parameter. Otherwise you can use \r, \n, or \0 to end reading (depending on the type parameter, see below).

socket_read() returns the data as a string on success, or FALSE on error. The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual representation of the error.

注: socket_read() may return a zero length string ("") indicating the end of communication (i.e. the remote end point has closed the connection).

Optional type parameter is a named constant:

  • PHP_BINARY_READ - use the system read() function. Safe for reading binary data. (Default in PHP >= 4.1.0)

  • PHP_NORMAL_READ - reading stops at \n or \r. (Default in PHP <= 4.0.6)

See also
socket_accept(),
socket_bind(),
socket_connect(),
socket_listen(),
socket_last_error(),
socket_strerror() and
socket_write().

后退 | 起点 | 前进
socket_listen | 上一级 | socket_readv


socket_readv

(PHP 4 >= 4.1.0)

socket_readv -- Reads from an fd, using the scatter-gather array defined by iovec_id

Description

bool socket_readv ( resource socket, resource iovec_id)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
socket_read | 上一级 | socket_recv


socket_recv

(PHP 4 >= 4.1.0)

socket_recv -- Receives data from a connected socket

Description

string socket_recv ( resource socket, int len, int flags)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
socket_readv | 上一级 | socket_recvfrom


socket_recvfrom

(PHP 4 >= 4.1.0)

socket_recvfrom -- Receives data from a socket, connected or not

Description

int socket_recvfrom ( resource socket, string &buf, int len, int flags, string &name [, int &port])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
socket_recv | 上一级 | socket_recvmsg


socket_recvmsg

(PHP 4 >= 4.1.0)

socket_recvmsg -- Used to receive messages on a socket, whether connection-oriented or not

Description

bool socket_recvmsg ( resource socket, resource iovec, array &control, int &controllen, int &flags, string &addr [, int &port])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
socket_recvfrom | 上一级 | socket_select


socket_select

(PHP 4 >= 4.1.0)

socket_select -- Runs the select() system call on the given arrays of sockets with a timeout specified by tv_sec and tv_usec

Description

int socket_select ( resource &read, resource &write, resource &except, int tv_sec [, int tv_usec])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

The socket_select() accepts arrays of sockets and waits for them to change status. Those coming with BSD sockets background will recognize that those socket resource arrays are in fact the so-called file descriptor sets. Three independent arrays of socket resources are watched.

The sockets listed in the read array will be watched to see if characters become available for reading (more precisely, to see if a read will not block - in particular, a socket resource is also ready on end-of-file, in which case a socket_read() will return a zero length string).

The sockets listed in the write array will be watched to see if a write will not block.

The sockets listed in the except array will be watched for exceptions.

警告

On exit, the arrays are modified to indicate which socket resource actually changed status.

You do not need to pass every array to socket_select(). You can leave it out and use an empty array or NULL instead. Also do not forget that those arrays are passed by reference and will be modified after socket_select() returns.

Example:
/* Prepare the read array */
$read = array($socket1, $socket2);

if (false === ($num_changed_sockets = socket_select($read, $write = NULL, $except = NULL, 0))) {
    /* Error handling */
else if ($num_changed_sockets > 0) {
    /* At least at one of the sockets something interesting happened */
}

注: Due a limitation in the current Zend Engine it is not possible to pass a constant modifier like NULL directly as a parameter to a function which expects this parameter to be passed by reference. Instead use a temporary variable or an expression with the leftmost member being a temporary variable:
socket_select($r, $w, $e = NULL, 0);

The tv_sec and tv_usec together form the timeout parameter. The timeout is an upper bound on the amount of time elapsed before socket_select() return. tv_sec may be zero , causing socket_select() to return immediately. This is useful for polling. If tv_sec is NULL (no timeout), socket_select() can block indefinitely.

On success socket_select() returns the number of socket resorces contained in the modified arrays, which may be zero if the timeout expires before anything interesting happens. On error FALSE is returned. The error code can be retrieved with socket_last_error().

注: Be sure to use the === operator when checking for an error. Since the socket_select() may return 0 the comparison with == would evaluate to TRUE:
if (false === socket_select($r, $w, $e = NULL, 0)) {
    echo "socket_select() failed, reason: " . socket_strerror(socket_last_error()) . "\n";
}

注: Be aware that some socket implementations need to be handled very carefully. A few basic rules:

  • You should always try to use socket_select() without timeout. Your program should have nothing to do if there is no data available. Code that depends on timeouts is not usually portable and difficult to debug.

  • No socket resource must be added to any set if you do not intend to check its result after the socket_select() call, and respond appropriately. After socket_select() returns, all socket resources in all arrays must be checked. Any socket resource that is available for writing must be written to, and any socket resource available for reading must be read from.

  • If you read/write to a socket returns in the arrays be aware that they do not necessarily read/write the full amount of data you have requested. Be prepared to even only be able to read/write a single byte.

  • It's common to most socket implementations that the only exception caught with the except array is out-of-bound data received on a socket.

See also
socket_read(),
socket_write(),
socket_last_error() and
socket_strerror().

后退 | 起点 | 前进
socket_recvmsg | 上一级 | socket_send


socket_send

(PHP 4 >= 4.1.0)

socket_send -- Sends data to a connected socket

Description

int socket_send ( resource socket, string buf, int len, int flags)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
socket_select | 上一级 | socket_sendmsg


socket_sendmsg

(PHP 4 >= 4.1.0)

socket_sendmsg -- Sends a message to a socket, regardless of whether it is connection-oriented or not

Description

bool socket_sendmsg ( resource socket, resource iovec, int flags, string addr [, int port])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
socket_send | 上一级 | socket_sendto


socket_sendto

(PHP 4 >= 4.1.0)

socket_sendto -- Sends a message to a socket, whether it is connected or not

Description

int socket_sendto ( resource socket, string buf, int len, int flags, string addr [, int port])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
socket_sendmsg | 上一级 | socket_set_nonblock


socket_set_nonblock

(PHP 4 >= 4.1.0)

socket_set_nonblock -- Sets nonblocking mode for file descriptor fd

Description

bool socket_set_nonblock ( resource socket)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
socket_sendto | 上一级 | socket_set_option


socket_set_option

(PHP 4 CVS only)

socket_set_option -- Sets socket options for the socket

Description

bool socket_set_option ( resource socket, int level, int optname, int )

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

注: This function used to be called socket_setopt() prior to PHP 4.3.0

后退 | 起点 | 前进
socket_set_nonblock | 上一级 | socket_shutdown


socket_shutdown

(PHP 4 >= 4.1.0)

socket_shutdown -- Shuts down a socket for receiving, sending, or both.

Description

bool socket_shutdown ( resource socket [, int how])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
socket_set_option | 上一级 | socket_strerror


socket_strerror

(PHP 4 >= 4.1.0)

socket_strerror -- Return a string describing a socket error

Description

string socket_strerror ( int errno)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

socket_strerror() takes as its errno parameter a socket error code as returned by socket_last_error() and returns the corresponding explanatory text. This makes it a bit more pleasant to figure out why something didn't work; for instance, instead of having to track down a system include file to find out what '-111' means, you just pass it to socket_strerror(), and it tells you what happened.

例子 1. socket_strerror() example

<?php
if (false == ($socket = @socket_create(AF_INET, SOCK_STREAM, 0))) {
   echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}

if (false == (@socket_bind($socket, '127.0.0.1', 80))) {
   echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}
?>

The expected output from the above example (assuming the script is not run with root privileges):
socket_bind() failed: reason: Permission denied

See also
socket_accept(),
socket_bind(),
socket_connect(),
socket_listen(), and
socket_create().

后退 | 起点 | 前进
socket_shutdown | 上一级 | socket_write


socket_write

(PHP 4 >= 4.1.0)

socket_write -- Write to a socket

Description

int socket_write ( resource socket, string buffer [, int length])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

The function socket_write() writes to the socket socket from buffer.

The optional parameter length can specify an alternate length of bytes written to the socket. If this length is greater then the buffer length, it is silently truncated to the length of the buffer.

Returns the number of bytes successfully written to the socket or FALSE one error. The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.

注: socket_write() does not necessarily write all bytes from the given buffer. It's valid that, depending on the network buffers etc., only a certain amount of data, even one byte, is written though your buffer is greater. You have to watch out so you don't unintentionally forget to transmit the rest of your data.

注: It is perfectly valid for socket_write() to return zero which means no bytes have been written. Be sure to use the === operator to check for FALSE in case of an error.

See also
socket_accept(),
socket_bind(),
socket_connect(),
socket_listen(),
socket_read() and
socket_strerror().

后退 | 起点 | 前进
socket_strerror | 上一级 | socket_writev


socket_writev

(PHP 4 >= 4.1.0)

socket_writev -- Writes to a file descriptor, fd, using the scatter-gather array defined by iovec_id

Description

bool socket_writev ( resource socket, resource iovec_id)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
socket_write | 上一级 | String functions


String functions

PHP 手册
后退 前进

XCVII. String functions

介绍

These functions all manipulate strings in various ways. Some more specialized sections can be found in the regular expression and URL handling sections.

For information on how strings behave, especially with regard to usage of single quotes, double quotes, and escape sequences, see the Strings entry in the Types section of the manual.

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

这些函数作为 PHP 核心的一部分，无需被安装即可使用。

预定义常量

该扩展模块未定义任何常量。

相关参考

For even more powerful string handling and manipulating functions take a look at the POSIX regular expression functions and the Perl compatible regular expression functions.

目录
addcslashes — Quote string with slashes in a C style
addslashes — Quote string with slashes
bin2hex — Convert binary data into hexadecimal representation
chop — Alias of rtrim()
chr — Return a specific character
chunk_split — Split a string into smaller chunks
convert_cyr_string — Convert from one Cyrillic character set to another
count_chars — Return information about characters used in a string
crc32 — Calculates the crc32 polynomial of a string
crypt — One-way string encryption (hashing)
echo — Output one or more strings
explode — Split a string by string
get_html_translation_table — Returns the translation table used by htmlspecialchars() and htmlentities()
get_meta_tags — Extracts all meta tag content attributes from a file and returns an array
hebrev — Convert logical Hebrew text to visual text
hebrevc — Convert logical Hebrew text to visual text with newline conversion
htmlentities — Convert all applicable characters to HTML entities
htmlspecialchars — Convert special characters to HTML entities
implode — Join array elements with a string
join — Join array elements with a string
levenshtein — Calculate Levenshtein distance between two strings
localeconv — Get numeric formatting information
ltrim — Strip whitespace from the beginning of a string
md5_file — Calculates the md5 hash of a given filename
md5 — Calculate the md5 hash of a string
metaphone — Calculate the metaphone key of a string
nl_langinfo — Query language and locale information
nl2br — Inserts HTML line breaks before all newlines in a string
ord — Return ASCII value of character
parse_str — Parses the string into variables
print — Output a string
printf — Output a formatted string
quoted_printable_decode — Convert a quoted-printable string to an 8 bit string
quotemeta — Quote meta characters
rtrim — Strip whitespace from the end of a string
setlocale — Set locale information
similar_text — Calculate the similarity between two strings
soundex — Calculate the soundex key of a string
sprintf — Return a formatted string
sscanf — Parses input from a string according to a format
str_pad — Pad a string to a certain length with another string
str_repeat — Repeat a string
str_replace — Replace all occurrences of the search string with the replacement string
str_rot13 — Perform the rot13 transform on a string
strcasecmp — Binary safe case-insensitive string comparison
strchr — Find the first occurrence of a character
strcmp — Binary safe string comparison
strcoll — Locale based string comparison
strcspn — Find length of initial segment not matching mask
strip_tags — Strip HTML and PHP tags from a string
stripcslashes — Un-quote string quoted with addcslashes()
stripslashes — Un-quote string quoted with addslashes()
stristr — Case-insensitive strstr()
strlen — Get string length
strnatcasecmp — Case insensitive string comparisons using a "natural order" algorithm
strnatcmp — String comparisons using a "natural order" algorithm
strncasecmp — Binary safe case-insensitive string comparison of the first n characters
strncmp — Binary safe string comparison of the first n characters
strpos — Find position of first occurrence of a string
strrchr — Find the last occurrence of a character in a string
strrev — Reverse a string
strrpos — Find position of last occurrence of a char in a string
strspn — Find length of initial segment matching mask
strstr — Find first occurrence of a string
strtok — Tokenize string
strtolower — Make a string lowercase
strtoupper — Make a string uppercase
strtr — Translate certain characters
substr_count — Count the number of substring occurrences
substr_replace — Replace text within a portion of a string
substr — Return part of a string
trim — Strip whitespace from the beginning and end of a string
ucfirst — Make a string's first character uppercase
ucwords — Uppercase the first character of each word in a string
vprintf — Output a formatted string
vsprintf — Return a formatted string
wordwrap — Wraps a string to a given number of characters using a string break character.

后退 | 起点 | 前进
socket_writev | 上一级 | addcslashes


addcslashes

(PHP 4 )

addcslashes -- Quote string with slashes in a C style

Description

string addcslashes ( string str, string charlist)

Returns a string with backslashes before characters that are listed in charlist parameter. It escapes \n, \r etc. in C-like style, characters with ASCII code lower than 32 and higher than 126 are converted to octal representation.

Be careful if you choose to escape characters 0, a, b, f, n, r, t and v. They will be converted to \0, \a, \b, \f, \n, \r, \t and \v. In PHP \0 (NULL), \r (carriage return), \n (newline) and \t (tab) are predefined escape sequences, while in C all of these are predefined escape sequences.

charlist like "\0..\37", which would escape all characters with ASCII code between 0 and 31.

例子 1. addcslashes() example

$escaped = addcslashes($not_escaped, "\0..\37!@\177..\377");

When you define a sequence of characters in the charlist argument make sure that you know what characters come between the characters that you set as the start and end of the range.

echo addcslashes('foo[ ]', 'A..z');
// output:  \f\o\o\[ \]
// All upper and lower-case letters will be escaped
// ... but so will the [\]^_` and any tabs, line
// feeds, carriage returns, etc.

Also, if the first character in a range has a lower ASCII value than the second character in the range, no range will be constructed. Only the start, end and period characters will be escaped. Use the ord() function to find the ASCII value for a character.

echo addcslashes("zoo['.']", 'z..A');
// output:  \zoo['\.']

See also stripcslashes(),
stripslashes(),
htmlspecialchars(), and
quotemeta().

后退 | 起点 | 前进
String functions | 上一级 | addslashes


addslashes

(PHP 3, PHP 4 )

addslashes -- Quote string with slashes

Description

string addslashes ( string str)

Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).

注: magic_quotes_gpc is ON by default.

See also stripslashes(),
htmlspecialchars(), and
quotemeta().

后退 | 起点 | 前进
addcslashes | 上一级 | bin2hex


bin2hex

(PHP 3>= 3.0.9, PHP 4 )

bin2hex -- Convert binary data into hexadecimal representation

Description

string bin2hex ( string str)

Returns an ASCII string containing the hexadecimal representation of str. The conversion is done byte-wise with the high-nibble first.

See also pack() and unpack().

后退 | 起点 | 前进
addslashes | 上一级 | chop


chop

chop -- Alias of rtrim()

Description

This function is an alias of rtrim().

注: chop() is different than the Perl chop() function, which removes the last character in the string.

后退 | 起点 | 前进
bin2hex | 上一级 | chr


chr

(PHP 3, PHP 4 )

chr -- Return a specific character

Description

string chr ( int ascii)

Returns a one-character string containing the character specified by ascii.

例子 1. chr() example

$str .= chr(27); /* add an escape character at the end of $str */

/* Often this is more useful */

$str = sprintf("The string ends in escape: %c", 27);

You can find an ASCII-table over here: http://www.asciitable.com.

This function complements ord(). See also sprintf() with a format string of %c.

后退 | 起点 | 前进
chop | 上一级 | chunk_split


chunk_split

(PHP 3>= 3.0.6, PHP 4 )

chunk_split -- Split a string into smaller chunks

Description

string chunk_split ( string body [, int chunklen [, string end]])

Can be used to split a string into smaller chunks which is useful for e.g. converting base64_encode output to match RFC 2045 semantics. It inserts end (defaults to "\r\n") every chunklen characters (defaults to 76). It returns the new string leaving the original string untouched.

例子 1. chunk_split() example

# format $data using RFC 2045 semantics

$new_string = chunk_split(base64_encode($data));

See also explode(), split() wordwrap() and RFC 2045.

后退 | 起点 | 前进
chr | 上一级 | convert_cyr_string


convert_cyr_string

(PHP 3>= 3.0.6, PHP 4 )

convert_cyr_string -- Convert from one Cyrillic character set to another

Description

string convert_cyr_string ( string str, string from, string to)

This function returns the given string converted from one Cyrillic character set to another. The from and to arguments are single characters that represent the source and target Cyrillic character sets. The supported types are:

  • k - koi8-r

  • w - windows-1251

  • i - iso8859-5

  • a - x-cp866

  • d - x-cp866

  • m - x-mac-cyrillic

后退 | 起点 | 前进
chunk_split | 上一级 | count_chars


count_chars

(PHP 4 )

count_chars -- Return information about characters used in a string

Description

mixed count_chars ( string string [, int mode])

Counts the number of occurrences of every byte-value (0..255) in string and returns it in various ways. The optional parameter Mode default to 0. Depending on mode count_chars() returns one of the following:

  • 0 - an array with the byte-value as key and the frequency of every byte as value.

  • 1 - same as 0 but only byte-values with a frequency greater than zero are listed.

  • 2 - same as 0 but only byte-values with a frequency equal to zero are listed.

  • 3 - a string containing all used byte-values is returned.

  • 4 - a string containing all not used byte-values is returned.

后退 | 起点 | 前进
convert_cyr_string | 上一级 | crc32


crc32

(PHP 4 >= 4.0.1)

crc32 -- Calculates the crc32 polynomial of a string

Description

int crc32 ( string str)

Generates the cyclic redundancy checksum polynomial of 32-bit lengths of the str. This is usually used to validate the integrity of data being transmitted.

See also md5()

后退 | 起点 | 前进
count_chars | 上一级 | crypt


crypt

(PHP 3, PHP 4 )

crypt -- One-way string encryption (hashing)

Description

string crypt ( string str [, string salt])

crypt() will return an encrypted string using the standard Unix DES-based encryption algorithm or alternative algorithms that may be available on the system. Arguments are a string to be encrypted and an optional salt string to base the encryption on. See the Unix man page for your crypt function for more information.

If the salt argument is not provided, one will be randomly generated by PHP.

Some operating systems support more than one type of encryption. In fact, sometimes the standard DES-based encryption is replaced by an MD5-based encryption algorithm. The encryption type is triggered by the salt argument. At install time, PHP determines the capabilities of the crypt function and will accept salts for other encryption types. If no salt is provided, PHP will auto-generate a standard two character salt by default, unless the default encryption type on the system is MD5, in which case a random MD5-compatible salt is generated. PHP sets a constant named CRYPT_SALT_LENGTH which tells you whether a regular two character salt applies to your system or the longer twelve character salt is applicable.

If you are using the supplied salt, you should be aware that the salt is generated once. If you are calling this function recursively, this may impact both appearance and security.

The standard DES-based encryption crypt() returns the salt as the first two characters of the output. It also only uses the first eight characters of str, so longer strings that start with the same eight characters will generate the same result (when the same salt is used).

On systems where the crypt() function supports multiple encryption types, the following constants are set to 0 or 1 depending on whether the given type is available:

  • CRYPT_STD_DES - Standard DES-based encryption with a two character salt

  • CRYPT_EXT_DES - Extended DES-based encryption with a nine character salt

  • CRYPT_MD5 - MD5 encryption with a twelve character salt starting with $1$

  • CRYPT_BLOWFISH - Blowfish encryption with a sixteen character salt starting with $2$

注: There is no decrypt function, since crypt() uses a one-way algorithm.

例子 1. crypt() examples

<?php
$password = crypt("My1sTpassword"); # let salt be generated

# You should pass the entire results of crypt() as the salt for comparing a
# password, to avoid problems when different hashing algorithms are used. (As
# it says above, standard DES-based password hashing uses a 2-character salt,
# but MD5-based hashing uses 12.)
if (crypt($user_input,$password) == $password) {
   echo "Password verified!";
}
?>

See also md5() and the Mcrypt extension.

后退 | 起点 | 前进
crc32 | 上一级 | echo


echo

(no version information, might be only in CVS)

echo -- Output one or more strings

Description

echo ( string arg1 [, string argn...])

Outputs all parameters.

echo() is not actually a function (it is a language construct) so you are not required to use parentheses with it. In fact, if you want to pass more than one parameter to echo, you must not enclose the parameters within parentheses. It is not possible to use echo() in a variable function context, but you can use print() instead.

例子 1. echo() examples

<?php
echo "Hello World";

echo "This spans
multiple lines. The newlines will be
output as well";

echo "This spans\nmultiple lines. The newlines will be\noutput as well.";

echo "Escaping characters is done \"Like this\".";

//You can use variables inside of an echo statement
$foo = "foobar";
$bar = "barbaz";

echo "foo is $foo"; // foo is foobar

// Using single quotes will print the variable name, not the value
echo 'foo is $foo'; // foo is $foo

// If you are not using any other characters, you can just echo variables
echo $foo;          // foobar
echo $foo,$bar;     // foobarbarbaz

echo <<<END
This uses the "here document" syntax to output
multiple lines with $variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon no extra whitespace!
END;

// Because echo is not a function, following code is invalid.
($some_var) ? echo('true'): echo('false');

// However, the following examples will work:
($some_var) ? print('true'): print('false'); // print is a function
echo $some_var ? 'true': 'false'; // changing the statement around
?>

echo() also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign.

I have <?=$foo?> foo.

注: This short syntax only works with the short_open_tag configuration setting enabled.

See also
print(),
printf(), and
flush().

后退 | 起点 | 前进
crypt | 上一级 | explode


explode

(PHP 3, PHP 4 )

explode -- Split a string by string

Description

array explode ( string separator, string string [, int limit])

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string separator. If limit is set, the returned array will contain a maximum of limit elements with the last element containing the rest of string.

If separator is an empty string (""), explode() will return FALSE. If separator contains a value that is not contained in string, then explode() will return an array containing string.

注: The limit parameter was added in PHP 4.0.1

例子 1. explode() examples

$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);

$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user,$pass,$uid,$gid,$gecos,$home,$shell) = explode(":",$data);

注: Although implode() can for historical reasons accept its parameters in either order, explode() cannot. You must ensure that the separator argument comes before the string argument.

See also
preg_split(),
spliti(),
split(), and
implode().

后退 | 起点 | 前进
echo | 上一级 | get_html_translation_table


get_html_translation_table

(PHP 4 )

get_html_translation_table -- Returns the translation table used by htmlspecialchars() and htmlentities()

Description

string get_html_translation_table ( int table [, int quote_style])

get_html_translation_table() will return the translation table that is used internally for htmlspecialchars() and htmlentities(). There are two new defines (HTML_ENTITIES, HTML_SPECIALCHARS) that allow you to specify the table you want. And as in the htmlspecialchars() and htmlentities() functions you can optionally specify the quote_style you are working with. The default is ENT_COMPAT mode. See the description of these modes in htmlspecialchars().

例子 1. Translation Table Example

$trans = get_html_translation_table(HTML_ENTITIES);
$str = "Hallo & <Frau> & Kr漤er";
$encoded = strtr($str, $trans);
The $encoded variable will now contain: "Hallo &amp; &lt;Frau&gt; &amp; Kr&auml;mer".

The cool thing is using array_flip() to change the direction of the translation.

$trans = array_flip($trans);
$original = strtr($encoded, $trans);

The content of $original would be: "Hallo & <Frau> & Krämer".

See also htmlspecialchars(),
htmlentities(), strtr(),
and array_flip().

后退 | 起点 | 前进
explode | 上一级 | get_meta_tags


get_meta_tags

(PHP 3>= 3.0.4, PHP 4 )

get_meta_tags -- Extracts all meta tag content attributes from a file and returns an array

Description

array get_meta_tags ( string filename [, int use_include_path])

Opens filename and parses it line by line for <meta> tags of the form

例子 1. Meta Tags Example

<meta name="author" content="name">
<meta name="tags" content="php3 documentation">
</head> <!-- parsing stops here -->
(pay attention to line endings - PHP uses a native function to parse the input, so a Mac file won't work on Unix).

The value of the name property becomes the key, the value of the content property becomes the value of the returned array, so you can easily use standard array functions to traverse it or access single values. Special characters in the value of the name property are substituted with '_', the rest is converted to lower case.

Setting use_include_path to 1 will result in PHP trying to open the file along the standard include path.

后退 | 起点 | 前进
get_html_translation_table | 上一级 | hebrev


hebrev

(PHP 3, PHP 4 )

hebrev -- Convert logical Hebrew text to visual text

Description

string hebrev ( string hebrew_text [, int max_chars_per_line])

The optional parameter max_chars_per_line indicates maximum number of characters per line will be output. The function tries to avoid breaking words.

See also hebrevc()

后退 | 起点 | 前进
get_meta_tags | 上一级 | hebrevc


hebrevc

(PHP 3, PHP 4 )

hebrevc -- Convert logical Hebrew text to visual text with newline conversion

Description

string hebrevc ( string hebrew_text [, int max_chars_per_line])

This function is similar to hebrev() with the difference that it converts newlines (\n) to "<br>\n". The optional parameter max_chars_per_line indicates maximum number of characters per line will be output. The function tries to avoid breaking words.

See also hebrev()

后退 | 起点 | 前进
hebrev | 上一级 | htmlentities


htmlentities

(PHP 3, PHP 4 )

htmlentities -- Convert all applicable characters to HTML entities

Description

string htmlentities ( string string [, int quote_style [, string charset]])

This function is identical to htmlspecialchars() in all ways, except that all characters which have HTML character entity equivalents are translated into these entities. Like htmlspecialchars(), it takes an optional second argument which indicates what should be done with single and double quotes. ENT_COMPAT (the default) will only convert double-quotes and leave single-quotes alone. ENT_QUOTES will convert both double and single quotes, and ENT_NOQUOTES will leave both double and single quotes unconverted.

At present, the ISO-8859-1 character set is used as default. Support for the optional second argument was added in PHP 3.0.17 and PHP 4.0.3.

Like htmlspecialchars(), it takes an optional third argument which defines character set used in conversion. Support for this argument was added in PHP 4.1.0.

There is no reverse of this function. However, you can create one on your own. Here is an example of how to do this.

例子 1. Reverse of htmlentities()

<?php
function unhtmlentities ($string)
{
    $trans_tbl = get_html_translation_table (HTML_ENTITIES);
    $trans_tbl = array_flip ($trans_tbl);
    return strtr ($string, $trans_tbl);
}
?>

See also get_html_translation_table(), htmlspecialchars() and nl2br().

后退 | 起点 | 前进
hebrevc | 上一级 | htmlspecialchars


htmlspecialchars

(PHP 3, PHP 4 )

htmlspecialchars -- Convert special characters to HTML entities

Description

string htmlspecialchars ( string string [, int quote_style [, string charset]])

Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use htmlentities() instead.

This function is useful in preventing user-supplied text from containing HTML markup, such as in a message board or guest book application. The optional second argument, quote_style, tells the function what to do with single and double quote characters. The default mode, ENT_COMPAT, is the backwards compatible mode which only translates the double-quote character and leaves the single-quote untranslated. If ENT_QUOTES is set, both single and double quotes are translated and if ENT_NOQUOTES is set neither single nor double quotes are translated.

The translations performed are:

  • '&' (ampersand) becomes '&amp;'

  • '"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.

  • ''' (single quote) becomes '&#039;' only when ENT_QUOTES is set.

  • '<' (less than) becomes '&lt;'

  • '>' (greater than) becomes '&gt;'

例子 1. htmlspecialchars() example

$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);

Note that this function does not translate anything beyond what is listed above. For full entity translation, see htmlentities(). Support for the optional second argument was added in PHP 3.0.17 and PHP 4.0.3.

The third argument defines character set used in conversion. The default character set is ISO-8859-1. Support for this third argument was added in PHP 4.1.0.

See also get_html_translation_table(), htmlentities() and nl2br().

后退 | 起点 | 前进
htmlentities | 上一级 | implode


implode

(PHP 3, PHP 4 )

implode -- Join array elements with a string

Description

string implode ( string glue, array pieces)

Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.

例子 1. implode() example

<?php

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

print $comma_separated; // lastname,email,phone

?>

注: implode() can, for historical reasons, accept its parameters in either order. For consistency with explode(), however, it may be less confusing to use the documented order of arguments.

See also explode(), and split().

后退 | 起点 | 前进
htmlspecialchars | 上一级 | join


join

(PHP 3, PHP 4 )

join -- Join array elements with a string

Description

string join ( string glue, array pieces)

join() is an alias to implode(), and is identical in every way.

See also explode(), implode(), and split().

后退 | 起点 | 前进
implode | 上一级 | levenshtein


levenshtein

(PHP 3>= 3.0.17, PHP 4 >= 4.0.1)

levenshtein -- Calculate Levenshtein distance between two strings

Description

int levenshtein ( string str1, string str2)

int levenshtein ( string str1, string str2, int cost_ins, int cost_rep, int cost_del)

int levenshtein ( string str1, string str2, function cost)

This function returns the Levenshtein-Distance between the two argument strings or -1, if one of the argument strings is longer than the limit of 255 characters (255 should be more than enough for name or dictionary comparison, and nobody serious would be doing genetic analysis with PHP).

The Levenshtein distance is defined as the minimal number of characters you have to replace, insert or delete to transform str1 into str2. The complexity of the algorithm is O(m*n), where n and m are the length of str1 and str2 (rather good when compared to similar_text(), which is O(max(n,m)**3), but still expensive).

In its simplest form the function will take only the two strings as parameter and will calculate just the number of insert, replace and delete operations needed to transform str1 into str2.

A second variant will take three additional parameters that define the cost of insert, replace and delete operations. This is more general and adaptive than variant one, but not as efficient.

The third variant (which is not implemented yet) will be the most general and adaptive, but also the slowest alternative. It will call a user-supplied function that will determine the cost for every possible operation.

The user-supplied function will be called with the following arguments:

  • operation to apply: 'I', 'R' or 'D'

  • actual character in string 1

  • actual character in string 2

  • position in string 1

  • position in string 2

  • remaining characters in string 1

  • remaining characters in string 2

The user-supplied function has to return a positive integer describing the cost for this particular operation, but it may decide to use only some of the supplied arguments.

The user-supplied function approach offers the possibility to take into account the relevance of and/or difference between certain symbols (characters) or even the context those symbols appear in to determine the cost of insert, replace and delete operations, but at the cost of losing all optimizations done regarding cpu register utilization and cache misses that have been worked into the other two variants.

See also soundex(),
similar_text(), and
metaphone().

后退 | 起点 | 前进
join | 上一级 | localeconv


localeconv

(PHP 4 >= 4.0.5)

localeconv -- Get numeric formatting information

Description

array localeconv ( void)

Returns an associative array containing localized numeric and monetary formatting information.

localeconv() returns data based upon the current locale as set by setlocale(). The associative array that is returned contains the following fields:

Array element | Description
decimal_point | Decimal point character
thousands_sep | Thousands separator
grouping | Array containing numeric groupings
int_curr_symbol | International currency symbol (i.e. USD)
currency_symbol | Local currency symbol (i.e. $)
mon_decimal_point | Monetary decimal point character
mon_thousands_sep | Monetary thousands separator
mon_grouping | Array containing monetary groupings
positive_sign | Sign for positive values
negative_sign | Sign for negative values
int_frac_digits | International fractional digits
frac_digits | Local fractional digits
p_cs_precedes | TRUE if currency_symbol precedes a positive value, FALSE if it succeeds one
p_sep_by_space | TRUE if a space separates currency_symbol from a positive value, FALSE otherwise
n_cs_precedes | TRUE if currency_symbol precedes a negative value, FALSE if it succeeds one
n_sep_by_space | TRUE if a space separates currency_symbol from a negative value, FALSE otherwise
p_sign_posn

0 | Parentheses surround the quantity and currency_symbol
1 | The sign string precedes the quantity and currency_symbol
2 | The sign string succeeds the quantity and currency_symbol
3 | The sign string immediately precedes the currency_symbol
4 | The sign string immediately succeeds the currency_symbol

n_sign_posn

0 | Parentheses surround the quantity and currency_symbol
1 | The sign string precedes the quantity and currency_symbol
2 | The sign string succeeds the quantity and currency_symbol
3 | The sign string immediately precedes the currency_symbol
4 | The sign string immediately succeeds the currency_symbol

The grouping fields contain arrays that define the way numbers should be grouped. For example, the grouping field for the en_US locale, would contain a 2 item array with the values 3 and 3. The higher the index in the array, the farther left the grouping is. If an array element is equal to CHAR_MAX, no further grouping is done. If an array element is equal to 0, the previous element should be used.

例子 1. localeconv() example

setlocale(LC_ALL, "en_US");

$locale_info = localeconv();

echo "<PRE>\n";
echo "--------------------------------------------\n";
echo "  Monetary information for current locale:  \n";
echo "--------------------------------------------\n\n";

echo "int_curr_symbol:   {$locale_info["int_curr_symbol"]}\n";
echo "currency_symbol:   {$locale_info["currency_symbol"]}\n";
echo "mon_decimal_point: {$locale_info["mon_decimal_point"]}\n";
echo "mon_thousands_sep: {$locale_info["mon_thousands_sep"]}\n";
echo "positive_sign:     {$locale_info["positive_sign"]}\n";
echo "negative_sign:     {$locale_info["negative_sign"]}\n";
echo "int_frac_digits:   {$locale_info["int_frac_digits"]}\n";
echo "frac_digits:       {$locale_info["frac_digits"]}\n";
echo "p_cs_precedes:     {$locale_info["p_cs_precedes"]}\n";
echo "p_sep_by_space:    {$locale_info["p_sep_by_space"]}\n";
echo "n_cs_precedes:     {$locale_info["n_cs_precedes"]}\n";
echo "n_sep_by_space:    {$locale_info["n_sep_by_space"]}\n";
echo "p_sign_posn:       {$locale_info["p_sign_posn"]}\n";
echo "n_sign_posn:       {$locale_info["n_sign_posn"]}\n";
echo "</PRE>\n";

The constant CHAR_MAX is also defined for the use mentioned above.

See also setlocale().

后退 | 起点 | 前进
levenshtein | 上一级 | ltrim


ltrim

(PHP 3, PHP 4 )

ltrim -- Strip whitespace from the beginning of a string

Description

string ltrim ( string str [, string charlist])

注: The second parameter was added in PHP 4.1.0

This function returns a string with whitespace stripped from the beginning of str. Without the second parameter, ltrim() will strip these characters:

  • " " (ASCII 32 (0x20)), an ordinary space.

  • "\t" (ASCII 9 (0x09)), a tab.

  • "\n" (ASCII 10 (0x0A)), a new line (line feed).

  • "\r" (ASCII 13 (0x0D)), a carriage return.

  • "\0" (ASCII 0 (0x00)), the NUL-byte.

  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.

You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

例子 1. Usage example of ltrim()

<?php

$text = "\t\tThese are a few words :) ...  ";
$trimmed = ltrim($text);
// $trimmed = "These are a few words :) ...  "
$trimmed = ltrim($text," \t.");
// $trimmed = "These are a few words :) ...  "
$clean = ltrim($binary,"\0x00..\0x1F");
// trim the ASCII control characters at the beginning of $binary
// (from 0 to 31 inclusive)

?>

See also trim() and rtrim().

后退 | 起点 | 前进
localeconv | 上一级 | md5_file


md5_file

(PHP 4 >= 4.2.0)

md5_file -- Calculates the md5 hash of a given filename

Description

string md5_file ( string filename)

Calculates the MD5 hash of the specified filename using the RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash.

This function has the same purpose of the command line utility md5sum.

See also md5() and crc32()

后退 | 起点 | 前进
ltrim | 上一级 | md5


md5

(PHP 3, PHP 4 )

md5 -- Calculate the md5 hash of a string

Description

string md5 ( string str)

Calculates the MD5 hash of str using the RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash. The hash is a 32-character hexadecimal number.

See also crc32() and md5_file()

后退 | 起点 | 前进
md5_file | 上一级 | metaphone


metaphone

(PHP 4 )

metaphone -- Calculate the metaphone key of a string

Description

string metaphone ( string str)

Calculates the metaphone key of str.

Similar to soundex() metaphone creates the same key for similar sounding words. It's more accurate than soundex() as it knows the basic rules of English pronunciation. The metaphone generated keys are of variable length.

Metaphone was developed by Lawrence Philips <lphilips@verity.com>. It is described in ["Practical Algorithms for Programmers", Binstock & Rex, Addison Wesley, 1995].

后退 | 起点 | 前进
md5 | 上一级 | nl_langinfo


nl_langinfo

(PHP 4 >= 4.1.0)

nl_langinfo -- Query language and locale information

Description

string nl_langinfo ( int item)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
metaphone | 上一级 | nl2br


nl2br

(PHP 3, PHP 4 )

nl2br -- Inserts HTML line breaks before all newlines in a string

Description

string nl2br ( string string)

Returns string with '<br />' inserted before all newlines.

注: Starting with PHP 4.0.5, nl2br() is now XHTML compliant. All versions before 4.0.5 will return string with '<br>' inserted before newlines instead of '<br />'.

See also htmlspecialchars(),
htmlentities() and
wordwrap().

后退 | 起点 | 前进
nl_langinfo | 上一级 | ord


ord

(PHP 3, PHP 4 )

ord -- Return ASCII value of character

Description

int ord ( string string)

Returns the ASCII value of the first character of string. This function complements chr().

例子 1. ord() example

if (ord($str) == 10) {
    echo "The first character of \$str is a line feed.\n";
}

You can find an ASCII-table over here: http://www.asciitable.com.

See also chr().

后退 | 起点 | 前进
nl2br | 上一级 | parse_str


parse_str

(PHP 3, PHP 4 )

parse_str -- Parses the string into variables

Description

void parse_str ( string str [, array arr])

Parses str as if it were the query string passed via an URL and sets variables in the current scope. If the second parameter arr is present, variables are stored in this variable as an array elements instead.

注: Support for the optional second parameter was added in PHP 4.0.3.

例子 1. Using parse_str()

$str = "first=value&second[]=this+works&second[]=another";
parse_str($str);
echo $first;     /* prints "value" */
echo $second[0]; /* prints "this works" */
echo $second[1]; /* prints "another" */

See also set_magic_quotes_runtime() and urldecode().

后退 | 起点 | 前进
ord | 上一级 | print


print

(no version information, might be only in CVS)

print -- Output a string

Description

print ( string arg)

Outputs arg. 如果成功则返回 TRUE，失败则返回 FALSE。

print() is not actually a real function (it is a language construct) so you are not required to use parentheses with it.

例子 1. print() examples

<?php
print("Hello World");

print "print() also works without parentheses.";

print "This spans
multiple lines. The newlines will be
output as well";

print "This spans\nmultiple lines. The newlines will be\noutput as well.";

print "escaping characters is done \"Like this\".";

// You can use variables inside of an print statement
$foo = "foobar";
$bar = "barbaz";

print "foo is $foo"; // foo is foobar

// Using single quotes will print the variable name, not the value
print 'foo is $foo'; // foo is $foo

// If you are not using any other characters, you can just print variables
print $foo;          // foobar

print <<<END
This uses the "here document" syntax to output
multiple lines with $variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon no extra whitespace!
END;
?>

See also echo(), printf(), and flush().

后退 | 起点 | 前进
parse_str | 上一级 | printf


printf

(PHP 3, PHP 4 )

printf -- Output a formatted string

Description

void printf ( string format [, mixed args])

Produces output according to format, which is described in the documentation for sprintf().

See also print(), sprintf(),
sscanf(), fscanf(),
and flush().

后退 | 起点 | 前进
print | 上一级 | quoted_printable_decode


quoted_printable_decode

(PHP 3>= 3.0.6, PHP 4 )

quoted_printable_decode -- Convert a quoted-printable string to an 8 bit string

Description

string quoted_printable_decode ( string str)

This function returns an 8-bit binary string corresponding to the decoded quoted printable string. This function is similar to imap_qprint(), except this one does not require the IMAP module to work.

后退 | 起点 | 前进
printf | 上一级 | quotemeta


quotemeta

(PHP 3, PHP 4 )

quotemeta -- Quote meta characters

Description

string quotemeta ( string str)

Returns a version of str with a backslash character (\) before every character that is among these:
. \\ + * ? [ ^ ] ( $ )

See also addslashes(),
htmlentities(),
htmlspecialchars(),
nl2br(), and
stripslashes().

后退 | 起点 | 前进
quoted_printable_decode | 上一级 | rtrim


rtrim

(PHP 3, PHP 4 )

rtrim -- Strip whitespace from the end of a string

Description

string rtrim ( string str [, string charlist])

注: The second parameter was added in PHP 4.1.0

This function returns a string with whitespace stripped from the end of str. Without the second parameter, rtrim() will strip these characters:

  • " " (ASCII 32 (0x20)), an ordinary space.

  • "\t" (ASCII 9 (0x09)), a tab.

  • "\n" (ASCII 10 (0x0A)), a new line (line feed).

  • "\r" (ASCII 13 (0x0D)), a carriage return.

  • "\0" (ASCII 0 (0x00)), the NUL-byte.

  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.

You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

例子 1. Usage example of rtrim()

<?php

$text = "\t\tThese are a few words :) ...  ";
$trimmed = rtrim($text);
// $trimmed = "\t\tThese are a few words :) ..."
$trimmed = rtrim($text," \t.");
// $trimmed = "\t\tThese are a few words :)"
$clean = rtrim($binary,"\0x00..\0x1F");
// trim the ASCII control characters at the end of $binary
// (from 0 to 31 inclusive)

?>

See also trim() and ltrim().

后退 | 起点 | 前进
quotemeta | 上一级 | setlocale


setlocale

(PHP 3, PHP 4 )

setlocale -- Set locale information

Description

string setlocale ( mixed category, string locale [, string ...])

string setlocale ( mixed category, array locale)

Category is a named constant (or string) specifying the category of the functions affected by the locale setting:

  • LC_ALL for all of the below

  • LC_COLLATE for string comparison, see strcoll()

  • LC_CTYPE for character classification and conversion, for example strtoupper()

  • LC_MONETARY for localeconv()

  • LC_NUMERIC for decimal separator (See also localeconv())

  • LC_TIME for date and time formatting with strftime()

If locale is the empty string "", the locale names will be set from the values of environment variables with the same names as the above categories, or from "LANG".

If locale is zero or "0", the locale setting is not affected, only the current setting is returned.

If locale is an array or followed by additional parameters then each array element or parameter is tried to be set as new locale until success. This is usefull if a locale is known under different names on different systems or for providing a fallback for a possibly not available locale.

注: Passing multiple locales is not available before PHP 4.3

Setlocale returns the new current locale, or FALSE if the locale functionality is not implemented in the platform, the specified locale does not exist or the category name is invalid. An invalid category name also causes a warning message.

例子 1. setlocale() Examples

<?php
    /* Set locale to Dutch */
    setlocale (LC_ALL, 'nl_NL');

    /* Output: vrijdag 22 december 1978 */
    echo strftime ("%A %e %B %Y", mktime (0, 0, 0, 12, 22, 1978));

    /* try different possible locale names for german */
    $loc_de = setlocale (LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge');
    echo "Preferred locale for german on this system is '$loc_de';
?>

后退 | 起点 | 前进
rtrim | 上一级 | similar_text


similar_text

(PHP 3>= 3.0.7, PHP 4 )

similar_text -- Calculate the similarity between two strings

Description

int similar_text ( string first, string second [, float percent])

This calculates the similarity between two strings as described in Oliver [1993]. Note that this implementation does not use a stack as in Oliver's pseudo code, but recursive calls which may or may not speed up the whole process. Note also that the complexity of this algorithm is O(N**3) where N is the length of the longest string.

By passing a reference as third argument, similar_text() will calculate the similarity in percent for you. It returns the number of matching chars in both strings.

后退 | 起点 | 前进
setlocale | 上一级 | soundex


soundex

(PHP 3, PHP 4 )

soundex -- Calculate the soundex key of a string

Description

string soundex ( string str)

Calculates the soundex key of str.

Soundex keys have the property that words pronounced similarly produce the same soundex key, and can thus be used to simplify searches in databases where you know the pronunciation but not the spelling. This soundex function returns a string 4 characters long, starting with a letter.

This particular soundex function is one described by Donald Knuth in "The Art Of Computer Programming, vol. 3: Sorting And Searching", Addison-Wesley (1973), pp. 391-392.

例子 1. Soundex Examples

soundex("Euler") == soundex("Ellery") == 'E460';
soundex("Gauss") == soundex("Ghosh") == 'G200';
soundex("Hilbert") == soundex("Heilbronn") == 'H416';
soundex("Knuth") == soundex("Kant") == 'K530';
soundex("Lloyd") == soundex("Ladd") == 'L300';
soundex("Lukasiewicz") == soundex("Lissajous") == 'L222';

See also levenshtein(), metaphone(), and similar_text().

后退 | 起点 | 前进
similar_text | 上一级 | sprintf


sprintf

(PHP 3, PHP 4 )

sprintf -- Return a formatted string

Description

string sprintf ( string format [, mixed args])

Returns a string produced according to the formatting string format.

The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result, and conversion specifications, each of which results in fetching its own parameter. This applies to both sprintf() and printf().

Each conversion specification consists of a percent sign (%), followed by one or more of these elements, in order:

  1. An optional padding specifier that says what character will be used for padding the results to the right string size. This may be a space character or a 0 (zero character). The default is to pad with spaces. An alternate padding character can be specified by prefixing it with a single quote ('). See the examples below.

  2. An optional alignment specifier that says if the result should be left-justified or right-justified. The default is right-justified; a - character here will make it left-justified.

  3. An optional number, a width specifier that says how many characters (minimum) this conversion should result in.

  4. An optional precision specifier that says how many decimal digits should be displayed for floating-point numbers. This option has no effect for other types than float. (Another function useful for formatting numbers is number_format().)

  5. A type specifier that says what type the argument data should be treated as. Possible types:

    % - a literal percent character. No argument is required.
    b - the argument is treated as an integer, and presented as a binary number.
    c - the argument is treated as an integer, and presented as the character with that ASCII value.
    d - the argument is treated as an integer, and presented as a (signed) decimal number.
    u - the argument is treated as an integer, and presented as an unsigned decimal number.
    f - the argument is treated as a float, and presented as a floating-point number.
    o - the argument is treated as an integer, and presented as an octal number.
    s - the argument is treated as and presented as a string.
    x - the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
    X - the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).

As of PHP version 4.0.6 the format string supports argument numbering/swapping. Here is an example:

例子 1. Argument swapping

$format = "There are %d monkeys in the %s";
printf($format,$num,$location);
This might output, "There are 5 monkeys in the tree". But imagine we are creating a format string in a separate file, commonly because we would like to internationalize it and we rewrite it as:

例子 2. Argument swapping

$format = "The %s contains %d monkeys";
printf($format,$num,$location);
We now have a problem. The order of the placeholders in the format string does not match the order of the arguments in the code. We would like to leave the code as is and simply indicate in the format string which arguments the placeholders refer to. We would write the format string like this instead:

例子 3. Argument swapping

$format = "The %2\$s contains %1\$d monkeys";
printf($format,$num,$location);
An added benefit here is that you can repeat the placeholders without adding more arguments in the code. For example:

例子 4. Argument swapping

$format = "The %2\$s contains %1\$d monkeys.
           That's a nice %2\$s full of %1\$d monkeys.";
printf($format, $num, $location);

See also printf(),
sscanf(), fscanf(), and
number_format().

Examples

例子 5. sprintf(): zero-padded integers

$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);

例子 6. sprintf(): formatting currency

$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money will output "123.1";
$formatted = sprintf("%01.2f", $money);
// echo $formatted will output "123.10"

后退 | 起点 | 前进
soundex | 上一级 | sscanf


sscanf

(PHP 4 >= 4.0.1)

sscanf -- Parses input from a string according to a format

Description

mixed sscanf ( string str, string format [, string var1])

The function sscanf() is the input analog of printf(). sscanf() reads from the string str and interprets it according to the specified format. If only two parameters were passed to this function, the values parsed will be returned as an array.

Any whitespace in the format string matches any whitespace in the input string. This means that even a tab \n in the format string can match a single space character in the input string.

例子 1. sscanf() Example

// getting the serial number
$serial = sscanf("SN/2350001","SN/%d");
// and the date of manufacturing
$mandate = "January 01 2000";
list($month, $day, $year) = sscanf($mandate,"%s %d %d");
echo "Item $serial was manufactured on: $year-".substr($month,0,3)."-$day\n";
If optional parameters are passed, the function will return the number of assigned values. The optional parameters must be passed by reference.

例子 2. sscanf() - using optional parameters

// get author info and generate DocBook entry
$auth = "24\tLewis Carroll";
$n = sscanf($auth,"%d\t%s %s", &$id, &$first, &$last);
echo "<author id='$id'>
    <firstname>$first</firstname>
    <surname>$last</surname>
</author>\n";

See also fscanf(), printf(), and sprintf().

后退 | 起点 | 前进
sprintf | 上一级 | str_pad


str_pad

(PHP 4 >= 4.0.1)

str_pad -- Pad a string to a certain length with another string

Description

string str_pad ( string input, int pad_length [, string pad_string [, int pad_type]])

This functions returns the input string padded on the left, the right, or both sides to the specified padding length. If the optional argument pad_string is not supplied, the input is padded with spaces, otherwise it is padded with characters from pad_string up to the limit.

Optional argument pad_type can be STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH. If pad_type is not specified it is assumed to be STR_PAD_RIGHT.

If the value of pad_length is negative or less than the length of the input string, no padding takes place.

例子 1. str_pad() example

$input = "Alien";
print str_pad($input, 10);                      // produces "Alien     "
print str_pad($input, 10, "-=", STR_PAD_LEFT);  // produces "-=-=-Alien"
print str_pad($input, 10, "_", STR_PAD_BOTH);   // produces "__Alien___"

后退 | 起点 | 前进
sscanf | 上一级 | str_repeat


str_repeat

(PHP 4 )

str_repeat -- Repeat a string

Description

string str_repeat ( string input, int multiplier)

Returns input_str repeated multiplier times. multiplier has to be greater than or equal to 0. If the multiplier is set to 0, the function will return an empty string.

例子 1. str_repeat() example

echo str_repeat("-=", 10);

This will output "-=-=-=-=-=-=-=-=-=-=".

See also for, str_pad(), and substr_count().

后退 | 起点 | 前进
str_pad | 上一级 | str_replace


str_replace

(PHP 3>= 3.0.6, PHP 4 )

str_replace -- Replace all occurrences of the search string with the replacement string

Description

mixed str_replace ( mixed search, mixed replace, mixed subject)

This function returns a string or an array with all occurences of search in subject replaced with the given replace value. If you don't need fancy replacing rules, you should always use this function instead of ereg_replace() or preg_replace().

In PHP 4.0.5 and later, every parameter to str_replace() can be an array.

If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well.

If search and replace are arrays, then str_replace() takes a value from each array and uses them to do search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values. If search is an array and replace is a string; then this replacement string is used for every value of search.

例子 1. str_replace() example

$bodytag = str_replace("%body%", "black", "<body text=%body%>");

This function is binary safe.

注: str_replace() was added in PHP 3.0.6, but was buggy up until PHP 3.0.8.

See also ereg_replace(), preg_replace(), and strtr().

后退 | 起点 | 前进
str_repeat | 上一级 | str_rot13


str_rot13

(PHP 4 >= 4.2.0)

str_rot13 -- Perform the rot13 transform on a string

Description

string str_rot13 ( string str)

This function performs the ROT13 encoding on the str argument and returns the resulting string. The ROT13 encoding simply shifts every letter by 13 places in the alphabet while leaving non-alpha characters untouched. Encoding and decoding are done by the same function, passing an encoded string as argument will return the original version.

后退 | 起点 | 前进
str_replace | 上一级 | strcasecmp


strcasecmp

(PHP 3>= 3.0.2, PHP 4 )

strcasecmp -- Binary safe case-insensitive string comparison

Description

int strcasecmp ( string str1, string str2)

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

例子 1. strcasecmp() example

$var1 = "Hello";
$var2 = "hello";
if (!strcasecmp($var1, $var2)) {
    echo '$var1 is equal to $var2 in a case-insensitive string comparison';
}

See also ereg(), strcmp(),
substr(), stristr(),
strncasecmp(), and
strstr().

后退 | 起点 | 前进
str_rot13 | 上一级 | strchr


strchr

(PHP 3, PHP 4 )

strchr -- Find the first occurrence of a character

Description

string strchr ( string haystack, string needle)

This function is an alias for strstr(), and is identical in every way.

后退 | 起点 | 前进
strcasecmp | 上一级 | strcmp


strcmp

(PHP 3, PHP 4 )

strcmp -- Binary safe string comparison

Description

int strcmp ( string str1, string str2)

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Note that this comparison is case sensitive.

See also ereg(),
strcasecmp(), substr(),
stristr(), strncasecmp(),
strncmp(), and strstr().

后退 | 起点 | 前进
strchr | 上一级 | strcoll


strcoll

(PHP 4 >= 4.0.5)

strcoll -- Locale based string comparison

Description

int strcoll ( string str1, string str2)

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. strcoll() uses the current locale for doing the comparisons. If the current locale is C or POSIX, this function is equivalent to strcmp().

Note that this comparison is case sensitive, and unlike strcmp() this function is not binary safe.

注: strcoll() was added in PHP 4.0.5, but was not enabled for win32 until 4.2.3.

See also ereg(), strcmp(),
strcasecmp(), substr(),
stristr(), strncasecmp(),
strncmp(), strstr(), and
setlocale().

后退 | 起点 | 前进
strcmp | 上一级 | strcspn


strcspn

(PHP 3>= 3.0.3, PHP 4 )

strcspn -- Find length of initial segment not matching mask

Description

int strcspn ( string str1, string str2)

Returns the length of the initial segment of str1 which does not contain any of the characters in str2.

See also strspn().

后退 | 起点 | 前进
strcoll | 上一级 | strip_tags


strip_tags

(PHP 3>= 3.0.8, PHP 4 )

strip_tags -- Strip HTML and PHP tags from a string

Description

string strip_tags ( string str [, string allowable_tags])

This function tries to return a string with all HTML and PHP tags stripped from a given str. It errors on the side of caution in case of incomplete or bogus tags. It uses the same tag stripping state machine as the fgetss() function.

You can use the optional second parameter to specify tags which should not be stripped.

注: allowable_tags was added in PHP 3.0.13 and PHP 4.0b3.

例子 1. strip_tags() example

$string = strip_tags($string, '<a><b><i><u>');

警告

This function does not modify any attributes on the tags that you allow using allowable_tags, including the style and onmouseover attributes that a mischievous user may abuse when posting text that will be shown to other users.

后退 | 起点 | 前进
strcspn | 上一级 | stripcslashes


stripcslashes

(PHP 4 )

stripcslashes -- Un-quote string quoted with addcslashes()

Description

string stripcslashes ( string str)

Returns a string with backslashes stripped off. Recognizes C-like \n, \r ..., octal and hexadecimal representation.

See also addcslashes().

后退 | 起点 | 前进
strip_tags | 上一级 | stripslashes


stripslashes

(PHP 3, PHP 4 )

stripslashes -- Un-quote string quoted with addslashes()

Description

string stripslashes ( string str)

Returns a string with backslashes stripped off. (\' becomes ' and so on.) Double backslashes are made into a single backslash.

See also addslashes().

后退 | 起点 | 前进
stripcslashes | 上一级 | stristr


stristr

(PHP 3>= 3.0.6, PHP 4 )

stristr -- Case-insensitive strstr()

Description

string stristr ( string haystack, string needle)

Returns all of haystack from the first occurrence of needle to the end. needle and haystack are examined in a case-insensitive manner.

If needle is not found, returns FALSE.

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

See also strchr(),
strrchr(), substr(), and
ereg().

后退 | 起点 | 前进
stripslashes | 上一级 | strlen


strlen

(PHP 3, PHP 4 )

strlen -- Get string length

Description

int strlen ( string str)

Returns the length of string.

后退 | 起点 | 前进
stristr | 上一级 | strnatcasecmp


strnatcasecmp

(PHP 4 )

strnatcasecmp -- Case insensitive string comparisons using a "natural order" algorithm

Description

int strnatcasecmp ( string str1, string str2)

This function implements a comparison algorithm that orders alphanumeric strings in the way a human being would. The behaviour of this function is similar to strnatcmp(), except that the comparison is not case sensitive. For more infomation see: Martin Pool's Natural Order String Comparison page.

Similar to other string comparison functions, this one returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

See also ereg(),
strcasecmp(), substr(),
stristr(), strcmp(),
strncmp(), strncasecmp(),
strnatcmp(), and strstr().

后退 | 起点 | 前进
strlen | 上一级 | strnatcmp


strnatcmp

(PHP 4 )

strnatcmp -- String comparisons using a "natural order" algorithm

Description

int strnatcmp ( string str1, string str2)

This function implements a comparison algorithm that orders alphanumeric strings in the way a human being would, this is described as a "natural ordering". An example of the difference between this algorithm and the regular computer string sorting algorithms (used in strcmp()) can be seen below:

$arr1 = $arr2 = array("img12.png","img10.png","img2.png","img1.png");
echo "Standard string comparison\n";
usort($arr1,"strcmp");
print_r($arr1);
echo "\nNatural order string comparison\n";
usort($arr2,"strnatcmp");
print_r($arr2);

The code above will generate the following output:

Standard string comparison
Array
(
    [0] => img1.png
    [1] => img10.png
    [2] => img12.png
    [3] => img2.png
)

Natural order string comparison
Array
(
    [0] => img1.png
    [1] => img2.png
    [2] => img10.png
    [3] => img12.png
)

For more information see: Martin Pool's Natural Order String Comparison page.

Similar to other string comparison functions, this one returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Note that this comparison is case sensitive.

See also ereg(),
strcasecmp(), substr(),
stristr(), strcmp(),
strncmp(), strncasecmp(),
strnatcasecmp(), strstr(),
natsort() and natcasesort().

后退 | 起点 | 前进
strnatcasecmp | 上一级 | strncasecmp


strncasecmp

(PHP 4 >= 4.0.2)

strncasecmp -- Binary safe case-insensitive string comparison of the first n characters

Description

int strncasecmp ( string str1, string str2, int len)

This function is similar to strcasecmp(), with the difference that you can specify the (upper limit of the) number of characters (len) from each string to be used in the comparison. If any of the strings is shorter than len, then the length of that string will be used for the comparison.

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

See also ereg(), strcasecmp(),
strcmp(), substr(),
stristr(), and strstr().

后退 | 起点 | 前进
strnatcmp | 上一级 | strncmp


strncmp

(PHP 4 )

strncmp -- Binary safe string comparison of the first n characters

Description

int strncmp ( string str1, string str2, int len)

This function is similar to strcmp(), with the difference that you can specify the (upper limit of the) number of characters (len) from each string to be used in the comparison. If any of the strings is shorter than len, then the length of that string will be used for the comparison.

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Note that this comparison is case sensitive.

See also ereg(),
strncasecmp(),
strcasecmp(), substr(),
stristr(), strcmp(), and
strstr().

后退 | 起点 | 前进
strncasecmp | 上一级 | strpos


strpos

(PHP 3, PHP 4 )

strpos -- Find position of first occurrence of a string

Description

int strpos ( string haystack, string needle [, int offset])

Returns the numeric position of the first occurrence of needle in the haystack string. Unlike the strrpos(), this function can take a full string as the needle parameter and the entire string will be used.

If needle is not found, returns FALSE.

注: It is easy to mistake the return values for "character found at position 0" and "character not found". Here's how to detect the difference:

// in PHP 4.0b3 and newer:
$pos = strpos($mystring, "b");
if ($pos === false) { // note: three equal signs
    // not found...
}

// in versions older than 4.0b3:
$pos = strpos($mystring, "b");
if (!is_integer($pos)) {
    // not found...
}

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

The optional offset parameter allows you to specify which character in haystack to start searching. The position returned is still relative to the the beginning of haystack.

See also strrpos(),
strrchr(), substr(),
stristr(), and strstr().

后退 | 起点 | 前进
strncmp | 上一级 | strrchr


strrchr

(PHP 3, PHP 4 )

strrchr -- Find the last occurrence of a character in a string

Description

string strrchr ( string haystack, string needle)

This function returns the portion of haystack which starts at the last occurrence of needle and goes until the end of haystack.

Returns FALSE if needle is not found.

If needle contains more than one character, the first is used.

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

例子 1. strrchr() example

// get last directory in $PATH
$dir = substr(strrchr($PATH, ":"), 1);

// get everything after last newline
$text = "Line 1\nLine 2\nLine 3";
$last = substr(strrchr($text, 10), 1 );

See also strchr(), substr(), stristr(), and strstr().

后退 | 起点 | 前进
strpos | 上一级 | strrev


strrev

(PHP 3, PHP 4 )

strrev -- Reverse a string

Description

string strrev ( string string)

Returns string, reversed.

例子 1. Reversing a string with strrev()

<php
echo strrev("Hello world!"); // outputs "!dlrow olleH"
?>

后退 | 起点 | 前进
strrchr | 上一级 | strrpos


strrpos

(PHP 3, PHP 4 )

strrpos -- Find position of last occurrence of a char in a string

Description

int strrpos ( string haystack, char needle)

Returns the numeric position of the last occurrence of needle in the haystack string. Note that the needle in this case can only be a single character. If a string is passed as the needle, then only the first character of that string will be used.

If needle is not found, returns FALSE.

注: It is easy to mistake the return values for "character found at position 0" and "character not found". Here's how to detect the difference:

// in PHP 4.0b3 and newer:
$pos = strrpos($mystring, "b");
if ($pos === false) { // note: three equal signs
    // not found...
}

// in versions older than 4.0b3:
$pos = strrpos($mystring, "b");
if (is_string($pos) && !$pos) {
    // not found...
}

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

See also strpos(),
strrchr(), substr(),
stristr(), and strstr().

后退 | 起点 | 前进
strrev | 上一级 | strspn


strspn

(PHP 3>= 3.0.3, PHP 4 )

strspn -- Find length of initial segment matching mask

Description

int strspn ( string str1, string str2)

Returns the length of the initial segment of str1 which consists entirely of characters in str2.

The line of code:

$var = strspn("42 is the answer, what is the question ...", "1234567890");

will assign 2 to $var, because the string "42" will be the longest segment containing characters from "1234567890".

See also strcspn().

后退 | 起点 | 前进
strrpos | 上一级 | strstr


strstr

(PHP 3, PHP 4 )

strstr -- Find first occurrence of a string

Description

string strstr ( string haystack, string needle)

Returns part of haystack string from the first occurrence of needle to the end of haystack.

If needle is not found, returns FALSE.

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

注: This function is case-sensitive. For case-insensitive searches, use stristr().

例子 1. strstr() example

$email = 'user@example.com';
$domain = strstr($email, '@');
print $domain; // prints @example.com

See also ereg(), preg_match(),
strchr(), stristr(),
strpos(), strrchr(), and
substr().

后退 | 起点 | 前进
strspn | 上一级 | strtok


strtok

(PHP 3, PHP 4 )

strtok -- Tokenize string

Description

string strtok ( string arg1, string arg2)

strtok() splits a string (arg1) into smaller strings (tokens), with each token being delimited by any character from arg2. That is, if you have a string like "This is an example string" you could tokenize this string into its individual words by using the space character as the token.

例子 1. strtok() example

$string = "This is\tan example\nstring";
/* Use tab and newline as tokenizing characters as well  */
$tok = strtok($string," \n\t");
while ($tok) {
    echo "Word=$tok<br>";
    $tok = strtok(" \n\t");
}

Note that only the first call to strtok uses the string argument. Every subsequent call to strtok only needs the token to use, as it keeps track of where it is in the current string. To start over, or to tokenize a new string you simply call strtok with the string argument again to initialize it. Note that you may put multiple tokens in the token parameter. The string will be tokenized when any one of the characters in the argument are found.

The behavior when an empty part was found changed with PHP 4.1.0. The old behavior returned an empty string, while the new, correct, behavior simply skips the part of the string:

例子 2. Old strtok() behavior

$first_token  = strtok('/something', '/');
    $second_token = strtok('/');
    var_dump ($first_token, $second_token);

/* Output:
    string(0) ""
    string(9) "something"
*/

例子 3. New strtok() behavior

$first_token  = strtok('/something', '/');
    $second_token = strtok('/');
    var_dump ($first_token, $second_token);

/* Output:
    string(9) "something"
    bool(false)
*/

Also be careful that your tokens may be equal to "0". This evaluates to FALSE in conditional expressions.

See also split() and explode().

后退 | 起点 | 前进
strstr | 上一级 | strtolower


strtolower

(PHP 3, PHP 4 )

strtolower -- Make a string lowercase

Description

string strtolower ( string str)

Returns string with all alphabetic characters converted to lowercase.

Note that 'alphabetic' is determined by the current locale. This means that in i.e. the default "C" locale, characters such as umlaut-A (Ä) will not be converted.

例子 1. strtolower() example

$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtolower($str);
print $str; # Prints mary had a little lamb and she loved it so

See also strtoupper(),
ucfirst(),
and ucwords().

后退 | 起点 | 前进
strtok | 上一级 | strtoupper


strtoupper

(PHP 3, PHP 4 )

strtoupper -- Make a string uppercase

Description

string strtoupper ( string string)

Returns string with all alphabetic characters converted to uppercase.

Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (洎 will not be converted.

例子 1. strtoupper() example

$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtoupper($str);
print $str; # Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO

See also strtolower(),
ucfirst(),
and ucwords().

后退 | 起点 | 前进
strtolower | 上一级 | strtr


strtr

(PHP 3, PHP 4 )

strtr -- Translate certain characters

Description

string strtr ( string str, string from, string to)

string strtr ( string str, array replace_pairs)

This function returns a copy of str, translating all occurrences of each character in from to the corresponding character in to and returning the result.

If from and to are different lengths, the extra characters in the longer of the two are ignored.

例子 1. strtr() example

$addr = strtr($addr, "溴觫, "aao");

strtr() can be called with only two arguments. If called with two arguments it behaves in a new way: from then has to be an array that contains string -> string pairs that will be replaced in the source string. strtr() will always look for the longest possible match first and will *NOT* try to replace stuff that it has already worked on.

Examples:

$trans = array("hello" => "hi", "hi" => "hello");
echo strtr("hi all, I said hello", $trans) . "\n";

This will show: "hello all, I said hi",

注: This optional to and from parameters were added in PHP 4.0.0

See also ereg_replace().

后退 | 起点 | 前进
strtoupper | 上一级 | substr_count


substr_count

(PHP 4 )

substr_count -- Count the number of substring occurrences

Description

int substr_count ( string haystack, string needle)

substr_count() returns the number of times the needle substring occurs in the haystack string.

例子 1. substr_count() example

print substr_count("This is a test", "is"); // prints out 2

后退 | 起点 | 前进
strtr | 上一级 | substr_replace


substr_replace

(PHP 4 )

substr_replace -- Replace text within a portion of a string

Description

string substr_replace ( string string, string replacement, int start [, int length])

substr_replace() replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement. The result is returned.

If start is positive, the replacing will begin at the start'th offset into string.

If start is negative, the replacing will begin at the start'th character from the end of string.

If length is given and is positive, it represents the length of the portion of string which is to be replaced. If it is negative, it represents the number of characters from the end of string at which to stop replacing. If it is not given, then it will default to strlen( string ); i.e. end the replacing at the end of string.

例子 1. substr_replace() example

<?php
$var = 'ABCDEFGH:/MNRPQR/';
echo "Original: $var<hr>\n";

/* These two examples replace all of $var with 'bob'. */
echo substr_replace($var, 'bob', 0) . "<br>\n";
echo substr_replace($var, 'bob', 0, strlen($var)) . "<br>\n";

/* Insert 'bob' right at the beginning of $var. */
echo substr_replace($var, 'bob', 0, 0) . "<br>\n";

/* These next two replace 'MNRPQR' in $var with 'bob'. */
echo substr_replace($var, 'bob', 10, -1) . "<br>\n";
echo substr_replace($var, 'bob', -7, -1) . "<br>\n";

/* Delete 'MNRPQR' from $var. */
echo substr_replace($var, '', 10, -1) . "<br>\n";
?>

See also str_replace() and substr().

后退 | 起点 | 前进
substr_count | 上一级 | substr


substr

(PHP 3, PHP 4 )

substr -- Return part of a string

Description

string substr ( string string, int start [, int length])

Substr returns the portion of string specified by the start and length parameters.

If start is non-negative, the returned string will start at the start'th position in string, counting from zero. For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', and so forth.

例子 1. Basic substr() usage

<?php
$rest = substr("abcdef", 1);    // returns "bcdef"
$rest = substr("abcdef", 1, 3); // returns "bcd"
$rest = substr("abcdef", 0, 4); // returns "abcd"
$rest = substr("abcdef", 0, 8); // returns "abcdef"

// Accessing via curly braces is another option
$string = 'abcdef';
echo $string{0};                // returns a
echo $string{3};                // returns d
?>

If start is negative, the returned string will start at the start'th character from the end of string.

例子 2. Using a negative start

<?php
$rest = substr("abcdef", -1);    // returns "f"
$rest = substr("abcdef", -2);    // returns "ef"
$rest = substr("abcdef", -3, 1); // returns "d"
?>

If length is given and is positive, the string returned will contain at most length characters beginning from start (depending on the length of string. If string is less than start characters long, FALSE will be returned.

If length is given and is negative, then that many characters will be omitted from the end of string (after the start position has been calculated when a start is negative). If start denotes a position beyond this truncation, an empty string will be returned.

例子 3. Using a negative length

<?php
$rest = substr("abcdef", 0, -1);  // returns "abcde"
$rest = substr("abcdef", 2, -1);  // returns "cde"
$rest = substr("abcdef", 4, -4);  // returns ""
$rest = substr("abcdef", -3, -1); // returns "de"
?>

See also strrchr() and ereg().

后退 | 起点 | 前进
substr_replace | 上一级 | trim


trim

(PHP 3, PHP 4 )

trim -- Strip whitespace from the beginning and end of a string

Description

string trim ( string str [, string charlist])

注: The optional charlist parameter was added in PHP 4.1.0

This function returns a string with whitespace stripped from the beginning and end of str. Without the second parameter, trim() will strip these characters:

  • " " (ASCII 32 (0x20)), an ordinary space.

  • "\t" (ASCII 9 (0x09)), a tab.

  • "\n" (ASCII 10 (0x0A)), a new line (line feed).

  • "\r" (ASCII 13 (0x0D)), a carriage return.

  • "\0" (ASCII 0 (0x00)), the NUL-byte.

  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.

You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

例子 1. Usage example of trim()

<?php

$text = "\t\tThese are a few words :) ...  ";
$trimmed = trim($text);
// $trimmed = "These are a few words :) ..."
$trimmed = trim($text," \t.");
// $trimmed = "These are a few words :)"
$clean = trim($binary,"\0x00..\0x1F");
// trim the ASCII control characters at the beginning and end of $binary
// (from 0 to 31 inclusive)

?>

See also ltrim() and rtrim().

后退 | 起点 | 前进
substr | 上一级 | ucfirst


ucfirst

(PHP 3, PHP 4 )

ucfirst -- Make a string's first character uppercase

Description

string ucfirst ( string str)

Returns a string with the first character of str capitalized, if that character is alphabetic.

Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted.

例子 1. ucfirst() example

$foo = 'hello world!';
$foo = ucfirst($foo);             // Hello world!

$bar = 'HELLO WORLD!';
$bar = ucfirst($bar);             // HELLO WORLD!
$bar = ucfirst(strtolower($bar)); // Hello world!

See also strtolower(), strtoupper(), and ucwords().

后退 | 起点 | 前进
trim | 上一级 | ucwords


ucwords

(PHP 3>= 3.0.3, PHP 4 )

ucwords -- Uppercase the first character of each word in a string

Description

string ucwords ( string str)

Returns a string with the first character of each word in str capitalized, if that character is alphabetic.

例子 1. ucwords() example

$foo = 'hello world!';
$foo = ucwords($foo);             // Hello World!

$bar = 'HELLO WORLD!';
$bar = ucwords($bar);             // HELLO WORLD!
$bar = ucwords(strtolower($bar)); // Hello World!

注: The definition of a word is any string of characters that is immediately after a whitespace (These are: space, form-feed, newline, carriage return, horizontal tab, and vertical tab).

See also strtoupper(), strtolower() and ucfirst().

后退 | 起点 | 前进
ucfirst | 上一级 | vprintf


vprintf

(PHP 4 >= 4.1.0)

vprintf -- Output a formatted string

Description

void vprintf ( string format, array args)

Display array values as a formatted string according to format (which is described in the documentation for sprintf()).

Operates as printf() but accepts an array of arguments, rather than a variable number of arguments.

See also printf(), sprintf(), vsprintf()

后退 | 起点 | 前进
ucwords | 上一级 | vsprintf


vsprintf

(PHP 4 >= 4.1.0)

vsprintf -- Return a formatted string

Description

string vsprintf ( string format, array args)

Return array values as a formatted string according to format (which is described in the documentation for sprintf()).

Operates as sprintf() but accepts an array of arguments, rather than a variable number of arguments.

See also sprintf(), vsprintf(), vprintf()

后退 | 起点 | 前进
vprintf | 上一级 | wordwrap


wordwrap

(PHP 4 >= 4.0.2)

wordwrap -- Wraps a string to a given number of characters using a string break character.

Description

string wordwrap ( string str [, int width [, string break [, int cut]]])

Returns a string with str wrapped at the column number specified by the (optional) width parameter. The line is broken using the (optional) break parameter.

wordwrap() will automatically wrap at column 75 and break using '\n' (newline) if width or break are not given.

If the cut is set to 1, the string is always wrapped at the specified width. So if you have a word that is larger than the given width, it is broken apart. (See second example).

注: The optional cut parameter was added in PHP 4.0.3

例子 1. wordwrap() example

$text = "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap( $text, 20 );

echo "$newtext\n";

This example would display:

The quick brown fox
jumped over the lazy dog.

例子 2. wordwrap() example

$text = "A very long woooooooooooord.";
$newtext = wordwrap( $text, 8, "\n", 1);

echo "$newtext\n";

This example would display:

A very
long
wooooooo
ooooord.

See also nl2br().

后退 | 起点 | 前进
vsprintf | 上一级 | Sybase functions


Sybase functions

PHP 手册
后退 前进

XCVIII. Sybase functions

介绍

需求

安装

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. Sybase configuration options

Name | Default | Changeable
sybase.allow_persistent | "On" | PHP_INI_SYSTEM
sybase.max_persistent | "-1" | PHP_INI_SYSTEM
sybase.max_links | "-1" | PHP_INI_SYSTEM
sybase.interface_file | "/usr/sybase/interfaces" | PHP_INI_SYSTEM
sybase.min_error_severity | "10" | PHP_INI_ALL
sybase.min_message_severity | "10" | PHP_INI_ALL
sybase.compatability_mode | "Off" | PHP_INI_SYSTEM
magic_quotes_sybase | "Off" | PHP_INI_ALL

Here is a short explanation of the configuration directives.

sybase.allow_persistent boolean

Whether to allow persistent Sybase connections.

sybase.max_persistent integer

The maximum number of persistent Sybase connections per process. -1 means no limit.

sybase.max_links integer

The maximum number of Sybase connections per process, including persistent connections. -1 means no limit.

sybase.min_error_severity integer

Minimum error severity to display.

sybase.min_message_severity integer

Minimum message severity to display.

sybase.compatability_mode boolean

Compatability mode with old versions of PHP 3.0. If on, this will cause PHP to automatically assign types to results according to their Sybase type, instead of treating them all as strings. This compatability mode will probably not stay around forever, so try applying whatever necessary changes to your code, and turn it off.

表格 2. Sybase-CT configuration options

Name | Default | Changeable
sybct.allow_persistent | "On" | PHP_INI_SYSTEM
sybct.max_persistent | "-1" | PHP_INI_SYSTEM
sybct.max_links | "-1" | PHP_INI_SYSTEM
sybct.min_server_severity | "10" | PHP_INI_ALL
sybct.min_client_severity | "10" | PHP_INI_ALL
sybct.hostname | NULL | PHP_INI_ALL

Here is a short explanation of the configuration directives.

sybct.allow_persistent boolean

Whether to allow persistent Sybase-CT connections. The default is on.

sybct.max_persistent integer

The maximum number of persistent Sybase-CT connections per process. The default is -1 meaning unlimited.

sybct.max_links integer

The maximum number of Sybase-CT connections per process, including persistent connections. The default is -1 meaning unlimited.

sybct.min_server_severity integer

Server messages with severity greater than or equal to sybct.min_server_severity will be reported as warnings. This value can also be set from a script by calling sybase_min_server_severity(). The default is 10 which reports errors of information severity or greater.

sybct.min_client_severity integer

Client library messages with severity greater than or equal to sybct.min_client_severity will be reported as warnings. This value can also be set from a script by calling sybase_min_client_severity(). The default is 10 which effectively disables reporting.

sybct.hostname string

The name of the host you claim to be connecting from, for display by sp_who. The default is none.

For further details and definition of the PHP_INI_* constants see ini_set().

资源类型

预定义常量

该扩展模块未定义任何常量。

目录
sybase_affected_rows — get number of affected rows in last query
sybase_close — close Sybase connection
sybase_connect — open Sybase server connection
sybase_data_seek — move internal row pointer
sybase_fetch_array — fetch row as array
sybase_fetch_field — get field information
sybase_fetch_object — fetch row as object
sybase_fetch_row — get row as enumerated array
sybase_field_seek — set field offset
sybase_free_result — free result memory
sybase_get_last_message — Returns the last message from the server
sybase_min_client_severity — Sets minimum client severity
sybase_min_error_severity — Sets minimum error severity
sybase_min_message_severity — Sets minimum message severity
sybase_min_server_severity — Sets minimum server severity
sybase_num_fields — get number of fields in result
sybase_num_rows — get number of rows in result
sybase_pconnect — open persistent Sybase connection
sybase_query — send Sybase query
sybase_result — get result data
sybase_select_db — select Sybase database

后退 | 起点 | 前进
wordwrap | 上一级 | sybase_affected_rows


sybase_affected_rows

(PHP 3>= 3.0.6, PHP 4 )

sybase_affected_rows -- get number of affected rows in last query

Description

int sybase_affected_rows ( [int link_identifier])

Returns: The number of affected rows by the last query.

sybase_affected_rows() returns the number of rows affected by the last INSERT, UPDATE or DELETE query on the server associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.

This command is not effective for SELECT statements, only on statements which modify records. To retrieve the number of rows returned from a SELECT, use sybase_num_rows().

注: This function is only available using the CT library interface to Sybase, and not the DB library.

后退 | 起点 | 前进
Sybase functions | 上一级 | sybase_close


sybase_close

(PHP 3, PHP 4 )

sybase_close -- close Sybase connection

Description

bool sybase_close ( int link_identifier)

Returns: TRUE on success, FALSE on error

sybase_close() closes the link to a Sybase database that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.

Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

sybase_close() will not close persistent links generated by sybase_pconnect().

See also: sybase_connect(), sybase_pconnect().

后退 | 起点 | 前进
sybase_affected_rows | 上一级 | sybase_connect


sybase_connect

(PHP 3, PHP 4 )

sybase_connect -- open Sybase server connection

Description

int sybase_connect ( string servername, string username, string password [, string charset])

Returns: A positive Sybase link identifier on success, or FALSE on error.

sybase_connect() establishes a connection to a Sybase server. The servername argument has to be a valid servername that is defined in the 'interfaces' file.

In case a second call is made to sybase_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 sybase_close().

See also sybase_pconnect(), sybase_close().

后退 | 起点 | 前进
sybase_close | 上一级 | sybase_data_seek


sybase_data_seek

(PHP 3, PHP 4 )

sybase_data_seek -- move internal row pointer

Description

bool sybase_data_seek ( int result_identifier, int row_number)

Returns: TRUE on success, FALSE on failure

sybase_data_seek() moves the internal row pointer of the Sybase result associated with the specified result identifier to pointer to the specifyed row number. The next call to sybase_fetch_row() would return that row.

See also: sybase_data_seek().

后退 | 起点 | 前进
sybase_connect | 上一级 | sybase_fetch_array


sybase_fetch_array

(PHP 3, PHP 4 )

sybase_fetch_array -- fetch row as array

Description

array sybase_fetch_array ( int result)

Returns: An array that corresponds to the fetched row, or FALSE if there are no more rows.

sybase_fetch_array() is an extended version of sybase_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

An important thing to note is that using sybase_fetch_array() is NOT significantly slower than using sybase_fetch_row(), while it provides a significant added value.

For further details, also see sybase_fetch_row().

后退 | 起点 | 前进
sybase_data_seek | 上一级 | sybase_fetch_field


sybase_fetch_field

(PHP 3, PHP 4 )

sybase_fetch_field -- get field information

Description

object sybase_fetch_field ( int result [, int field_offset])

Returns an object containing field information.

sybase_fetch_field() can be used in order to obtain information about fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retreived by sybase_fetch_field() is retreived.

The properties of the object are:

  • name - column name. if the column is a result of a function, this property is set to computed#N, where #N is a serial number.

  • column_source - the table from which the column was taken

  • max_length - maximum length of the column

  • numeric - 1 if the column is numeric

  • type - datatype of the column

See also sybase_field_seek()

后退 | 起点 | 前进
sybase_fetch_array | 上一级 | sybase_fetch_object


sybase_fetch_object

(PHP 3, PHP 4 )

sybase_fetch_object -- fetch row as object

Description

int sybase_fetch_object ( int result)

Returns: An object with properties that correspond to the fetched row, or FALSE if there are no more rows.

sybase_fetch_object() is similar to sybase_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

Speed-wise, the function is identical to sybase_fetch_array(), and almost as quick as sybase_fetch_row() (the difference is insignificant).

See also: sybase_fetch_array() and sybase_fetch_row().

后退 | 起点 | 前进
sybase_fetch_field | 上一级 | sybase_fetch_row


sybase_fetch_row

(PHP 3, PHP 4 )

sybase_fetch_row -- get row as enumerated array

Description

array sybase_fetch_row ( int result)

Returns: An array that corresponds to the fetched row, or FALSE if there are no more rows.

sybase_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 call to sybase_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

See also: sybase_fetch_array(),
          sybase_fetch_object(),
          sybase_data_seek(),
          sybase_fetch_lengths(), and
          sybase_result().

后退 | 起点 | 前进
sybase_fetch_object | 上一级 | sybase_field_seek


sybase_field_seek

(PHP 3, PHP 4 )

sybase_field_seek -- set field offset

Description

int sybase_field_seek ( int result, int field_offset)

Seeks to the specified field offset. If the next call to sybase_fetch_field() won't include a field offset, this field would be returned.

See also: sybase_fetch_field().

后退 | 起点 | 前进
sybase_fetch_row | 上一级 | sybase_free_result


sybase_free_result

(PHP 3, PHP 4 )

sybase_free_result -- free result memory

Description

bool sybase_free_result ( int result)

sybase_free_result() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script ends. You may call sybase_free_result() with the result identifier as an argument and the associated result memory will be freed.

后退 | 起点 | 前进
sybase_field_seek | 上一级 | sybase_get_last_message


sybase_get_last_message

(PHP 3, PHP 4 )

sybase_get_last_message -- Returns the last message from the server

Description

string sybase_get_last_message ( void)

sybase_get_last_message() returns the last message reported by the server.

后退 | 起点 | 前进
sybase_free_result | 上一级 | sybase_min_client_severity


sybase_min_client_severity

(PHP 3, PHP 4 )

sybase_min_client_severity -- Sets minimum client severity

Description

void sybase_min_client_severity ( int severity)

sybase_min_client_severity() sets the minimum client severity level.

注: This function is only available using the CT library interface to Sybase, and not the DB library.

See also: sybase_min_server_severity().

后退 | 起点 | 前进
sybase_get_last_message | 上一级 | sybase_min_error_severity


sybase_min_error_severity

(PHP 3, PHP 4 )

sybase_min_error_severity -- Sets minimum error severity

Description

void sybase_min_error_severity ( int severity)

sybase_min_error_severity() sets the minimum error severity level.

See also: sybase_min_message_severity().

后退 | 起点 | 前进
sybase_min_client_severity | 上一级 | sybase_min_message_severity


sybase_min_message_severity

(PHP 3, PHP 4 )

sybase_min_message_severity -- Sets minimum message severity

Description

void sybase_min_message_severity ( int severity)

sybase_min_message_severity() sets the minimum message severity level.

See also: sybase_min_error_severity().

后退 | 起点 | 前进
sybase_min_error_severity | 上一级 | sybase_min_server_severity


sybase_min_server_severity

(PHP 3, PHP 4 )

sybase_min_server_severity -- Sets minimum server severity

Description

void sybase_min_server_severity ( int severity)

sybase_min_server_severity() sets the minimum server severity level.

注: This function is only available using the CT library interface to Sybase, and not the DB library.

See also: sybase_min_client_severity().

后退 | 起点 | 前进
sybase_min_message_severity | 上一级 | sybase_num_fields


sybase_num_fields

(PHP 3, PHP 4 )

sybase_num_fields -- get number of fields in result

Description

int sybase_num_fields ( int result)

sybase_num_fields() returns the number of fields in a result set.

See also:
sybase_db_query(),
sybase_query(),
sybase_fetch_field(),
sybase_num_rows().

后退 | 起点 | 前进
sybase_min_server_severity | 上一级 | sybase_num_rows


sybase_num_rows

(PHP 3, PHP 4 )

sybase_num_rows -- get number of rows in result

Description

int sybase_num_rows ( int result)

sybase_num_rows() returns the number of rows in a result set.

See also:
sybase_db_query(),
sybase_query() and,
sybase_fetch_row().

后退 | 起点 | 前进
sybase_num_fields | 上一级 | sybase_pconnect


sybase_pconnect

(PHP 3, PHP 4 )

sybase_pconnect -- open persistent Sybase connection

Description

int sybase_pconnect ( string servername, string username, string password [, string charset])

Returns: A positive Sybase persistent link identifier on success, or FALSE on error

sybase_pconnect() acts very much like sybase_connect() with two major differences.

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (sybase_close() will not close links established by sybase_pconnect()()).

This type of links is therefore called 'persistent'.

后退 | 起点 | 前进
sybase_num_rows | 上一级 | sybase_query


sybase_query

(PHP 3, PHP 4 )

sybase_query -- send Sybase query

Description

int sybase_query ( string query, int link_identifier)

Returns: A positive Sybase result identifier on success, or FALSE on error.

sybase_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if sybase_connect() was called, and use it.

See also:
sybase_db_query(),
sybase_select_db(), and
sybase_connect().

后退 | 起点 | 前进
sybase_pconnect | 上一级 | sybase_result


sybase_result

(PHP 3, PHP 4 )

sybase_result -- get result data

Description

string sybase_result ( int result, int row, mixed field)

Returns: The contents of the cell at the row and offset in the specified Sybase result set.

sybase_result() returns the contents of one cell from a Sybase result set. The field argument can be the field's offset, or the field's name, or the field's table dot field's name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name.

When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than sybase_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Recommended high-performance alternatives:
sybase_fetch_row(),
sybase_fetch_array(), and
sybase_fetch_object().

后退 | 起点 | 前进
sybase_query | 上一级 | sybase_select_db


sybase_select_db

(PHP 3, PHP 4 )

sybase_select_db -- select Sybase database

Description

bool sybase_select_db ( string database_name, int link_identifier)

Returns: TRUE on success, FALSE on error

sybase_select_db() sets the current active database on the server that's associated with the specified link identifier. If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if sybase_connect() was called, and use it.

Every subsequent call to sybase_query() will be made on the active database.

See also:
    sybase_connect(),
    sybase_pconnect(), and
    sybase_query()

后退 | 起点 | 前进
sybase_result | 上一级 | Tokenizer functions


Tokenizer functions

PHP 手册
后退 前进

XCIX. Tokenizer functions

介绍

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

See also the appendix about tokens.

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

T_INCLUDE (integer)

T_INCLUDE_ONCE (integer)

T_EVAL (integer)

T_REQUIRE (integer)

T_REQUIRE_ONCE (integer)

T_LOGICAL_OR (integer)

T_LOGICAL_XOR (integer)

T_LOGICAL_AND (integer)

T_PRINT (integer)

T_PLUS_EQUAL (integer)

T_MINUS_EQUAL (integer)

T_MUL_EQUAL (integer)

T_DIV_EQUAL (integer)

T_CONCAT_EQUAL (integer)

T_MOD_EQUAL (integer)

T_AND_EQUAL (integer)

T_OR_EQUAL (integer)

T_XOR_EQUAL (integer)

T_SL_EQUAL (integer)

T_SR_EQUAL (integer)

T_BOOLEAN_OR (integer)

T_BOOLEAN_AND (integer)

T_IS_EQUAL (integer)

T_IS_NOT_EQUAL (integer)

T_IS_IDENTICAL (integer)

T_IS_NOT_IDENTICAL (integer)

T_IS_SMALLER_OR_EQUAL (integer)

T_IS_GREATER_OR_EQUAL (integer)

T_SL (integer)

T_SR (integer)

T_INC (integer)

T_DEC (integer)

T_INT_CAST (integer)

T_DOUBLE_CAST (integer)

T_STRING_CAST (integer)

T_ARRAY_CAST (integer)

T_OBJECT_CAST (integer)

T_BOOL_CAST (integer)

T_UNSET_CAST (integer)

T_NEW (integer)

T_EXIT (integer)

T_IF (integer)

T_ELSEIF (integer)

T_ELSE (integer)

T_ENDIF (integer)

T_LNUMBER (integer)

T_DNUMBER (integer)

T_STRING (integer)

T_STRING_VARNAME (integer)

T_VARIABLE (integer)

T_NUM_STRING (integer)

T_INLINE_HTML (integer)

T_CHARACTER (integer)

T_BAD_CHARACTER (integer)

T_ENCAPSED_AND_WHITESPACE (integer)

T_CONSTANT_ENCAPSED_STRING (integer)

T_ECHO (integer)

T_DO (integer)

T_WHILE (integer)

T_ENDWHILE (integer)

T_FOR (integer)

T_ENDFOR (integer)

T_FOREACH (integer)

T_ENDFOREACH (integer)

T_DECLARE (integer)

T_ENDDECLARE (integer)

T_AS (integer)

T_SWITCH (integer)

T_ENDSWITCH (integer)

T_CASE (integer)

T_DEFAULT (integer)

T_BREAK (integer)

T_CONTINUE (integer)

T_OLD_FUNCTION (integer)

T_FUNCTION (integer)

T_CONST (integer)

T_RETURN (integer)

T_USE (integer)

T_GLOBAL (integer)

T_STATIC (integer)

T_VAR (integer)

T_UNSET (integer)

T_ISSET (integer)

T_EMPTY (integer)

T_CLASS (integer)

T_EXTENDS (integer)

T_OBJECT_OPERATOR (integer)

T_DOUBLE_ARROW (integer)

T_LIST (integer)

T_ARRAY (integer)

T_LINE (integer)

T_FILE (integer)

T_COMMENT (integer)

T_ML_COMMENT (integer)

T_OPEN_TAG (integer)

T_OPEN_TAG_WITH_ECHO (integer)

T_CLOSE_TAG (integer)

T_WHITESPACE (integer)

T_START_HEREDOC (integer)

T_END_HEREDOC (integer)

T_DOLLAR_OPEN_CURLY_BRACES (integer)

T_CURLY_OPEN (integer)

T_PAAMAYIM_NEKUDOTAYIM (integer)

T_DOUBLE_COLON (integer)

目录
token_get_all — Split given source in tokens
token_name — Get the name of a given token

后退 | 起点 | 前进
sybase_select_db | 上一级 | token_get_all


token_get_all

(PHP 4 >= 4.2.0)

token_get_all -- Split given source in tokens

Description

array token_get_all ( string source)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
Tokenizer functions | 上一级 | token_name


token_name

(PHP 4 >= 4.2.0)

token_name -- Get the name of a given token

Description

string token_name ( int type)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
token_get_all | 上一级 | URL Functions


URL Functions

PHP 手册
后退 前进

C. URL Functions

介绍

Dealing with URL strings: encoding, decoding and parsing.

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

这些函数作为 PHP 核心的一部分，无需被安装即可使用。

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

目录
base64_decode — Decodes data encoded with MIME base64
base64_encode — Encodes data with MIME base64
parse_url — Parse a URL and return its components
rawurldecode — Decode URL-encoded strings
rawurlencode — URL-encode according to RFC 1738
urldecode — Decodes URL-encoded string
urlencode — URL-encodes string

后退 | 起点 | 前进
token_name | 上一级 | base64_decode


base64_decode

(PHP 3, PHP 4 )

base64_decode -- Decodes data encoded with MIME base64

Description

string base64_decode ( string encoded_data)

base64_decode() decodes encoded_data and returns the original data. The returned data may be binary.

See also: base64_encode(), RFC 2045 section 6.8.

后退 | 起点 | 前进
URL Functions | 上一级 | base64_encode


base64_encode

(PHP 3, PHP 4 )

base64_encode -- Encodes data with MIME base64

Description

string base64_encode ( string data)

base64_encode() returns data encoded with base64. This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies.

Base64-encoded data takes about 33% more space than the original data.

See also: base64_decode(), chunk_split(), RFC 2045 section 6.8.

后退 | 起点 | 前进
base64_decode | 上一级 | parse_url


parse_url

(PHP 3, PHP 4 )

parse_url -- Parse a URL and return its components

Description

array parse_url ( string url)

This function returns an associative array returning any of the various components of the URL that are present. This includes the

  • scheme - e.g. http

  • host

  • port

  • user

  • pass

  • path

  • query - after the question mark ?

  • fragment - after the hashmark #

This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial urls are also accepted, parse_url() tries its best to parse them correctly.

例子 1. Using parse_url()

$ php -r 'print_r( parse_url("http://username:password@hostname/path?arg=value#anchor"));'
Array
(
    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /path
    [query] => arg=value
    [fragment] => anchor
)

$ php -r 'print_r( parse_url("http://invalid_host..name/"));'
Array
(
    [scheme] => http
    [host] => invalid_host..name
    [path] => /
)

See also pathinfo().

后退 | 起点 | 前进
base64_encode | 上一级 | rawurldecode


rawurldecode

(PHP 3, PHP 4 )

rawurldecode -- Decode URL-encoded strings

Description

string rawurldecode ( string str)

Returns a string in which the sequences with percent (%) signs followed by two hex digits have been replaced with literal characters. For example, the string
foo%20bar%40baz
decodes into
foo bar@baz
.

注: rawurldecode() does not decode plus symbols ('+') into spaces. urldecode() does.

See also rawurlencode(),
urldecode(),
urlencode().

后退 | 起点 | 前进
parse_url | 上一级 | rawurlencode


rawurlencode

(PHP 3, PHP 4 )

rawurlencode -- URL-encode according to RFC 1738

Description

string rawurlencode ( string str)

Returns a string in which all non-alphanumeric characters except
-_.
have been replaced with a percent (%) sign followed by two hex digits. This is the encoding described in RFC 1738 for protecting literal characters from being interpreted as special URL delimiters, and for protecting URL's from being mangled by transmission media with character conversions (like some email systems). For example, if you want to include a password in an FTP URL:

例子 1. rawurlencode() example 1

echo '<a href="ftp://user:', rawurlencode('foo @+%/'),
     '@ftp.my.com/x.txt">';

Or, if you pass information in a PATH_INFO component of the URL:

例子 2. rawurlencode() example 2

echo '<a href="http://x.com/department_list_script/',
    rawurlencode('sales and marketing/Miami'), '">';

See also rawurldecode(),
urldecode(),
urlencode() and
RFC 1738

后退 | 起点 | 前进
rawurldecode | 上一级 | urldecode


urldecode

(PHP 3, PHP 4 )

urldecode -- Decodes URL-encoded string

Description

string urldecode ( string str)

Decodes any %## encoding in the given string. The decoded string is returned.

例子 1. urldecode() example

$a = explode('&', $QUERY_STRING);
$i = 0;
while ($i < count($a)) {
    $b = split('=', $a[$i]);
    echo 'Value for parameter ', htmlspecialchars(urldecode($b[0])),
         ' is ', htmlspecialchars(urldecode($b[1])), "<br />\n";
    $i++;
}

See also urlencode(),
rawurlencode(),
rawurldecode().

后退 | 起点 | 前进
rawurlencode | 上一级 | urlencode


urlencode

(PHP 3, PHP 4 )

urlencode -- URL-encodes string

Description

string urlencode ( string str)

Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type. This differs from the RFC1738 encoding (see rawurlencode()) in that for historical reasons, spaces are encoded as plus (+) signs. This function is convenient when encoding a string to be used in a query part of an URL, as a convenient way to pass variables to the next page:

例子 1. urlencode() example

echo '<a href="mycgi?foo=', urlencode($userinput), '">';

Note: Be careful about variables that may match HTML entities. Things like &amp, &copy and &pound are parsed by the browser and the actual entity is used instead of the desired variable name. This is an obvious hassle that the W3C has been telling people about for years. The reference is here: http://www.w3.org/TR/html4/appendix/notes.html#h-B.2.2 PHP supports changing the argument separator to the W3C-suggested semi-colon through the arg_separator .ini directive. Unfortunately most user agents do not send form data in this semi-colon separated format. A more portable way around this is to use &amp; instead of & as the separator. You don't need to change PHP's arg_separator for this. Leave it as &, but simply encode your URLs using htmlentities()(urlencode($data)).

例子 2. urlencode/htmlentities() example

echo '<a href="mycgi?foo=', htmlentities(urlencode($userinput)), '">';

See also urldecode(),
htmlentities(),
rawurldecode(),
rawurlencode().

后退 | 起点 | 前进
urldecode | 上一级 | Variable Functions


Variable Functions

PHP 手册
后退 前进

CI. Variable Functions

介绍

For information on how variables behave, see the Variables entry in the Language Reference section of the manual.

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

这些函数作为 PHP 核心的一部分，无需被安装即可使用。

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

目录
doubleval — Alias of floatval()
empty — Determine whether a variable is set
floatval — Get float value of a variable
get_defined_vars — Returns an array of all defined variables
get_resource_type — Returns the resource type
gettype — Get the type of a variable
import_request_variables — Import GET/POST/Cookie variables into the global scope
intval — Get integer value of a variable
is_array — Finds whether a variable is an array
is_bool — Finds out whether a variable is a boolean
is_callable — Find out whether the argument is a valid callable construct
is_double — Alias of is_float()
is_float — Finds whether a variable is a float
is_int — Find whether a variable is an integer
is_integer — Alias of is_int()
is_long — Alias of is_int()
is_null — Finds whether a variable is NULL
is_numeric — Finds whether a variable is a number or a numeric string
is_object — Finds whether a variable is an object
is_real — Alias of is_float()
is_resource — Finds whether a variable is a resource
is_scalar — Finds whether a variable is a scalar
is_string — Finds whether a variable is a string
isset — Determine whether a variable is set
print_r — Prints human-readable information about a variable
serialize — Generates a storable representation of a value
settype — Set the type of a variable
strval — Get string value of a variable
unserialize — Creates a PHP value from a stored representation
unset — Unset a given variable
var_dump — Dumps information about a variable
var_export — Outputs or returns a string representation of a variable

后退 | 起点 | 前进
urlencode | 上一级 | doubleval


doubleval

doubleval -- Alias of floatval()

Description

This function is an alias of floatval().

注: This alias is a left-over from a function-renaming. In older versions of PHP you'll need to use this alias of the floatval() function, because floatval() wasn't yet available in that version.

后退 | 起点 | 前进
Variable Functions | 上一级 | empty


empty

(no version information, might be only in CVS)

empty -- Determine whether a variable is set

Description

boolean empty ( mixed var)

注: empty() is a language construct.

This is the opposite of (boolean) var, except that no warning is generated when the variable is not set. See converting to boolean for more information.

$var = 0;

if (empty($var)) {  // evaluates true
    echo '$var is either 0 or not set at all';
}

if (!isset($var)) { // evaluates false
    echo '$var is not set at all';
}

Note that this is meaningless when used on anything which isn't a variable; i.e. empty (addslashes ($name)) has no meaning since it would be checking whether something which isn't a variable is a variable with a FALSE value.

See also isset() and unset().

后退 | 起点 | 前进
doubleval | 上一级 | floatval


floatval

(PHP 4 >= 4.2.0)

floatval -- Get float value of a variable

Description

float floatval ( mixed var)

Returns the float value of var.

Var may be any scalar type. You cannot use floatval() on arrays or objects.

$var = '122.34343The';
$float_value_of_var = floatval ($var);
print $float_value_of_var; // prints 122.34343

See also intval(), strval(), settype() and Type juggling.

后退 | 起点 | 前进
empty | 上一级 | get_defined_vars


get_defined_vars

(PHP 4 >= 4.0.4)

get_defined_vars -- Returns an array of all defined variables

Description

array get_defined_vars ( void)

This function returns an multidimensional array containing a list of all defined variables, be them environment, server or user-defined variables.

$b = array(1,1,2,3,5,8);

$arr = get_defined_vars();

// print $b
print_r($arr["b"]);

// print path to the PHP interpreter (if used as a CGI)
// e.g. /usr/local/bin/php
echo $arr["_"];

// print the command-line paramaters if any
print_r($arr["argv"]);

// print all the server vars
print_r($arr["_SERVER"]);

// print all the available keys for the arrays of variables
print_r(array_keys(get_defined_vars()));

See also get_defined_functions() and get_defined_constants().

后退 | 起点 | 前进
floatval | 上一级 | get_resource_type


get_resource_type

(PHP 4 >= 4.0.2)

get_resource_type -- Returns the resource type

Description

string get_resource_type ( resource handle)

This function returns a string representing the type of the resource passed to it. If the paramater is not a valid resource, it generates an error.

$c = mysql_connect();
echo get_resource_type($c)."\n";
// prints: mysql link

$fp = fopen("foo","w");
echo get_resource_type($fp)."\n";
// prints: file

$doc = new_xmldoc("1.0");
echo get_resource_type($doc->doc)."\n";
// prints: domxml document

后退 | 起点 | 前进
get_defined_vars | 上一级 | gettype


gettype

(PHP 3, PHP 4 )

gettype -- Get the type of a variable

Description

string gettype ( mixed var)

Returns the type of the PHP variable var.

警告

Never use gettype() to test for a certain type, since the returned string may be subject to change in a future version. In addition, it is slow too, as it involves string comparision .

Instead, use the is_* functions.

Possibles values for the returned string are:

  • "boolean" (since PHP 4)

  • "integer"

  • "double" (for historical reasons "double" is returned in case of a float, and not simply "float")

  • "string"

  • "array"

  • "object"

  • "resource" (since PHP 4)

  • "NULL" (since PHP 4)

  • "user function" (PHP 3 only, deprecated)

  • "unknown type"

For PHP 4, you should use function_exists() and method_exists() to replace the prior usage of gettype() on a function.

See also
settype(),
is_array(),
is_bool(),
is_float(),
is_integer(),
is_null(),
is_numeric(),
is_object(),
is_resource(),
is_scalar(), and
is_string().

后退 | 起点 | 前进
get_resource_type | 上一级 | import_request_variables


import_request_variables

(PHP 4 >= 4.1.0)

import_request_variables -- Import GET/POST/Cookie variables into the global scope

Description

bool import_request_variables ( string types [, string prefix])

Imports GET/POST/Cookie variables into the global scope. It is useful if you disabled register_globals, but would like to see some variables in the global scope.

Using the types parameter, you can specify which request variables to import. You can use 'G', 'P' and 'C' characters respectively for GET, POST and Cookie. These characters are not case sensitive, so you can also use any combination of 'g', 'p' and 'c'. POST includes the POST uploaded file information. Note that the order of the letters matters, as when using "gp", the POST variables will overwrite GET variables with the same name. Any other letters than GPC are discarded.

The prefix parameter is used as a variable name prefix, prepended before all variable's name imported into the global scope. So if you have a GET value named "userid", and provide a prefix "pref_", then you'll get a global variable named $pref_userid.

If you're interested in importing other variables into the global scope, such as SERVER, consider using extract().

注: Although the prefix parameter is optional, you will get an E_NOTICE level error if you specify no prefix, or specify an empty string as a prefix. This is a possible security hazard. Notice level errors are not displayed using the default error reporting level.

// This will import GET and POST vars
// with an "rvar_" prefix
import_request_variables("gP", "rvar_");

print $rvar_foo;

See also $_REQUEST, register_globals, Predefined Variables, and extract().

后退 | 起点 | 前进
gettype | 上一级 | intval


intval

(PHP 3, PHP 4 )

intval -- Get integer value of a variable

Description

int intval ( mixed var [, int base])

Returns the integer value of var, using the specified base for the conversion (the default is base 10).

var may be any scalar type. You cannot use intval() on arrays or objects.

注: The base argument for intval() has no effect unless the var argument is a string.

See also floatval(), strval(), settype() and Type juggling.

后退 | 起点 | 前进
import_request_variables | 上一级 | is_array


is_array

(PHP 3, PHP 4 )

is_array -- Finds whether a variable is an array

Description

bool is_array ( mixed var)

Returns TRUE if var is an array, FALSE otherwise.

See also
is_float(),
is_int(),
is_integer(),
is_string(), and
is_object().

后退 | 起点 | 前进
intval | 上一级 | is_bool


is_bool

(PHP 4 )

is_bool -- Finds out whether a variable is a boolean

Description

bool is_bool ( mixed var)

Returns TRUE if the var parameter is a boolean.

See also
is_array(),
is_float(),
is_int(),
is_integer(),
is_string(), and
is_object().

后退 | 起点 | 前进
is_array | 上一级 | is_callable


is_callable

(PHP 4 >= 4.0.6)

is_callable -- Find out whether the argument is a valid callable construct

Description

bool is_callable ( mixed var [, bool syntax_only [, string callable_name]])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
is_bool | 上一级 | is_double


is_double

is_double -- Alias of is_float()

Description

This function is an alias of is_float().

后退 | 起点 | 前进
is_callable | 上一级 | is_float


is_float

(PHP 3, PHP 4 )

is_float -- Finds whether a variable is a float

Description

bool is_float ( mixed var)

Returns TRUE if var is a float, FALSE otherwise.

注: To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric().

See also
is_bool(),
is_int(),
is_integer(),
is_numeric(),
is_string(),
is_array(), and
is_object(),

后退 | 起点 | 前进
is_double | 上一级 | is_int


is_int

(PHP 3, PHP 4 )

is_int -- Find whether a variable is an integer

Description

bool is_int ( mixed var)

Returns TRUE if var is an integer FALSE otherwise.

注: To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric().

See also is_bool(),
is_float(),
is_integer(),
is_numeric(),
is_string(),
is_array(), and
is_object().

后退 | 起点 | 前进
is_float | 上一级 | is_integer


is_integer

is_integer -- Alias of is_int()

Description

This function is an alias of is_int().

后退 | 起点 | 前进
is_int | 上一级 | is_long


is_long

is_long -- Alias of is_int()

Description

This function is an alias of is_int().

后退 | 起点 | 前进
is_integer | 上一级 | is_null


is_null

(PHP 4 >= 4.0.4)

is_null -- Finds whether a variable is NULL

Description

bool is_null ( mixed var)

Returns TRUE if var is null, FALSE otherwise.

See the NULL type when a variable is considered to be NULL and when not.

See also NULL,
is_bool(),
is_numeric(),
is_float(),
is_int(),
is_string(),
is_object(),
is_array(),
is_integer(), and
is_real()

后退 | 起点 | 前进
is_long | 上一级 | is_numeric


is_numeric

(PHP 4 )

is_numeric -- Finds whether a variable is a number or a numeric string

Description

bool is_numeric ( mixed var)

Returns TRUE if var is a number or a numeric string, FALSE otherwise.

See also is_bool(),
is_float(),
is_int(),
is_string(),
is_object(),
is_array(), and
is_integer().

后退 | 起点 | 前进
is_null | 上一级 | is_object


is_object

(PHP 3, PHP 4 )

is_object -- Finds whether a variable is an object

Description

bool is_object ( mixed var)

Returns TRUE if var is an object, FALSE otherwise.

See also is_bool(),
is_int(),
is_integer(),
is_float(),
is_string(), and
is_array().

后退 | 起点 | 前进
is_numeric | 上一级 | is_real


is_real

is_real -- Alias of is_float()

Description

This function is an alias of is_float().

后退 | 起点 | 前进
is_object | 上一级 | is_resource


is_resource

(PHP 4 )

is_resource -- Finds whether a variable is a resource

Description

bool is_resource ( mixed var)

is_resource() returns TRUE if the variable given by the var parameter is a resource, otherwise it returns FALSE.

See the documentation on the resource-type for more information.

后退 | 起点 | 前进
is_real | 上一级 | is_scalar


is_scalar

(PHP 4 >= 4.0.5)

is_scalar -- Finds whether a variable is a scalar

Description

bool is_scalar ( mixed var)

is_scalar() returns TRUE if the variable given by the var parameter is a scalar, otherwise it returns FALSE.

Scalar variables are those containing an integer, float, string or boolean. Types array, object and resource or not scalar.

function show_var($var) {
    if (is_scalar($var)) {
        echo $var;
    } else {
        var_dump($var);
    }
}
$pi = 3.1416;
$proteins = array("hemoglobin", "cytochrome c oxidase", "ferredoxin");

show_var($pi);
// prints: 3.1416

show_var($proteins)
// prints:
// array(3) {
//   [0]=>
//   string(10) "hemoglobin"
//   [1]=>
//   string(20) "cytochrome c oxidase"
//   [2]=>
//   string(10) "ferredoxin"
// }

注: is_scalar() does not consider resource type values to be scalar as resources are abstract datatypes which are currently based on integers. This implementation detail should not be relied upon, as it may change.

See also is_bool(),
is_numeric(),
is_float(),
is_int(),
is_real(),
is_string(),
is_object(),
is_array(), and
is_integer().

后退 | 起点 | 前进
is_resource | 上一级 | is_string


is_string

(PHP 3, PHP 4 )

is_string -- Finds whether a variable is a string

Description

bool is_string ( mixed var)

Returns TRUE if var is a string, FALSE otherwise.

See also is_bool(),
is_int(),
is_integer(),
is_float(),
is_real(),
is_object(), and
is_array().

后退 | 起点 | 前进
is_scalar | 上一级 | isset


isset

(no version information, might be only in CVS)

isset -- Determine whether a variable is set

Description

bool isset ( mixed var [, mixed var [, ...]])

注: isset() is a language construct.

Returns TRUE if var exists; FALSE otherwise.

If a variable has been unset with unset(), it will no longer be isset(). isset() will return FALSE if testing a variable that has been set to NULL. Also note that a NULL byte ("\0") is not equivalent to the PHP NULL constant.

<?php
    $a = "test";
    $b = "anothertest";

    echo isset ($a); // TRUE
    echo isset ($a, $b); //TRUE

    unset ($a);
    echo isset ($a); // FALSE
    echo isset ($a, $b); //FALSE

$foo = NULL;
    print isset ($foo); // FALSE
?>

This also work for elements in arrays:

<?php
    $a = array ('test' => 1, 'hello' => null);

    echo isset ($a['test']);  // TRUE
    echo isset ($a['foo']);   // FALSE
    echo isset ($a['hello']); // FALSE
    echo array_key_exists('hello', $a); // TRUE
?>

See also empty(),
unset(), and
array_key_exists().

后退 | 起点 | 前进
is_string | 上一级 | print_r


print_r

(PHP 4 )

print_r -- Prints human-readable information about a variable

Description

bool print_r ( mixed expression)

print_r() displays information about a variable in a way that's readable by humans. If given a string, integer or float, the value itself will be printed. If given an array, values will be presented in a format that shows keys and elements. Similar notation is used for objects.

Remember that print_r() will move the array pointer to the end. Use reset() to bring it back to beginning.

提示: 为了防止程序直接将结果输出到浏览器，您可以使用输出控制函数（output-control functions）来捕获函数的输出，并把它们保存到一个 string 型的变量中。

<pre>
<?php
    $a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x','y','z'));
    print_r ($a);
?>
</pre>

Which will output:
<pre>
Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)
</pre>

注: Prior to PHP 4.0.4, print_r() will continue forever if given an array or object that contains a direct or indirect reference to itself. An example is print_r($GLOBALS) because $GLOBALS is itself a global variable that contains a reference to itself.

See also ob_start(), var_dump(), and var_export().

后退 | 起点 | 前进
isset | 上一级 | serialize


serialize

(PHP 3>= 3.0.5, PHP 4 )

serialize -- Generates a storable representation of a value

Description

string serialize ( mixed value)

serialize() returns a string containing a byte-stream representation of value that can be stored anywhere.

This is useful for storing or passing PHP values around without losing their type and structure.

To make the serialized string into a PHP value again, use unserialize(). serialize() handles all types, except the resource-type. You can even serialize() arrays that contain references to itself. References inside the array/object you are serialize()ing will also be stored.

注: In PHP 3, object properties will be serialized, but methods are lost. PHP 4 removes that limitation and restores both properties and methods. Please see the Serializing Objects section of Classes and Objects for more information.

例子 1. serialize() example

// $session_data contains a multi-dimensional array with session
// information for the current user.  We use serialize() to store
// it in a database at the end of the request.

$conn = odbc_connect ("webdb", "php", "chicken");
$stmt = odbc_prepare ($conn,
      "UPDATE sessions SET data = ? WHERE id = ?");
$sqldata = array (serialize($session_data), $PHP_AUTH_USER);
if (!odbc_execute ($stmt, &$sqldata)) {
    $stmt = odbc_prepare($conn,
     "INSERT INTO sessions (id, data) VALUES(?, ?)");
    if (!odbc_execute($stmt, &$sqldata)) {
    /* Something went wrong.  Bitch, whine and moan. */
    }
}

See Also: unserialize().

后退 | 起点 | 前进
print_r | 上一级 | settype


settype

(PHP 3, PHP 4 )

settype -- Set the type of a variable

Description

bool settype ( mixed var, string type)

Set the type of variable var to type.

Possibles values of type are:

  • "boolean" (or, since PHP 4.2.0, "bool")

  • "integer" (or, since PHP 4.2.0, "int")

  • "float" (only possible since PHP 4.2.0, for older versions use the deprecated variant "double")

  • "string"

  • "array"

  • "object"

  • "null" (since PHP 4.2.0)

Returns TRUE if successful; otherwise returns FALSE.

例子 1. settype() example

$foo = "5bar"; // string
$bar = true;   // boolean

settype($foo, "integer"); // $foo is now 5   (integer)
settype($bar, "string");  // $bar is now "1" (string)

See also gettype(), type-casting and type-juggling.

后退 | 起点 | 前进
serialize | 上一级 | strval


strval

(PHP 3, PHP 4 )

strval -- Get string value of a variable

Description

string strval ( mixed var)

Returns the string value of var. See the documentation on string for more information on converting to string.

var may be any scalar type. You cannot use strval() on arrays or objects.

See also floatval(), intval(), settype() and Type juggling.

后退 | 起点 | 前进
settype | 上一级 | unserialize


unserialize

(PHP 3>= 3.0.5, PHP 4 )

unserialize -- Creates a PHP value from a stored representation

Description

mixed unserialize ( string str)

unserialize() takes a single serialized variable (see serialize()) and converts it back into a PHP value. The converted value is returned, and can be an integer, float, string, array or object.

注: It's possible to set a callback-function which will be called, if an undefined class should be instanciated during unserializing. (to prevent getting an incomplete object "__PHP_Incomplete_Class".) Use your php.ini, ini_set() or .htaccess-file to define 'unserialize_callback_func'. Everytime an undefined class should be instanciated, it'll be called. To disable this feature just empty this setting.

例子 1. unserialize_callback_func example

$serialized_object='O:1:"a":1:{s:5:"value";s:3:"100";}';

ini_set('unserialize_callback_func','mycallback'); // set your callback_function

function mycallback($classname) {
    // just include a file containing your classdefinition
    // you get $classname to figure out which classdefinition is required
}

注: In PHP 3, methods are not preserved when unserializing a serialized object. PHP 4 removes that limitation and restores both properties and methods. Please see the Serializing Objects section of Classes and Objects or more information.

例子 2. unserialize() example

// Here, we use unserialize() to load session data to the
// $session_data array from the string selected from a database.
// This example complements the one described with serialize().

$conn = odbc_connect ("webdb", "php", "chicken");
$stmt = odbc_prepare ($conn, "SELECT data FROM sessions WHERE id = ?");
$sqldata = array ($PHP_AUTH_USER);
if (!odbc_execute ($stmt, &$sqldata) || !odbc_fetch_into ($stmt, &$tmp)) {
    // if the execute or fetch fails, initialize to empty array
    $session_data = array();
} else {
    // we should now have the serialized data in $tmp[0].
    $session_data = unserialize ($tmp[0]);
    if (!is_array ($session_data)) {
        // something went wrong, initialize to empty array
        $session_data = array();
    }
}

See Also: serialize().

后退 | 起点 | 前进
strval | 上一级 | unset


unset

(no version information, might be only in CVS)

unset -- Unset a given variable

Description

void unset ( mixed var [, mixed var [, ...]])

注: unset() is a language construct.

unset() destroys the specified variables. Note that in PHP 3, unset() will always return TRUE (actually, the integer value 1). In PHP 4, however, unset() is no longer a true function: it is now a statement. As such no value is returned, and attempting to take the value of unset() results in a parse error.

例子 1. unset() example

// destroy a single variable
unset ($foo);

// destroy a single element of an array
unset ($bar['quux']);

// destroy more than one variable
unset ($foo1, $foo2, $foo3);

The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy.

If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.

function destroy_foo() {
    global $foo;
    unset($foo);
}

$foo = 'bar';
destroy_foo();
echo $foo;

The above example would output:

bar

If a variable that is PASSED BY REFERENCE is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.

function foo(&$bar) {
    unset($bar);
    $bar = "blah";
}

$bar = 'something';
echo "$bar\n";

foo($bar);
echo "$bar\n";

The above example would output:

something
something

If a static variable is unset() inside of a function, unset() destroyes the variable and all its references.

function foo() {
    static $a;
    $a++;
    echo "$a\n";
    unset($a);
}

foo();
foo();
foo();

The above example would output:

1
2
3

If you would like to unset() a global variable inside of a function, you can use the $GLOBALS array to do so:

function foo() {
    unset($GLOBALS['bar']);
}

$bar = "something";
foo();

See also isset() and empty().

后退 | 起点 | 前进
unserialize | 上一级 | var_dump


var_dump

(PHP 3>= 3.0.5, PHP 4 )

var_dump -- Dumps information about a variable

Description

void var_dump ( mixed expression [, mixed expression [, ...]])

This function returns structured information about one or more expressions that includes its type and value. Arrays are explored recursively with values indented to show structure.

提示: 为了防止程序直接将结果输出到浏览器，您可以使用输出控制函数（output-control functions）来捕获函数的输出，并把它们保存到一个 string 型的变量中。

Compare var_dump() to print_r().

<pre>
<?php
$a = array (1, 2, array ("a", "b", "c"));
var_dump ($a);

/* output:
array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
  }
}

*/

$b = 3.1;
$c = TRUE;
var_dump($b,$c);

/* output:
float(3.1)
bool(true)

*/
?>
</pre>

后退 | 起点 | 前进
unset | 上一级 | var_export


var_export

(PHP 4 >= 4.2.0)

var_export -- Outputs or returns a string representation of a variable

Description

mixed var_export ( mixed expression [, bool return])

This function returns structured information about the variable that is passed to this function. It is similar to var_dump() with the exception that the returned representation is valid PHP code.

You can also return the variable representation by using TRUE as second parameter to this function.

Compare var_export() to var_dump().

<pre>
<?php
$a = array (1, 2, array ("a", "b", "c"));
var_export ($a);

/* output:
array (
  0 => 1,
  1 => 2,
  2 =>
  array (
    0 => 'a',
    1 => 'b',
    2 => 'c',
  ),
)
*/

$b = 3.1;
$v = var_export($b, TRUE);
echo $v;

/* output:
3.1
*/
?>
</pre>

后退 | 起点 | 前进
var_dump | 上一级 | vpopmail functions


vpopmail functions

PHP 手册
后退 前进

CII. vpopmail functions

介绍

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

目录
vpopmail_add_alias_domain_ex — Add alias to an existing virtual domain
vpopmail_add_alias_domain — Add an alias for a virtual domain
vpopmail_add_domain_ex — Add a new virtual domain
vpopmail_add_domain — Add a new virtual domain
vpopmail_add_user — Add a new user to the specified virtual domain
vpopmail_alias_add — insert a virtual alias
vpopmail_alias_del_domain — deletes all virtual aliases of a domain
vpopmail_alias_del — deletes all virtual aliases of a user
vpopmail_alias_get_all — get all lines of an alias for a domain
vpopmail_alias_get — get all lines of an alias for a domain
vpopmail_auth_user — Attempt to validate a username/domain/password. Returns true/false
vpopmail_del_domain_ex — Delete a virtual domain
vpopmail_del_domain — Delete a virtual domain
vpopmail_del_user — Delete a user from a virtual domain
vpopmail_error — Get text message for last vpopmail error. Returns string
vpopmail_passwd — Change a virtual user's password
vpopmail_set_user_quota — Sets a virtual user's quota

后退 | 起点 | 前进
var_export | 上一级 | vpopmail_add_alias_domain_ex


vpopmail_add_alias_domain_ex

(4.0.5 - 4.2.3 only)

vpopmail_add_alias_domain_ex -- Add alias to an existing virtual domain

Description

bool vpopmail_add_alias_domain_ex ( string olddomain, string newdomain)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
vpopmail functions | 上一级 | vpopmail_add_alias_domain


vpopmail_add_alias_domain

(4.0.5 - 4.2.3 only)

vpopmail_add_alias_domain -- Add an alias for a virtual domain

Description

bool vpopmail_add_alias_domain ( string domain, string aliasdomain)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
vpopmail_add_alias_domain_ex | 上一级 | vpopmail_add_domain_ex


vpopmail_add_domain_ex

(4.0.5 - 4.2.3 only)

vpopmail_add_domain_ex -- Add a new virtual domain

Description

bool vpopmail_add_domain_ex ( string domain, string passwd [, string quota [, string bounce [, bool apop]]])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
vpopmail_add_alias_domain | 上一级 | vpopmail_add_domain


vpopmail_add_domain

(4.0.5 - 4.2.3 only)

vpopmail_add_domain -- Add a new virtual domain

Description

bool vpopmail_add_domain ( string domain, string dir, int uid, int gid)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
vpopmail_add_domain_ex | 上一级 | vpopmail_add_user


vpopmail_add_user

(4.0.5 - 4.2.3 only)

vpopmail_add_user -- Add a new user to the specified virtual domain

Description

bool vpopmail_add_user ( string user, string domain, string password [, string gecos [, bool apop]])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
vpopmail_add_domain | 上一级 | vpopmail_alias_add


vpopmail_alias_add

(4.1.0 - 4.2.3 only)

vpopmail_alias_add -- insert a virtual alias

Description

bool vpopmail_alias_add ( string user, string domain, string alias)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
vpopmail_add_user | 上一级 | vpopmail_alias_del_domain


vpopmail_alias_del_domain

(4.1.0 - 4.2.3 only)

vpopmail_alias_del_domain -- deletes all virtual aliases of a domain

Description

bool vpopmail_alias_del_domain ( string domain)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
vpopmail_alias_add | 上一级 | vpopmail_alias_del


vpopmail_alias_del

(4.1.0 - 4.2.3 only)

vpopmail_alias_del -- deletes all virtual aliases of a user

Description

bool vpopmail_alias_del ( string user, string domain)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
vpopmail_alias_del_domain | 上一级 | vpopmail_alias_get_all


vpopmail_alias_get_all

(4.1.0 - 4.2.3 only)

vpopmail_alias_get_all -- get all lines of an alias for a domain

Description

array vpopmail_alias_get_all ( string domain)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
vpopmail_alias_del | 上一级 | vpopmail_alias_get


vpopmail_alias_get

(4.1.0 - 4.2.3 only)

vpopmail_alias_get -- get all lines of an alias for a domain

Description

array vpopmail_alias_get ( string alias, string domain)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
vpopmail_alias_get_all | 上一级 | vpopmail_auth_user


vpopmail_auth_user

(4.0.5 - 4.2.3 only)

vpopmail_auth_user -- Attempt to validate a username/domain/password. Returns true/false

Description

bool vpopmail_auth_user ( string user, string domain, string password [, string apop])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
vpopmail_alias_get | 上一级 | vpopmail_del_domain_ex


vpopmail_del_domain_ex

(4.0.5 - 4.2.3 only)

vpopmail_del_domain_ex -- Delete a virtual domain

Description

bool vpopmail_del_domain_ex ( string domain)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
vpopmail_auth_user | 上一级 | vpopmail_del_domain


vpopmail_del_domain

(4.0.5 - 4.2.3 only)

vpopmail_del_domain -- Delete a virtual domain

Description

bool vpopmail_del_domain ( string domain)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
vpopmail_del_domain_ex | 上一级 | vpopmail_del_user


vpopmail_del_user

(4.0.5 - 4.2.3 only)

vpopmail_del_user -- Delete a user from a virtual domain

Description

bool vpopmail_del_user ( string user, string domain)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
vpopmail_del_domain | 上一级 | vpopmail_error


vpopmail_error

(4.0.5 - 4.2.3 only)

vpopmail_error -- Get text message for last vpopmail error. Returns string

Description

string vpopmail_error ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
vpopmail_del_user | 上一级 | vpopmail_passwd


vpopmail_passwd

(4.0.5 - 4.2.3 only)

vpopmail_passwd -- Change a virtual user's password

Description

bool vpopmail_passwd ( string user, string domain, string password)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
vpopmail_error | 上一级 | vpopmail_set_user_quota


vpopmail_set_user_quota

(4.0.5 - 4.2.3 only)

vpopmail_set_user_quota -- Sets a virtual user's quota

Description

bool vpopmail_set_user_quota ( string user, string domain, string quota)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
vpopmail_passwd | 上一级 | W32api functions


W32api functions

PHP 手册
后退 前进

CIII. W32api functions

介绍

This extension is a generic extension API to DLLs. This was originally written to allow access to the Win32 API from PHP, although you can also access other functions exported via other DLLs.

Currently supported types are generic PHP types (strings, booleans, floats, integers and nulls) and types you define with w32api_deftype().

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

需求

This extension will only work on Windows systems.

安装

这些函数作为 PHP 核心的一部分，无需被安装即可使用。

运行时配置

该扩展模块未定义任何设置指令。

资源类型

This extension defines one resource type, used for user defined types. The name of this resource is "dynaparm".

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

DC_MICROSOFT (integer)

DC_BORLAND (integer)

DC_CALL_CDECL (integer)

DC_CALL_STD (integer)

DC_RETVAL_MATH4 (integer)

DC_RETVAL_MATH8 (integer)

DC_CALL_STD_BO (integer)

DC_CALL_STD_MS (integer)

DC_CALL_STD_M8 (integer)

DC_FLAG_ARGPTR (integer)

范例

This example gets the amount of time the system has been running and displays it in a message box.

例子 1. Get the uptime and display it in a message box

<?php
// Define constants needed, taken from
// Visual Studio/Tools/Winapi/WIN32API.txt
define("MB_OK", 0);

// Load the extension in
dl("php_w32api.dll");

// Register the GetTickCount function from kernel32.dll
w32api_register_function("kernel32.dll",
                         "GetTickCount",
                         "long");

// Register the MessageBoxA function from User32.dll
w32api_register_function("User32.dll",
                         "MessageBoxA",
                         "long");

// Get uptime information
$ticks = GetTickCount();

// Convert it to a nicely displayable text
$secs  = floor($ticks / 1000);
$mins  = floor($secs / 60);
$hours = floor($mins / 60);

$str = sprintf("You have been using your computer for:".
                "\r\n %d Milliseconds, or \r\n %d Seconds".
                "or \r\n %d mins or\r\n %d hours %d mins.",
                $ticks,
                $secs,
                $mins,
                $hours,
                $mins - ($hours*60));

// Display a message box with only an OK button and the uptime text
MessageBoxA(NULL,
            $str,
            "Uptime Information",
            MB_OK);
?>
目录
w32api_deftype — Defines a type for use with other w32api_functions
w32api_init_dtype — Creates an instance of the data type typename and fills it with the values passed
w32api_invoke_function — Invokes function funcname with the arguments passed after the function name
w32api_register_function — Registers function function_name from library with PHP
w32api_set_call_method — Sets the calling method used

后退 | 起点 | 前进
vpopmail_set_user_quota | 上一级 | w32api_deftype


w32api_deftype

(PHP 4 >= 4.2.0)

w32api_deftype -- Defines a type for use with other w32api_functions

Description

bool w32api_deftype ( string typename, string member1_type, string member1_name [, string ... [, string ...]])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

If you would like to define a type for a w32api call, you need to call w32api_deftype(). This function takes 2n+1 arguments, where n is the number of members the type has. The first argument is the name of the type. After that is the type of the member followed by the members name (in pairs). A member type can be a user defined type. All the type names are case sensitive. Built in type names should be provided in lowercase. 如果成功则返回 TRUE，失败则返回 FALSE。

后退 | 起点 | 前进
W32api functions | 上一级 | w32api_init_dtype


w32api_init_dtype

(PHP 4 >= 4.2.0)

w32api_init_dtype -- Creates an instance of the data type typename and fills it with the values passed

Description

resource w32api_init_dtype ( string typename, mixed value [, mixed ...])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

This function creates an instance of the data type named typename, filling in the values of the data type. The typename parameter is case sensitive. You should give the values in the same order as you defined the data type with w32api_deftype(). The type of the resource returned is dynaparm.

后退 | 起点 | 前进
w32api_deftype | 上一级 | w32api_invoke_function


w32api_invoke_function

(PHP 4 >= 4.2.0)

w32api_invoke_function -- Invokes function funcname with the arguments passed after the function name

Description

mixed w32api_invoke_function ( string funcname, mixed argument [, mixed ...])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

w32api_invoke_function() tries to find the previously registered function, named funcname, passing the parameters you provided. The return type is the one you set when you registered the function, the value is the one returned by the function itself. Any of the arguments can be of any PHP type or w32api_deftype() defined type, as needed.

后退 | 起点 | 前进
w32api_init_dtype | 上一级 | w32api_register_function


w32api_register_function

(PHP 4 >= 4.2.0)

w32api_register_function -- Registers function function_name from library with PHP

Description

bool w32api_register_function ( string libary, string function_name, string return_type)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

This function tries to find the function_name function in libary, and tries to import it into PHP. The function will be registered with the given return_type. This type can be a generic PHP type, or a type defined with w32api_deftype(). All type names are case sensitive. Built in type names should be provided in lowercase. 如果成功则返回 TRUE，失败则返回 FALSE。

后退 | 起点 | 前进
w32api_invoke_function | 上一级 | w32api_set_call_method


w32api_set_call_method

(PHP 4 >= 4.2.0)

w32api_set_call_method -- Sets the calling method used

Description

void w32api_set_call_method ( int method)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

This function sets the method call type. The parameter can be one of the constants DC_CALL_CDECL or DC_CALL_STD. The extension default is DC_CALL_STD.

后退 | 起点 | 前进
w32api_register_function | 上一级 | WDDX Functions


WDDX Functions

PHP 手册
后退 前进

CIV. WDDX Functions

介绍

These functions are intended for work with WDDX.

需求

In order to use WDDX, you will need to install the expat library (which comes with Apache 1.3.7 or higher).

安装

After installing expat compile PHP with --with-xml and --enable-wddx.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

范例

All the functions that serialize variables use the first element of an array to determine whether the array is to be serialized into an array or structure. If the first element has string key, then it is serialized into a structure, otherwise, into an array.

例子 1. Serializing a single value

<?php
print wddx_serialize_value("PHP to WDDX packet example", "PHP packet");
?>

This example will produce:

<wddxPacket version='1.0'><header comment='PHP packet'/><data>
<string>PHP to WDDX packet example</string></data></wddxPacket>

例子 2. Using incremental packets

<?php
$pi = 3.1415926;
$packet_id = wddx_packet_start("PHP");
wddx_add_vars($packet_id, "pi");

/* Suppose $cities came from database */
$cities = array("Austin", "Novato", "Seattle");
wddx_add_vars($packet_id, "cities");

$packet = wddx_packet_end($packet_id);
print $packet;
?>

This example will produce:

<wddxPacket version='1.0'><header comment='PHP'/><data><struct>
<var name='pi'><number>3.1415926</number></var><var name='cities'>
<array length='3'><string>Austin</string><string>Novato</string>
<string>Seattle</string></array></var></struct></data></wddxPacket>

注: If you want to serialize non-ASCII characters you have to set the appropriate locale before doing so (see setlocale()).

目录
wddx_add_vars — Add variables to a WDDX packet with the specified ID
wddx_deserialize — Deserializes a WDDX packet
wddx_packet_end — Ends a WDDX packet with the specified ID
wddx_packet_start — Starts a new WDDX packet with structure inside it
wddx_serialize_value — Serialize a single value into a WDDX packet
wddx_serialize_vars — Serialize variables into a WDDX packet

后退 | 起点 | 前进
w32api_set_call_method | 上一级 | wddx_add_vars


wddx_add_vars

(PHP 3>= 3.0.7, PHP 4 )

wddx_add_vars -- Add variables to a WDDX packet with the specified ID

Description

wddx_add_vars ( int packet_id, mixed name_var [, mixed ...])

wddx_add_vars() is used to serialize passed variables and add the result to the packet specified by the packet_id. The variables to be serialized are specified in exactly the same way as wddx_serialize_vars().

后退 | 起点 | 前进
WDDX Functions | 上一级 | wddx_deserialize


wddx_deserialize

(PHP 3>= 3.0.7, PHP 4 )

wddx_deserialize -- Deserializes a WDDX packet

Description

mixed wddx_deserialize ( string packet)

wddx_deserialize() takes a packet string and deserializes it. It returns the result which can be string, number, or array. Note that structures are deserialized into associative arrays.

后退 | 起点 | 前进
wddx_add_vars | 上一级 | wddx_packet_end


wddx_packet_end

(PHP 3>= 3.0.7, PHP 4 )

wddx_packet_end -- Ends a WDDX packet with the specified ID

Description

string wddx_packet_end ( int packet_id)

wddx_packet_end() ends the WDDX packet specified by the packet_id and returns the string with the packet.

后退 | 起点 | 前进
wddx_deserialize | 上一级 | wddx_packet_start


wddx_packet_start

(PHP 3>= 3.0.7, PHP 4 )

wddx_packet_start -- Starts a new WDDX packet with structure inside it

Description

int wddx_packet_start ( [string comment])

Use wddx_packet_start() to start a new WDDX packet for incremental addition of variables. It takes an optional comment string and returns a packet ID for use in later functions. It automatically creates a structure definition inside the packet to contain the variables.

后退 | 起点 | 前进
wddx_packet_end | 上一级 | wddx_serialize_value


wddx_serialize_value

(PHP 3>= 3.0.7, PHP 4 )

wddx_serialize_value -- Serialize a single value into a WDDX packet

Description

string wddx_serialize_value ( mixed var [, string comment])

wddx_serialize_value() is used to create a WDDX packet from a single given value. It takes the value contained in var, and an optional comment string that appears in the packet header, and returns the WDDX packet.

后退 | 起点 | 前进
wddx_packet_start | 上一级 | wddx_serialize_vars


wddx_serialize_vars

(PHP 3>= 3.0.7, PHP 4 )

wddx_serialize_vars -- Serialize variables into a WDDX packet

Description

string wddx_serialize_vars ( mixed var_name [, mixed ...])

wddx_serialize_vars() is used to create a WDDX packet with a structure that contains the serialized representation of the passed variables.

wddx_serialize_vars() takes a variable number of arguments, each of which can be either a string naming a variable or an array containing strings naming the variables or another array, etc.

例子 1. wddx_serialize_vars() example

<?php
$a = 1;
$b = 5.5;
$c = array("blue", "orange", "violet");
$d = "colors";

$clvars = array("c", "d");
print wddx_serialize_vars("a", "b", $clvars);
?>

The above example will produce:
<wddxPacket version='1.0'><header/><data><struct><var name='a'><number>1</number></var>
<var name='b'><number>5.5</number></var><var name='c'><array length='3'>
<string>blue</string><string>orange</string><string>violet</string></array></var>
<var name='d'><string>colors</string></var></struct></data></wddxPacket>

后退 | 起点 | 前进
wddx_serialize_value | 上一级 | XML 语法解析函数


XML 语法解析函数

PHP 手册
后退 前进

CV. XML 语法解析函数

介绍

XML（eXtensible Markup Language，可扩展标记语言）是一种在 WEB 上进行文档交换的数据格式。该语言是由 W3C（World Wide Web Concortium，世界万维网组织）定义的一种标准。您可以访问 http://www.w3.org/XML/ 以获取关于 XML 及其相关技术的更多信息。

本扩展模块可为 James Clark 的 expat 提供支持。该工具包帮助您解析 XML 文档（而非 XML 文档的有效化）。它支持三种源代码的编码方式，这三种编码方式也被 PHP 本身所支持，它们分别是：US-ASCII、ISO-8859-1 和 UTF-8。 该系统尚不支持 UTF-16。

该扩展模块使您能够建立 XML 语法解析器，并对不同的 XML 事件定义对应的处理器。每个 XML 语法解析器都有若干个您可以根据需要调整的参数。

需求

该扩展模块需要使用 expat，您可以访问 http://www.jclark.com/xml/ 来获取。expat 自带的 Makefile 文件不会生成默认的扩展库，您可以使用以下的生成规则来实现：
libexpat.a: $(OBJS)
    ar -rc $@ $(OBJS)
    ranlib $@

请访问 http://sourceforge.net/projects/expat/ 以获取 expat 源文件的 RPM 包。

安装

如果您使用 Apache-1.3.7 或者更高版本，那么您已经具备了 expat 扩展库。您只需简单地用 --with-xml（无需加任何其它的路径）来配置 PHP，expat 扩展库将会被自动地嵌入到 Apache 系统中。

在 Unix 上，带 --with-xml 参数运行 configure 命令。expat 扩展库应该被安装到您编译器能够找到的地方。如果您将 PHP 编译为 Apache 1.3.9 和更高版本的一个模块，PHP 会自动将 expat 库集成到 Apache 中。如果您将 expat 安装在了 Apache 之外，那么在您运行 configure 命令之前，您可能需要设置 CPPFLAGS 和 LDFLAGS 这两个环境变量。

最后编译 PHP，该扩展模块应该就可以使用了。

【译者注】在 Win32 环境下，XML Parser 模块已经被集成到 PHP 内核中，您可以在用函数 phpinfo() 生成的页面中看到有关信息的表格。

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

XML_ERROR_NONE (integer)

XML_ERROR_NO_MEMORY (integer)

XML_ERROR_SYNTAX (integer)

XML_ERROR_NO_ELEMENTS (integer)

XML_ERROR_INVALID_TOKEN (integer)

XML_ERROR_UNCLOSED_TOKEN (integer)

XML_ERROR_PARTIAL_CHAR (integer)

XML_ERROR_TAG_MISMATCH (integer)

XML_ERROR_DUPLICATE_ATTRIBUTE (integer)

XML_ERROR_JUNK_AFTER_DOC_ELEMENT (integer)

XML_ERROR_PARAM_ENTITY_REF (integer)

XML_ERROR_UNDEFINED_ENTITY (integer)

XML_ERROR_RECURSIVE_ENTITY_REF (integer)

XML_ERROR_ASYNC_ENTITY (integer)

XML_ERROR_BAD_CHAR_REF (integer)

XML_ERROR_BINARY_ENTITY_REF (integer)

XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF (integer)

XML_ERROR_MISPLACED_XML_PI (integer)

XML_ERROR_UNKNOWN_ENCODING (integer)

XML_ERROR_INCORRECT_ENCODING (integer)

XML_ERROR_UNCLOSED_CDATA_SECTION (integer)

XML_ERROR_EXTERNAL_ENTITY_HANDLING (integer)

XML_OPTION_CASE_FOLDING (integer)

XML_OPTION_TARGET_ENCODING (integer)

XML_OPTION_SKIP_TAGSTART (integer)

XML_OPTION_SKIP_WHITE (integer)

事件处理器

XML 事件处理器定义如下：

表格 1. 已支持的 XML 事件处理器

用来设置处理器的 PHP 函数 | 事件描述
xml_set_element_handler() | 元素事件（Element events）将在 XML 解析器遇到标记符的起始符或者终止符时发生。另外，对于起始符和终止符也有独立的处理器。
xml_set_character_data_handler() | 粗略的说，字符数据（Character data）是指 XML 文档中所有标记符以外的内容，包括标记符之间的空格。需要注意的是 XML 语法解析器不会加上或者去掉任何空格。空格的取舍将由应用程序（也就是您自己）来决定。
xml_set_processing_instruction_handler() | PHP 程序员对“处理指令”（Processing Instructions，PIs）应该已经很熟悉了。<?php ?> 就是一个处理指令，其中 php 被称为“PI target”。除了以“XML”开头的 PI target 已被保留以外，对这些 PIs 的处理将由应用程序来完成。
xml_set_default_handler() | 所有无法被其它处理器处理的事件将由默认处理器来处理。这些事件包括诸如 XML 和文档类型声明等内容。
xml_set_unparsed_entity_decl_handler() | 该处理器将在遇到无法解析的实体名称（NDATA）声明时被调用。
xml_set_notation_decl_handler() | 该处理器将在声明一个注释时被调用。
xml_set_external_entity_ref_handler() | 当 XML 解析器遇到指向外部解析的一般实体名时，该处理器将被调用。该指向的目标可以是一个文件，也可以是 URL。请参阅“外部实体名范例”。

大小写折叠（Case Folding）

元素处理函数可能会导致元素名称“大小写折叠”（case-folded）。“大小写折叠”被 XML 标准定义为“一个应用于一系列字符的过程，在该过程中，这些字符中的所有的非大写字符将被替换成它们对应大写等价字符”。换句话说，对于 XML，“大小写折叠”就是指将字符串转换成大写字符。

所有被传递给处理器函数的元素名称将默认的发生“大小写折叠”。该过程可以分别被 xml_parser_get_option() 和 xml_parser_set_option() 函数查询和控制。

错误代码

以下常量被定义为 XML 的错误代码，将由 xml_parse() 返回：

XML_ERROR_NONE
XML_ERROR_NO_MEMORY
XML_ERROR_SYNTAX
XML_ERROR_NO_ELEMENTS
XML_ERROR_INVALID_TOKEN
XML_ERROR_UNCLOSED_TOKEN
XML_ERROR_PARTIAL_CHAR
XML_ERROR_TAG_MISMATCH
XML_ERROR_DUPLICATE_ATTRIBUTE
XML_ERROR_JUNK_AFTER_DOC_ELEMENT
XML_ERROR_PARAM_ENTITY_REF
XML_ERROR_UNDEFINED_ENTITY
XML_ERROR_RECURSIVE_ENTITY_REF
XML_ERROR_ASYNC_ENTITY
XML_ERROR_BAD_CHAR_REF
XML_ERROR_BINARY_ENTITY_REF
XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF
XML_ERROR_MISPLACED_XML_PI
XML_ERROR_UNKNOWN_ENCODING
XML_ERROR_INCORRECT_ENCODING
XML_ERROR_UNCLOSED_CDATA_SECTION
XML_ERROR_EXTERNAL_ENTITY_HANDLING

字符编码

PHP 的 XML 扩展库支持不同字符编码（character encoding）的 Unicode 字符集。字符编码有两种形式，它们分别是“源编码”（source encoding）和“目标编码”（target encoding）。PHP 对文档内部表示的编码方式是 UTF-8。

源编码将在 XML 文档被解析后完成。源编码可在建立一个 XML 解析器时指明（该编码方式在 XML 解析器的生命周期中不能被再次改变）。支持的编码方式包括 ISO-8859-1，US-ASCII 和 UTF-8。前两种为单字节编码，即每个字符被一个单一的字节表示。 UTF-8 支持 1 至 4 个字节的多 bit（最多 12）字符编码。PHP 默认使用 ISO-8859-1 作为源编码方式。

目标编码将在 PHP 向 XML 处理器函数传送数据时被完成。当 XML 解析器被建立后，目标编码将被设置成与源编码相同的编码方式，但该方式可在任何时候被更改。目标编码将影响字符数据、标记符名称以及处理指令目标（PI target）。

如果 XML 解析器遇到其源编码方式表示能力之外的字符，它将返回一个错误。

当 PHP 在被解析的 XML 文档中遇到当前目标编码无法表示的字符时，这些字符将被“降级”。简单的说，这些字符将被问号替换。

范例

以下是 PHP 脚本解析 XML 文档的一些范例。

XML 元素结构范例

第一个范例用缩进格式显示一个文档中起始元素的结构。

例子 1. 显示 XML 元素结构

$file = "data.xml";
$depth = array();

function startElement($parser, $name, $attrs) {
    global $depth;
    for ($i = 0; $i < $depth[$parser]; $i++) {
        print "  ";
    }
    print "$name\n";
    $depth[$parser]++;
}

function endElement($parser, $name) {
    global $depth;
    $depth[$parser]--;
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
xml_parser_free($xml_parser);

XML 标记符映射范例

例子 2. 将 XML 映射为 HTML

以下范例将 XML 文档中的标记符直接映射成 HTML 标记符。在“映射数组”中不存在的元素将被忽略。当然，该范例将只对一个特定的 XML 文档有效。
$file = "data.xml";
$map_array = array(
    "BOLD"     => "B",
    "EMPHASIS" => "I",
    "LITERAL"  => "TT"
);

function startElement($parser, $name, $attrs) {
    global $map_array;
    if ($htmltag = $map_array[$name]) {
        print "<$htmltag>";
    }
}

function endElement($parser, $name) {
    global $map_array;
    if ($htmltag = $map_array[$name]) {
        print "</$htmltag>";
    }
}

function characterData($parser, $data) {
    print $data;
}

$xml_parser = xml_parser_create();
// 使用大小写折叠来保证我们能在元素数组中找到这些元素名称
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
xml_parser_free($xml_parser);

XML 外部实体范例

该范例能够高亮显示 XML 源代码。它将说明如何外部实体指向处理器来包含和解析其它文档，如何处理 PIs，以及一种确定包含有 PIs 的代码的可信度。

能被该范例使用的的 XML 文档（xmltest.xml 和 xmltest2.xml）被列在该范例之后。

例子 3. 外部实体范例

<?php
$file = "xmltest.xml";

function trustedFile($file) {
    // only trust local files owned by ourselves
    if (!eregi("^([a-z]+)://", $file)
        && fileowner($file) == getmyuid()) {
            return true;
    }
    return false;
}

function startElement($parser, $name, $attribs) {
    print "&lt;<font color=\"#0000cc\">$name</font>";
    if (sizeof($attribs)) {
        while (list($k, $v) = each($attribs)) {
            print " <font color=\"#009900\">$k</font>=\"<font
                   color=\"#990000\">$v</font>\"";
        }
    }
    print "&gt;";
}

function endElement($parser, $name) {
    print "&lt;/<font color=\"#0000cc\">$name</font>&gt;";
}

function characterData($parser, $data) {
    print "<b>$data</b>";
}

function PIHandler($parser, $target, $data) {
    switch (strtolower($target)) {
        case "php":
            global $parser_file;
            // If the parsed document is "trusted", we say it is safe
            // to execute PHP code inside it.  If not, display the code
            // instead.
            if (trustedFile($parser_file[$parser])) {
                eval($data);
            } else {
                printf("Untrusted PHP code: <i>%s</i>",
                        htmlspecialchars($data));
            }
            break;
    }
}

function defaultHandler($parser, $data) {
    if (substr($data, 0, 1) == "&" && substr($data, -1, 1) == ";") {
        printf('<font color="#aa00aa">%s</font>',
                htmlspecialchars($data));
    } else {
        printf('<font size="-1">%s</font>',
                htmlspecialchars($data));
    }
}

function externalEntityRefHandler($parser, $openEntityNames, $base, $systemId,
                                  $publicId) {
    if ($systemId) {
        if (!list($parser, $fp) = new_xml_parser($systemId)) {
            printf("Could not open entity %s at %s\n", $openEntityNames,
                   $systemId);
            return false;
        }
        while ($data = fread($fp, 4096)) {
            if (!xml_parse($parser, $data, feof($fp))) {
                printf("XML error: %s at line %d while parsing entity %s\n",
                       xml_error_string(xml_get_error_code($parser)),
                       xml_get_current_line_number($parser), $openEntityNames);
                xml_parser_free($parser);
                return false;
            }
        }
        xml_parser_free($parser);
        return true;
    }
    return false;
}

function new_xml_parser($file) {
    global $parser_file;

    $xml_parser = xml_parser_create();
    xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 1);
    xml_set_element_handler($xml_parser, "startElement", "endElement");
    xml_set_character_data_handler($xml_parser, "characterData");
    xml_set_processing_instruction_handler($xml_parser, "PIHandler");
    xml_set_default_handler($xml_parser, "defaultHandler");
    xml_set_external_entity_ref_handler($xml_parser, "externalEntityRefHandler");

    if (!($fp = @fopen($file, "r"))) {
        return false;
    }
    if (!is_array($parser_file)) {
        settype($parser_file, "array");
    }
    $parser_file[$xml_parser] = $file;
    return array($xml_parser, $fp);
}

if (!(list($xml_parser, $fp) = new_xml_parser($file))) {
    die("could not open XML input");
}

print "<pre>";
while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d\n",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
print "</pre>";
print "parse complete\n";
xml_parser_free($xml_parser);

?>

例子 4. xmltest.xml

<?xml version='1.0'?>
<!DOCTYPE chapter SYSTEM "/just/a/test.dtd" [
<!ENTITY plainEntity "FOO entity">
<!ENTITY systemEntity SYSTEM "xmltest2.xml">
]>
<chapter>
 <TITLE>Title &plainEntity;</TITLE>
 <para>
  <informaltable>
   <tgroup cols="3">
    <tbody>
     <row><entry>a1</entry><entry morerows="1">b1</entry><entry>c1</entry></row>
     <row><entry>a2</entry><entry>c2</entry></row>
     <row><entry>a3</entry><entry>b3</entry><entry>c3</entry></row>
    </tbody>
   </tgroup>
  </informaltable>
 </para>
 &systemEntity;
 <section id="about">
  <title>About this Document</title>
  <para>
   <!-- this is a comment -->
   <?php print 'Hi!  This is PHP version '.phpversion(); ?>
  </para>
 </section>
</chapter>

以下文档将被 xmltest.xml 文件调用：

例子 5. xmltest2.xml

<?xml version="1.0"?>
<!DOCTYPE foo [
<!ENTITY testEnt "test entity">
]>
<foo>
   <element attrib="value"/>
   &testEnt;
   <?php print "This is some more PHP code being executed."; ?>
</foo>

目录
utf8_decode — 将用 UTF-8 方式编码的 ISO-8859-1 字符串转换成单字节的 ISO-8859-1 字符串。
utf8_encode — 将 ISO-8859-1 编码的字符串转换为 UTF-8 编码
xml_error_string — 获取 XML 解析器的错误字符串
xml_get_current_byte_index — 获取 XML 解析器的当前字节索引（current byte index）。
xml_get_current_column_number — 获取 XML 解析器的当前列号
xml_get_current_line_number — 获取 XML 解析器的当前行号
xml_get_error_code — 获取 XML 解析器错误代码
xml_parse_into_struct — 将 XML 数据解析到数组中
xml_parse — 开始解析一个 XML 文档
xml_parser_create_ns — 生成一个 XML 解析器
xml_parser_create — 建立一个 XML 解析器
xml_parser_free — 释放指定的 XML 解析器
xml_parser_get_option — 从 XML 解析器获取选项设置信息
xml_parser_set_option — 为指定 XML 解析进行选项设置
xml_set_character_data_handler — 建立字符数据处理器
xml_set_default_handler — 建立默认处理器
xml_set_element_handler — 建立起始和终止元素处理器
xml_set_end_namespace_decl_handler — 建立终止命名空间声明处理器
xml_set_external_entity_ref_handler — 建立外部实体指向处理器
xml_set_notation_decl_handler — 建立注释声明处理器
xml_set_object — 在对象中使用 XML 解析器
xml_set_processing_instruction_handler — 建立处理指令（PI）处理器
xml_set_start_namespace_decl_handler — 建立起始命名空间声明处理器
xml_set_unparsed_entity_decl_handler — 建立未解析实体定义声明处理器

后退 | 起点 | 前进
wddx_serialize_vars | 上一级 | utf8_decode


utf8_decode

(PHP 3>= 3.0.6, PHP 4 )

utf8_decode -- 将用 UTF-8 方式编码的 ISO-8859-1 字符串转换成单字节的 ISO-8859-1 字符串。

描述

string utf8_decode ( string data)

该函数将用 UTF-8 编码的数据解码为 ISO-8859-1 编码。

请参阅 utf8_encode() 以查看关于 UTF-8 编码的解释。

后退 | 起点 | 前进
XML 语法解析函数 | 上一级 | utf8_encode


utf8_encode

(PHP 3>= 3.0.6, PHP 4 )

utf8_encode -- 将 ISO-8859-1 编码的字符串转换为 UTF-8 编码

描述

string utf8_encode ( string data)

该函数将 data 字符串转换为 UTF-8 编码，并返回编码后的字符串。UTF-8 是一种用于将宽字符值转换为字节流的 Unicode 的标准机制。UTF-8 对于纯 ASCII 字符来说是透明的，且是自同步的（也就是说这使得程序能够得知字符从字节流的何处开始），并可被普通字符串比较函数用以比较等操作。PHP 可将 UTF-8 编码为多达四个字节的字符，如：

表格 1. UTF-8 编码

字节（bytes） | 位（bits） | 表 示
1 | 7 | 0bbbbbbb
2 | 11 | 110bbbbb 10bbbbbb
3 | 16 | 1110bbbb 10bbbbbb 10bbbbbb
4 | 21 | 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb

每个 UTF-8 表示一个能被用以储存字符数据的位。

后退 | 起点 | 前进
utf8_decode | 上一级 | xml_error_string


xml_error_string

(PHP 3>= 3.0.6, PHP 4 )

xml_error_string -- 获取 XML 解析器的错误字符串

描述

string xml_error_string ( int code)

code

由 xml_get_error_code() 返回的错误代码。

返回与 code 描述的错误代码参数对应的文本描述字符串，若没有与之对应的描述，则返回 FALSE。

后退 | 起点 | 前进
utf8_encode | 上一级 | xml_get_current_byte_index


xml_get_current_byte_index

(PHP 3>= 3.0.6, PHP 4 )

xml_get_current_byte_index -- 获取 XML 解析器的当前字节索引（current byte index）。

描述

int xml_get_current_byte_index ( resource parser)

parser

一个指向要获取当前字节索引的 XML 解析器的指针。

如果 parser 没有指向一个合法的解析器，该函数将返回 FALSE，否则将返回解析器在其缓存中的字节索引（起始值为0）。

后退 | 起点 | 前进
xml_error_string | 上一级 | xml_get_current_column_number


xml_get_current_column_number

(PHP 3>= 3.0.6, PHP 4 )

xml_get_current_column_number -- 获取 XML 解析器的当前列号

描述

int xml_get_current_column_number ( resource parser)

parser

一个指向要获取列号的 XML 解析器的指针。

如果 parser 参数没有指向一个合法的解析器，该函数将返回 FALSE，否则将返回指定解析器所在行（由函数 xml_get_current_line_number() 给定）的当前列号。

后退 | 起点 | 前进
xml_get_current_byte_index | 上一级 | xml_get_current_line_number


xml_get_current_line_number

(PHP 3>= 3.0.6, PHP 4 )

xml_get_current_line_number -- 获取 XML 解析器的当前行号

描述

int xml_get_current_line_number ( resource parser)

parser

一个指向要获取当前行号的 XML 解析器的指针。

如果 parser 参数没有指向一个合法的解析器，该函数将返回 FALSE，否则将返回指定解析器在其缓存中的当前行号。

后退 | 起点 | 前进
xml_get_current_column_number | 上一级 | xml_get_error_code


xml_get_error_code

(PHP 3>= 3.0.6, PHP 4 )

xml_get_error_code -- 获取 XML 解析器错误代码

描述

int xml_get_error_code ( resource parser)

parser

一个指向要返回错误代码的 XML 解析器的指针

如果 parser 参数没有指向一个合法的解析器，该函数将返回 FALSE，否则将返回错误代码列表中的一个错误代码。

后退 | 起点 | 前进
xml_get_current_line_number | 上一级 | xml_parse_into_struct


xml_parse_into_struct

(PHP 3>= 3.0.8, PHP 4 )

xml_parse_into_struct -- 将 XML 数据解析到数组中

描述

int xml_parse_into_struct ( resource parser, string data, array &values, array &index)

该函数将 XML 文件解析到两个对应的数组中，index 参数含有指向 values 数组中对应值的指针。最后两个数组参数可由指针传递给函数。

以下范例显示了由该函数生成的数组的内部结构。我们简单地将一个 note 嵌入到一个 para 标记中，解析后我们可以打印出生成的数组的结构：

$simple = "<para><note>simple note</note></para>";
$p = xml_parser_create();
xml_parse_into_struct($p,$simple,$vals,$index);
xml_parser_free($p);
echo "Index array\n";
print_r($index);
echo "\nVals array\n";
print_r($vals);

运行以上代码，我们得到的输出将是：

Index array
Array
(
    [PARA] => Array
        (
            [0] => 0
            [1] => 2
        )

    [NOTE] => Array
        (
            [0] => 1
        )

)

Vals array
Array
(
    [0] => Array
        (
            [tag] => PARA
            [type] => open
            [level] => 1
        )

    [1] => Array
        (
            [tag] => NOTE
            [type] => complete
            [level] => 2
            [value] => simple note
        )

    [2] => Array
        (
            [tag] => PARA
            [type] => close
            [level] => 1
        )

)

如果您的 XML 文档很复杂，基于该文档的事件处理（Event-driven）解析（基于 expat 扩展库）也会对应的变得复杂。该函数生成的并非 DOM 风格的对象，而是横向的树状结构。因此，我们能够方便的建立表达 XML 文件数据的对象。我们假设以下 XML 文件表示一个关于氨基酸信息的小型数据库：

例子 1. moldb.xml - 分子信息的小型数据库

<?xml version="1.0"?>
<moldb>

    <molecule>
        <name>Alanine</name>
        <symbol>ala</symbol>
        <code>A</code>
        <type>hydrophobic</type>
    </molecule>

    <molecule>
        <name>Lysine</name>
        <symbol>lys</symbol>
        <code>K</code>
        <type>charged</type>
    </molecule>

</moldb>
以下是解析该文档并生成相应对象的代码：

例子 2. parsemoldb.php - 将 moldb.xml 解析到分子（molecular）对象的数组中

<?php

class AminoAcid {
    var $name;  // aa name
    var $symbol;    // three letter symbol
    var $code;  // one letter code
    var $type;  // hydrophobic, charged or neutral

    function AminoAcid ($aa) {
        foreach ($aa as $k=>$v)
            $this->$k = $aa[$k];
    }
}

function readDatabase($filename) {
    // read the xml database of aminoacids
    $data = implode("",file($filename));
    $parser = xml_parser_create();
    xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0);
    xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,1);
    xml_parse_into_struct($parser,$data,$values,$tags);
    xml_parser_free($parser);

    // loop through the structures
    foreach ($tags as $key=>$val) {
        if ($key == "molecule") {
            $molranges = $val;
            // each contiguous pair of array entries are the
            // lower and upper range for each molecule definition
            for ($i=0; $i < count($molranges); $i+=2) {
                    $offset = $molranges[$i] + 1;
                $len = $molranges[$i + 1] - $offset;
                $tdb[] = parseMol(array_slice($values, $offset, $len));
            }
        } else {
            continue;
        }
    }
    return $tdb;
}

function parseMol($mvalues) {
    for ($i=0; $i < count($mvalues); $i++)
        $mol[$mvalues[$i]["tag"]] = $mvalues[$i]["value"];
    return new AminoAcid($mol);
}

$db = readDatabase("moldb.xml");
echo "** Database of AminoAcid objects:\n";
print_r($db);

?>
在执行完 parsemoldb.php 后，变量 $db 将包含有一个由 AminoAcid 对象组成的数组，该脚本的输出如下：

** Database of AminoAcid objects:
Array
(
    [0] => aminoacid Object
        (
            [name] => Alanine
            [symbol] => ala
            [code] => A
            [type] => hydrophobic
        )

    [1] => aminoacid Object
        (
            [name] => Lysine
            [symbol] => lys
            [code] => K
            [type] => charged
        )

)

后退 | 起点 | 前进
xml_get_error_code | 上一级 | xml_parse


xml_parse

(PHP 3>= 3.0.6, PHP 4 )

xml_parse -- 开始解析一个 XML 文档

描述

bool xml_parse ( resource parser, string data [, bool is_final])

parser

一个指向将要使用的 XML 解析器的指针

data

需要解析的数据集。您可以多次对新的数据调用 xml_parse() 函数来分段解析一个文档；只要在解析最后一段数据时将 is_final 参数设置为 TRUE。

is_final （可选参数）

如果被设置为 TRUE；，则 data 为当前解析中最后一段数据。

当 XML 文档被解析后，已定义的时间处理器将在被需要时调用，结束后该函数将返回 TRUE 或 FALSE。

如果解析成功，函数将返回 TRUE；如果解析不成功或者 parser 参数没有指向一个合法的解析器，函数将返回 FALSE。如果解析不成功，您可以用函数 xml_get_error_code()，xml_error_string()，xml_get_current_line_number()，xml_get_current_column_number() 以及 xml_get_current_byte_index() 来获取错误信息。

后退 | 起点 | 前进
xml_parse_into_struct | 上一级 | xml_parser_create_ns


xml_parser_create_ns

(PHP 4 >= 4.0.5)

xml_parser_create_ns -- 生成一个 XML 解析器

描述

resource xml_parser_create_ns ( [string encoding [, string sep]])

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
xml_parse | 上一级 | xml_parser_create


xml_parser_create

(PHP 3>= 3.0.6, PHP 4 )

xml_parser_create -- 建立一个 XML 解析器

描述

resource xml_parser_create ( [string encoding])

encoding （可选参数）

指定解析器使用的编码方式。目前该扩展库支持以下编码方式：

ISO-8859-1 （默认值）
US-ASCII
UTF-8

该函数建立一个 XML 解析器并返回一个可被其它 XML 函数使用的句柄；若执行失败则返回 FALSE。

后退 | 起点 | 前进
xml_parser_create_ns | 上一级 | xml_parser_free


xml_parser_free

(PHP 3>= 3.0.6, PHP 4 )

xml_parser_free -- 释放指定的 XML 解析器

描述

bool xml_parser_free ( resource parser)

parser

指向要释放的 XML 解析器的指针。

如果 parser 参数没有指向一个合法的解析器，该函数将返回 FALSE，否则将释放指定的解析器并返回 TRUE。

后退 | 起点 | 前进
xml_parser_create | 上一级 | xml_parser_get_option


xml_parser_get_option

(PHP 3>= 3.0.6, PHP 4 )

xml_parser_get_option -- 从 XML 解析器获取选项设置信息

描述

mixed xml_parser_get_option ( resource parser, int option)

parser

指向要获取设置信息的 XML 解析器的指针。

option

要获取得设置选项名称。请参阅 xml_parser_set_option() 函数获取选项名称列表。

如果 parser 参数没有指向一个合法的解析器或者指定的选项名称不存在，该函数将返回 FALSE，否则将返回指定设置选项的值。

请参阅 xml_parser_set_option() 函数获取选项名称列表。

后退 | 起点 | 前进
xml_parser_free | 上一级 | xml_parser_set_option


xml_parser_set_option

(PHP 3>= 3.0.6, PHP 4 )

xml_parser_set_option -- 为指定 XML 解析进行选项设置

描述

bool xml_parser_set_option ( resource parser, int option, mixed value)

parser

指向要设置选项信息的 XML 解析器的指针。

option

要设置的选项名称。请参考下文。

value

要给选项设置的新值。

如果 parser 参数没有指向一个合法的解析器或者指定的选项无法设置，该函数将返回 FALSE，否则将会把选项设置为指定的值并返回 TRUE。

可被设置的选项如下：

表格 1. XML 解析器选项

选项常量 | 数据类型 | 描述
XML_OPTION_CASE_FOLDING | integer | 控制在该 XML 解析器中 大小写折叠（case-folding） 是否有效。其默认值为有效。
XML_OPTION_TARGET_ENCODING | string | 设置该 XML 解析器所使用的目标编码（target encoding）方式。其默认值和由 xml_parser_create() 函数设置的源编码（source encoding）方式相同。支持的目标编码方式有 ISO-8859-1、US-ASCII 和 UTF-8。

后退 | 起点 | 前进
xml_parser_get_option | 上一级 | xml_set_character_data_handler


xml_set_character_data_handler

(PHP 3>= 3.0.6, PHP 4 )

xml_set_character_data_handler -- 建立字符数据处理器

描述

bool xml_set_character_data_handler ( resource parser, string handler)

为 parser 变量指向的 XML 解析器指定字符数据处理函数。handler 为表示一个函数名称的字符串，该函数必须在为 parser 指定的解析器调用 xml_parse() 函数时已存在。

由 handler 参数命名的函数名必须接受两个参数： handler ( resource parser, string data)

parser

第一个参数 parser 为指向要调用处理器的 XML 解析器的指针。

data

第二个参数 data 为包含有字符数据的字符串。

如果处理器函数名被设置为空字符串或者 FALSE，则该有问题的处理器将被屏蔽。

如果处理器被成功的建立，该函数将返回 TRUE，如果 parser 指向的不是合法的解析器，函数该函数将返回 FALSE。

注: 第二个参数函数名可以替换为一个数组，该数组由一个对象名和该对象名的一个方法名两个元素组成。

后退 | 起点 | 前进
xml_parser_set_option | 上一级 | xml_set_default_handler


xml_set_default_handler

(PHP 3>= 3.0.6, PHP 4 )

xml_set_default_handler -- 建立默认处理器

描述

bool xml_set_default_handler ( resource parser, string handler)

为 parser 指定的 XML 处理器建立默认处理函数。handler 为表示一个函数名称的字符串，该函数必须在为 parser 指定的解析器调用 xml_parse() 函数时已存在。

由 handler 参数命名的函数名必须接受两个参数： handler ( resource parser, string data)

parser

第一个参数 parser 为指向要调用处理器的 XML 解析器的指针。

data

第二个参数 data 为包含有字符数据的字符串。其内容可以是 XML 声明、文档类型声明、实体名或者其它没有已存在处理器的地数据。

如果处理器函数名被设置为空字符串或者 FALSE，则该有问题的处理器将被屏蔽。

如果处理器被成功的建立，该函数将返回 TRUE，如果 parser 指向的不是合法的解析器，函数该函数将返回 FALSE。

注: 第二个参数函数名可以替换为一个数组，该数组由一个对象名和该对象名的一个方法名两个元素组成。

后退 | 起点 | 前进
xml_set_character_data_handler | 上一级 | xml_set_element_handler


xml_set_element_handler

(PHP 3>= 3.0.6, PHP 4 )

xml_set_element_handler -- 建立起始和终止元素处理器

描述

bool xml_set_element_handler ( resource parser, string start_element_handler, string end_element_handler)

为 parser 参数指定的 XML 解析器建立元素处理器函数。参数 start_element_handler 和 end_element_handler 为表示函数名称的字符串，这些函数必须在为 parser 指定的解析器调用 xml_parse() 函数时已存在。

由 start_element_handler 参数命名的函数名必须接受三个参数： start_element_handler ( resource parser, string name, array attribs)

parser

第一个参数 parser 为指向要调用处理器的 XML 解析器的指针。

name

第二个参数 name 为该处理器为之被调用的元素名。如果大小写折叠（case-folding）对该解析器有效，元素名将用大写字母表示。

attribs

第三个参数 attribs 为一个包含有对应元素的属性的数组（如果该元素有属性）。数组元素的下标为属性名，元素的值即为属性的值。属性名将以和元素名同样的标准进行大小写折叠（case-folded），其值不进行大小写折叠。

属性的原始顺序将会被参数保留，用 each() 函数遍历 attribs 时，该数组下表的顺序和属性的顺序相同。

由 end_element_handler 参数命名的函数名必须接受两个参数： end_element_handler ( resource parser, string name)

parser

第一个参数 parser 为指向要调用处理器的 XML 解析器的指针。

name

第二个参数 name 为该处理器为之被调用的元素名。如果大小写折叠（case-folding）对该解析器有效，元素名将用大写字母表示。

如果处理器函数名被设置为空字符串或者 FALSE，则该有问题的处理器将被屏蔽。

如果处理器被成功的建立，该函数将返回 TRUE；如果 parser 指向的不是合法的解析器，函数该函数将返回 FALSE。

注: 第二个参数函数名可以替换为一个数组，该数组由一个对象名和该对象名的一个方法名两个元素组成。

后退 | 起点 | 前进
xml_set_default_handler | 上一级 | xml_set_end_namespace_decl_handler


xml_set_end_namespace_decl_handler

(PHP 4 >= 4.0.5)

xml_set_end_namespace_decl_handler -- 建立终止命名空间声明处理器

描述

bool xml_set_end_namespace_decl_handler ( resource pind, string hdl)

警告

该文档目前尚无参考文档；仅参数列表可用。

注: 第二个参数函数名可以替换为一个数组，该数组由一个对象名和该对象名的一个方法名两个元素组成。

后退 | 起点 | 前进
xml_set_element_handler | 上一级 | xml_set_external_entity_ref_handler


xml_set_external_entity_ref_handler

(PHP 3>= 3.0.6, PHP 4 )

xml_set_external_entity_ref_handler -- 建立外部实体指向处理器

描述

bool xml_set_external_entity_ref_handler ( resource parser, string handler)

为 parser 参数指定的 XML 解析器建立外部实体指向处理器函数。参数 start_element_handler 和 end_element_handler 为表示函数名称的字符串，这些函数必须在为 parser 指定的解析器调用 xml_parse() 函数时已存在。

由 handler 参数命名的函数名必须接受五个参数，并应该返回一个整型值。如果处理器的返回值为 FALSE（这也是函数没有确定返回值时的返回值），XML 解析器将停止解析， xml_get_error_code() 函数将返回 XML_ERROR_EXTERNAL_ENTITY_HANDLING。 handler ( resource parser, string open_entity_names, string base, string system_id, string public_id)

parser

第一个参数 parser 为指向要调用处理器的 XML 解析器的指针。

open_entity_names

第二个参数 open_entity_names 是为该实体的解析开放的实体名列表（包括被指向的实体名），这些实体名由空格隔开。

base

这个参数是解析外部实体的系统标识符（system_id）的基础。当前该参数通常都被设置为空字符串。

system_id

第四个参数 system_id 是在实体定义声明中指定的系统标识符。

public_id

第五个参数 public_id 是在实体定义声明中指定的公共标识符，如果未指定任何标识符，则该字符串为空。公共标识符中的空格将按照 XML 的要求被正常化。

如果处理器函数名被设置为空字符串或者 FALSE，则该有问题的处理器将被屏蔽。

如果处理器被成功的建立，该函数将返回 TRUE；如果 parser 指向的不是合法的解析器，函数该函数将返回 FALSE。

注: 第二个参数函数名可以替换为一个数组，该数组由一个对象名和该对象名的一个方法名两个元素组成。

后退 | 起点 | 前进
xml_set_end_namespace_decl_handler | 上一级 | xml_set_notation_decl_handler


xml_set_notation_decl_handler

(PHP 3>= 3.0.6, PHP 4 )

xml_set_notation_decl_handler -- 建立注释声明处理器

Description

bool xml_set_notation_decl_handler ( resource parser, string handler)

为 parser 参数指定的 XML 解析器建立注释声明处理器函数。参数 start_element_handler 和 end_element_handler 为表示函数名称的字符串，这些函数必须在为 parser 指定的解析器调用 xml_parse() 函数时已存在。

注释声明是文档 DTD 的一部分，并有如下格式：
<!NOTATION
     name {system_id |
     public_id}>
。请参考 XML 1.0 参考的第 4.7 节以了解注释声明的定义。

由 handler 参数命名的函数名必须接受五个参数： handler ( resource parser, string notation_name, string base, string system_id, string public_id)

parser

第一个参数 parser 为指向要调用处理器的 XML 解析器的指针。

notation_name

该参数为以上注释格式定义中的 name 参数。

base

这个参数是解析注释声明的系统标识符（system_id）的基础。当前该参数通常都被设置为空字符串。

system_id

外部注释声明的系统标识符。

public_id

外部注释声明的公共标识符。

如果处理器函数名被设置为空字符串或者 FALSE，则该有问题的处理器将被屏蔽。

如果处理器被成功的建立，该函数将返回 TRUE；如果 parser 指向的不是合法的解析器，函数该函数将返回 FALSE。

注: 第二个参数函数名可以替换为一个数组，该数组由一个对象名和该对象名的一个方法名两个元素组成。

后退 | 起点 | 前进
xml_set_external_entity_ref_handler | 上一级 | xml_set_object


xml_set_object

(PHP 4 )

xml_set_object -- 在对象中使用 XML 解析器

描述

void xml_set_object ( resource parser, object object)

该函数使得 parser 指定的解析器可以被用在 object 对象中。所有的回叫函数（callback function）都可以由 xml_set_element_handler() 等函数来设置，它们被假定为 object 对象的方法。

<?php
class xml  {
    var $parser;

    function xml()
    {
        $this->parser = xml_parser_create();

        xml_set_object($this->parser, &$this);
        xml_set_element_handler($this->parser, "tag_open", "tag_close");
        xml_set_character_data_handler($this->parser, "cdata");
    }

    function parse($data)
    {
        xml_parse($this->parser, $data);
    }

    function tag_open($parser, $tag, $attributes)
    {
        var_dump($parser, $tag, $attributes);
    }

    function cdata($parser, $cdata)
    {
        var_dump($parser, $cdata);
    }

    function tag_close($parser, $tag)
    {
        var_dump($parser, $tag);
    }

} // end of class xml

$xml_parser = new xml();
$xml_parser->parse("<A ID='hallo'>PHP</A>");
?>

后退 | 起点 | 前进
xml_set_notation_decl_handler | 上一级 | xml_set_processing_instruction_handler


xml_set_processing_instruction_handler

(PHP 3>= 3.0.6, PHP 4 )

xml_set_processing_instruction_handler -- 建立处理指令（PI）处理器

描述

bool xml_set_processing_instruction_handler ( resource parser, string handler)

为 parser 参数指定的 XML 解析器建立处理指令（PI）处理器函数。参数 start_element_handler 和 end_element_handler 为表示函数名称的字符串，这些函数必须在为 parser 指定的解析器调用 xml_parse() 函数时已存在。

处理指令有如下格式：

<?
       target
       data?>

您可以将 PHP 代码放置在类似的标识符中，但要注意一个限制：在 XML 处理指令（PI）中，PI 的终止符（?>）不能被引号引用，因此该字符序列不应该在您用 PI 嵌入到 XML 文档中的 PHP 代码中出现。否则，剩下的 PHP 代码，包括“真正”的 PI 终止符将被当作字符数据处理。

由 handler 参数命名的函数名必须接受三个参数： handler ( resource parser, string target, string data)

parser

第一个参数 parser 为指向要调用处理器的 XML 解析器的指针。

target

第二个参数 target 为 PI 对象（PI target）。

data

第二个参数 target 为 PI 数据（PI data）。

如果处理器函数名被设置为空字符串或者 FALSE，则该有问题的处理器将被屏蔽。

如果处理器被成功的建立，该函数将返回 TRUE；如果 parser 指向的不是合法的解析器，函数该函数将返回 FALSE。

注: 第二个参数函数名可以替换为一个数组，该数组由一个对象名和该对象名的一个方法名两个元素组成。

后退 | 起点 | 前进
xml_set_object | 上一级 | xml_set_start_namespace_decl_handler


xml_set_start_namespace_decl_handler

(PHP 4 >= 4.0.5)

xml_set_start_namespace_decl_handler -- 建立起始命名空间声明处理器

描述

bool xml_set_start_namespace_decl_handler ( resource pind, string hdl)

警告

该文档目前尚无参考文档；仅参数列表可用。

注: 第二个参数函数名可以替换为一个数组，该数组由一个对象名和该对象名的一个方法名两个元素组成。

后退 | 起点 | 前进
xml_set_processing_instruction_handler | 上一级 | xml_set_unparsed_entity_decl_handler


xml_set_unparsed_entity_decl_handler

(PHP 3>= 3.0.6, PHP 4 )

xml_set_unparsed_entity_decl_handler -- 建立未解析实体定义声明处理器

描述

bool xml_set_unparsed_entity_decl_handler ( resource parser, string handler)

为 parser 参数指定的 XML 解析器建立未解析实体定义声明处理器函数。参数 start_element_handler 和 end_element_handler 为表示函数名称的字符串，这些函数必须在为 parser 指定的解析器调用 xml_parse() 函数时已存在。

当 XML 解析器遇到如下含有 NDATA 声明的外部实体定义声明时，该处理器将被调用：
<!ENTITY name {publicId | systemId}
        NDATA notationName>

请参阅 XML 1.0 参考的第 4.2.2 节以获取有关已声明外部实体注释定义的信息。

由 handler 参数命名的函数名必须接受六个参数： handler ( resource parser, string entity_name, string base, string system_id, string public_id, string notation_name)

parser

第一个参数 parser 为指向要调用处理器的 XML 解析器的指针。

entity_name

将被定义的实体名。

base

这个参数是解析外部实体的系统标识符（system_id）的基础。当前该参数通常都被设置为空字符串。

system_id

外部实体的系统标识符。

public_id

外部实体的公共标识符。

notation_name

该实体的注释名（请参阅 xml_set_notation_decl_handler()）。

如果处理器函数名被设置为空字符串或者 FALSE，则该有问题的处理器将被屏蔽。

如果处理器被成功的建立，该函数将返回 TRUE；如果 parser 指向的不是合法的解析器，函数该函数将返回 FALSE。

注: 第二个参数函数名可以替换为一个数组，该数组由一个对象名和该对象名的一个方法名两个元素组成。

后退 | 起点 | 前进
xml_set_start_namespace_decl_handler | 上一级 | XML-RPC functions


XML-RPC functions

PHP 手册
后退 前进

CVI. XML-RPC functions

介绍

These functions can be used to write XML-RPC servers and clients. You can find more information about XML-RPC at http://www.xmlrpc.com/, and more documentation on this extension and it's functions at http://xmlrpc-epi.sourceforge.net/.

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

需求

无需外部库文件就可以加入本扩展模块的支持。

安装

XML-RPC support in PHP is not enabled by default. You will need to use the --with-xmlrpc configuration option when compiling PHP to enable XML-RPC support. This extension is bundled into PHP as of 4.1.0.

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. XML-RPC configuration options

Name | Default | Changeable
xmlrpc_errors | "0" | PHP_INI_SYSTEM
xmlrpc_error_number | "0" | PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

目录
xmlrpc_decode_request — Decodes XML into native PHP types
xmlrpc_decode — Decodes XML into native PHP types
xmlrpc_encode_request — Generates XML for a method request
xmlrpc_encode — Generates XML for a PHP value
xmlrpc_get_type — Gets xmlrpc type for a PHP value. Especially useful for base64 and datetime strings
xmlrpc_parse_method_descriptions — Decodes XML into a list of method descriptions
xmlrpc_server_add_introspection_data — Adds introspection documentation
xmlrpc_server_call_method — Parses XML requests and call methods
xmlrpc_server_create — Creates an xmlrpc server
xmlrpc_server_destroy — Destroys server resources
xmlrpc_server_register_introspection_callback — Register a PHP function to generate documentation
xmlrpc_server_register_method — Register a PHP function to resource method matching method_name
xmlrpc_set_type — Sets xmlrpc type, base64 or datetime, for a PHP string value

后退 | 起点 | 前进
xml_set_unparsed_entity_decl_handler | 上一级 | xmlrpc_decode_request


xmlrpc_decode_request

(PHP 4 >= 4.1.0)

xmlrpc_decode_request -- Decodes XML into native PHP types

Description

array xmlrpc_decode_request ( string xml, string method [, string encoding])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
XML-RPC functions | 上一级 | xmlrpc_decode


xmlrpc_decode

(PHP 4 >= 4.1.0)

xmlrpc_decode -- Decodes XML into native PHP types

Description

array xmlrpc_decode ( string xml [, string encoding])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
xmlrpc_decode_request | 上一级 | xmlrpc_encode_request


xmlrpc_encode_request

(PHP 4 >= 4.1.0)

xmlrpc_encode_request -- Generates XML for a method request

Description

string xmlrpc_encode_request ( string method, mixed params)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
xmlrpc_decode | 上一级 | xmlrpc_encode


xmlrpc_encode

(PHP 4 >= 4.1.0)

xmlrpc_encode -- Generates XML for a PHP value

Description

string xmlrpc_encode ( mixed value)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
xmlrpc_encode_request | 上一级 | xmlrpc_get_type


xmlrpc_get_type

(PHP 4 >= 4.1.0)

xmlrpc_get_type -- Gets xmlrpc type for a PHP value. Especially useful for base64 and datetime strings

Description

string xmlrpc_get_type ( mixed value)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
xmlrpc_encode | 上一级 | xmlrpc_parse_method_descriptions


xmlrpc_parse_method_descriptions

(PHP 4 >= 4.1.0)

xmlrpc_parse_method_descriptions -- Decodes XML into a list of method descriptions

Description

array xmlrpc_parse_method_descriptions ( string xml)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
xmlrpc_get_type | 上一级 | xmlrpc_server_add_introspection_data


xmlrpc_server_add_introspection_data

(PHP 4 >= 4.1.0)

xmlrpc_server_add_introspection_data -- Adds introspection documentation

Description

int xmlrpc_server_add_introspection_data ( resource server, array desc)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
xmlrpc_parse_method_descriptions | 上一级 | xmlrpc_server_call_method


xmlrpc_server_call_method

(PHP 4 >= 4.1.0)

xmlrpc_server_call_method -- Parses XML requests and call methods

Description

mixed xmlrpc_server_call_method ( resource server, string xml, mixed user_data [, array output_options])

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
xmlrpc_server_add_introspection_data | 上一级 | xmlrpc_server_create


xmlrpc_server_create

(PHP 4 >= 4.1.0)

xmlrpc_server_create -- Creates an xmlrpc server

Description

resource xmlrpc_server_create ( void)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
xmlrpc_server_call_method | 上一级 | xmlrpc_server_destroy


xmlrpc_server_destroy

(PHP 4 >= 4.1.0)

xmlrpc_server_destroy -- Destroys server resources

Description

void xmlrpc_server_destroy ( resource server)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
xmlrpc_server_create | 上一级 | xmlrpc_server_register_introspection_callback


xmlrpc_server_register_introspection_callback

(PHP 4 >= 4.1.0)

xmlrpc_server_register_introspection_callback -- Register a PHP function to generate documentation

Description

bool xmlrpc_server_register_introspection_callback ( resource server, string function)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
xmlrpc_server_destroy | 上一级 | xmlrpc_server_register_method


xmlrpc_server_register_method

(PHP 4 >= 4.1.0)

xmlrpc_server_register_method -- Register a PHP function to resource method matching method_name

Description

bool xmlrpc_server_register_method ( resource server, string method_name, string function)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
xmlrpc_server_register_introspection_callback | 上一级 | xmlrpc_set_type


xmlrpc_set_type

(PHP 4 >= 4.1.0)

xmlrpc_set_type -- Sets xmlrpc type, base64 or datetime, for a PHP string value

Description

bool xmlrpc_set_type ( string value, string type)

警告

本扩展模块是实验性的。该模块的行为，包括其函数的名称以及其它任何关于此模块的文档可能会在没有通知的情况下随 PHP 以后的发布而改变。我们提醒您在使用本扩展模块的同时自担风险。

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
xmlrpc_server_register_method | 上一级 | XSLT functions


XSLT functions

PHP 手册
后退 前进

CVII. XSLT functions

介绍

This PHP extension provides a processor independent API to XSLT transformations. Currently this extension only supports the Sablotron library from the Ginger Alliance. Support is planned for other libraries, such as the Xalan library or the libxslt library.

XSLT (Extensible Stylesheet Language (XSL) Transformations) is a language for transforming XML documents into other XML documents. It is a standard defined by The World Wide Web Consortium (W3C). Information about XSLT and related technologies can be found at http://www.w3.org/TR/xslt.

注: This extension is different than the sablotron extension distributed with versions of PHP prior to PHP 4.1, currently only the new XSLT extension in PHP 4.1 is supported. If you need support for the old extension, please ask your questions on the PHP mailing lists.

需求

This extension uses Sablotron and expat, which can both be found at http://www.gingerall.com/. Binaries are provided as well as source.

安装

On UNIX, run configure with the --enable-xslt --with-xslt-sablot options. The Sablotron library should be installed somewhere your compiler can find it.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

目录
xslt_create — Create a new XSLT processor
xslt_errno — Return a error number
xslt_error — Return a error string
xslt_free — Free XSLT processor
xslt_process — Perform an XSLT transformation
xslt_set_base — Set the base URI for all XSLT transformations
xslt_set_encoding — Set the encoding for the parsing of XML documents
xslt_set_error_handler — Set an error handler for a XSLT processor
xslt_set_log — Set the log file to write log messages to
xslt_set_sax_handler — Set SAX handlers for a XSLT processor
xslt_set_sax_handlers — Set the SAX handlers to be called when the XML document gets processed
xslt_set_scheme_handler — Set Scheme handlers for a XSLT processor
xslt_set_scheme_handlers — Set the scheme handlers for the XSLT processor

后退 | 起点 | 前进
xmlrpc_set_type | 上一级 | xslt_create


xslt_create

(PHP 4 >= 4.0.3)

xslt_create -- Create a new XSLT processor

Description

resource xslt_create ( void)

Create and return a new XSLT processor resource for manipulation by the other XSLT functions.

后退 | 起点 | 前进
XSLT functions | 上一级 | xslt_errno


xslt_errno

(PHP 4 >= 4.0.3)

xslt_errno -- Return a error number

Description

int xslt_errno ( resource xh)

Return an error code describing the last error that occured on the passed XSLT processor.

后退 | 起点 | 前进
xslt_create | 上一级 | xslt_error


xslt_error

(PHP 4 >= 4.0.3)

xslt_error -- Return a error string

Description

mixed xslt_error ( resource xh)

Return a string describing the last error that occured on the passed XSLT processor.

例子 1. Handling errors using the xslt_error() and xslt_errno() functions.

<?php

$xh = xslt_create();
$result = xslt_process($xh, 'dog.xml', 'pets.xsl');
if (!$result) {
    die(sprintf("Cannot process XSLT document [%d]: %s",
                xslt_errno($xh), xslt_error($xh)));
}

print($result);

xslt_free($xh);
?>

后退 | 起点 | 前进
xslt_errno | 上一级 | xslt_free


xslt_free

(PHP 4 >= 4.0.3)

xslt_free -- Free XSLT processor

Description

void xslt_free ( resource xh)

Free the XSLT processor identified by the given handle.

后退 | 起点 | 前进
xslt_error | 上一级 | xslt_process


xslt_process

(PHP 4 >= 4.0.3)

xslt_process -- Perform an XSLT transformation

Description

mixed xslt_process ( resource xh, string xml, string xsl [, string result [, array arguments [, array parameters]]])

The xslt_process() function is the crux of the new XSLT extension. It allows you to perform an XSLT transformation using almost any type of input source. This is accomplished through the use of argument buffers -- a concept taken from the Sablotron XSLT processor (currently the only XSLT processor this extension supports).

The simplest type of transformation with the xslt_process() function is the transformation of an XML file with an XSLT file, placing the result in a third file containing the new XML (or HTML) document. Doing this with sablotron is really quite easy...

例子 1. Using the xslt_process() to transform an XML file and a XSL file to a new XML file

<?php

// Allocate a new XSLT processor
$xh = xslt_create();

// Process the document
if (xslt_process($xh, 'sample.xml', 'sample.xsl', 'result.xml')) {
    print "SUCCESS, sample.xml was transformed by sample.xsl into result.xml";
    print ", result.xml has the following contents\n<br>\n";
    print "<pre>\n";
    readfile('result.xml');
    print "</pre>\n";
}
else {
    print "Sorry, sample.xml could not be transformed by sample.xsl into";
    print "  result.xml the reason is that " . xslt_error($xh) . " and the ";
    print "error code is " . xslt_errno($xh);
}

xslt_free($xh);

?>

While this functionality is great, many times, especially in a web environment, you want to be able to print out your results directly. Therefore, if you omit the third argument to the xslt_process() function (or provide a NULL value for the argument), it will automatically return the value of the XSLT transformation, instead of writing it to a file...

例子 2. Using the xslt_process() to transform an XML file and a XSL file to a variable containing the resulting XML data

<?php

// Allocate a new XSLT processor
$xh = xslt_create();

// Process the document, returning the result into the $result variable
$result = xslt_process($xh, 'sample.xml', 'sample.xsl');
if ($result) {
    print "SUCCESS, sample.xml was transformed by sample.xsl into the \$result";
    print " variable, the \$result variable has the following contents\n<br>\n";
    print "<pre>\n";
    print $result;
    print "</pre>\n";
}
else {
    print "Sorry, sample.xml could not be transformed by sample.xsl into";
    print "  the \$result variable the reason is that " . xslt_error($xh) .
    print " and the error code is " . xslt_errno($xh);
}

xslt_free($xh);

?>

The above two cases are the two simplest cases there are when it comes to XSLT transformation and I'd dare say that they are the most common cases, however, sometimes you get your XML and XSLT code from external sources, such as a database or a socket. In these cases you'll have the XML and/or XSLT data in a variable -- and in production applications the overhead of dumping these to file may be too much. This is where XSLT's "argument" syntax, comes to the rescue. Instead of files as the XML and XSLT arguments to the xslt_process() function, you can specify "argument place holders" which are then subsituted by values given in the arguments array (5th parameter to the xslt_process() function). The following is an example of processing XML and XSLT into a result variable without the use of files at all.

例子 3. Using the xslt_process() to transform a variable containing XML data and a variable containing XSL data into a variable containing the resulting XML data

<?php
// $xml and $xsl contain the XML and XSL data

$arguments = array(
     '/_xml' => $xml,
     '/_xsl' => $xsl
);

// Allocate a new XSLT processor
$xh = xslt_create();

// Process the document
$result = xslt_process($xh, 'arg:/_xml', 'arg:/_xsl', NULL, $arguments);
if ($result) {
    print "SUCCESS, sample.xml was transformed by sample.xsl into the \$result";
    print " variable, the \$result variable has the following contents\n<br>\n";
    print "<pre>\n";
    print $result;
    print "</pre>\n";
}
else {
    print "Sorry, sample.xml could not be transformed by sample.xsl into";
    print "  the \$result variable the reason is that " . xslt_error($xh) .
    print " and the error code is " . xslt_errno($xh);
}
xslt_free($xh);
?>

Finally, the last argument to the xslt_process() function is any parameters that you want to pass to the XSLT document. These parameters can then be accessed within your XSL files using the <xsl:param name="parameter_name"> instruction.

后退 | 起点 | 前进
xslt_free | 上一级 | xslt_set_base


xslt_set_base

(PHP 4 >= 4.0.5)

xslt_set_base -- Set the base URI for all XSLT transformations

Description

void xslt_set_base ( resource xh, string uri)

Sets the base URI for all XSLT transformations, the base URI is used with Xpath instructions to resolve document() and other commands which access external resources.

后退 | 起点 | 前进
xslt_process | 上一级 | xslt_set_encoding


xslt_set_encoding

(PHP 4 >= 4.0.5)

xslt_set_encoding -- Set the encoding for the parsing of XML documents

Description

void xslt_set_encoding ( resource xh, string encoding)

Set the output encoding for the XSLT transformations. When using the Sablotron backend this option is only available when you compile Sablotron with encoding support.

后退 | 起点 | 前进
xslt_set_base | 上一级 | xslt_set_error_handler


xslt_set_error_handler

(PHP 4 >= 4.0.4)

xslt_set_error_handler -- Set an error handler for a XSLT processor

Description

void xslt_set_error_handler ( resource xh, mixed handler)

Set an error handler function for the XSLT processor given by xh, this function will be called whenever an error occurs in the XSLT transformation (this function is also called for notices).

后退 | 起点 | 前进
xslt_set_encoding | 上一级 | xslt_set_log


xslt_set_log

(PHP 4 >= 4.0.6)

xslt_set_log -- Set the log file to write log messages to

Description

void xslt_set_log ( resource xh, mixed log)

xh

A reference to the XSLT parser.

log

This parameter is either a boolean value which toggles logging on and off, or a string containing the logfile in which log errors too.

This function allows you to set the file in which you want XSLT log messages to, XSLT log messages are different than error messages, in that log messages are not actually error messages but rather messages related to the state of the XSLT processor. They are useful for debugging XSLT, when something goes wrong.

By default logging is disabled, in order to enable logging you must first call xslt_set_log() with a boolean parameter which enables logging, then if you want to set the log file to debug to, you must then pass it a string containing the filename:

例子 1. Using the XSLT Logging features

<?php

$xh = xslt_create();
xslt_set_log($xh, true);
xslt_set_log($xh, getcwd() . 'myfile.log');

$result = xslt_process($xh, 'dog.xml', 'pets.xsl');
print($result);

xslt_free($xh);
?>

后退 | 起点 | 前进
xslt_set_error_handler | 上一级 | xslt_set_sax_handler


xslt_set_sax_handler

(4.0.3 - 4.0.6 only)

xslt_set_sax_handler -- Set SAX handlers for a XSLT processor

Description

void xslt_set_sax_handler ( resource xh, array handlers)

Set SAX handlers on the resource handle given by xh. SAX handlers should be a two dimensional array with the format (all top level elements are optional):

array(
[document] =>
    array(
        start document handler,
        end document handler
    ),
[element] =>
    array(
        start element handler,
        end element handler
    ),
[namespace] =>
    array(
        start namespace handler,
        end namespace handler
    ),
[comment] => comment handler,
[pi] => processing instruction handler,
[character] => character data handler
)

后退 | 起点 | 前进
xslt_set_log | 上一级 | xslt_set_sax_handlers


xslt_set_sax_handlers

(PHP 4 >= 4.0.6)

xslt_set_sax_handlers -- Set the SAX handlers to be called when the XML document gets processed

Description

void xslt_set_sax_handlers ( resource processor, array handlers)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
xslt_set_sax_handler | 上一级 | xslt_set_scheme_handler


xslt_set_scheme_handler

(4.0.5 - 4.0.6 only)

xslt_set_scheme_handler -- Set Scheme handlers for a XSLT processor

Description

void xslt_set_scheme_handler ( resource xh, array handlers)

Set Scheme handlers on the resource handle given by xh. Scheme handlers should be an array with the format (all elements are optional):

array(
[get_all] => get all handler,
[open] => open handler,
[get] => get handler,
[put] => put handler,
[close] => close handler
)

后退 | 起点 | 前进
xslt_set_sax_handlers | 上一级 | xslt_set_scheme_handlers


xslt_set_scheme_handlers

(PHP 4 >= 4.0.6)

xslt_set_scheme_handlers -- Set the scheme handlers for the XSLT processor

Description

void xslt_set_scheme_handlers ( resource processor, array handlers)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
xslt_set_scheme_handler | 上一级 | YAZ functions


YAZ functions

PHP 手册
后退 前进

CVIII. YAZ functions

介绍

This extension offers a PHP interface to the YAZ toolkit that implements the Z39.50 protocol for information retrieval. With this extension you can easily implement a Z39.50 origin (client) that searches or scans Z39.50 targets (servers) in parallel.

The module hides most of the complexity of Z39.50 so it should be fairly easy to use. It supports persistent stateless connections very similar to those offered by the various SQL APIs that are available for PHP. This means that sessions are stateless but shared amongst users, thus saving the connect and initialize phase steps in most cases.

YAZ is available at http://www.indexdata.dk/yaz/. You can find news information, example scripts, etc. for this extension at http://www.indexdata.dk/phpyaz/.

安装

Compile YAZ and install it. Build PHP with your favourite modules and add option --with-yaz. Your task is roughly the following:

gunzip -c yaz-1.6.tar.gz|tar xf -
gunzip -c php-4.0.X.tar.gz|tar xf -
cd yaz-1.6
./configure --prefix=/usr
make
make install
cd ../php-4.0.X
./configure --with-yaz=/usr/bin
make
make install

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

表格 1. YAZ configuration options

Name | Default | Changeable
yaz.max_links | "100" | PHP_INI_ALL
yaz.log_file | "" | PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

范例

PHP/YAZ keeps track of connections with targets (Z-Associations). A positive integer represents the ID of a particular association.

例子 1. Parallel searching using YAZ()

The script below demonstrates the parallel searching feature of the API. When invoked with no arguments it prints a query form; else (arguments are supplied) it searches the targets as given in in array host.

$num_hosts = count ($host);
if (empty($term) || count($host) == 0) {
    echo '<form method="get">
    <input type="checkbox"
    name="host[]" value="bagel.indexdata.dk/gils">
        GILS test
    <input type="checkbox"
    name="host[]" value="localhost:9999/Default">
        local test
    <input type="checkbox" checked="1"
    name="host[]" value="z3950.bell-labs.com/books">
        BELL Labs Library
    <br>
    RPN Query:
    <input type="text" size="30" name="term">
    <input type="submit" name="action" value="Search">
    ';
} else {
    echo 'You searced for ' . htmlspecialchars($term) . '<br>';
    for ($i = 0; $i < $num_hosts; $i++) {
        $id[] = yaz_connect($host[$i]);
        yaz_syntax($id[$i],"sutrs");
        yaz_search($id[$i],"rpn",$term);
    }
    yaz_wait();
    for ($i = 0; $i < $num_hosts; $i++) {
        echo '<hr>' . $host[$i] . ":";
        $error = yaz_error($id[$i]);
        if (!empty($error)) {
            echo "Error: $error";
        } else {
            $hits = yaz_hits($id[$i]);
            echo "Result Count $hits";
        }
        echo '<dl>';
        for ($p = 1; $p <= 10; $p++) {
            $rec = yaz_record($id[$i],$p,"string");
            if (empty($rec)) continue;
            echo "<dt><b>$p</b></dt><dd>";
            echo ereg_replace("\n", "<br>\n",$rec);
            echo "</dd>";
        }
        echo '</dl>';
    }
}

目录
yaz_addinfo — Returns additional error information
yaz_ccl_conf — Configure CCL parser
yaz_ccl_parse — Invoke CCL Parser
yaz_close — Closes a YAZ connection
yaz_connect — Prepares for a connection and Z-association to a Z39.50 target.
yaz_database — Specifies the databases within a session
yaz_element — Specifies Element-Set Name for retrieval
yaz_errno — Returns error number
yaz_error — Returns error description
yaz_hits — Returns number of hits for last search
yaz_itemorder — Prepares for Z39.50 Item Order with an ILL-Request package
yaz_present — Prepares for retrieval (Z39.50 present).
yaz_range — Specifies the maximum number of records to retrieve
yaz_record — Returns a record
yaz_scan_result — Returns Scan Response result
yaz_scan — Prepares for a scan
yaz_search — Prepares for a search
yaz_sort — Sets sorting criteria
yaz_syntax — Specifies the preferred record syntax for retrieval.
yaz_wait — Wait for Z39.50 requests to complete

后退 | 起点 | 前进
xslt_set_scheme_handlers | 上一级 | yaz_addinfo


yaz_addinfo

(PHP 4 >= 4.0.1)

yaz_addinfo -- Returns additional error information

Description

int yaz_addinfo ( int id)

Returns additional error message for target (last request). An empty string is returned if last operation was a success or if no additional information was provided by the target.

后退 | 起点 | 前进
YAZ functions | 上一级 | yaz_ccl_conf


yaz_ccl_conf

(PHP 4 >= 4.0.5)

yaz_ccl_conf -- Configure CCL parser

Description

int yaz_ccl_conf ( int id, array config)

This function configures the CCL query parser for a target with definitions of access points (CCL qualifiers) and their mapping to RPN. To map a specific CCL query to RPN afterwards call the yaz_ccl_parse() function. Each index of the array config is the name of a CCL field and the corresponding value holds a string that specifies a mapping to RPN. The mapping is a sequence of attribute-type, attribute-value pairs. Attribute-type and attribute-value is separated by an equal sign (=). Each pair is separated by white space.

例子 1. CCL configuration

In the example below, the CCL parser is configured to support three CCL fields: ti, au and isbn. Each field is mapped to their BIB-1 equivalent. It is assumed that variable $id is a target ID.

$field["ti"] = "1=4";
      $field["au"] = "1=1";
      $field["isbn"] = "1=7";
      yaz_ccl_conf($id,$field);

后退 | 起点 | 前进
yaz_addinfo | 上一级 | yaz_ccl_parse


yaz_ccl_parse

(PHP 4 >= 4.0.5)

yaz_ccl_parse -- Invoke CCL Parser

Description

int yaz_ccl_parse ( int id, string query, array & result)

This function invokes the CCL parser. It converts a given CCL FIND query to an RPN query which may be passed to the yaz_search() function to perform a search. To define a set of valid CCL fields call yaz_ccl_conf() prior to this function. If the supplied query was successfully converted to RPN, this function returns TRUE, and the index rpn of the supplied array result holds a valid RPN query. If the query could not be converted (because of invalid syntax, unknown field, etc.) this function returns FALSE and three indexes are set in the resulting array to indicate the cause of failure: errorcodeCCL error code (integer), errorstringCCL error string, and errorposapproximate position in query of failure (integer is character position).

后退 | 起点 | 前进
yaz_ccl_conf | 上一级 | yaz_close


yaz_close

(PHP 4 >= 4.0.1)

yaz_close -- Closes a YAZ connection

Description

int yaz_close ( int id)

Closes the Z-association given by id. The id is a target ID as returned by a previous yaz_connect() command.

后退 | 起点 | 前进
yaz_ccl_parse | 上一级 | yaz_connect


yaz_connect

(PHP 4 >= 4.0.1)

yaz_connect -- Prepares for a connection and Z-association to a Z39.50 target.

Description

int yaz_connect ( string zurl [, mixed options])

This function returns a positive ID on success; zero on failure.

yaz_connect() prepares for a connection to a Z39.50 target. The zurl argument takes the form host[:port][/database]. If port is omitted 210 is used. If database is omitted Default is used. This function is non-blocking and doesn't attempt to establish a socket - it merely prepares a connect to be performed later when yaz_wait() is called.

If the second argument, options, is given as a string it is treated as the Z39.50 V2 authentication string (OpenAuth).

If options is given as an array the contents of the array serves as options. Note that array options are only supported for PHP 4.1.0 and later.

yaz_connect() options

user

Username for authentication.

group

Group for authentication.

password

Password for authentication.

cookie

Cookie for session (YAZ proxy).

proxy

Proxy for connection (YAZ proxy).

persistent

A boolean. If TRUE the connection is persistent; If FALSE the connection is not persistent. By default connections are persistent.

piggyback

A boolean. If TRUE piggyback is enabled for searches; If FALSE piggyback is disabled. By default piggyback is enabled. Enabling piggyback is more efficient and usually saves a network-round-trip for first time fetches of records. However, a few Z39.50 targets doesn't support piggyback or they ignore element set names. For those, piggyback should be disabled.

后退 | 起点 | 前进
yaz_close | 上一级 | yaz_database


yaz_database

(PHP 4 >= 4.0.6)

yaz_database -- Specifies the databases within a session

Description

int yaz_database ( int id, string databases)

This function specifies one or more databases to be used in search, retrieval, etc. - overriding databases specified in call to yaz_connect(). Multiple databases are separated by a plus sign +.

This function allows you to use different sets of databases within a session.

Returns TRUE on success; FALSE on error.

后退 | 起点 | 前进
yaz_connect | 上一级 | yaz_element


yaz_element

(PHP 4 >= 4.0.1)

yaz_element -- Specifies Element-Set Name for retrieval

Description

int yaz_element ( int id, string elementset)

This function is used in conjunction with yaz_search() and yaz_present() to specify the element set name for records to be retrieved. Most servers support F (full) and B (brief).

Returns TRUE on success; FALSE on error.

后退 | 起点 | 前进
yaz_database | 上一级 | yaz_errno


yaz_errno

(PHP 4 >= 4.0.1)

yaz_errno -- Returns error number

Description

int yaz_errno ( int id)

Returns error for target (last request). A positive value is returned if the target returned a diagnostic code; a value of zero is returned if no errors occurred (success); negative value is returned for other errors (such as when the target closed connection, etc).

yaz_errno() should be called after network activity for each target - (after yaz_wait() returns) to determine the success or failure of the last operation (e.g. search).

后退 | 起点 | 前进
yaz_element | 上一级 | yaz_error


yaz_error

(PHP 4 >= 4.0.1)

yaz_error -- Returns error description

Description

string yaz_error ( int id)

Returns error message for target (last request). An empty string is returned if last operation was a success.

yaz_error() returns an english text message corresponding to the last error number as returned by yaz_errno().

后退 | 起点 | 前进
yaz_errno | 上一级 | yaz_hits


yaz_hits

(PHP 4 >= 4.0.1)

yaz_hits -- Returns number of hits for last search

Description

int yaz_hits ( int id)

yaz_hits() returns number of hits for last search.

后退 | 起点 | 前进
yaz_error | 上一级 | yaz_itemorder


yaz_itemorder

(PHP 4 >= 4.0.5)

yaz_itemorder -- Prepares for Z39.50 Item Order with an ILL-Request package

Description

int yaz_itemorder ( array args)

This function prepares for an Extended Services request using the Profile for the Use of Z39.50 Item Order Extended Service to Transport ILL (Profile/1). See this and the specification. The args parameter must be a hash array with information about the Item Order request to be sent. The key of the hash is the name of the corresponding ASN.1 tag path. For example, the ISBN below the Item-ID has the key item-id,ISBN.

The ILL-Request parameters are:

protocol-version-num
transaction-id,initial-requester-id,person-or-institution-symbol,person
transaction-id,initial-requester-id,person-or-institution-symbol,institution
transaction-id,initial-requester-id,name-of-person-or-institution,name-of-person
transaction-id,initial-requester-id,name-of-person-or-institution,name-of-institution
transaction-id,transaction-group-qualifier
transaction-id,transaction-qualifier
transaction-id,sub-transaction-qualifier
service-date-time,this,date
service-date-time,this,time
service-date-time,original,date
service-date-time,original,time
requester-id,person-or-institution-symbol,person
requester-id,person-or-institution-symbol,institution
requester-id,name-of-person-or-institution,name-of-person
requester-id,name-of-person-or-institution,name-of-institution
responder-id,person-or-institution-symbol,person
responder-id,person-or-institution-symbol,institution
responder-id,name-of-person-or-institution,name-of-person
responder-id,name-of-person-or-institution,name-of-institution
transaction-type
delivery-address,postal-address,name-of-person-or-institution,name-of-person
delivery-address,postal-address,name-of-person-or-institution,name-of-institution
delivery-address,postal-address,extended-postal-delivery-address
delivery-address,postal-address,street-and-number
delivery-address,postal-address,post-office-box
delivery-address,postal-address,city
delivery-address,postal-address,region
delivery-address,postal-address,country
delivery-address,postal-address,postal-code
delivery-address,electronic-address,telecom-service-identifier
delivery-address,electronic-address,telecom-service-addreess
billing-address,postal-address,name-of-person-or-institution,name-of-person
billing-address,postal-address,name-of-person-or-institution,name-of-institution
billing-address,postal-address,extended-postal-delivery-address
billing-address,postal-address,street-and-number
billing-address,postal-address,post-office-box
billing-address,postal-address,city
billing-address,postal-address,region
billing-address,postal-address,country
billing-address,postal-address,postal-code
billing-address,electronic-address,telecom-service-identifier
billing-address,electronic-address,telecom-service-addreess
ill-service-type
requester-optional-messages,can-send-RECEIVED
requester-optional-messages,can-send-RETURNED
requester-optional-messages,requester-SHIPPED
requester-optional-messages,requester-CHECKED-IN
search-type,level-of-service
search-type,need-before-date
search-type,expiry-date
search-type,expiry-flag
place-on-hold
client-id,client-name
client-id,client-status
client-id,client-identifier
item-id,item-type
item-id,call-number
item-id,author
item-id,title
item-id,sub-title
item-id,sponsoring-body
item-id,place-of-publication
item-id,publisher
item-id,series-title-number
item-id,volume-issue
item-id,edition
item-id,publication-date
item-id,publication-date-of-component
item-id,author-of-article
item-id,title-of-article
item-id,pagination
item-id,ISBN
item-id,ISSN
item-id,additional-no-letters
item-id,verification-reference-source
copyright-complicance
retry-flag
forward-flag
requester-note
forward-note

There are also a few parameters that are part of the Extended Services Request package and the ItemOrder package:

package-name
user-id
contact-name
contact-phone
contact-email
itemorder-item

后退 | 起点 | 前进
yaz_hits | 上一级 | yaz_present


yaz_present

(PHP 4 >= 4.0.5)

yaz_present -- Prepares for retrieval (Z39.50 present).

Description

int yaz_present ( void)

This function prepares for retrieval of records after a successful search. The yaz_range() should be called prior to this function to specify the range of records to be retrieved.

后退 | 起点 | 前进
yaz_itemorder | 上一级 | yaz_range


yaz_range

(PHP 4 >= 4.0.1)

yaz_range -- Specifies the maximum number of records to retrieve

Description

int yaz_range ( int id, int start, int number)

This function is used in conjunction with yaz_search() to specify the maximum number of records to retrieve (number) and the first record position (start). If this function is not invoked (only yaz_search()) start is set to 1 and number is set to 10.

Returns TRUE on success; FALSE on error.

后退 | 起点 | 前进
yaz_present | 上一级 | yaz_record


yaz_record

(PHP 4 >= 4.0.1)

yaz_record -- Returns a record

Description

int yaz_record ( int id, int pos, string type)

Returns record at position or empty string if no record exists at given position.

The yaz_record() function inspects a record in the current result set at the position specified. If no database record exists at the given position an empty string is returned. The argument, type, specifies the form of the returned record. If type is "string" the record is returned in a string representation suitable for printing (for XML and SUTRS). If type is "array" the record is returned as an array representation (for structured records).

后退 | 起点 | 前进
yaz_range | 上一级 | yaz_scan_result


yaz_scan_result

(PHP 4 >= 4.0.5)

yaz_scan_result -- Returns Scan Response result

Description

array yaz_scan_result ( int id [, array & result])

Given a target ID this function returns and array with terms as received from the target in the last Scan Response. This function returns an array (0..n-1) where n is the number of terms returned. Each value is a pair where first item is term, second item is result-count. If the result is given it will be modified to hold additional information taken from the Scan Response: number (number of entries returned), stepsize (Step-size), position (position of term), status (Scan Status).

后退 | 起点 | 前进
yaz_record | 上一级 | yaz_scan


yaz_scan

(PHP 4 >= 4.0.5)

yaz_scan -- Prepares for a scan

Description

int yaz_scan ( int id, string type, string startterm [, array flags])

This function prepares for a Z39.50 Scan Request. Argument id specifies target ID. Starting term point for the scan is given by startterm. The form in which is the starting term is specified is given by type. Currently type rpn is supported. The optional flags specifies additional information to control the behaviour of the scan request. Three indexes are currently read from the flags: number (number of terms requested), position (preferred position of term) and stepSize (preferred step size). To actually tranfer the Scan Request to the target and receive the Scan Response, yaz_wait() must be called. Upon completion of yaz_wait() call yaz_error() and yaz_scan_result() to handle the response.

The syntax of startterm is similar to the RPN query as described in yaz_search(). The startterm consists of zero or more @attr-operator specifications, then followed by exactly one token.

例子 1. PHP function that scans titles

function scan_titles($id, $starterm) {
        yaz_scan($id,"rpn", "@attr 1=4 " . $starterm);
        yaz_wait();
        $errno = yaz_errno($id);
        if ($errno == 0) {
          $ar = yaz_scan_result($id,&$options);
          echo 'Scan ok; ';
          $ar = yaz_scan_result($id, &$options);
          while(list($key,$val)=each($options)) {
             echo "$key = $val &nbsp;";
          }
          echo '<br><table><tr><td>';
          while(list($key,list($k, $term, $tcount))=each($ar)) {
            if (empty($k)) continue;
            echo "<tr><td>$term</td><td>";
            echo $tcount;
            echo "</td></tr>";
          }
          echo '</table>';
        } else {
          echo "Scan failed. Error: " . yaz_error($id) . "<br>";
        }
      }

后退 | 起点 | 前进
yaz_scan_result | 上一级 | yaz_search


yaz_search

(PHP 4 >= 4.0.1)

yaz_search -- Prepares for a search

Description

int yaz_search ( int id, string type, string query)

yaz_search() prepares for a search on the target with given id. The type represents the query type - only "rpn" is supported now in which case the third argument specifies a Type-1 query (RPN). Like yaz_connect() this function is non-blocking and only prepares for a search to be executed later when yaz_wait() is called.

The RPN query

The RPN query is a textual represenation of the Type-1 query as defined by the Z39.50 standard. However, in the text representation as used by YAZ a prefix notation is used, that is the operater precedes the operands. The query string is a sequence of tokens where white space is ignored is ignored unless surrounded by double quotes. Tokens beginning with an at-character (@) are considered operators, otherwise they are treated as search terms.

表格 1. RPN Operators

Syntax | Description
@and query1 query2 | intersection of query1 and query2
@or query1 query2 | union of query1 and query2
@not query1 query2 | query1 and not query2
@set name | result set reference
@attrset set query | specifies attribute-set for query. This construction is only allowed once - in the beginning of the whole query
@attr set type=value query | applies attribute to query. The type and value are integers specifying the attribute-type and attribute-value respectively. The set, if given, specifies the attribute-set.

例子 1. Query Examples

Query
computer
matches documents where "computer" occur. No attributes are specified.

The Query
"donald knuth"
matches documents where "donald knuth" occur.

For the query
@attr 1=4 art
attribute type is 1 (Bib-1 use), attribute value is 4 Title), so this should match documents where art occur in the title.

Another more complex one:
@attrset gils @and @attr 1=4 art @attr 1=1003 "donald knuth"
The query as a whole uses the GILS attributeset. The query matches documents where art occur in the title and in which donald knuth occur in the author.

后退 | 起点 | 前进
yaz_scan | 上一级 | yaz_sort


yaz_sort

(PHP 4 >= 4.1.0)

yaz_sort -- Sets sorting criteria

Description

int yaz_sort ( int id, string criteria)

This function sets sorting criteria and enables Z39.50 Sort. Use this function together with yaz_search() or yaz_present(). Using this function alone doesn't have any effect. If used in conjunction with yaz_search() a Z39.50 Sort will be sent after a search response has been received and before any records are retrieved with Z39.50 Present. The criteria takes the form

field1 flags1 field2 flags2 ...

where field1 specifies primary attributes for sort, field2 seconds, etc.. The field specifies either numerical attribute combinations consisting of type=value pairs separated by comma (e.g. 1=4,2=1) ; or the field may specify a plain string criteria (e.g. title. The flags is a sequnce of the following characters which may not be separated by any white space.

Sort Flags

a

Sort ascending

d

Sort descending

i

Case insensitive sorting

s

Case sensitive sorting

例子 1. Sort Criterias

To sort on Bib1 attribute title, case insensitive, and ascending you'd use the following sort criteria:
1=4 ia

If the secondary sorting criteria should be author, case sensitive and ascending you'd use:
1=4 ia 1=1003 sa

后退 | 起点 | 前进
yaz_search | 上一级 | yaz_syntax


yaz_syntax

(PHP 4 >= 4.0.1)

yaz_syntax -- Specifies the preferred record syntax for retrieval.

Description

int yaz_syntax ( int id, string syntax)

The syntax is specified as an OID (Object Identifier) in a raw dot-notation (like 1.2.840.10003.5.10) or as one of the known registered record syntaxes (sutrs, usmarc, grs1, xml, etc.). This function is used in conjunction with yaz_search() and yaz_present() to specify the preferred record syntax for retrieval.

后退 | 起点 | 前进
yaz_sort | 上一级 | yaz_wait


yaz_wait

(PHP 4 >= 4.0.1)

yaz_wait -- Wait for Z39.50 requests to complete

Description

int yaz_wait ( [ array options])

This function carries out networked (blocked) activity for outstanding requests which have been prepared by the functions yaz_connect(), yaz_search(), yaz_present(), yaz_scan() and yaz_itemorder(). yaz_wait() returns when all targets have either completed all requests or aborted (in case of errors).

If the options array is given that holds options that change the behaviour of yaz_wait().

timeout

Sets timeout in seconds. If a target hasn't responded within the timeout it is considered dead and yaz_wait() returns. The default value for timeout is 15 seconds.

后退 | 起点 | 前进
yaz_syntax | 上一级 | YP/NIS Functions


YP/NIS Functions

PHP 手册
后退 前进

CIX. YP/NIS Functions

介绍

NIS (formerly called Yellow Pages) allows network management of important administrative files (e.g. the password file). For more information refer to the NIS manpage and Introduction to YP/NIS. There is also a book called Managing NFS and NIS by Hal Stern.

安装

To get these functions to work, you have to configure PHP with --with-yp(PHP 3) or --enable-yp(PHP 4).

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

YPERR_BADARGS (integer)

YPERR_BADDB (integer)

YPERR_BUSY (integer)

YPERR_DOMAIN (integer)

YPERR_KEY (integer)

YPERR_MAP (integer)

YPERR_NODOM (integer)

YPERR_NOMORE (integer)

YPERR_PMAP (integer)

YPERR_RESRC (integer)

YPERR_RPC (integer)

YPERR_YPBIND (integer)

YPERR_YPERR (integer)

YPERR_YPSERV (integer)

YPERR_VERS (integer)

目录
yp_all — Traverse the map and call a function on each entry
yp_cat — Return an array containing the entire map
yp_err_string — Returns the error string associated with the previous operation
yp_errno — Returns the error code of the previous operation
yp_first — Returns the first key-value pair from the named map
yp_get_default_domain — Fetches the machine's default NIS domain
yp_master — Returns the machine name of the master NIS server for a map
yp_match — Returns the matched line
yp_next — Returns the next key-value pair in the named map.
yp_order — Returns the order number for a map

后退 | 起点 | 前进
yaz_wait | 上一级 | yp_all


yp_all

(PHP 4 >= 4.0.6)

yp_all -- Traverse the map and call a function on each entry

Description

void yp_all ( string domain, string map, string callback)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
YP/NIS Functions | 上一级 | yp_cat


yp_cat

(PHP 4 >= 4.0.6)

yp_cat -- Return an array containing the entire map

Description

array yp_cat ( string domain, string map)

警告

该文档目前尚无参考文档；仅参数列表可用。

后退 | 起点 | 前进
yp_all | 上一级 | yp_err_string


yp_err_string

(PHP 4 >= 4.0.6)

yp_err_string -- Returns the error string associated with the previous operation

Description

string yp_err_string ( void)

yp_err_string() returns the error message associated with the previous operation. Useful to indicate what exactly went wrong.

例子 1. Example for NIS errors

<?php
    echo "Error: " . yp_err_string();
?>

See also yp_errno().

后退 | 起点 | 前进
yp_cat | 上一级 | yp_errno


yp_errno

(PHP 4 >= 4.0.6)

yp_errno -- Returns the error code of the previous operation

Description

int yp_errno ( void)

yp_errno() returns the error code of the previous operation.

Possible errors are:

1 args to function are bad
2 RPC failure - domain has been unbound
3 can't bind to server on this domain
4 no such map in server's domain
5 no such key in map
6 internal yp server or client error
7 resource allocation failure
8 no more records in map database
9 can't communicate with portmapper
10 can't communicate with ypbind
11 can't communicate with ypserv
12 local domain name not set
13 yp database is bad
14 yp version mismatch
15 access violation
16 database busy

See also yp_err_string().

后退 | 起点 | 前进
yp_err_string | 上一级 | yp_first


yp_first

(PHP 3>= 3.0.7, PHP 4 )

yp_first -- Returns the first key-value pair from the named map

Description

array yp_first ( string domain, string map)

yp_first() returns the first key-value pair from the named map in the named domain, otherwise FALSE.

例子 1. Example for the NIS first

<?php
$entry = yp_first($domain, "passwd.byname");
$key = $entry ["key"];
$value = $entry ["value"];
echo "First entry in this map has key " . $key . " and value " . $value;
?>

See also yp-get-default-domain()

后退 | 起点 | 前进
yp_errno | 上一级 | yp_get_default_domain


yp_get_default_domain

(PHP 3>= 3.0.7, PHP 4 )

yp_get_default_domain -- Fetches the machine's default NIS domain

Description

int yp_get_default_domain ( void)

yp_get_default_domain() returns the default domain of the node or FALSE. Can be used as the domain parameter for successive NIS calls.

A NIS domain can be described a group of NIS maps. Every host that needs to look up information binds itself to a certain domain. Refer to the documents mentioned at the beginning for more detailed information.

例子 1. Example for the default domain

<?php
$domain = yp_get_default_domain();
echo "Default NIS domain is: " . $domain;
?>

后退 | 起点 | 前进
yp_first | 上一级 | yp_master


yp_master

(PHP 3>= 3.0.7, PHP 4 )

yp_master -- Returns the machine name of the master NIS server for a map

Description

string yp_master ( string domain, string map)

yp_master() returns the machine name of the master NIS server for a map.

例子 1. Example for the NIS master

<?php
$number = yp_master ($domain, $mapname);
echo "Master for this map is: " . $master;
?>

See also yp-get-default-domain().

后退 | 起点 | 前进
yp_get_default_domain | 上一级 | yp_match


yp_match

(PHP 3>= 3.0.7, PHP 4 )

yp_match -- Returns the matched line

Description

string yp_match ( string domain, string map, string key)

yp_match() returns the value associated with the passed key out of the specified map or FALSE. This key must be exact.

例子 1. Example for NIS match

<?php
$entry = yp_match ($domain, "passwd.byname", "joe");
echo "Matched entry is: " . $entry;
?>

In this case this could be: joe:##joe:11111:100:Joe User:/home/j/joe:/usr/local/bin/bash

See also yp-get-default-domain()

后退 | 起点 | 前进
yp_master | 上一级 | yp_next


yp_next

(PHP 3>= 3.0.7, PHP 4 )

yp_next -- Returns the next key-value pair in the named map.

Description

array yp_next ( string domain, string map, string key)

yp_next() returns the next key-value pair in the named map after the specified key or FALSE.

例子 1. Example for NIS next

<?php
$entry = yp_next ($domain, "passwd.byname", "joe");

if (!$entry) {
    echo "No more entries found\n";
    <!-- echo yp_errno() . ": " . yp_err_string(); -->
}

$key = key ($entry);

echo "The next entry after joe has key " . $key
      . " and value " . $entry[$key];
?>

See also yp-get-default-domain().

后退 | 起点 | 前进
yp_match | 上一级 | yp_order


yp_order

(PHP 3>= 3.0.7, PHP 4 )

yp_order -- Returns the order number for a map

Description

int yp_order ( string domain, string map)

yp_order() returns the order number for a map or FALSE.

例子 1. Example for the NIS order

<?php
    $number = yp_order($domain,$mapname);
    echo "Order number for this map is: " . $number;
?>

See also yp-get-default-domain().

后退 | 起点 | 前进
yp_next | 上一级 | Zip File Functions (Read Only Access)


Zip File Functions (Read Only Access)

PHP 手册
后退 前进

CX. Zip File Functions (Read Only Access)

介绍

This module enables you to transparently read ZIP compressed archives and the files inside them.

需求

This module uses the functions of the ZZIPlib library by Guido Draheim. You need ZZIPlib version >= 0.10.6.

Note that ZZIPlib only provides a subset of functions provided in a full implementation of the ZIP compression algorithm and can only read ZIP file archives. A normal ZIP utility is needed to create the ZIP file archives read by this library.

安装

Zip support in PHP is not enabled by default. You will need to use the --with-zip configuration option when compiling PHP to enable zip support.

注: Zip support before PHP 4.1.0 is experimental. This section reflects the Zip extension as it exists in PHP 4.1.0 and later.

运行时配置

该扩展模块未定义任何设置指令。

资源类型

该扩展模块未定义任何资源类型。

预定义常量

该扩展模块未定义任何常量。

范例

This example opens a ZIP file archive, reads each file in the archive and prints out its contents. The test2.zip archive used in this example is one of the test archives in the ZZIPlib source distribution.

例子 1. Zip Usage Example

<?php

$zip = zip_open("/tmp/test2.zip");

if ($zip) {

    while ($zip_entry = zip_read($zip)) {
        echo "Name:               " . zip_entry_name($zip_entry) . "\n";
        echo "Actual Filesize:    " . zip_entry_filesize($zip_entry) . "\n";
        echo "Compressed Size:    " . zip_entry_compressedsize($zip_entry) . "\n";
        echo "Compression Method: " . zip_entry_compressionmethod($zip_entry) . "\n";

        if (zip_entry_open($zip, $zip_entry, "r")) {
            echo "File Contents:\n";
            $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
            echo "$buf\n";

            zip_entry_close($zip_entry);
        }
        echo "\n";

    }

    zip_close($zip);

}

?>
目录
zip_close — Close a Zip File Archive
zip_entry_close — Close a Directory Entry
zip_entry_compressedsize — Retrieve the Compressed Size of a Directory Entry
zip_entry_compressionmethod — Retrieve the Compression Method of a Directory Entry
zip_entry_filesize — Retrieve the Actual File Size of a Directory Entry
zip_entry_name — Retrieve the Name of a Directory Entry
zip_entry_open — Open a Directory Entry for Reading
zip_entry_read — Read From an Open Directory Entry
zip_open — Open a Zip File Archive
zip_read — Read Next Entry in a Zip File Archive

后退 | 起点 | 前进
yp_order | 上一级 | zip_close


zip_close

(PHP 4 >= 4.1.0)

zip_close -- Close a Zip File Archive

Description

void zip_close ( resource zip)

Closes a zip file archive. The parameter zip must be a zip archive previously opened by zip_open().

This function has no return value.

See also zip_open() and zip_read().

后退 | 起点 | 前进
Zip File Functions (Read Only Access) | 上一级 | zip_entry_close


zip_entry_close

(PHP 4 >= 4.1.0)

zip_entry_close -- Close a Directory Entry

Description

void zip_entry_close ( resource zip_entry)

Closes a directory entry specified by zip_entry. The parameter zip_entry must be a valid directory entry opened by zip_entry_open().

This function has no return value.

See also zip_entry_open() and zip_entry_read().

后退 | 起点 | 前进
zip_close | 上一级 | zip_entry_compressedsize


zip_entry_compressedsize

(PHP 4 >= 4.1.0)

zip_entry_compressedsize -- Retrieve the Compressed Size of a Directory Entry

Description

int zip_entry_compressedsize ( resource zip_entry)

Returns the compressed size of the directory entry specified by zip_entry. The parameter zip_entry is a valid directory entry returned by zip_read().

See also zip_open() and zip_read().

后退 | 起点 | 前进
zip_entry_close | 上一级 | zip_entry_compressionmethod


zip_entry_compressionmethod

(PHP 4 >= 4.1.0)

zip_entry_compressionmethod -- Retrieve the Compression Method of a Directory Entry

Description

string zip_entry_compressionmethod ( resource zip_entry)

Returns the compression method of the directory entry specified by zip_entry. The parameter zip_entry is a valid directory entry returned by zip_read().

See also zip_open() and zip_read().

后退 | 起点 | 前进
zip_entry_compressedsize | 上一级 | zip_entry_filesize


zip_entry_filesize

(PHP 4 >= 4.1.0)

zip_entry_filesize -- Retrieve the Actual File Size of a Directory Entry

Description

int zip_entry_filesize ( resource zip_entry)

Returns the actual size of the directory entry specified by zip_entry. The parameter zip_entry is a valid directory entry returned by zip_read().

See also zip_open() and zip_read().

后退 | 起点 | 前进
zip_entry_compressionmethod | 上一级 | zip_entry_name


zip_entry_name

(PHP 4 >= 4.1.0)

zip_entry_name -- Retrieve the Name of a Directory Entry

Description

string zip_entry_name ( resource zip_entry)

Returns the name of the directory entry specified by zip_entry. The parameter zip_entry is a valid directory entry returned by zip_read().

See also zip_open() and zip_read().

后退 | 起点 | 前进
zip_entry_filesize | 上一级 | zip_entry_open


zip_entry_open

(PHP 4 >= 4.1.0)

zip_entry_open -- Open a Directory Entry for Reading

Description

bool zip_entry_open ( resource zip, resource zip_entry [, string mode])

Opens a directory entry in a zip file for reading. The parameter zip is a valid resource handle returned by zip_open(). The parameter zip_entry is a directory entry resource returned by zip_read(). The optional parameter mode can be any of the modes specified in the documentaion for fopen().

注: Currently, mode is ignored and is always "rb". This is due to the fact that zip support in PHP is read only access. Please see fopen() for an explanation of various modes, including "rb".

如果成功则返回 TRUE，失败则返回 FALSE。

注: Unlike fopen() and other similar functions, the return value of zip_entry_open() only indicates the result of the operation and is not needed for reading or closing the directory entry.

See also zip_entry_read() and zip_entry_close().

后退 | 起点 | 前进
zip_entry_name | 上一级 | zip_entry_read


zip_entry_read

(PHP 4 >= 4.1.0)

zip_entry_read -- Read From an Open Directory Entry

Description

string zip_entry_read ( resource zip_entry [, int length])

Reads up to length bytes from an open directory entry. If length is not specified, then zip_entry_read() will attempt to read 1024 bytes. The parameter zip_entry is a valid directory entry returned by zip_read().

注: The length parameter should be the uncompressed length you wish to read.

Returns the data read, or FALSE if the end of the file is reached.

See also zip_entry_open(),
zip_entry_close() and
zip_entry_filesize().

后退 | 起点 | 前进
zip_entry_open | 上一级 | zip_open


zip_open

(PHP 4 >= 4.1.0)

zip_open -- Open a Zip File Archive

Description

resource zip_open ( string filename)

Opens a new zip archive for reading. The filename parameter is the filename of the zip archive to open.

Returns a resource handle for later use with zip_read() and zip_close() or returns FALSE if filename does not exist.

See also zip_read() and zip_close().

后退 | 起点 | 前进
zip_entry_read | 上一级 | zip_read


zip_read

(PHP 4 >= 4.1.0)

zip_read -- Read Next Entry in a Zip File Archive

Description

resource zip_read ( resource zip)

Reads the next entry in a zip file archive. The parameter zip must be a zip archive previously opened by zip_open().

Returns a directory entry resource for later use with the zip_entry_...() functions.

See also zip_open(),
zip_close(),
zip_entry_open(), and
zip_entry_read().

后退 | 起点 | 前进
zip_open | 上一级 | Zlib Compression Functions


Zlib Compression Functions

PHP 手册
后退 前进

CXI. Zlib Compression Functions

介绍

This module enables you to transparently read and write gzip (.gz) compressed files, through versions of most of the filesystem functions which work with gzip-compressed files (and uncompressed files, too, but not with sockets).

注: Version 4.0.4 introduced a fopen-wrapper for .gz-files, so that you can use a special 'zlib:' URL to access compressed files transparently using the normal f*() file access functions if you prepend the filename or path with a 'zlib:' prefix when calling fopen().

In version 4.3.0, this special prefix has been changed to 'zlib://' to prevent ambiguities with filenames containing ':'.

This feature requires a C runtime library that provides the fopencookie() function. To my current knowledge the GNU libc is the only library that provides this feature.

需求

This module uses the functions of zlib by Jean-loup Gailly and Mark Adler. You have to use a zlib version >= 1.0.9 with this module.

运行时配置

这些函数的行为受到全局配置文件 php.ini 的影响。

The zlib extension offers the option to transparently compress your pages on-the-fly, if the requesting browser supports this. Therefore there are three options in the configuration file php.ini.

表格 1. Zlib Configuration Options

Name | Default | Changeable
zlib.output_compression | "Off" | PHP_INI_ALL
zlib.output_compression_level | "-1" | PHP_INI_ALL
zlib.output_handler | "" | PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

Here is a short explanation of the configuration directives.

zlib.output_compression boolean/integer

Whether to transparently compress pages. If this option is set to "On" in php.ini or the Apache configuration, pages are compressed if the browser sends an "Accept-Encoding: gzip" or "deflate" header. "Content-Encoding: gzip" (respectively "deflate") and "Vary: Accept-Encoding" headers are added to the output.

You can use ini_set() to disable this in your script if the headers aren't already sent. If you output a "Content-Type: image/" header the compression is disabled, too (in order to circumvent a Netscape bug). You can reenable it, if you add "ini_set('zlib.output_compression', 'On')" after the header call which added the image content-type.

This option also accepts integer values instead of boolean "On"/"Off", using this you can set the output buffer size (default is 4KB).

注: output_handler must be empty if this is set 'On' ! Instead you must use zlib.output_handler.

zlib.output_compression_level integer

Compression level used for transparent output compression.

zlib.output_handler string

You cannot specify additional output handlers if zlib.output_compression is activated here. This setting does the same as output_handler but in a different order.

资源类型

该扩展模块未定义任何资源类型。

预定义常量

由于这些常量是由该扩展模块定义的，因此只有在该扩展模块被编译到 PHP 中，或者在运行时被动态加载后，这些常量才有效。

FORCE_GZIP (integer)

FORCE_DEFLATE (integer)

范例

This example opens a temporary file and writes a test string to it, then it prints out the content of this file twice.

例子 1. Small Zlib Example

<?php

$filename = tempnam ('/tmp', 'zlibtest').'.gz';
print "<html>\n<head></head>\n<body>\n<pre>\n";
$s = "Only a test, test, test, test, test, test, test, test!\n";

// open file for writing with maximum compression
$zp = gzopen($filename, "w9");

// write string to file
gzwrite($zp, $s);

// close file
gzclose($zp);

// open file for reading
$zp = gzopen($filename, "r");

// read 3 char
print gzread($zp, 3);

// output until end of the file and close it.
gzpassthru($zp);

print "\n";

// open file and print content (the 2nd time).
if (readgzfile($filename) != strlen($s)) {
        echo "Error with zlib functions!";
}
unlink($filename);
print "</pre>\n</h1></body>\n</html>\n";

?>
目录
gzclose — Close an open gz-file pointer
gzcompress — Compress a string
gzdeflate — Deflate a string
gzencode — Create a gzip compressed string
gzeof — Test for end-of-file on a gz-file pointer
gzfile — Read entire gz-file into an array
gzgetc — Get character from gz-file pointer
gzgets — Get line from file pointer
gzgetss — Get line from gz-file pointer and strip HTML tags
gzinflate — Inflate a deflated string
gzopen — Open gz-file
gzpassthru — Output all remaining data on a gz-file pointer
gzputs — Write to a gz-file pointer
gzread — Binary-safe gz-file read
gzrewind — Rewind the position of a gz-file pointer
gzseek — Seek on a gz-file pointer
gztell — Tell gz-file pointer read/write position
gzuncompress — Uncompress a deflated string
gzwrite — Binary-safe gz-file write
readgzfile — Output a gz-file

后退 | 起点 | 前进
zip_read | 上一级 | gzclose


gzclose

(PHP 3, PHP 4 )

gzclose -- Close an open gz-file pointer

Description

int gzclose ( resource zp)

The gz-file pointed to by zp is closed.

如果成功则返回 TRUE，失败则返回 FALSE。

The gz-file pointer must be valid, and must point to a file successfully opened by gzopen().

后退 | 起点 | 前进
Zlib Compression Functions | 上一级 | gzcompress


gzcompress

(PHP 4 >= 4.0.1)

gzcompress -- Compress a string

Description

string gzcompress ( string data [, int level])

This function returns a compressed version of the input data using the ZLIB data format, or FALSE if an error is encountered. The optional parameter level can be given as 0 for no compression up to 9 for maximum compression.

For details on the ZLIB compression algorithm see the document "ZLIB Compressed Data Format Specification version 3.3" (RFC 1950).

注: This is not the same as gzip compression, which includes some header data. See gzencode() for gzip compression.

See also gzdeflate(),
gzinflate(),
gzuncompress(),
gzencode().

后退 | 起点 | 前进
gzclose | 上一级 | gzdeflate


gzdeflate

(PHP 4 >= 4.0.4)

gzdeflate -- Deflate a string

Description

string gzdeflate ( string data [, int level])

This function returns a compressed version of the input data using the DEFLATE data format, or FALSE if an error is encountered. The optional parameter level can be given as 0 for no compression up to 9 for maximum compression.

For details on the DEFLATE compression algorithm see the document "DEFLATE Compressed Data Format Specification version 1.3" (RFC 1951).

See also
gzinflate(),
gzcompress(),
gzuncompress(),
gzencode().

后退 | 起点 | 前进
gzcompress | 上一级 | gzencode


gzencode

(PHP 4 >= 4.0.4)

gzencode -- Create a gzip compressed string

Description

string gzencode ( string data [, int level [, int encoding_mode]])

This function returns a compressed version of the input data compatible with the output of the gzip program, or FALSE if an error is encountered. The optional parameter level can be given as 0 for no compression up to 9 for maximum compression, if not given the default compression level will be the default compression level of the zlib library.

You can also give FORCE_GZIP (the default) or FORCE_DEFLATE as optional third paramter encoding_mode. If you use FORCE_DEFLATE, you get a standard zlib deflated string (inclusive zlib headers) after the gzip file header but without the trailing crc32 checksum.

注: level was added in PHP 4.2, before PHP 4.2 gzencode() only had the data and (optional) encoding_mode parameters..

The resulting data contains the appropriate headers and data structure to make a standard .gz file, e.g.:

例子 1. Creating a gzip file

<?php
    $data = implode("", file("bigfile.txt"));
    $gzdata = gzencode($data, 9);
    $fp = fopen("bigfile.txt.gz", "w");
    fwrite($fp, $gzdata);
    fclose($fp);
?>

For more information on the GZIP file format, see the document: GZIP file format specification version 4.3 (RFC 1952).

See also gzcompress().
gzuncompress(),
gzdeflate(),
gzinflate().

后退 | 起点 | 前进
gzdeflate | 上一级 | gzeof


gzeof

(PHP 3, PHP 4 )

gzeof -- Test for end-of-file on a gz-file pointer

Description

int gzeof ( resource zp)

Returns TRUE if the gz-file pointer is at EOF or an error occurs; otherwise returns FALSE.

The gz-file pointer must be valid, and must point to a file successfully opened by gzopen().

后退 | 起点 | 前进
gzencode | 上一级 | gzfile


gzfile

(PHP 3, PHP 4 )

gzfile -- Read entire gz-file into an array

Description

array gzfile ( string filename [, int use_include_path])

Identical to readgzfile(), except that gzfile() returns the file in an array.

You can use the optional second parameter and set it to "1", if you want to search for the file in the include_path, too.

See also readgzfile(), and gzopen().

后退 | 起点 | 前进
gzeof | 上一级 | gzgetc


gzgetc

(PHP 3, PHP 4 )

gzgetc -- Get character from gz-file pointer

Description

string gzgetc ( resource zp)

Returns a string containing a single (uncompressed) character read from the file pointed to by zp. Returns FALSE on EOF (as does gzeof()).

The gz-file pointer must be valid, and must point to a file successfully opened by gzopen().

See also gzopen(), and gzgets().

后退 | 起点 | 前进
gzfile | 上一级 | gzgets


gzgets

(PHP 3, PHP 4 )

gzgets -- Get line from file pointer

Description

string gzgets ( resource zp, int length)

Returns a (uncompressed) string of up to length - 1 bytes read from the file pointed to by fp. Reading ends when length - 1 bytes have been read, on a newline, or on EOF (whichever comes first).

If an error occurs, returns FALSE.

The file pointer must be valid, and must point to a file successfully opened by gzopen().

See also gzopen(), gzgetc(), and fgets().

后退 | 起点 | 前进
gzgetc | 上一级 | gzgetss


gzgetss

(PHP 3, PHP 4 )

gzgetss -- Get line from gz-file pointer and strip HTML tags

Description

string gzgetss ( resource zp, int length [, string allowable_tags])

Identical to gzgets(), except that gzgetss() attempts to strip any HTML and PHP tags from the text it reads.

You can use the optional third parameter to specify tags which should not be stripped.

注: Allowable_tags was added in PHP 3.0.13, PHP4B3.

See also gzgets(), gzopen(), and strip_tags().

后退 | 起点 | 前进
gzgets | 上一级 | gzinflate


gzinflate

(PHP 4 >= 4.0.4)

gzinflate -- Inflate a deflated string

Description

string gzinflate ( string data [, int length])

This function takes data compressed by gzdeflate() and returns the original uncompressed data or FALSE on error. The function will return an error if the uncompressed data is more than 256 times the length of the compressed input data or more than the optional parameter length.

See also gzcompress().
gzuncompress(),
gzdeflate(),
gzencode().

后退 | 起点 | 前进
gzgetss | 上一级 | gzopen


gzopen

(PHP 3, PHP 4 )

gzopen -- Open gz-file

Description

resource gzopen ( string filename, string mode [, int use_include_path])

Opens a gzip (.gz) file for reading or writing. The mode parameter is as in fopen() ("rb" or "wb") but can also include a compression level ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman only compression as in "wb1h". (See the description of deflateInit2 in zlib.h for more information about the strategy parameter.)

gzopen() can be used to read a file which is not in gzip format; in this case gzread() will directly read from the file without decompression.

gzopen() returns a file pointer to the file opened, after that, everything you read from this file descriptor will be transparently decompressed and what you write gets compressed.

If the open fails, the function returns FALSE.

You can use the optional third parameter and set it to "1", if you want to search for the file in the include_path, too.

例子 1. gzopen() Example

$fp = gzopen ("/tmp/file.gz", "r");

See also gzclose().

后退 | 起点 | 前进
gzinflate | 上一级 | gzpassthru


gzpassthru

(PHP 3, PHP 4 )

gzpassthru -- Output all remaining data on a gz-file pointer

Description

int gzpassthru ( resource zp)

Reads to EOF on the given gz-file pointer and writes the (uncompressed) results to standard output.

If an error occurs, returns FALSE.

The file pointer must be valid, and must point to a file successfully opened by gzopen().

The gz-file is closed when gzpassthru() is done reading it (leaving zp useless).

后退 | 起点 | 前进
gzopen | 上一级 | gzputs


gzputs

(PHP 3, PHP 4 )

gzputs -- Write to a gz-file pointer

Description

int gzputs ( resource zp, string str [, int length])

gzputs() is an alias to gzwrite(), and is identical in every way.

后退 | 起点 | 前进
gzpassthru | 上一级 | gzread


gzread

(PHP 3, PHP 4 )

gzread -- Binary-safe gz-file read

Description

string gzread ( resource zp, int length)

gzread() reads up to length bytes from the gz-file pointer referenced by zp. Reading stops when length (uncompressed) bytes have been read or EOF is reached, whichever comes first.

// get contents of a gz-file into a string
$filename = "/usr/local/something.txt.gz";
$zd = gzopen ($filename, "r");
$contents = gzread ($zd, 10000);
gzclose ($zd);

See also gzwrite(), gzopen(),
gzgets(), gzgetss(),
gzfile(), and gzpassthru().

后退 | 起点 | 前进
gzputs | 上一级 | gzrewind


gzrewind

(PHP 3, PHP 4 )

gzrewind -- Rewind the position of a gz-file pointer

Description

int gzrewind ( resource zp)

Sets the file position indicator for zp to the beginning of the file stream.

If an error occurs, returns 0.

The file pointer must be valid, and must point to a file successfully opened by gzopen().

See also gzseek() and gztell().

后退 | 起点 | 前进
gzread | 上一级 | gzseek


gzseek

(PHP 3, PHP 4 )

gzseek -- Seek on a gz-file pointer

Description

int gzseek ( resource zp, int offset)

Sets the file position indicator for the file referenced by zp to offset bytes into the file stream. Equivalent to calling (in C) gzseek( zp, offset, SEEK_SET ).

If the file is opened for reading, this function is emulated but can be extremely slow. If the file is opened for writing, only forward seeks are supported; gzseek then compresses a sequence of zeroes up to the new starting position.

Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF is not considered an error.

See also gztell() and gzrewind().

后退 | 起点 | 前进
gzrewind | 上一级 | gztell


gztell

(PHP 3, PHP 4 )

gztell -- Tell gz-file pointer read/write position

Description

int gztell ( resource zp)

Returns the position of the file pointer referenced by zp; i.e., its offset into the file stream.

If an error occurs, returns FALSE.

The file pointer must be valid, and must point to a file successfully opened by gzopen().

See also gzopen(), gzseek() and gzrewind().

后退 | 起点 | 前进
gzseek | 上一级 | gzuncompress


gzuncompress

(PHP 4 >= 4.0.1)

gzuncompress -- Uncompress a deflated string

Description

string gzuncompress ( string data [, int length])

This function takes data compressed by gzcompress() and returns the original uncompressed data or FALSE on error. The function will return an error if the uncompressed data is more than 256 times the length of the compressed input data or more than the optional parameter length.

See also gzdeflate(),
gzinflate(),
gzcompress(),
gzencode().

后退 | 起点 | 前进
gztell | 上一级 | gzwrite


gzwrite

(PHP 3, PHP 4 )

gzwrite -- Binary-safe gz-file write

Description

int gzwrite ( resource zp, string string [, int length])

gzwrite() writes the contents of string to the gz-file stream pointed to by zp. If the length argument is given, writing will stop after length (uncompressed) bytes have been written or the end of string is reached, whichever comes first.

gzwrite() returns the number of (uncompressed) bytes written to the gz-file stream pointed to by zp.

Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string.

See also gzread(), gzopen(), and gzputs().

后退 | 起点 | 前进
gzuncompress | 上一级 | readgzfile


readgzfile

(PHP 3, PHP 4 )

readgzfile -- Output a gz-file

Description

int readgzfile ( string filename [, int use_include_path])

Reads a file, decompresses it and writes it to standard output.

readgzfile() can be used to read a file which is not in gzip format; in this case readgzfile() will directly read from the file without decompression.

Returns the number of (uncompressed) bytes read from the file. If an error occurs, FALSE is returned and unless the function was called as @readgzfile, an error message is printed.

The file filename will be opened from the filesystem and its contents written to standard output.

You can use the optional second parameter and set it to "1", if you want to search for the file in the include_path, too.

See also gzpassthru(), gzfile(), and gzopen().

后退 | 起点 | 前进
gzwrite | 上一级 | Extending PHP 4.0


Extending PHP 4.0

PHP 手册
后退 前进

V. Extending PHP 4.0

Hacking the Core of PHP

Those who know don't talk.

Those who talk don't know.

Sometimes, PHP "as is" simply isn't enough. Although these cases are rare for the average user, professional applications will soon lead PHP to the edge of its capabilities, in terms of either speed or functionality. New functionality cannot always be implemented natively due to language restrictions and inconveniences that arise when having to carry around a huge library of default code appended to every single script, so another method needs to be found for overcoming these eventual lacks in PHP.

As soon as this point is reached, it's time to touch the heart of PHP and take a look at its core, the C code that makes PHP go.

Note: This chapter only deals with the extension of PHP 4.0. Although a lot of the information is relevant to PHP 3.0, none of the examples are designed to be compatible with PHP 3.0. We believe that, if someone makes the effort to extend PHP, PHP 4.0 will be installed anyway. (Recompiling old PHP 3.0 servers doesn't make sense, considering the benefits of the new PHP version).

Also, at the time of this writing, quite a few things in PHP 4.0 were not completely finished and working yet (one of the major things is the thread-safe version of Zend).

注: Updates of this chapter can be found at http://www.zend.com.

目录
26. Overview
27. Extension Possibilities
28. Source Layout
29. PHP's Automatic Build System
30. Creating Extensions
31. Using Extensions
32. Troubleshooting
33. Source Discussion
34. Accepting Arguments
35. Creating Variables
36. Duplicating Variable Contents: The Copy Constructor
37. Returning Values
38. Printing Information
39. Startup and Shutdown Functions
40. Calling User Functions
41. Initialization File Support
42. Where to Go from Here
43. Reference: Some Configuration Macros
44. API Macros
Hacking the Core of PHP

后退 | 起点 | 前进
readgzfile |  | Overview


Overview

PHP 手册
后退 前进

章 26. Overview

目录
What Is Zend? and What Is PHP?

"Extending PHP" is easier said than done. PHP has evolved to a full-fledged tool consisting of a few megabytes of source code, and to hack a system like this quite a few things have to be learned and considered. When structuring this chapter, we finally decided on the "learn by doing" approach. This is not the most scientific and professional approach, but the method that's the most fun and gives the best end results. In the following sections, you'll learn quickly how to get the most basic extensions to work almost instantly. After that, you'll learn about Zend's advanced API functionality. The alternative would have been to try to impart the functionality, design, tips, tricks, etc. as a whole, all at once, thus giving a complete look at the big picture before doing anything practical. Although this is the "better" method, as no dirty hacks have to be made, it can be very frustrating as well as energy- and time-consuming, which is why we've decided on the direct approach.

Note that even though this chapter tries to impart as much knowledge as possible about the inner workings of PHP, it's impossible to really give a complete guide to extending PHP that works 100% of the time in all cases. PHP is such a huge and complex package that its inner workings can only be understood if you make yourself familiar with it by practicing, so we encourage you to work with the source.

What Is Zend? and What Is PHP?

The name Zend refers to the language engine, PHP's core. The term PHP refers to the complete system as it appears from the outside. This might sound a bit confusing at first, but it's not that complicated (see Figure 9.1). To implement a Web script interpreter, you need three parts:

  1. The interpreter part analyzes the input code, translates it, and executes it.

  2. The functionality part implements the functionality of the language (its functions, etc.).

  3. The interface part talks to the Web server, etc.

Zend takes part 1 completely and a bit of part 2; PHP takes parts 2 and 3. Together they form the complete PHP package. Zend itself really forms only the language core, implementing PHP at its very basics with some predefined functions. PHP contains all the modules that actually create the language's outstanding capabilities.

图形 26-1. Figure 9.1. The internal structure of PHP.

The following sections discuss where PHP can be extended and how it's done.

后退 | 起点 | 前进
Extending PHP 4.0 | 上一级 | Extension Possibilities


Extension Possibilities

PHP 手册
后退 前进

章 27. Extension Possibilities

目录
External Modules
Built-in Modules
The Zend Engine

As shown in Figure 9.1 above, PHP can be extended primarily at three points: external modules, built-in modules, and the Zend engine. The following sections discuss these options.

External Modules

External modules can be loaded at script runtime using the function dl(). This function loads a shared object from disk and makes its functionality available to the script to which it's being bound. After the script is terminated, the external module is discarded from memory. This method has both advantages and disadvantages, as described in the following table:

Advantages | Disadvantages
External modules don't require recompiling of PHP. | The shared objects need to be loaded every time a script is being executed (every hit), which is very slow.
The size of PHP remains small by "outsourcing" certain functionality. | External additional files clutter up the disk.
 | Every script that wants to use an external module's functionality has to specifically include a call to dl(), or the extension tag in php.ini needs to be modified (which is not always a suitable solution).

To sum up, external modules are great for third-party products, small additions to PHP that are rarely used, or just for testing purposes. To develop additional functionality quickly, external modules provide the best results. For frequent usage, larger implementations, and complex code, the disadvantages outweigh the advantages.

Third parties might consider using the extension tag in php.ini to create additional external modules to PHP. These external modules are completely detached from the main package, which is a very handy feature in commercial environments. Commercial distributors can simply ship disks or archives containing only their additional modules, without the need to create fixed and solid PHP binaries that don't allow other modules to be bound to them.

后退 | 起点 | 前进
Overview | 上一级 | Built-in Modules


Built-in Modules

Built-in modules are compiled directly into PHP and carried around with every PHP process; their functionality is instantly available to every script that's being run. Like external modules, built-in modules have advantages and disadvantages, as described in the following table:

Advantages | Disadvantages
No need to load the module specifically; the functionality is instantly available. | Changes to built-in modules require recompiling of PHP.
No external files clutter up the disk; everything resides in the PHP binary. | The PHP binary grows and consumes more memory.

Built-in modules are best when you have a solid library of functions that remains relatively unchanged, requires better than poor-to-average performance, or is used frequently by many scripts on your site. The need to recompile PHP is quickly compensated by the benefit in speed and ease of use. However, built-in modules are not ideal when rapid development of small additions is required.

后退 | 起点 | 前进
Extension Possibilities | 上一级 | The Zend Engine


The Zend Engine

Of course, extensions can also be implemented directly in the Zend engine. This strategy is good if you need a change in the language behavior or require special functions to be built directly into the language core. In general, however, modifications to the Zend engine should be avoided. Changes here result in incompatibilities with the rest of the world, and hardly anyone will ever adapt to specially patched Zend engines. Modifications can't be detached from the main PHP sources and are overridden with the next update using the "official" source repositories. Therefore, this method is generally considered bad practice and, due to its rarity, is not covered in this book.

后退 | 起点 | 前进
Built-in Modules | 上一级 | Source Layout


Source Layout

PHP 手册
后退 前进

章 28. Source Layout

目录
Extension Conventions
Macros
Memory Management
Directory and File Functions
String Handling
Complex Types

Prerequisites. Prior to working through the rest of this chapter, you should retrieve clean, unmodified source trees of your favorite Web server. We're working with Apache (available at http://www.apache.org) and, of course, with PHP (available at http://www.php.net - does it need to be said?).

Alternatively, you can use the provided source archives on the CD-ROM accompanying this book. All the examples in this book work with the source archives on the CD-ROM; we can't guarantee this for every version retrieved from the Net. However, as Open Source software develops extremely rapidly, chances are that the versions on the CD-ROM are already outdated and don't have all the functionality you need. If you can't get the official archives from the corresponding Web sites to work, experiment with the CD-ROM archives and then try to go on from there.

Make sure that you can compile a working PHP environment by yourself! We won't go into this issue here, however, as you should already have this most basic ability when studying this chapter.

Before we start discussing code issues, you should familiarize yourself with the source tree to be able to quickly navigate through PHP's files. This is a must-have ability to implement and debug extensions.

After extracting the PHP archive, you'll see a directory layout similar to that in Figure 9.2.

图形 28-1. Figure 9.2. Main directory layout of the PHP source tree.

The following table describes the contents of the major directories.

Directory | Contents
php-4 | Main PHP source files and main header files; here you'll find all of PHP's API definitions, macros, etc. (important).
ext | Repository for dynamic and built-in modules; by default, these are the "official" PHP modules that have been integrated into the main source tree. In PHP 4.0, it's possible to compile these standard extensions as dynamic loadable modules (at least, those that support it).
pear | Directory for the PHP class repository. At the time of this writing, this is still in the design phase, but it's being tried to establish something similar to CPAN for Perl here.
sapi | Contains the code for the different server abstraction layers.
TSRM | Location of the "Thread Safe Resource Manager" (TSRM) for Zend and PHP.
Zend | Location of Zend's file; here you'll find all of Zend's API definitions, macros, etc. (important).

Discussing all the files included in the PHP package is beyond the scope of this chapter. However, you should take a close look at the following files:

  • php.h, located in the main PHP directory. This file contains most of PHP's macro and API definitions.

  • zend.h, located in the main Zend directory. This file contains most of Zend's macros and definitions.

  • zend_API.h, also located in the Zend directory, which defines Zend's API.

You should also follow some sub-inclusions from these files; for example, the ones relating to the Zend executor, the PHP initialization file support, and such. After reading these files, take the time to navigate around the package a little to see the interdependencies of all files and modules - how they relate to each other and especially how they make use of each other. This also helps you to adapt to the coding style in which PHP is authored. To extend PHP, you should quickly adapt to this style.

Extension Conventions

Zend is built using certain conventions; to avoid breaking its standards, you should follow the rules described in the following sections.

后退 | 起点 | 前进
The Zend Engine | 上一级 | Macros


Macros

For almost every important task, Zend ships predefined macros that are extremely handy. The tables and figures in the following sections describe most of the basic functions, structures, and macros. The macro definitions can be found mainly in zend.h and zend_API.h. We suggest that you take a close look at these files after having studied this chapter. (Although you can go ahead and read them now, not everything will make sense to you yet.)

后退 | 起点 | 前进
Source Layout | 上一级 | Memory Management


Memory Management

Resource management is a crucial issue, especially in server software. One of the most valuable resources is memory, and memory management should be handled with extreme care. Memory management has been partially abstracted in Zend, and you should stick to this abstraction for obvious reasons: Due to the abstraction, Zend gets full control over all memory allocations. Zend is able to determine whether a block is in use, automatically freeing unused blocks and blocks with lost references, and thus prevent memory leaks. The functions to be used are described in the following table:

Function | Description
emalloc() | Serves as replacement for malloc().
efree() | Serves as replacement for free().
estrdup() | Serves as replacement for strdup().
estrndup() | Serves as replacement for strndup(). Faster than estrdup() and binary-safe. This is the recommended function to use if you know the string length prior to duplicating it.
ecalloc() | Serves as replacement for calloc().
erealloc() | Serves as replacement for realloc().

emalloc(), estrdup(), estrndup(), ecalloc(), and erealloc() allocate internal memory; efree() frees these previously allocated blocks. Memory handled by the e*() functions is considered local to the current process and is discarded as soon as the script executed by this process is terminated.

警告

To allocate resident memory that survives termination of the current script, you can use malloc() and free(). This should only be done with extreme care, however, and only in conjunction with demands of the Zend API; otherwise, you risk memory leaks.

Zend also features a thread-safe resource manager to provide better native support for multithreaded Web servers. This requires you to allocate local structures for all of your global variables to allow concurrent threads to be run. Because the thread-safe mode of Zend is not finished yet, we could not include coverage in this book.

后退 | 起点 | 前进
Macros | 上一级 | Directory and File Functions


Directory and File Functions

The following directory and file functions should be used in Zend modules (they behave exactly like their C counterparts):

Zend Function | Regular C Function
V_GETCWD() | getcwd()
V_FOPEN() | fopen()
V_OPEN() | open()
V_CHDIR() | chdir()
V_GETWD() | getwd()
V_CHDIR_FILE() | Takes a file path as an argument and changes the current working directory to that file's directory.
V_STAT() | stat()
V_LSTAT() | lstat()

后退 | 起点 | 前进
Memory Management | 上一级 | String Handling


String Handling

Strings are handled a bit differently by the Zend engine than other values such as integers, Booleans, etc., which don't require additional memory allocation for storing their values. If you want to return a string from a function, introduce a new string variable to the symbol table, or do something similar, you have to make sure that the memory the string will be occupying has previously been allocated, using the aforementioned e*() functions for allocation. (This might not make much sense to you yet; just keep it somewhere in your head for now - we'll get back to it shortly.)

后退 | 起点 | 前进
Directory and File Functions | 上一级 | Complex Types


Complex Types

Complex types such as arrays and objects require different treatment. Zend features a single API for these types - they're stored using hash tables.

Note: To reduce complexity in the following source examples, we're only working with simple types such as integers at first. A discussion about creating more advanced types follows later in this chapter.

后退 | 起点 | 前进
String Handling | 上一级 | PHP's Automatic Build System


PHP's Automatic Build System

PHP 手册
后退 前进

章 29. PHP's Automatic Build System

PHP 4.0 features an automatic build system that's very flexible. All modules reside in a subdirectory of the ext directory. In addition to its own sources, each module consists of an M4 file (for example, see http://www.gnu.org/manual/m4/html_mono/m4.html) for configuration and a Makefile.in file, which is responsible for compilation (the results of autoconf and automake; for example, see http://sourceware.cygnus.com/autoconf/autoconf.html and http://sourceware.cygnus.com/automake/automake.html).

Both files are generated automatically, along with .cvsignore, by a little shell script named ext_skel that resides in the ext directory. As argument it takes the name of the module that you want to create. The shell script then creates a directory of the same name, along with the appropriate config.m4 and Makefile.in files.

Step by step, the process looks like this:
root@dev:/usr/local/src/php4/ext > ./ext_skel my_module
Creating directory
Creating basic files: config.m4 Makefile.in .cvsignore [done].

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

    $ cd ..
    $ ./buildconf
    $ ./configure                 (your extension is automatically enabled)
    $ vi ext/my_module/my_module.c
    $ make

Repeat the last two steps as often as necessary.
This instruction creates the aforementioned files. To include the new module in the automatic configuration and build process, you have to run buildconf, which regenerates the configure script by searching through the ext directory and including all found config.m4 files.

Finally, running configure parses all configuration options and generates a makefile based on those options and the options you specify in Makefile.in.

Listing 9.1 shows the previously generated Makefile.in:

图形 29-1. Listing 9.1. The default Makefile.in.

# $Id: Extending_Zend_Build.xml,v 1.1 2002/01/09 12:16:30 derick Exp $

LTLIBRARY_NAME        = libmy_module.la
LTLIBRARY_SOURCES     = my_module.c
LTLIBRARY_SHARED_NAME = my_module.la

include $(top_srcdir)/build/dynlib.mk

There's not much to tell about this one: It contains the names of the input and output files. You could also specify build instructions for other files if your module is built from multiple source files.

The default config.m4 shown in Listing 9.2 is a bit more complex:

图形 29-2. Listing 9.2. The default config.m4.

dnl $Id: Extending_Zend_Build.xml,v 1.1 2002/01/09 12:16:30 derick Exp $
dnl config.m4 for extension my_module
dnl don't forget to call PHP_EXTENSION(my_module)

dnl If your extension references something external, use with:

PHP_ARG_WITH(my_module, for my_module support,
dnl Make sure that the comment is aligned:
[  --with-my_module             Include my_module support])

dnl Otherwise use enable:

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

if test "$PHP_MY_MODULE" != "no"; then
  dnl Action..
  PHP_EXTENSION(my_module, $ext_shared)
fi

If you're unfamiliar with M4 files (now is certainly a good time to get familiar), this might be a bit confusing at first; but it's actually quite easy.

Note: Everything prefixed with dnl is treated as a comment and is not parsed.

The config.m4 file is responsible for parsing the command-line options passed to configure at configuration time. This means that it has to check for required external files and do similar configuration and setup tasks.

The default file creates two configuration directives in the configure script: --with-my_module and --enable-my_module. Use the first option when referring external files (such as the --with-apache directive that refers to the Apache directory). Use the second option when the user simply has to decide whether to enable your extension. Regardless of which option you use, you should uncomment the other, unnecessary one; that is, if you're using --enable-my_module, you should remove support for --with-my_module, and vice versa.

By default, the config.m4 file created by ext_skel accepts both directives and automatically enables your extension. Enabling the extension is done by using the PHP_EXTENSION macro. To change the default behavior to include your module into the PHP binary when desired by the user (by explicitly specifying --enable-my_module or --with-my_module), change the test for $PHP_MY_MODULE to == "yes":
if test "$PHP_MY_MODULE" == "yes"; then
  dnl Action..
  PHP_EXTENSION(my_module, $ext_shared)
fi
This would require you to use --enable-my_module each time when reconfiguring and recompiling PHP.

Note: Be sure to run buildconf every time you change config.m4!

We'll go into more details on the M4 macros available to your configuration scripts later in this chapter. For now, we'll simply use the default files. The sample sources on the CD-ROM all have working config.m4 files. To include them into the PHP build process, simply copy the source directories to your PHP ext directory, run buildconf, and then include the sample modules you want by using the appropriate --enable-* directives with configure.

后退 | 起点 | 前进
Complex Types | 上一级 | Creating Extensions


Creating Extensions

PHP 手册
后退 前进

章 30. Creating Extensions

目录
Compiling Modules

We'll start with the creation of a very simple extension at first, which basically does nothing more than implement a function that returns the integer it receives as parameter. Listing 9.3 shows the source.

图形 30-1. Listing 9.3. A simple extension.

/* include standard header */
#include "php.h"

/* declaration of functions to be exported */
ZEND_FUNCTION(first_module);

/* compiled function list so Zend knows what's in this module */
zend_function_entry firstmod_functions[] =
{
    ZEND_FE(first_module, NULL)
    {NULL, NULL, NULL}
};

/* compiled module information */
zend_module_entry firstmod_module_entry =
{
    STANDARD_MODULE_HEADER,
    "First Module",
    firstmod_functions,
    NULL, NULL, NULL, NULL, NULL,
    NO_VERSION_YET,
    STANDARD_MODULE_PROPERTIES
};

/* implement standard "stub" routine to introduce ourselves to Zend */
#if COMPILE_DL_FIRST_MODULE
ZEND_GET_MODULE(firstmod)
#endif

/* implement function that is meant to be made available to PHP */
ZEND_FUNCTION(first_module)
{
    long parameter;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &parameter) == FAILURE) {
        return;
    }

    RETURN_LONG(parmeter);
}

This code contains a complete PHP module. We'll explain the source code in detail shortly, but first we'd like to discuss the build process. (This will allow the impatient to experiment before we dive into API discussions.)

Compiling Modules

There are basically three ways to compile modules:

  • Use the provided "make" mechanism in the dl directory.

  • Use the provided "make" mechanism in the ext directory, which also allows building of dynamic loadable modules.

  • Compile the sources manually.

The second method should definitely be favored, since, as of PHP 4.0, this has been standardized into a sophisticated build process. The fact that it is so sophisticated is also its drawback, unfortunately - it's hard to understand at first. We'll provide a more detailed introduction to this later in the chapter, but first let's work with the default files.

The make process contained in the dl directory is a bit of a dirty hack, outdated and planned for removal from the source tree. To be honest, it's much simpler to use this at first to build dynamic extensions, but because it doesn't have the possibilities of the ext directory and it's scheduled for deletion anyway, usage of the dl directory is deprecated.

The third method is good for those who (for some reason) don't have the full PHP source tree available, don't have access to all files, or just like to juggle with their keyboard. These cases should be extremely rare, but for the sake of completeness we'll also describe this method.

Compiling Using Make. To compile the sample sources using the standard mechanism, copy all their subdirectories to the ext directory of your PHP source tree. Then run buildconf, which will create a new configure script containing appropriate options. By default, all the sample sources are disabled, so you don't have to fear breaking your build process.

After you run buildconf, configure --help shows the following additional modules:
--enable-array_experiments   BOOK: Enables array experiments
  --enable-call_userland       BOOK: Enables userland module
  --enable-cross_conversion    BOOK: Enables cross-conversion module
  --enable-first_module        BOOK: Enables first module
  --enable-infoprint           BOOK: Enables infoprint module
  --enable-reference_test      BOOK: Enables reference test module
  --enable-resource_test       BOOK: Enables resource test module
  --enable-variable_creation   BOOK: Enables variable-creation module
The module shown earlier in Listing 9.3 can be enabled with --enable-first_module or --enable-first_module=yes.

Compiling Manually. To compile your modules manually, you need the following commands:

Action | Command
Compiling | cc -fpic -DCOMPILE_DL=1 -I/usr/local/include -I. -I.. -I../Zend -c -o <your_object_file> <your_c_file>
Linking | cc -shared -L/usr/local/lib -rdynamic -o <your_module_file> <your_object_file(s)>

The command to compile the module simply instructs the compiler to generate position-independent code (-fpic shouldn't be omitted) and additionally defines the constant COMPILE_DL to tell the module code that it's compiled as a dynamically loadable module (the test module above checks for this; we'll discuss it shortly). After these options, it specifies a number of standard include paths that should be used as the minimal set to compile the source files.

Note: All include paths in the example are relative to the directory ext. If you're compiling from another directory, change the pathnames accordingly. Required items are the PHP directory, the Zend directory, and (if necessary), the directory in which your module resides.

The link command is also a plain vanilla command instructing linkage as a dynamic module.

You can include optimization options in the compilation command, although these have been omitted in this example (but some are included in the makefile template described in an earlier section).

Note: Compiling and linking manually as a static module into the PHP binary involves very long instructions and thus is not discussed here. (It's not very efficient to type all those commands.)

后退 | 起点 | 前进
PHP's Automatic Build System | 上一级 | Using Extensions


Using Extensions

PHP 手册
后退 前进

章 31. Using Extensions

Depending on the build process you selected, you should either end up with a new PHP binary to be linked into your Web server (or run as CGI), or with an .so (shared object) file. If you compiled the example file first_module.c as a shared object, your result file should be first_module.so. To use it, you first have to copy it to a place from which it's accessible to PHP. For a simple test procedure, you can copy it to your htdocs directory and try it with the source in Listing 9.4. If you compiled it into the PHP binary, omit the call to dl(), as the module's functionality is instantly available to your scripts.

警告

For security reasons, you should not put your dynamic modules into publicly accessible directories. Even though it can be done and it simplifies testing, you should put them into a separate directory in production environments.

图形 31-1. Listing 9.4. A test file for first_module.so.

<?php

//dl("first_module.so");

$param = 2;
$return = first_module($param);

print("We sent \"$param\" and got \"$return\"");

?>

Calling this PHP file in your Web browser should give you the output shown in Figure 9.3.

图形 31-2. Figure 9.3. Output of first_module.php.

If required, the dynamic loadable module is loaded by calling the dl() function. This function looks for the specified shared object, loads it, and makes its functions available to PHP. The module exports the function first_module(), which accepts a single parameter, converts it to an integer, and returns the result of the conversion.

If you've gotten this far, congratulations! You just built your first extension to PHP.

后退 | 起点 | 前进
Creating Extensions | 上一级 | Troubleshooting


Troubleshooting

PHP 手册
后退 前进

章 32. Troubleshooting

Actually, not much troubleshooting can be done when compiling static or dynamic modules. The only problem that could arise is that the compiler will complain about missing definitions or something similar. In this case, make sure that all header files are available and that you specified their path correctly in the compilation command. To be sure that everything is located correctly, extract a clean PHP source tree and use the automatic build in the ext directory with the fresh files from the CD-ROM; this will guarantee a safe compilation environment. If this fails, try manual compilation.

PHP might also complain about missing functions in your module. (This shouldn't happen with the sample sources if you didn't modify them.) If the names of external functions you're trying to access from your module are misspelled, they'll remain as "unlinked symbols" in the symbol table. During dynamic loading and linkage by PHP, they won't resolve because of the typing errors - there are no corresponding symbols in the main binary. Look for incorrect declarations in your module file or incorrectly written external references. Note that this problem is specific to dynamic loadable modules; it doesn't occur with static modules. Errors in static modules show up at compile time.

后退 | 起点 | 前进
Using Extensions | 上一级 | Source Discussion


Source Discussion

PHP 手册
后退 前进

章 33. Source Discussion

目录
Module Structure
Header File Inclusions
Declaring Exported Functions
Declaration of the Zend Function Block
Declaration of the Zend Module Block
Creation of get_module()
Implementation of All Exported Functions
Summary

Now that you've got a safe build environment and you're able to include the modules into PHP files, it's time to discuss how everything works.

Module Structure

All PHP modules follow a common structure:

  • Header file inclusions (to include all required macros, API definitions, etc.)

  • C declaration of exported functions (required to declare the Zend function block)

  • Declaration of the Zend function block

  • Declaration of the Zend module block

  • Implementation of get_module()

  • Implementation of all exported functions

后退 | 起点 | 前进
Troubleshooting | 上一级 | Header File Inclusions


Header File Inclusions

The only header file you really have to include for your modules is php.h, located in the PHP directory. This file makes all macros and API definitions required to build new modules available to your code.

Tip: It's good practice to create a separate header file for your module that contains module-specific definitions. This header file should contain all the forward definitions for exported functions and include php.h.

后退 | 起点 | 前进
Source Discussion | 上一级 | Declaring Exported Functions


Declaring Exported Functions

To declare functions that are to be exported (i.e., made available to PHP as new native functions), Zend provides a set of macros. A sample declaration looks like this:
ZEND_FUNCTION(my_function);

ZEND_FUNCTION declares a new C function that complies with Zend's internal API. This means that the function is of type void and accepts INTERNAL_FUNCTION_PARAMETERS (another macro) as parameters. Additionally, it prefixes the function name with zif. The immediately expanded version of the above definitions would look like this:
void zif_my_function(INTERNAL_FUNCTION_PARAMETERS);
Expanding INTERNAL_FUNCTION_PARAMETERS results in the following:
void zif_my_function(int ht, zval *return_value, zval *this_ptr, int return_value_used, zend_executor_globals *executor_globals);

Since the interpreter and executor core have been separated from the main PHP package, a second API defining macros and function sets has evolved: the Zend API. As the Zend API now handles quite a few of the responsibilities that previously belonged to PHP, a lot of PHP functions have been reduced to macros aliasing to calls into the Zend API. The recommended practice is to use the Zend API wherever possible, as the old API is only preserved for compatibility reasons. For example, the types zval and pval are identical. zval is Zend's definition; pval is PHP's definition (actually, pval is an alias for zval now). As the macro INTERNAL_FUNCTION_PARAMETERS is a Zend macro, the above declaration contains zval. When writing code, you should always use zval to conform to the new Zend API.

The parameter list of this declaration is very important; you should keep these parameters in mind (see Table 9.1 for descriptions).

图形 33-1. Table 9.1. Zend's Parameters to Functions Called from PHP

Parameter | Description
ht | The number of arguments passed to the Zend function. You should not touch this directly, but instead use ZEND_NUM_ARGS() to obtain the value.
return_value | This variable is used to pass any return values of your function back to PHP. Access to this variable is best done using the predefined macros. For a description of these see below.
this_ptr | Using this variable, you can gain access to the object in which your function is contained, if it's used within an object. Use the function getThis() to obtain this pointer.
return_value_used | This flag indicates whether an eventual return value from this function will actually be used by the calling script. 0 indicates that the return value is not used; 1 indicates that the caller expects a return value. Evaluation of this flag can be done to verify correct usage of the function as well as speed optimizations in case returning a value requires expensive operations (for an example, see how array.c makes use of this).
executor_globals | This variable points to global settings of the Zend engine. You'll find this useful when creating new variables, for example (more about this later). The executor globals can also be introduced to your function by using the macro ELS_FETCH().

后退 | 起点 | 前进
Header File Inclusions | 上一级 | Declaration of the Zend Function Block


Declaration of the Zend Function Block

Now that you have declared the functions to be exported, you also have to introduce them to Zend. Introducing the list of functions is done by using an array of zend_function_entry. This array consecutively contains all functions that are to be made available externally, with the function's name as it should appear in PHP and its name as defined in the C source. Internally, zend_function_entry is defined as shown in Listing 9.5.

图形 33-2. Listing 9.5. Internal declaration of zend_function_entry.

typedef struct _zend_function_entry {
    char *fname;
    void (*handler)(INTERNAL_FUNCTION_PARAMETERS);
    unsigned char *func_arg_types;
} zend_function_entry;

Entry | Description
fname | Denotes the function name as seen in PHP (for example, fopen, mysql_connect, or, in our example, first_module).
handler | Pointer to the C function responsible for handling calls to this function. For example, see the standard macro INTERNAL_FUNCTION_PARAMETERS discussed earlier.
func_arg_types | Allows you to mark certain parameters so that they're forced to be passed by reference. You usually should set this to NULL.

In the example above, the declaration looks like this:
zend_function_entry firstmod_functions[] =
{
    ZEND_FE(first_module, NULL)
    {NULL, NULL, NULL}
};
You can see that the last entry in the list always has to be {NULL, NULL, NULL}. This marker has to be set for Zend to know when the end of the list of exported functions is reached.

Note: You cannot use the predefined macros for the end marker, as these would try to refer to a function named "NULL"!

The macro ZEND_FE simply expands to a structure entry in zend_function_entry. Note that these macros introduce a special naming scheme to your functions - your C functions will be prefixed with zif_, meaning that ZEND_FE(first_module) will refer to a C function zif_first_module(). If you want to mix macro usage with hand-coded entries (not a good practice), keep this in mind.

Tip: Compilation errors that refer to functions named zif_*() relate to functions defined with ZEND_FE.

Table 9.2 shows a list of all the macros that you can use to define functions.

图形 33-3. Table 9.2. Macros for Defining Functions

Macro Name | Description
ZEND_FE(name, arg_types) | Defines a function entry of the name name in zend_function_entry. Requires a corresponding C function. arg_types needs to be set to NULL. This function uses automatic C function name generation by prefixing the PHP function name with zif_. For example, ZEND_FE("first_module", NULL) introduces a function first_module() to PHP and links it to the C function zif_first_module(). Use in conjunction with ZEND_FUNCTION.
ZEND_NAMED_FE(php_name, name, arg_types) | Defines a function that will be available to PHP by the name php_name and links it to the corresponding C function name. arg_types needs to be set to NULL. Use this function if you don't want the automatic name prefixing introduced by ZEND_FE. Use in conjunction with ZEND_NAMED_FUNCTION.
ZEND_FALIAS(name, alias, arg_types) | Defines an alias named alias for name. arg_types needs to be set to NULL. Doesn't require a corresponding C function; refers to the alias target instead.
PHP_FE(name, arg_types) | Old PHP API equivalent of ZEND_FE.
PHP_NAMED_FE(runtime_name, name, arg_types) | Old PHP API equivalent of ZEND_NAMED_FE.

Note: You can't use ZEND_FE in conjunction with PHP_FUNCTION, or PHP_FE in conjunction with ZEND_FUNCTION. However, it's perfectly legal to mix ZEND_FE and ZEND_FUNCTION with PHP_FE and PHP_FUNCTION when staying with the same macro set for each function to be declared. But mixing is not recommended; instead, you're advised to use the ZEND_* macros only.

后退 | 起点 | 前进
Declaring Exported Functions | 上一级 | Declaration of the Zend Module Block


Declaration of the Zend Module Block

This block is stored in the structure zend_module_entry and contains all necessary information to describe the contents of this module to Zend. You can see the internal definition of this module in Listing 9.6.

图形 33-4. Internal declaration of zend_module_entry.

typedef struct _zend_module_entry zend_module_entry;

struct _zend_module_entry {
    unsigned short size;
    unsigned int zend_api;
    unsigned char zend_debug;
    unsigned char zts;
    char *name;
    zend_function_entry *functions;
    int (*module_startup_func)(INIT_FUNC_ARGS);
    int (*module_shutdown_func)(SHUTDOWN_FUNC_ARGS);
    int (*request_startup_func)(INIT_FUNC_ARGS);
    int (*request_shutdown_func)(SHUTDOWN_FUNC_ARGS);
    void (*info_func)(ZEND_MODULE_INFO_FUNC_ARGS);
    char *version;
    int (*global_startup_func)(void);
    int (*global_shutdown_func)(void);

[ Rest of the structure is not interesting here ]

};

Entry | Description
size, zend_api, zend_debug and zts | Usually filled with the "STANDARD_MODULE_HEADER", which fills these four members with the size of the whole zend_module_entry, the ZEND_MODULE_API_NO, whether it is a debug build or normal build (ZEND_DEBUG) and if ZTS is enabled (USING_ZTS).
name | Contains the module name (for example, "File functions", "Socket functions", "Crypt", etc.). This name will show up in phpinfo(), in the section "Additional Modules."
functions | Points to the Zend function block, discussed in the preceding section.
module_startup_func | This function is called once upon module initialization and can be used to do one-time initialization steps (such as initial memory allocation, etc.). To indicate a failure during initialization, return FAILURE; otherwise, SUCCESS. To mark this field as unused, use NULL. To declare a function, use the macro ZEND_MINIT.
module_shutdown_func | This function is called once upon module shutdown and can be used to do one-time deinitialization steps (such as memory deallocation). This is the counterpart to module_startup_func(). To indicate a failure during deinitialization, return FAILURE; otherwise, SUCCESS. To mark this field as unused, use NULL. To declare a function, use the macro ZEND_MSHUTDOWN.
request_startup_func | This function is called once upon every page request and can be used to do one-time initialization steps that are required to process a request. To indicate a failure here, return FAILURE; otherwise, SUCCESS. Note: As dynamic loadable modules are loaded only on page requests, the request startup function is called right after the module startup function (both initialization events happen at the same time). To mark this field as unused, use NULL. To declare a function, use the macro ZEND_RINIT.
request_shutdown_func | This function is called once after every page request and works as counterpart to request_startup_func(). To indicate a failure here, return FAILURE; otherwise, SUCCESS. Note: As dynamic loadable modules are loaded only on page requests, the request shutdown function is immediately followed by a call to the module shutdown handler (both deinitialization events happen at the same time). To mark this field as unused, use NULL. To declare a function, use the macro ZEND_RSHUTDOWN.
info_func | When phpinfo() is called in a script, Zend cycles through all loaded modules and calls this function. Every module then has the chance to print its own "footprint" into the output page. Generally this is used to dump environmental or statistical information. To mark this field as unused, use NULL. To declare a function, use the macro ZEND_MINFO.
version | The version of the module. You can use NO_VERSION_YET if you don't want to give the module a version number yet, but we really recommend that you add a version string here. Such a version string can look like this (in chronological order): "2.5-dev", "2.5RC1", "2.5" or "2.5pl3".
global_startup_func | The global startup functions are rarely used. You should usually skip through the rest of this structure by placing the macro STANDARD_MODULE_PROPERTIES. To mark this field as unused, use NULL. To declare a function, use the macro ZEND_GINIT.
global_shutdown_func | To mark this field as unused, use NULL. To declare a function, use the macro ZEND_GSHUTDOWN.
Remaining structure elements | These are used internally and can be prefilled by using the macro STANDARD_MODULE_PROPERTIES_EX. You should not assign any values to them. Use STANDARD_MODULE_PROPERTIES_EX only if you use global startup and shutdown functions; otherwise, use STANDARD_MODULE_PROPERTIES directly.

In our example, this structure is implemented as follows:
zend_module_entry firstmod_module_entry =
{
    STANDARD_MODULE_HEADER,
    "First Module",
    firstmod_functions,
    NULL, NULL, NULL, NULL, NULL,
    NO_VERSION_YET,
    STANDARD_MODULE_PROPERTIES,
};
This is basically the easiest and most minimal set of values you could ever use. The module name is set to First Module, then the function list is referenced, after which all startup and shutdown functions are marked as being unused.

For reference purposes, you can find a list of the macros involved in declared startup and shutdown functions in Table 9.3. These are not used in our basic example yet, but will be demonstrated later on. You should make use of these macros to declare your startup and shutdown functions, as these require special arguments to be passed (INIT_FUNC_ARGS and SHUTDOWN_FUNC_ARGS), which are automatically included into the function declaration when using the predefined macros. If you declare your functions manually and the PHP developers decide that a change in the argument list is necessary, you'll have to change your module sources to remain compatible.

图形 33-5. Macros to Declare Startup and Shutdown Functions

Macro | Description
ZEND_MINIT(module) | Declares a function for module startup. The generated name will be zend_minit_<module> (for example, zend_minit_first_module). Use in conjunction with ZEND_MINIT_FUNCTION.
ZEND_MSHUTDOWN(module) | Declares a function for module shutdown. The generated name will be zend_mshutdown_<module> (for example, zend_mshutdown_first_module). Use in conjunction with ZEND_MSHUTDOWN_FUNCTION.
ZEND_RINIT(module) | Declares a function for request startup. The generated name will be zend_rinit_<module> (for example, zend_rinit_first_module). Use in conjunction with ZEND_RINIT_FUNCTION.
ZEND_RSHUTDOWN(module) | Declares a function for request shutdown. The generated name will be zend_rshutdown_<module> (for example, zend_rshutdown_first_module). Use in conjunction with ZEND_RSHUTDOWN_FUNCTION.
ZEND_GINIT(module) | Declares a function for global startup. The generated name will be zend_ginit_<module> (for example, zend_ginit_first_module). Use in conjunction with ZEND_GINIT_FUNCTION.
ZEND_GSHUTDOWN(module) | Declares a function for global shutdown. The generated name will be zend_gshutdown_<module> (for example, zend_gshutdown_first_module). Use in conjunction with ZEND_GSHUTDOWN_FUNCTION.
ZEND_MINFO(module) | Declares a function for printing module information, used when phpinfo() is called. The generated name will be zend_info_<module> (for example, zend_info_first_module). Use in conjunction with ZEND_MINFO_FUNCTION.

后退 | 起点 | 前进
Declaration of the Zend Function Block | 上一级 | Creation of get_module()


Creation of get_module

PHP 手册
后退 章 33. Source Discussion 前进

Creation of get_module()

This function is special to all dynamic loadable modules. Take a look at the creation via the ZEND_GET_MODULE macro first:
#if COMPILE_DL_FIRSTMOD
ZEND_GET_MODULE(firstmod)
#endif
The function implementation is surrounded by a conditional compilation statement. This is needed since the function get_module() is only required if your module is built as a dynamic extension. By specifying a definition of COMPILE_DL_FIRSTMOD in the compiler command (see above for a discussion of the compilation instructions required to build a dynamic extension), you can instruct your module whether you intend to build it as a dynamic extension or as a built-in module. If you want a built-in module, the implementation of get_module() is simply left out.

get_module() is called by Zend at load time of the module. You can think of it as being invoked by the dl() call in your script. Its purpose is to pass the module information block back to Zend in order to inform the engine about the module contents.

If you don't implement a get_module() function in your dynamic loadable module, Zend will compliment you with an error message when trying to access it.

后退 | 起点 | 前进
Declaration of the Zend Module Block | 上一级 | Implementation of All Exported Functions


Implementation of All Exported Functions

Implementing the exported functions is the final step. The example function in first_module looks like this:
ZEND_FUNCTION(first_module)
{
    long parameter;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &parameter) == FAILURE) {
        return;
    }

    RETURN_LONG(parameter);
}
The function declaration is done using ZEND_FUNCTION, which corresponds to ZEND_FE in the function entry table (discussed earlier).

After the declaration, code for checking and retrieving the function's arguments, argument conversion, and return value generation follows (more on this later).

后退 | 起点 | 前进
Creation of get_module() | 上一级 | Summary


Summary

That's it, basically - there's nothing more to implementing PHP modules. Built-in modules are structured similarly to dynamic modules, so, equipped with the information presented in the previous sections, you'll be able to fight the odds when encountering PHP module source files.

Now, in the following sections, read on about how to make use of PHP's internals to build powerful extensions.

后退 | 起点 | 前进
Implementation of All Exported Functions | 上一级 | Accepting Arguments


Accepting Arguments

PHP 手册
后退 前进

章 34. Accepting Arguments

目录
Determining the Number of Arguments
Retrieving Arguments
Old way of retrieving arguments (deprecated)
Dealing with a Variable Number of Arguments/Optional Parameters
Accessing Arguments
Dealing with Arguments Passed by Reference
Assuring Write Safety for Other Parameters

One of the most important issues for language extensions is accepting and dealing with data passed via arguments. Most extensions are built to deal with specific input data (or require parameters to perform their specific actions), and function arguments are the only real way to exchange data between the PHP level and the C level. Of course, there's also the possibility of exchanging data using predefined global values (which is also discussed later), but this should be avoided by all means, as it's extremely bad practice. For details, refer to Chapter 1, "Development Concepts."

PHP doesn't make use of any formal function declarations; this is why call syntax is always completely dynamic and never checked for errors. Checking for correct call syntax is left to the user code. For example, it's possible to call a function using only one argument at one time and four arguments the next time - both invocations are syntactically absolutely correct.

Determining the Number of Arguments

Since PHP doesn't have formal function definitions with support for call syntax checking, and since PHP features variable arguments, sometimes you need to find out with how many arguments your function has been called. You can use the ZEND_NUM_ARGS macro in this case. In previous versions of PHP, this macro retrieved the number of arguments with which the function has been called based on the function's hash table entry, ht, which is passed in the INTERNAL_FUNCTION_PARAMETERS list. As ht itself now contains the number of arguments that have been passed to the function, ZEND_NUM_ARGS has been stripped down to a dummy macro (see its definition in zend_API.h). But it's still good practice to use it, to remain compatible with future changes in the call interface. Note: The old PHP equivalent of this macro is ARG_COUNT.

The following code checks for the correct number of arguments:
if(ZEND_NUM_ARGS() != 2)
    WRONG_PARAM_COUNT;
If the function is not called with two arguments, it exits with an error message. The code snippet above makes use of the tool macro WRONG_PARAM_COUNT, which can be used to generate a standard error message (see Figure 9.4).

图形 34-1. Figure 9.4. WRONG_PARAM_COUNT in action.

This macro prints a default error message and then returns to the caller. Its definition can also be found in zend_API.h and looks like this:
ZEND_API void wrong_param_count(void);

#define WRONG_PARAM_COUNT { wrong_param_count(); return; }
As you can see, it calls an internal function named wrong_param_count() that's responsible for printing the warning. For details on generating customized error messages, see the later section "Printing Information."

后退 | 起点 | 前进
Summary | 上一级 | Retrieving Arguments


Retrieving Arguments

New parameter parsing API: This chapter documents the new Zend parameter parsing API introduced by Andrei Zmievski. It was introduced in the development stage between PHP 4.0.6 and 4.1.0 .

Parsing parameters is a very common operation and it may get a bit tedious. It would also be nice to have standardized error checking and error messages. Since PHP 4.1.0, there is a way to do just that by using the new parameter parsing API. It greatly simplifies the process of receiving parameteres, but it has a drawback in that it can't be used for functions that expect variable number of parameters. But since the vast majority of functions do not fall into those categories, this parsing API is recommended as the new standard way.

The prototype for parameter parsing function looks like this:
int zend_parse_parameters(int num_args TSRMLS_DC, char *type_spec, ...);
The first argument to this function is supposed to be the number of actual parameters passed to your function, so ZEND_NUM_ARGS() can be used for that. The second parameter should always be TSRMLS_CC macro. The third argument is a string that specifies the number and types of arguments your function is expecting, similar to how printf format string specifies the number and format of the output values it should operate on. And finally the rest of the arguments are pointers to variables which should receive the values from the parameters.

zend_parse_parameters() also performs type conversions whenever possible, so that you always receive the data in the format you asked for. Any type of scalar can be converted to another one, but conversions between complex types (arrays, objects, and resources) and scalar types are not allowed.

If the parameters could be obtained successfully and there were no errors during type conversion, the function will return SUCCESS, otherwise it will return FAILURE. The function will output informative error messages, if the number of received parameters does not match the requested number, or if type conversion could not be performed.

Here are some sample error messages:
Warning - ini_get_all() requires at most 1 parameter, 2 given

Warning - wddx_deserialize() expects parameter 1 to be string, array given
Of course each error message is accompanied by the filename and line number on which it occurs.

Here is the full list of type specifiers:

  • l - long

  • d - double

  • s - string (with possible null bytes) and its length

  • b - boolean

  • r - resource, stored in zval*

  • a - array, stored in zval*

  • o - object (of any class), stored in zval*

  • O - object (of class specified by class entry), stored in zval*

  • z - the actual zval*

The following characters also have a meaning in the specifier string:

  • | - indicates that the remaining parameters are optional. The storage variables corresponding to these parameters should be initialized to default values by the extension, since they will not be touched by the parsing function if the parameters are not passed.

  • / - the parsing function will call SEPARATE_ZVAL_IF_NOT_REF() on the parameter it follows, to provide a copy of the parameter, unless it's a reference.

  • ! - the parameter it follows can be of specified type or NULL (only applies to a, o, O, r, and z). If NULL value is passed by the user, the storage pointer will be set to NULL.

The best way to illustrate the usage of this function is through examples:
/* Gets a long, a string and its length, and a zval. */
long l;
char *s;
int s_len;
zval *param;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,
                          "lsz", &l, &s, &s_len, &param) == FAILURE) {
    return;
}

* Gets an object of class specified by my_ce, and an optional double. */
zval *obj;
double d = 0.5;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,
                          "O|d", &obj, my_ce, &d) == FAILURE) {
    return;
}

/* Gets an object or null, and an array.
   If null is passed for object, obj will be set to NULL. */
zval *obj;
zval *arr;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O!a", &obj, &arr) == FAILURE) {
    return;
}

/* Gets a separated array. */
zval *arr;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a/", &arr) == FAILURE) {
    return;
}

/* Get only the first three parameters (useful for varargs functions). */
zval *z;
zend_bool b;
zval *r;
if (zend_parse_parameters(3, "zbr!", &z, &b, &r) == FAILURE) {
    return;
}

Note that in the last example we pass 3 for the number of received parameters, instead of ZEND_NUM_ARGS(). What this lets us do is receive the least number of parameters if our function expects a variable number of them. Of course, if you want to operate on the rest of the parameters, you will have to use zend_get_parameters_array_ex() to obtain them.

The parsing function has an extended version that allows for an additional flags argument that controls its actions.
int zend_parse_parameters_ex(int flags, int num_args TSRMLS_DC, char *type_spec, ...);

The only flag you can pass currently is ZEND_PARSE_PARAMS_QUIET, which instructs the function to not output any error messages during its operation. This is useful for functions that expect several sets of completely different arguments, but you will have to output your own error messages.

For example, here is how you would get either a set of three longs or a string:
long l1, l2, l3;
char *s;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET,
                             ZEND_NUM_ARGS() TSRMLS_CC,
                             "lll", &l1, &l2, &l3) == SUCCESS) {
    /* manipulate longs */
} else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET,
                                    ZEND_NUM_ARGS(), "s", &s, &s_len) == SUCCESS) {
    /* manipulate string */
} else {
    php_error(E_WARNING, "%s() takes either three long values or a string as argument",
              get_active_function_name(TSRMLS_C));
    return;
}

With all the abovementioned ways of receiving function parameters you should have a good handle on this process. For even more example, look through the source code for extensions that are shipped with PHP - they illustrate every conceivable situation.

后退 | 起点 | 前进
Accepting Arguments | 上一级 | Old way of retrieving arguments (deprecated)


Old way of retrieving arguments (deprecated)

Deprecated parameter parsing API: This API is deprecated and superseded by the new ZEND parameter parsing API.

After having checked the number of arguments, you need to get access to the arguments themselves. This is done with the help of zend_get_parameters_ex():
zval **parameter;

if(zend_get_parameters_ex(1, &parameter) != SUCCESS)
    WRONG_PARAM_COUNT;
All arguments are stored in a zval container, which needs to be pointed to twice. The snippet above tries to retrieve one argument and make it available to us via the parameter pointer.

zend_get_parameters_ex() accepts at least two arguments. The first argument is the number of arguments to retrieve (which should match the number of arguments with which the function has been called; this is why it's important to check for correct call syntax). The second argument (and all following arguments) are pointers to pointers to pointers to zvals. (Confusing, isn't it?) All these pointers are required because Zend works internally with **zval; to adjust a local **zval in our function,zend_get_parameters_ex() requires a pointer to it.

The return value of zend_get_parameters_ex() can either be SUCCESS or FAILURE, indicating (unsurprisingly) success or failure of the argument processing. A failure is most likely related to an incorrect number of arguments being specified, in which case you should exit with WRONG_PARAM_COUNT.

To retrieve more than one argument, you can use a similar snippet:
zval **param1, **param2, **param3, **param4;

if(zend_get_parameters_ex(4, &param1, &param2, &param3, &param4) != SUCCESS)
    WRONG_PARAM_COUNT;

zend_get_parameters_ex() only checks whether you're trying to retrieve too many parameters. If the function is called with five arguments, but you're only retrieving three of them with zend_get_parameters_ex(), you won't get an error but will get the first three parameters instead. Subsequent calls of zend_get_parameters_ex() won't retrieve the remaining arguments, but will get the same arguments again.

后退 | 起点 | 前进
Retrieving Arguments | 上一级 | Dealing with a Variable Number of Arguments/Optional Parameters


Dealing with a Variable Number of Arguments/Optional Parameters

If your function is meant to accept a variable number of arguments, the snippets just described are sometimes suboptimal solutions. You have to create a line calling zend_get_parameters_ex() for every possible number of arguments, which is often unsatisfying.

For this case, you can use the function zend_get_parameters_array_ex(), which accepts the number of parameters to retrieve and an array in which to store them:
zval **parameter_array[4];

/* get the number of arguments */
argument_count = ZEND_NUM_ARGS();

/* see if it satisfies our minimal request (2 arguments) */
/* and our maximal acceptance (4 arguments) */
if(argument_count < 2 || argument_count > 5)
    WRONG_PARAM_COUNT;

/* argument count is correct, now retrieve arguments */
if(zend_get_parameters_array_ex(argument_count, parameter_array) != SUCCESS)
    WRONG_PARAM_COUNT;
First, the number of arguments is checked to make sure that it's in the accepted range. After that, zend_get_parameters_array_ex() is used to fill parameter_array with valid pointers to the argument values.

A very clever implementation of this can be found in the code handling PHP's fsockopen() located in ext/standard/fsock.c, as shown in Listing 9.7. Don't worry if you don't know all the functions used in this source yet; we'll get to them shortly.

图形 34-2. Listing 9.7. PHP's implementation of variable arguments in fsockopen().

pval **args[5];
int *sock=emalloc(sizeof(int));
int *sockp;
int arg_count=ARG_COUNT(ht);
int socketd = -1;
unsigned char udp = 0;
struct timeval timeout = { 60, 0 };
unsigned short portno;
unsigned long conv;
char *key = NULL;
FLS_FETCH();

if (arg_count > 5 || arg_count < 2 || zend_get_parameters_array_ex(arg_count,args)==FAILURE) {
    CLOSE_SOCK(1);
    WRONG_PARAM_COUNT;
}

switch(arg_count) {
    case 5:
        convert_to_double_ex(args[4]);
        conv = (unsigned long) (Z_DVAL_P(args[4]) * 1000000.0);
        timeout.tv_sec = conv / 1000000;
        timeout.tv_usec = conv % 1000000;
        /* fall-through */
    case 4:
        if (!PZVAL_IS_REF(*args[3])) {
            php_error(E_WARNING,"error string argument to fsockopen not passed by reference");
        }
        pval_copy_constructor(*args[3]);
        ZVAL_EMPTY_STRING(*args[3]);
        /* fall-through */
    case 3:
        if (!PZVAL_IS_REF(*args[2])) {
            php_error(E_WARNING,"error argument to fsockopen not passed by reference");
            return;
        }
        ZVAL_LONG(*args[2], 0);
        break;
}

convert_to_string_ex(args[0]);
convert_to_long_ex(args[1]);
portno = (unsigned short) Z_LVAL_P(args[1]);

key = emalloc(Z_STRLEN_P(args[0]) + 10);

fsockopen() accepts two, three, four, or five parameters. After the obligatory variable declarations, the function checks for the correct range of arguments. Then it uses a fall-through mechanism in a switch() statement to deal with all arguments. The switch() statement starts with the maximum number of arguments being passed (five). After that, it automatically processes the case of four arguments being passed, then three, by omitting the otherwise obligatory break keyword in all stages. After having processed the last case, it exits the switch() statement and does the minimal argument processing needed if the function is invoked with only two arguments.

This multiple-stage type of processing, similar to a stairway, allows convenient processing of a variable number of arguments.

后退 | 起点 | 前进
Old way of retrieving arguments (deprecated) | 上一级 | Accessing Arguments


Accessing Arguments

To access arguments, it's necessary for each argument to have a clearly defined type. Again, PHP's extremely dynamic nature introduces some quirks. Because PHP never does any kind of type checking, it's possible for a caller to pass any kind of data to your functions, whether you want it or not. If you expect an integer, for example, the caller might pass an array, and vice versa - PHP simply won't notice.

To work around this, you have to use a set of API functions to force a type conversion on every argument that's being passed (see Table 9.4).

Note: All conversion functions expect a **zval as parameter.

图形 34-3. Table 9.4. Argument Conversion Functions

Function | Description
convert_to_boolean_ex() | Forces conversion to a Boolean type. Boolean values remain untouched. Longs, doubles, and strings containing 0 as well as NULL values will result in Boolean 0 (FALSE). Arrays and objects are converted based on the number of entries or properties, respectively, that they have. Empty arrays and objects are converted to FALSE; otherwise, to TRUE. All other values result in a Boolean 1 (TRUE).
convert_to_long_ex() | Forces conversion to a long, the default integer type. NULL values, Booleans, resources, and of course longs remain untouched. Doubles are truncated. Strings containing an integer are converted to their corresponding numeric representation, otherwise resulting in 0. Arrays and objects are converted to 0 if empty, 1 otherwise.
convert_to_double_ex() | Forces conversion to a double, the default floating-point type. NULL values, Booleans, resources, longs, and of course doubles remain untouched. Strings containing a number are converted to their corresponding numeric representation, otherwise resulting in 0.0. Arrays and objects are converted to 0.0 if empty, 1.0 otherwise.
convert_to_string_ex() | Forces conversion to a string. Strings remain untouched. NULL values are converted to an empty string. Booleans containing TRUE are converted to "1", otherwise resulting in an empty string. Longs and doubles are converted to their corresponding string representation. Arrays are converted to the string "Array" and objects to the string "Object".
convert_to_array_ex(value) | Forces conversion to an array. Arrays remain untouched. Objects are converted to an array by assigning all their properties to the array table. All property names are used as keys, property contents as values. NULL values are converted to an empty array. All other values are converted to an array that contains the specific source value in the element with the key 0.
convert_to_object_ex(value) | Forces conversion to an object. Objects remain untouched. NULL values are converted to an empty object. Arrays are converted to objects by introducing their keys as properties into the objects and their values as corresponding property contents in the object. All other types result in an object with the property scalar , having the corresponding source value as content.
convert_to_null_ex(value) | Forces the type to become a NULL value, meaning empty.

注: You can find a demonstration of the behavior in cross_conversion.php on the accompanying CD-ROM. Figure 9.5 shows the output.

图形 34-4. Figure 9.5. Cross-conversion behavior of PHP.

Using these functions on your arguments will ensure type safety for all data that's passed to you. If the supplied type doesn't match the required type, PHP forces dummy contents on the resulting value (empty strings, arrays, or objects, 0 for numeric values, FALSE for Booleans) to ensure a defined state.

Following is a quote from the sample module discussed previously, which makes use of the conversion functions:
zval **parameter;

if((ZEND_NUM_ARGS() != 1) || (zend_get_parameters_ex(1, &parameter) != SUCCESS))
{
    WRONG_PARAM_COUNT;
}

convert_to_long_ex(parameter);

RETURN_LONG(Z_LVAL_P(parameter));
After retrieving the parameter pointer, the parameter value is converted to a long (an integer), which also forms the return value of this function. Understanding access to the contents of the value requires a short discussion of the zval type, whose definition is shown in Listing 9.8.

图形 34-5. Listing 9.8. PHP/Zend zval type definition.

typedef pval zval;

typedef struct _zval_struct zval;

typedef union _zvalue_value {
    long lval;					/* long value */
    double dval;				/* double value */
    struct {
        char *val;
        int len;
    } str;
    HashTable *ht;				/* hash table value */
    struct {
        zend_class_entry *ce;
        HashTable *properties;
    } obj;
} zvalue_value;

struct _zval_struct {
    /* Variable information */
    zvalue_value value;		/* value */
    unsigned char type;	/* active type */
    unsigned char is_ref;
    short refcount;
};

Actually, pval (defined in php.h) is only an alias of zval (defined in zend.h), which in turn refers to _zval_struct. This is a most interesting structure. _zval_struct is the "master" structure, containing the value structure, type, and reference information. The substructure zvalue_value is a union that contains the variable's contents. Depending on the variable's type, you'll have to access different members of this union. For a description of both structures, see Tables 9.5, 9.6, and 9.7.

图形 34-6. Table 9.5. Zend zval Structure

Entry | Description
value | Union containing this variable's contents. See Table 9.6 for a description.
type | Contains this variable's type. For a list of available types, see Table 9.7.
is_ref | 0 means that this variable is not a reference; 1 means that this variable is a reference to another variable.
refcount | The number of references that exist for this variable. For every new reference to the value stored in this variable, this counter is increased by 1. For every lost reference, this counter is decreased by 1. When the reference counter reaches 0, no references exist to this value anymore, which causes automatic freeing of the value.

图形 34-7. Table 9.6. Zend zvalue_value Structure

Entry | Description
lval | Use this property if the variable is of the type IS_LONG, IS_BOOLEAN, or IS_RESOURCE.
dval | Use this property if the variable is of the type IS_DOUBLE.
str | This structure can be used to access variables of the type IS_STRING. The member len contains the string length; the member val points to the string itself. Zend uses C strings; thus, the string length contains a trailing 0x00.
ht | This entry points to the variable's hash table entry if the variable is an array.
obj | Use this property if the variable is of the type IS_OBJECT.

图形 34-8. Table 9.7. Zend Variable Type Constants

Constant | Description
IS_NULL | Denotes a NULL (empty) value.
IS_LONG | A long (integer) value.
IS_DOUBLE | A double (floating point) value.
IS_STRING | A string.
IS_ARRAY | Denotes an array.
IS_OBJECT | An object.
IS_BOOL | A Boolean value.
IS_RESOURCE | A resource (for a discussion of resources, see the appropriate section below).
IS_CONSTANT | A constant (defined) value.

To access a long you access zval.value.lval, to access a double you use zval.value.dval, and so on. Because all values are stored in a union, trying to access data with incorrect union members results in meaningless output.

Accessing arrays and objects is a bit more complicated and is discussed later.

后退 | 起点 | 前进
Dealing with a Variable Number of Arguments/Optional Parameters | 上一级 | Dealing with Arguments Passed by Reference


Dealing with Arguments Passed by Reference

If your function accepts arguments passed by reference that you intend to modify, you need to take some precautions.

What we didn't say yet is that under the circumstances presented so far, you don't have write access to any zval containers designating function parameters that have been passed to you. Of course, you can change any zval containers that you created within your function, but you mustn't change any zvals that refer to Zend-internal data!

We've only discussed the so-called *_ex() API so far. You may have noticed that the API functions we've used are called zend_get_parameters_ex() instead of zend_get_parameters(), convert_to_long_ex() instead of convert_to_long(), etc. The *_ex() functions form the so-called new "extended" Zend API. They give a minor speed increase over the old API, but as a tradeoff are only meant for providing read-only access.

Because Zend works internally with references, different variables may reference the same value. Write access to a zval container requires this container to contain an isolated value, meaning a value that's not referenced by any other containers. If a zval container were referenced by other containers and you changed the referenced zval, you would automatically change the contents of the other containers referencing this zval (because they'd simply point to the changed value and thus change their own value as well).

zend_get_parameters_ex() doesn't care about this situation, but simply returns a pointer to the desired zval containers, whether they consist of references or not. Its corresponding function in the traditional API, zend_get_parameters(), immediately checks for referenced values. If it finds a reference, it creates a new, isolated zval container; copies the referenced data into this newly allocated space; and then returns a pointer to the new, isolated value.

This action is called zval separation (or pval separation). Because the *_ex() API doesn't perform zval separation, it's considerably faster, while at the same time disabling write access.

To change parameters, however, write access is required. Zend deals with this situation in a special way: Whenever a parameter to a function is passed by reference, it performs automatic zval separation. This means that whenever you're calling a function like this in PHP, Zend will automatically ensure that $parameter is being passed as an isolated value, rendering it to a write-safe state:
my_function(&$parameter);

But this is not the case with regular parameters! All other parameters that are not passed by reference are in a read-only state.

This requires you to make sure that you're really working with a reference - otherwise you might produce unwanted results. To check for a parameter being passed by reference, you can use the macro PZVAL_IS_REF. This macro accepts a zval* to check if it is a reference or not. Examples are given in in Listing 9.6 and Figure 9.9 (see the CD-ROM for the full source).

图形 34-9. Listing 9.6. Testing for referenced parameter passing.

zval *parameter;

if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &parameter) == FAILURE)
    return;
}

/* check for parameter being passed by reference */
if (!PZVAL_IS_REF(*parameter)) {
{
    zend_error(E_WARNING, "Parameter wasn't passed by reference");
    RETURN_NULL();
}

/* make changes to the parameter */
ZVAL_LONG(*parameter, 10);

后退 | 起点 | 前进
Accessing Arguments | 上一级 | Assuring Write Safety for Other Parameters


Assuring Write Safety for Other Parameters

You might run into a situation in which you need write access to a parameter that's retrieved with zend_get_parameters_ex() but not passed by reference. For this case, you can use the macro SEPARATE_ZVAL, which does a zval separation on the provided container. The newly generated zval is detached from internal data and has only a local scope, meaning that it can be changed or destroyed without implying global changes in the script context:
zval **parameter;

/* retrieve parameter */
zend_get_parameters_ex(1, &parameter);

/* at this stage, <parameter> still is connected */
/* to Zend's internal data buffers */

/* make <parameter> write-safe */
SEPARATE_ZVAL(parameter);

/* now we can safely modify <parameter> */
/* without implying global changes */
SEPARATE_ZVAL uses emalloc() to allocate the new zval container, which means that even if you don't deallocate this memory yourself, it will be destroyed automatically upon script termination. However, doing a lot of calls to this macro without freeing the resulting containers will clutter up your RAM.

Note: As you can easily work around the lack of write access in the "traditional" API (with zend_get_parameters() and so on), this API seems to be obsolete, and is not discussed further in this chapter.

后退 | 起点 | 前进
Dealing with Arguments Passed by Reference | 上一级 | Creating Variables


Creating Variables

PHP 手册
后退 前进

章 35. Creating Variables

目录
Overview
Longs (Integers)
Doubles (Floats)
Strings
Booleans
Arrays
Objects
Resources
Macros for Automatic Global Variable Creation
Creating Constants

When exchanging data from your own extensions with PHP scripts, one of the most important issues is the creation of variables. This section shows you how to deal with the variable types that PHP supports.

Overview

To create new variables that can be seen "from the outside" by the executing script, you need to allocate a new zval container, fill this container with meaningful values, and then introduce it to Zend's internal symbol table. This basic process is common to all variable creations:
zval *new_variable;

/* allocate and initialize new container */
MAKE_STD_ZVAL(new_variable);

/* set type and variable contents here, see the following sections */

/* introduce this variable by the name "new_variable_name" into the symbol table */
ZEND_SET_SYMBOL(EG(active_symbol_table), "new_variable_name", new_variable);

/* the variable is now accessible to the script by using $new_variable_name */
The macro MAKE_STD_ZVAL allocates a new zval container using ALLOC_ZVAL and initializes it using INIT_ZVAL. As implemented in Zend at the time of this writing, initializing means setting the reference count to 1 and clearing the is_ref flag, but this process could be extended later - this is why it's a good idea to keep using MAKE_STD_ZVAL instead of only using ALLOC_ZVAL. If you want to optimize for speed (and you don't have to explicitly initialize the zval container here), you can use ALLOC_ZVAL, but this isn't recommended because it doesn't ensure data integrity.

ZEND_SET_SYMBOL takes care of introducing the new variable to Zend's symbol table. This macro checks whether the value already exists in the symbol table and converts the new symbol to a reference if so (with automatic deallocation of the old zval container). This is the preferred method if speed is not a crucial issue and you'd like to keep memory usage low.

Note that ZEND_SET_SYMBOL makes use of the Zend executor globals via the macro EG. By specifying EG(active_symbol_table), you get access to the currently active symbol table, dealing with the active, local scope. The local scope may differ depending on whether the function was invoked from within a function.

If you need to optimize for speed and don't care about optimal memory usage, you can omit the check for an existing variable with the same value and instead force insertion into the symbol table by using zend_hash_update():
zval *new_variable;

/* allocate and initialize new container */
MAKE_STD_ZVAL(new_variable);

/* set type and variable contents here, see the following sections */

/* introduce this variable by the name "new_variable_name" into the symbol table */
zend_hash_update(
    EG(active_symbol_table),
    "new_variable_name",
    strlen("new_variable_name") + 1,
    &new_variable,
    sizeof(zval *),
    NULL
);
This is actually the standard method used in most modules.

The variables generated with the snippet above will always be of local scope, so they reside in the context in which the function has been called. To create new variables in the global scope, use the same method but refer to another symbol table:
zval *new_variable;

// allocate and initialize new container
MAKE_STD_ZVAL(new_variable);

//
// set type and variable contents here
//

// introduce this variable by the name "new_variable_name" into the global symbol table
ZEND_SET_SYMBOL(&EG(symbol_table), "new_variable_name", new_variable);
The macro ZEND_SET_SYMBOL is now being called with a reference to the main, global symbol table by referring EG(symbol_table).

Note: The active_symbol_table variable is a pointer, but symbol_table is not. This is why you have to use EG(active_symbol_table) and &EG(symbol_table) as parameters to ZEND_SET_SYMBOL - it requires a pointer.

Similarly, to get a more efficient version, you can hardcode the symbol table update:
zval *new_variable;

// allocate and initialize new container
MAKE_STD_ZVAL(new_variable);

//
// set type and variable contents here
//

// introduce this variable by the name "new_variable_name" into the global symbol table
zend_hash_update(
    &EG(symbol_table),
    "new_variable_name",
    strlen("new_variable_name") + 1,
    &new_variable,
    sizeof(zval *),
    NULL
);
Listing 9.10 shows a sample source that creates two variables - local_variable with a local scope and global_variable with a global scope (see Figure 9.7). The full example can be found on the CD-ROM.

Note: You can see that the global variable is actually not accessible from within the function. This is because it's not imported into the local scope using global $global_variable; in the PHP source.

图形 35-1. Listing 9.10. Creating variables with different scopes.

ZEND_FUNCTION(variable_creation)
{
    zval *new_var1, *new_var2;

    MAKE_STD_ZVAL(new_var1);
    MAKE_STD_ZVAL(new_var2);

    ZVAL_LONG(new_var1, 10);
    ZVAL_LONG(new_var2, 5);

    ZEND_SET_SYMBOL(EG(active_symbol_table), "local_variable", new_var1);
    ZEND_SET_SYMBOL(&EG(symbol_table), "global_variable", new_var2);

    RETURN_NULL();

}

后退 | 起点 | 前进
Assuring Write Safety for Other Parameters | 上一级 | Longs (Integers)


Longs (Integers)

Now let's get to the assignment of data to variables, starting with longs. Longs are PHP's integers and are very simple to store. Looking at the zval.value container structure discussed earlier in this chapter, you can see that the long data type is directly contained in the union, namely in the lval field. The corresponding type value for longs is IS_LONG (see Listing 9.11).

图形 35-2. Listing 9.11. Creation of a long.

zval *new_long;

MAKE_STD_ZVAL(new_long);

new_long->type = IS_LONG;
new_long->value.lval = 10;
Alternatively, you can use the macro ZVAL_LONG:
zval *new_long;

MAKE_STD_ZVAL(new_long);
ZVAL_LONG(new_long, 10);

后退 | 起点 | 前进
Creating Variables | 上一级 | Doubles (Floats)


Doubles (Floats)

Doubles are PHP's floats and are as easy to assign as longs, because their value is also contained directly in the union. The member in the zval.value container is dval; the corresponding type is IS_DOUBLE.
zval *new_double;

MAKE_STD_ZVAL(new_double);

new_double->type = IS_DOUBLE;
new_double->value.dval = 3.45;
Alternatively, you can use the macro ZVAL_DOUBLE:
zval *new_double;

MAKE_STD_ZVAL(new_double);
ZVAL_DOUBLE(new_double, 3.45);

后退 | 起点 | 前进
Longs (Integers) | 上一级 | Strings


Strings

Strings need slightly more effort. As mentioned earlier, all strings that will be associated with Zend's internal data structures need to be allocated using Zend's own memory-management functions. Referencing of static strings or strings allocated with standard routines is not allowed. To assign strings, you have to access the structure str in the zval.value container. The corresponding type is IS_STRING:
zval *new_string;
char *string_contents = "This is a new string variable";

MAKE_STD_ZVAL(new_string);

new_string->type = IS_STRING;
new_string->value.str.len = strlen(string_contents);
new_string->value.str.val = estrdup(string_contents);
Note the usage of Zend's estrdup() here. Of course, you can also use the predefined macro ZVAL_STRING:
zval *new_string;
char *string_contents = "This is a new string variable";

MAKE_STD_ZVAL(new_string);
ZVAL_STRING(new_string, string_contents, 1);
ZVAL_STRING accepts a third parameter that indicates whether the supplied string contents should be duplicated (using estrdup()). Setting this parameter to 1 causes the string to be duplicated; 0 simply uses the supplied pointer for the variable contents. This is most useful if you want to create a new variable referring to a string that's already allocated in Zend internal memory.

If you want to truncate the string at a certain position or you already know its length, you can use ZVAL_STRINGL(zval, string, length, duplicate), which accepts an explicit string length to be set for the new string. This macro is faster than ZVAL_STRING and also binary-safe.

To create empty strings, set the string length to 0 and use empty_string as contents:
new_string->type = IS_STRING;
new_string->value.str.len = 0;
new_string->value.str.val = empty_string;
Of course, there's a macro for this as well (ZVAL_EMPTY_STRING):
MAKE_STD_ZVAL(new_string);
ZVAL_EMPTY_STRING(new_string);

后退 | 起点 | 前进
Doubles (Floats) | 上一级 | Booleans


Booleans

Booleans are created just like longs, but have the type IS_BOOL. Allowed values in lval are 0 and 1:
zval *new_bool;

MAKE_STD_ZVAL(new_bool);

new_bool->type = IS_BOOL;
new_bool->value.lval = 1;
The corresponding macros for this type are ZVAL_BOOL (allowing specification of the value) as well as ZVAL_TRUE and ZVAL_FALSE (which explicitly set the value to TRUE and FALSE, respectively).

后退 | 起点 | 前进
Strings | 上一级 | Arrays


Arrays

Arrays are stored using Zend's internal hash tables, which can be accessed using the zend_hash_*() API. For every array that you want to create, you need a new hash table handle, which will be stored in the ht member of the zval.value container.

There's a whole API solely for the creation of arrays, which is extremely handy. To start a new array, you call array_init().
zval *new_array;

MAKE_STD_ZVAL(new_array);

if(array_init(new_array) != SUCCESS)
{
    // do error handling here
}
If array_init() fails to create a new array, it returns FAILURE.

To add new elements to the array, you can use numerous functions, depending on what you want to do. Tables 9.8, 9.9, and 9.10 describe these functions. All functions return FAILURE on failure and SUCCESS on success.

图形 35-3. Table 9.8. Zend's API for Associative Arrays

Note: The functions in Table 9.8 all operate on the array "array" with the key "key". The key string doesn't have to reside in Zend internal memory; it will be duplicated by the API.

Function | Description
add_assoc_long(zval *array, char *key, long n);() | Adds an element of type long.
add_assoc_unset(zval *array, char *key);() | Adds an unset element.
add_assoc_bool(zval *array, char *key, int b);() | Adds a Boolean element.
add_assoc_resource(zval *array, char *key, int r);() | Adds a resource to the array.
add_assoc_double(zval *array, char *key, double d);() | Adds a floating-point value.
add_assoc_string(zval *array, char *key, char *str, int duplicate);() | Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory.
add_assoc_stringl(zval *array, char *key, char *str, uint length, int duplicate);() | Adds a string with the desired length length to the array. Otherwise, behaves like add_assoc_string().

图形 35-4. Table 9.9. Zend's API for Indexed Arrays, Part 1

Note: The functions in Table 9.9 all operate on the array "array" with the index "idx".
The index is always an integer.

Function | Description
add_index_long(zval *array, uint idx, long n);() | Adds an element of type long.
add_index_unset(zval *array, uint idx);() | Adds an unset element.
add_index_bool(zval *array, uint idx, int b);() | Adds a Boolean element.
add_index_resource(zval *array, uint idx, int r);() | Adds a resource to the array.
add_index_double(zval *array, uint idx, double d);() | Adds a floating-point value.
add_index_string(zval *array, uint idx, char *str, int duplicate);() | Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory.
add_index_stringl(zval *array, uint idx, char *str, uint length, int duplicate);() | Adds a string with the desired length length to the array. This function is faster and binary-safe. Otherwise, behaves like add_index_string()().

图形 35-5. Table 9.10. Zend's API for Indexed Arrays, Part 2

Note: The functions in Table 9.10 all operate on the array "array".
These functions automatically generate a new index based on the highest index found in the array.

Function | Description
add_next_index_long(zval *array, long n);() | Adds an element of type long.
add_next_index_unset(zval *array);() | Adds an unset element.
add_next_index_bool(zval *array, int b);() | Adds a Boolean element.
add_next_index_resource(zval *array, int r);() | Adds a resource to the array.
add_next_index_double(zval *array, double d);() | Adds a floating-point value.
add_next_index_string(zval *array, char *str, int duplicate);() | Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory.
add_next_index_stringl(zval *array, char *str, uint length, int duplicate);() | Adds a string with the desired length length to the array. This function is faster and binary-safe. Otherwise, behaves like add_index_string()().

All these functions provide a handy abstraction to Zend's internal hash API. Of course, you can also use the hash functions directly - for example, if you already have a zval container allocated that you want to insert into an array. This is done using zend_hash_update()() for associative arrays (see Listing 9.12) and zend_hash_index_update() for indexed arrays (see Listing 9.13):

图形 35-6. Listing 9.12. Adding an element to an associative array.

zval *new_array, *new_element;
char *key = "element_key";

MAKE_STD_ZVAL(new_array);
MAKE_STD_ZVAL(new_element);

if(array_init(new_array) == FAILURE)
{
    // do error handling here
}

ZVAL_LONG(new_element, 10);

if(zend_hash_update(new_array->value.ht, key, strlen(key) + 1, (void *)&new_element, sizeof(zval *), NULL) == FAILURE)
{
    // do error handling here
}

图形 35-7. Listing 9.13. Adding an element to an indexed array.

zval *new_array, *new_element;
int key = 2;

MAKE_STD_ZVAL(new_array);
MAKE_STD_ZVAL(new_element);

if(array_init(new_array) == FAILURE)
{
    // do error handling here
}

ZVAL_LONG(new_element, 10);

if(zend_hash_index_update(new_array->value.ht, key, (void *)&new_element, sizeof(zval *), NULL) == FAILURE)
{
    // do error handling here
}

To emulate the functionality of add_next_index_*(), you can use this:

zend_hash_next_index_insert(ht, zval **new_element, sizeof(zval *), NULL)

Note: To return arrays from a function, use array_init() and all following actions on the predefined variable return_value (given as argument to your exported function; see the earlier discussion of the call interface). You do not have to use MAKE_STD_ZVAL on this.

Tip: To avoid having to write new_array->value.ht every time, you can use HASH_OF(new_array), which is also recommended for compatibility and style reasons.

后退 | 起点 | 前进
Booleans | 上一级 | Objects


Objects

Since objects can be converted to arrays (and vice versa), you might have already guessed that they have a lot of similarities to arrays in PHP. Objects are maintained with the same hash functions, but there's a different API for creating them.

To initialize an object, you use the function object_init():
zval *new_object;

MAKE_STD_ZVAL(new_object);

if(object_init(new_object) != SUCCESS)
{
    // do error handling here
}
You can use the functions described in Table 9.11 to add members to your object.

图形 35-8. Table 9.11. Zend's API for Object Creation

Note: All functions in Table 9.11 work on the object "object" with the key "key". The key forms the member name,
so the resulting member can be accessed via $object->key.

Function | Description
add_property_long(zval *object, char *key, long l);() | Adds a long to the object.
add_property_unset(zval *object, char *key);() | Adds an unset property to the object.
add_property_bool(zval *object, char *key, int b);() | Adds a Boolean to the object.
add_property_resource(zval *object, char *key, long r);() | Adds a resource to the object.
add_property_double(zval *object, char *key, double d);() | Adds a double to the object.
add_property_string(zval *object, char *key, char *str, int duplicate);() | Adds a string to the object.
add_property_stringl(zval *object, char *key, char *str, uint length, int duplicate);() | Adds a string of the specified length to the object. This function is faster than add_property_string() and also binary-safe.
add_property_zval(zval *obect, char *key, zval *container):() | Adds a zval container to the object. This is useful if you have to add properties which aren't simple types like integers or strings but arrays or other objects.

后退 | 起点 | 前进
Arrays | 上一级 | Resources


Resources

Resources are a special kind of data type in PHP. The term resources doesn't really refer to any special kind of data, but to an abstraction method for maintaining any kind of information. Resources are kept in a special resource list within Zend. Each entry in the list has a correspondending type definition that denotes the kind of resource to which it refers. Zend then internally manages all references to this resource. Access to a resource is never possible directly - only via a provided API. As soon as all references to a specific resource are lost, a corresponding shutdown function is called.

For example, resources are used to store database links and file descriptors. The de facto standard implementation can be found in the MySQL module, but other modules such as the Oracle module also make use of resources.

注: In fact, a resource can be a pointer to anything you need to handle in your functions (e.g. pointer to a structure) and the user only has to pass a single resource variable to your function.

To create a new resource you need to register a resource destruction handler for it. Since you can store any kind of data as a resource, Zend needs to know how to free this resource if its not longer needed. This works by registering your own resource destruction handler to Zend which in turn gets called by Zend whenever your resource can be freed (whether manually or automatically). Registering your resource handler within Zend returns you the resource type handle for that resource. This handle is needed whenever you want to access a resource of this type later and is most of time stored in a global static variable within your extension. There is no need to worry about thread safety here because you only register your resource handler once during module initialization.

The Zend function to register your resource handler is defined as:
ZEND_API int zend_register_list_destructors_ex(rsrc_dtor_func_t ld, rsrc_dtor_func_t pld, char *type_name, int module_number);

There are two different kinds of resource destruction handlers you can pass to this function: a handler for normal resources and a handler for persistent resources. Persistent resources are for example used for database connection. When registering a resource, either of these handlers must be given. For the other handler just pass NULL.

zend_register_list_destructors_ex() accepts the following parameters:

ld | Normal resource destruction handler callback
pld | Pesistent resource destruction handler callback
type_name | A string specifying the name of your resource. It's always a good thing to specify an unique name within PHP for the resource type so when the user for example calls var_dump($resource); he also gets the name of the resource.
module_number | The module_number is automatically available in your PHP_MINIT_FUNCTION function and therefore you just pass it over.

The return value is an unique integer ID for your resource type.

The resource destruction handler (either normal or persistent resources) has the following prototype:
void resource_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC);
The passed rsrc is a pointer to the following structure:
typedef struct _zend_rsrc_list_entry {

    void *ptr;
    int type;
    int refcount;

} zend_rsrc_list_entry;
The member void *ptr is the actual pointer to your resource.

Now we know how to start things, we define our own resource we want register within Zend. It is only a simple structure with two integer members:
typedef struct {

    int resource_link;
    int resource_type;

} my_resource;
Our resource destruction handler is probably going to look something like this:
void my_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC) {

    // You most likely cast the void pointer to your structure type

    my_resource *my_rsrc = (my_resource *) rsrc->ptr;

    // Now do whatever needs to be done with you resource. Closing
    // Files, Sockets, freeing additional memory, etc.
    // Also, don't forget to actually free the memory for your resource too!

    do_whatever_needs_to_be_done_with_the_resource(my_rsrc);
}

注: One important thing to mention: If your resource is a rather complex structure which also contains pointers to memory you allocated during runtime you have to free them before freeing the resource itself!

Now that we have defined

  1. what our resource is and

  2. our resource destruction handler

we can go on and do the rest of the steps:

  1. create a global variable within the extension holding the resource ID so it can be accessed from every function which needs it

  2. define the resource name

  3. write the resource destruction handler

  4. and finally register the handler

// Somewhere in your extension, define the variable for your registered resources.
    // If you wondered what 'le' stands for: it simply means 'list entry'.
    static int le_myresource;

    // It's nice to define your resource name somewhere
    #define le_myresource_name  "My type of resource"

    [...]

    // Now actually define our resource destruction handler
    void my_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC) {

        my_resource *my_rsrc = (my_resource *) rsrc->ptr;
        do_whatever_needs_to_be_done_with_the_resource(my_rsrc);
    }

    [...]

    PHP_MINIT_FUNCTION(my_extension) {

        // Note that 'module_number' is already provided through the
        // PHP_MINIT_FUNCTION() function definition.

        le_myresource = zend_register_resource_destructors_ex(my_destruction_handler, NULL, le_myresource_name, module_number);

        // You can register additional resources, initialize
        // your global vars, constants, whatever.
    }

To actually register a new resource you use can either use the zend_register_resource() function or the ZEND_REGISTER_RESOURE() macro, both defined in zend_list.h . Although the arguments for both map 1:1 it's a good idea to always use macros to be upwards compatible:
int ZEND_REGISTER_RESOURCE(zval *rsrc_result, void *rsrc_pointer, int rsrc_type);

rsrc_result | This is an already initialized zval * container.
rsrc_pointer | Your resource pointer you want to store.
rsrc_type | The type which you received when you registered the resource destruction handler. If you followed the naming scheme this would be le_myresource.

The return value is an unique integer identifier for that resource.

What is really going on when you register a new resource is it gets inserted in an internal list in Zend and the result is just stored in the given zval * container:
rsrc_id = zend_list_insert(rsrc_pointer, rsrc_type);

    if (rsrc_result) {
        rsrc_result->value.lval = rsrc_id;
        rsrc_result->type = IS_RESOURCE;
    }

    return rsrc_id;
The returned rsrc_id uniquly identifies the newly registered resource. You can use the macro RETURN_RESOURE to return it to the user:
RETURN_RESOURCE(rsrc_id)

注: It is common practice that if you want to return the resource immidiately to the user you specify the return_value as the zval * container.

Zend now keeps track of all references to this resource. As soon as all references to the resource are lost, the destructor that you previously registered for this resource is called. The nice thing about this setup is that you don't have to worry about memory leakages introduced by allocations in your module - just register all memory allocations that your calling script will refer to as resources. As soon as the script decides it doesn't need them anymore, Zend will find out and tell you.

Now that the user got his resource, at some point he is passing it back to one of your functions. The value.lval inside the zval * container contains the key to your resource and thus can be used to fetch the resource with the following macro: ZEND_FETCH_RESOURCE:
ZEND_FETCH_RESOURCE(rsrc, rsrc_type, rsrc_id, default_rsrc_id, resource_type_name, resource_type)

rsrc | This is your pointer which will point to your previously registered resource.
rsrc_type | This is the typecast argument for your pointer, e.g. myresource *.
rsrc_id | This is the address of the zval *container the user passed to your function, e.g. &z_resource if zval *z_resource is given.
default_rsrc_id | This integer specifies the default resource ID if no resource could be fetched or -1.
resource_type_name | This is the name of the requested resource. It's a string and is used when the resource can't be found or is invalid to form a meaningful error message.
resource_type | The resource_type you got back when registering the resource destruction handler. In our example this was le_myresource.

This macro has no return value. It is for the developers convenience and takes care of TSRMLS arguments passing and also does check if the resource could be fetched. It throws a warning message and returns the current PHP function with NULL if there was a problem retrieving the resource.

To force removal of a resource from the list, use the function zend_list_delete(). You can also force the reference count to increase if you know that you're creating another reference for a previously allocated value (for example, if you're automatically reusing a default database link). For this case, use the function zend_list_addref(). To search for previously allocated resource entries, use zend_list_find(). The complete API can be found in zend_list.h.

后退 | 起点 | 前进
Objects | 上一级 | Macros for Automatic Global Variable Creation


Macros for Automatic Global Variable Creation

In addition to the macros discussed earlier, a few macros allow easy creation of simple global variables. These are nice to know in case you want to introduce global flags, for example. This is somewhat bad practice, but Table 9.12 describes macros that do exactly this task. They don't need any zval allocation; you simply have to supply a variable name and value.

图形 35-9. Table 9.12. Macros for Global Variable Creation

Note: All macros in Table 9.12 create a global variable of the name "name" with the value "value".

Macro | Description
SET_VAR_STRING(name, value) | Creates a new string.
SET_VAR_STRINGL(name, value, length) | Creates a new string of the specified length. This macro is faster than SET_VAR_STRING and also binary-safe.
SET_VAR_LONG(name, value) | Creates a new long.
SET_VAR_DOUBLE(name, value) | Creates a new double.

后退 | 起点 | 前进
Resources | 上一级 | Creating Constants


Creating Constants

Zend supports the creation of true constants (as opposed to regular variables). Constants are accessed without the typical dollar sign ($) prefix and are available in all scopes. Examples include TRUE and FALSE, to name just two.

To create your own constants, you can use the macros in Table 9.13. All the macros create a constant with the specified name and value.

You can also specify flags for each constant:

  • CONST_CS - This constant's name is to be treated as case sensitive.

  • CONST_PERSISTENT - This constant is persistent and won't be "forgotten" when the current process carrying this constant shuts down.

To use the flags, combine them using a binary OR:
// register a new constant of type "long"
REGISTER_LONG_CONSTANT("NEW_MEANINGFUL_CONSTANT", 324, CONST_CS | CONST_PERSISTENT);
There are two types of macros - REGISTER_*_CONSTANT andREGISTER_MAIN_*_CONSTANT. The first type creates constants bound to the current module. These constants are dumped from the symbol table as soon as the module that registered the constant is unloaded from memory. The second type creates constants that remain in the symbol table independently of the module.

图形 35-10. Table 9.13. Macros for Creating Constants

Macro | Description
REGISTER_LONG_CONSTANT(name, value, flags) REGISTER_MAIN_LONG_CONSTANT(name, value, flags) | Registers a new constant of type long.
REGISTER_DOUBLE_CONSTANT(name, value, flags) REGISTER_MAIN_DOUBLE_CONSTANT(name, value, flags) | Registers a new constant of type double.
REGISTER_STRING_CONSTANT(name, value, flags) REGISTER_MAIN_STRING_CONSTANT(name, value, flags) | Registers a new constant of type string. The specified string must reside in Zend's internal memory.
REGISTER_STRINGL_CONSTANT(name, value, length, flags) REGISTER_MAIN_STRINGL_CONSTANT(name, value, length, flags) | Registers a new constant of type string. The string length is explicitly set to length. The specified string must reside in Zend's internal memory.

后退 | 起点 | 前进
Macros for Automatic Global Variable Creation | 上一级 | Duplicating Variable Contents: The Copy Constructor


Duplicating Variable Contents: The Copy Constructor

PHP 手册
后退 前进

章 36. Duplicating Variable Contents: The Copy Constructor

Sooner or later, you may need to assign the contents of one zval container to another. This is easier said than done, since the zval container doesn't contain only type information, but also references to places in Zend's internal data. For example, depending on their size, arrays and objects may be nested with lots of hash table entries. By assigning one zval to another, you avoid duplicating the hash table entries, using only a reference to them (at most).

To copy this complex kind of data, use the copy constructor. Copy constructors are typically defined in languages that support operator overloading, with the express purpose of copying complex types. If you define an object in such a language, you have the possibility of overloading the "=" operator, which is usually responsible for assigning the contents of the lvalue (result of the evaluation of the left side of the operator) to the rvalue (same for the right side).

Overloading means assigning a different meaning to this operator, and is usually used to assign a function call to an operator. Whenever this operator would be used on such an object in a program, this function would be called with the lvalue and rvalue as parameters. Equipped with that information, it can perform the operation it intends the "=" operator to have (usually an extended form of copying).

This same form of "extended copying" is also necessary for PHP's zval containers. Again, in the case of an array, this extended copying would imply re-creation of all hash table entries relating to this array. For strings, proper memory allocation would have to be assured, and so on.

Zend ships with such a function, called zend_copy_ctor() (the previous PHP equivalent was pval_copy_constructor()).

A most useful demonstration is a function that accepts a complex type as argument, modifies it, and then returns the argument:
zval *parameter;

if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &parameter) == FAILURE)
    return;
}

// do modifications to the parameter here

// now we want to return the modified container:
*return_value == *parameter;
zval_copy_ctor(return_value);
The first part of the function is plain-vanilla argument retrieval. After the (left out) modifications, however, it gets interesting: The container of parameter is assigned to the (predefined) return_value container. Now, in order to effectively duplicate its contents, the copy constructor is called. The copy constructor works directly with the supplied argument, and the standard return values are FAILURE on failure and SUCCESS on success.

If you omit the call to the copy constructor in this example, both parameter and return_value would point to the same internal data, meaning that return_value would be an illegal additional reference to the same data structures. Whenever changes occurred in the data that parameter points to, return_value might be affected. Thus, in order to create separate copies, the copy constructor must be used.

The copy constructor's counterpart in the Zend API, the destructor zval_dtor(), does the opposite of the constructor.

后退 | 起点 | 前进
Creating Constants | 上一级 | Returning Values


Returning Values

PHP 手册
后退 前进

章 37. Returning Values

Returning values from your functions to PHP was described briefly in an earlier section; this section gives the details. Return values are passed via the return_value variable, which is passed to your functions as argument. The return_value argument consists of a zval container (see the earlier discussion of the call interface) that you can freely modify. The container itself is already allocated, so you don't have to run MAKE_STD_ZVAL on it. Instead, you can access its members directly.

To make returning values from functions easier and to prevent hassles with accessing the internal structures of the zval container, a set of predefined macros is available (as usual). These macros automatically set the correspondent type and value, as described in Tables 9.14 and 9.15.

图形 37-1. Table 9.14. Predefined Macros for Returning Values from a Function

Note: The macros in Table 9.14 automatically return from your function.

Macro | Description
RETURN_RESOURCE(resource) | Returns a resource.
RETURN_BOOL(bool) | Returns a Boolean.
RETURN_NULL() | Returns nothing (a NULL value).
RETURN_LONG(long) | Returns a long.
RETURN_DOUBLE(double) | Returns a double.
RETURN_STRING(string, duplicate) | Returns a string. The duplicate flag indicates whether the string should be duplicated using estrdup().
RETURN_STRINGL(string, length, duplicate) | Returns a string of the specified length; otherwise, behaves like RETURN_STRING. This macro is faster and binary-safe, however.
RETURN_EMPTY_STRING() | Returns an empty string.
RETURN_FALSE | Returns Boolean false.
RETURN_TRUE | Returns Boolean true.

图形 37-2. Table 9.15. Predefined Macros for Setting the Return Value of a Function

Note: The macros in Table 9.15 only set the return value; they don't return from your function.

Macro | Description
RETVAL_RESOURCE(resource) | Sets the return value to the specified resource.
RETVAL_BOOL(bool) | Sets the return value to the specified Boolean value.
RETVAL_NULL | Sets the return value to NULL.
RETVAL_LONG(long) | Sets the return value to the specified long.
RETVAL_DOUBLE(double) | Sets the return value to the specified double.
RETVAL_STRING(string, duplicate) | Sets the return value to the specified string and duplicates it to Zend internal memory if desired (see also RETURN_STRING).
RETVAL_STRINGL(string, length, duplicate) | Sets the return value to the specified string and forces the length to become length (see also RETVAL_STRING). This macro is faster and binary-safe, and should be used whenever the string length is known.
RETVAL_EMPTY_STRING | Sets the return value to an empty string.
RETVAL_FALSE | Sets the return value to Boolean false.
RETVAL_TRUE | Sets the return value to Boolean true.

Complex types such as arrays and objects can be returned by using array_init() and object_init(), as well as the corresponding hash functions on return_value. Since these types cannot be constructed of trivial information, there are no predefined macros for them.

后退 | 起点 | 前进
Duplicating Variable Contents: The Copy Constructor | 上一级 | Printing Information


Printing Information

PHP 手册
后退 前进

章 38. Printing Information

目录
zend_printf()
zend_error()
Including Output in phpinfo()
Execution Information

Often it's necessary to print messages to the output stream from your module, just as print() would be used within a script. PHP offers functions for most generic tasks, such as printing warning messages, generating output for phpinfo(), and so on. The following sections provide more details. Examples of these functions can be found on the CD-ROM.

zend_printf()

zend_printf() works like the standard printf(), except that it prints to Zend's output stream.

后退 | 起点 | 前进
Returning Values | 上一级 | zend_error()


zend_error

PHP 手册
后退 章 38. Printing Information 前进

zend_error()

zend_error() can be used to generate error messages. This function accepts two arguments; the first is the error type (see zend_errors.h), and the second is the error message.
zend_error(E_WARNING, "This function has been called with empty arguments");
Table 9.16 shows a list of possible values (see Figure 9.8). These values are also referred to in php.ini. Depending on which error type you choose, your messages will be logged.

图形 38-1. Table 9.16. Zend's Predefined Error Messages.

Error | Description
E_ERROR | Signals an error and terminates execution of the script immediately.
E_WARNING | Signals a generic warning. Execution continues.
E_PARSE | Signals a parser error. Execution continues.
E_NOTICE | Signals a notice. Execution continues. Note that by default the display of this type of error messages is turned off in php.ini.
E_CORE_ERROR | Internal error by the core; shouldn't be used by user-written modules.
E_COMPILE_ERROR | Internal error by the compiler; shouldn't be used by user-written modules.
E_COMPILE_WARNING | Internal warning by the compiler; shouldn't be used by user-written modules.

图形 38-2. Figure 9.8. Display of warning messages in the browser.

后退 | 起点 | 前进
Printing Information | 上一级 | Including Output in phpinfo()


Including Output in phpinfo

PHP 手册
后退 章 38. Printing Information 前进

Including Output in phpinfo()

After creating a real module, you'll want to show information about the module in phpinfo() (in addition to the module name, which appears in the module list by default). PHP allows you to create your own section in the phpinfo() output with the ZEND_MINFO() function. This function should be placed in the module descriptor block (discussed earlier) and is always called whenever a script calls phpinfo().

PHP automatically prints a section in phpinfo() for you if you specify the ZEND_MINFO function, including the module name in the heading. Everything else must be formatted and printed by you.

Typically, you can print an HTML table header using php_info_print_table_start() and then use the standard functions php_info_print_table_header() and php_info_print_table_row(). As arguments, both take the number of columns (as integers) and the column contents (as strings). Listing 9.14 shows a source example; Figure 9.9 shows the output. To print the table footer, use php_info_print_table_end().

图形 38-3. Listing 9.14. Source code and screenshot for output in phpinfo().

php_info_print_table_start();
php_info_print_table_header(2, "First column", "Second column");
php_info_print_table_row(2, "Entry in first row", "Another entry");
php_info_print_table_row(2, "Just to fill", "another row here");
php_info_print_table_end();

后退 | 起点 | 前进
zend_error() | 上一级 | Execution Information


Execution Information

You can also print execution information, such as the current file being executed. The name of the function currently being executed can be retrieved using the function get_active_function_name(). This function returns a pointer to the function name and doesn't accept any arguments. To retrieve the name of the file currently being executed, use zend_get_executed_filename(). This function accesses the executor globals, which are passed to it using the ELS_C macro. The executor globals are automatically available to every function that's called directly by Zend (they're part of the INTERNAL_FUNCTION_PARAMETERS described earlier in this chapter). If you want to access the executor globals in another function that doesn't have them available automatically, call the macro ELS_FETCH() once in that function; this will introduce them to your local scope.

Finally, the line number currently being executed can be retrieved using the function zend_get_executed_lineno(). This function also requires the executor globals as arguments. For examples of these functions, see Listing 9.15 and Figure 9.10. Of course, all the examples are also available on the CD-ROM.

图形 38-4. Listing 9.15. Printing execution information.

zend_printf("The name of the current function is %s<br>", get_active_function_name());
zend_printf("The file currently executed is %s<br>", zend_get_executed_filename(ELS_C));
zend_printf("The current line being executed is %i<br>", zend_get_executed_lineno(ELS_C));

后退 | 起点 | 前进
Including Output in phpinfo() | 上一级 | Startup and Shutdown Functions


Startup and Shutdown Functions

PHP 手册
后退 前进

章 39. Startup and Shutdown Functions

Startup and shutdown functions can be used for one-time initialization and deinitialization of your modules. As discussed earlier in this chapter (see the description of the Zend module descriptor block), there are global, module, and request startup and shutdown events.

The global startup functions are called once when PHP starts up; similarly, the global shutdown functions are called once when PHP shuts down. Please note that they're really only called once, not when a new Apache process is being created!

The module startup and shutdown functions are called whenever a module is loaded and needs initialization; the request startup and shutdown functions are called every time a request is processed (meaning that a file is being executed).

For dynamic extensions, module and request startup/shutdown events happen at the same time.

Declaration and implementation of these functions can be done with macros; see the earlier section "Declaration of the Zend Module Block" for details.

后退 | 起点 | 前进
Execution Information | 上一级 | Calling User Functions


Calling User Functions

PHP 手册
后退 前进

章 40. Calling User Functions

You can call user functions from your own modules, which is very handy when implementing callbacks; for example, for array walking, searching, or simply for event-based programs.

User functions can be called with the function call_user_function_ex(). It requires a hash value for the function table you want to access, a pointer to an object (if you want to call a method), the function name, return value, number of arguments, argument array, and a flag indicating whether you want to perform zval separation.
ZEND_API int call_user_function_ex(HashTable *function_table, zval *object,
                                   zval *function_name, zval **retval_ptr_ptr,
                                   int param_count, zval **params[],
                                   int no_separation);
Note that you don't have to specify both function_table and object; either will do. If you want to call a method, you have to supply the object that contains this method, in which case call_user_function()automatically sets the function table to this object's function table. Otherwise, you only need to specify function_table and can set object to NULL.

Usually, the default function table is the "root" function table containing all function entries. This function table is part of the compiler globals and can be accessed using the macro CG. To introduce the compiler globals to your function, call the macro CLS_FETCH once.

The function name is specified in a zval container. This might be a bit surprising at first, but is quite a logical step, since most of the time you'll accept function names as parameters from calling functions within your script, which in turn are contained in zval containers again. Thus, you only have to pass your arguments through to this function. This zval must be of type IS_STRING.

The next argument consists of a pointer to the return value. You don't have to allocate memory for this container; the function will do so by itself. However, you have to destroy this container (using zval_dtor()) afterward!

Next is the parameter count as integer and an array containing all necessary parameters. The last argument specifies whether the function should perform zval separation - this should always be set to 0. If set to 1, the function consumes less memory but fails if any of the parameters need separation.

Listing 9.16 and Figure 9.11 show a small demonstration of calling a user function. The code calls a function that's supplied to it as argument and directly passes this function's return value through as its own return value. Note the use of the constructor and destructor calls at the end - it might not be necessary to do it this way here (since they should be separate values, the assignment might be safe), but this is bulletproof.

图形 40-1. Listing 9.16. Calling user functions.

zval **function_name;
zval *retval;

if((ZEND_NUM_ARGS() != 1) || (zend_get_parameters_ex(1, &function_name) != SUCCESS))
{
    WRONG_PARAM_COUNT;
}

if((*function_name)->type != IS_STRING)
{
    zend_error(E_ERROR, "Function requires string argument");
}

CLS_FETCH();

if(call_user_function_ex(CG(function_table), NULL, *function_name, &retval, 0, NULL, 0) != SUCCESS)
{
    zend_error(E_ERROR, "Function call failed");
}

zend_printf("We have %i as type<br>", retval->type);

*return_value = *retval;
zval_copy_ctor(return_value);
zval_ptr_dtor();

<?php

dl("call_userland.so");

function test_function()
{

    print("We are in the test function!<br>");

    return("hello");

}

$return_value = call_userland("test_function");

print("Return value: \"$return_value\"<br>");
?>

后退 | 起点 | 前进
Startup and Shutdown Functions | 上一级 | Initialization File Support


Initialization File Support

PHP 手册
后退 前进

章 41. Initialization File Support

PHP 4 features a redesigned initialization file support. It's now possible to specify default initialization entries directly in your code, read and change these values at runtime, and create message handlers for change notifications.

To create an .ini section in your own module, use the macros PHP_INI_BEGIN() to mark the beginning of such a section and PHP_INI_END() to mark its end. In between you can use PHP_INI_ENTRY() to create entries.
PHP_INI_BEGIN()
    PHP_INI_ENTRY("first_ini_entry",  "has_string_value", PHP_INI_ALL, NULL)
    PHP_INI_ENTRY("second_ini_entry", "2",                PHP_INI_SYSTEM, OnChangeSecond)
    PHP_INI_ENTRY("third_ini_entry",  "xyz",              PHP_INI_USER, NULL)
PHP_INI_END()
The PHP_INI_ENTRY() macro accepts four parameters: the entry name, the entry value, its change permissions, and a pointer to a change-notification handler. Both entry name and value must be specified as strings, regardless of whether they really are strings or integers.

The permissions are grouped into three sections:PHP_INI_SYSTEM allows a change only directly in the php3.ini file; PHP_INI_USER allows a change to be overridden by a user at runtime using additional configuration files, such as .htaccess; and PHP_INI_ALL allows changes to be made without restrictions. There's also a fourth level, PHP_INI_PERDIR, for which we couldn't verify its behavior yet.

The fourth parameter consists of a pointer to a change-notification handler. Whenever one of these initialization entries is changed, this handler is called. Such a handler can be declared using the PHP_INI_MH macro:
PHP_INI_MH(OnChangeSecond);             // handler for ini-entry "second_ini_entry"

// specify ini-entries here

PHP_INI_MH(OnChangeSecond)
{

    zend_printf("Message caught, our ini entry has been changed to %s<br>", new_value);

    return(SUCCESS);

}
The new value is given to the change handler as string in the variable new_value. When looking at the definition of PHP_INI_MH, you actually have a few parameters to use:
#define PHP_INI_MH(name) int name(php_ini_entry *entry, char *new_value,
                                  uint new_value_length, void *mh_arg1,
                                  void *mh_arg2, void *mh_arg3)
All these definitions can be found in php_ini.h. Your message handler will have access to a structure that contains the full entry, the new value, its length, and three optional arguments. These optional arguments can be specified with the additional macros PHP_INI_ENTRY1 (allowing one additional argument), PHP_INI_ENTRY2 (allowing two additional arguments), and PHP_INI_ENTRY3 (allowing three additional arguments).

The change-notification handlers should be used to cache initialization entries locally for faster access or to perform certain tasks that are required if a value changes. For example, if a constant connection to a certain host is required by a module and someone changes the hostname, automatically terminate the old connection and attempt a new one.

Access to initialization entries can also be handled with the macros shown in Table 9.17.

图形 41-1. Table 9.17. Macros to Access Initialization Entries in PHP

Macro | Description
INI_INT(name) | Returns the current value of entry name as integer (long).
INI_FLT(name) | Returns the current value of entry name as float (double).
INI_STR(name) | Returns the current value of entry name as string. Note: This string is not duplicated, but instead points to internal data. Further access requires duplication to local memory.
INI_BOOL(name) | Returns the current value of entry name as Boolean (defined as zend_bool, which currently means unsigned char).
INI_ORIG_INT(name) | Returns the original value of entry name as integer (long).
INI_ORIG_FLT(name) | Returns the original value of entry name as float (double).
INI_ORIG_STR(name) | Returns the original value of entry name as string. Note: This string is not duplicated, but instead points to internal data. Further access requires duplication to local memory.
INI_ORIG_BOOL(name) | Returns the original value of entry name as Boolean (defined as zend_bool, which currently means unsigned char).

Finally, you have to introduce your initialization entries to PHP. This can be done in the module startup and shutdown functions, using the macros REGISTER_INI_ENTRIES() and UNREGISTER_INI_ENTRIES():
ZEND_MINIT_FUNCTION(mymodule)
{

    REGISTER_INI_ENTRIES();

}

ZEND_MSHUTDOWN_FUNCTION(mymodule)
{

    UNREGISTER_INI_ENTRIES();

}

后退 | 起点 | 前进
Calling User Functions | 上一级 | Where to Go from Here


Where to Go from Here

PHP 手册
后退 前进

章 42. Where to Go from Here

You've learned a lot about PHP. You now know how to create dynamic loadable modules and statically linked extensions. You've learned how PHP and Zend deal with internal storage of variables and how you can create and access these variables. You know quite a set of tool functions that do a lot of routine tasks such as printing informational texts, automatically introducing variables to the symbol table, and so on.

Even though this chapter often had a mostly "referential" character, we hope that it gave you insight on how to start writing your own extensions. For the sake of space, we had to leave out a lot; we suggest that you take the time to study the header files and some modules (especially the ones in the ext/standard directory and the MySQL module, as these implement commonly known functionality). This will give you an idea of how other people have used the API functions - particularly those that didn't make it into this chapter.

后退 | 起点 | 前进
Initialization File Support | 上一级 | Reference: Some Configuration Macros


Reference: Some Configuration Macros

PHP 手册
后退 前进

章 43. Reference: Some Configuration Macros

目录
config.m4

config.m4

The file config.m4 is processed by buildconf and must contain all the instructions to be executed during configuration. For example, these can include tests for required external files, such as header files, libraries, and so on. PHP defines a set of macros that can be used in this process, the most useful of which are described in Table 9.18.

图形 43-1. Table 9.18. M4 Macros for config.m4

Macro | Description
AC_MSG_CHECKING(message) | Prints a "checking <message>" text during configure.
AC_MSG_RESULT(value) | Gives the result to AC_MSG_CHECKING; should specify either yes or no as value.
AC_MSG_ERROR(message) | Prints message as error message during configure and aborts the script.
AC_DEFINE(name,value,description) | Adds #define to php_config.h with the value of value and a comment that says description (this is useful for conditional compilation of your module).
AC_ADD_INCLUDE(path) | Adds a compiler include path; for example, used if the module needs to add search paths for header files.
AC_ADD_LIBRARY_WITH_PATH(libraryname,librarypath) | Specifies an additional library to link.
AC_ARG_WITH(modulename,description,unconditionaltest,conditionaltest) | Quite a powerful macro, adding the module with description to the configure --help output. PHP checks whether the option --with-<modulename> is given to the configure script. If so, it runs the script unconditionaltest (for example, --with-myext=yes), in which case the value of the option is contained in the variable $withval. Otherwise, it executes conditionaltest.
PHP_EXTENSION(modulename, [shared]) | This macro is a must to call for PHP to configure your extension. You can supply a second argument in addition to your module name, indicating whether you intend compilation as a shared module. This will result in a definition at compile time for your source as COMPILE_DL_<modulename>.

后退 | 起点 | 前进
Where to Go from Here | 上一级 | API Macros


API Macros

PHP 手册
后退 前进

章 44. API Macros

A set of macros was introduced into Zend's API that simplify access to zval containers (see Table 9.19).

图形 44-1. Table 9.19. API Macros for Accessing zval Containers

Macro | Refers to
Z_LVAL(zval) | (zval).value.lval
Z_DVAL(zval) | (zval).value.dval
Z_STRVAL(zval) | (zval).value.str.val
Z_STRLEN(zval) | (zval).value.str.len
Z_ARRVAL(zval) | (zval).value.ht
Z_LVAL_P(zval) | (*zval).value.lval
Z_DVAL_P(zval) | (*zval).value.dval
Z_STRVAL_P(zval_p) | (*zval).value.str.val
Z_STRLEN_P(zval_p) | (*zval).value.str.len
Z_ARRVAL_P(zval_p) | (*zval).value.ht
Z_LVAL_PP(zval_pp) | (**zval).value.lval
Z_DVAL_PP(zval_pp) | (**zval).value.dval
Z_STRVAL_PP(zval_pp) | (**zval).value.str.val
Z_STRLEN_PP(zval_pp) | (**zval).value.str.len
Z_ARRVAL_PP(zval_pp) | (**zval).value.ht

后退 | 起点 | 前进
Reference: Some Configuration Macros | 上一级 | Streams API for PHP Extension Authors


Streams API for PHP Extension Authors

PHP 手册
后退 前进

章 45. Streams API for PHP Extension Authors

目录
Overview
Streams Basics
Streams Common API Reference
Streams Dir API Reference
Streams File API Reference
Streams Socket API Reference
Streams Structures
Streams Constants

Overview

The PHP Streams API introduces a unified approach to the handling of files and sockets in PHP extension. Using a single API with standard functions for common operations, the streams API allows your extension to access files, sockets, URLs, memory and script-defined objects. Streams is a run-time extensible API that allows dynamically loaded modules (and scripts!) to register new streams.

The aim of the Streams API is to make it comfortable for developers to open files, urls and other streamable data sources with a unified API that is easy to understand. The API is more or less based on the ANSI C stdio family of functions (with identical semantics for most of the main functions), so C programmers will have a feeling of familiarity with streams.

The streams API operates on a couple of different levels: at the base level, the API defines php_stream objects to represent streamable data sources. On a slightly higher level, the API defines php_stream_wrapper objects which "wrap" around the lower level API to provide support for retrieving data and meta-data from URLs.

Streams can be cast (converted) into other types of file-handles, so that they can be used with third-party libraries without a great deal of trouble. This allows those libraries to access data directly from URL sources. If your system has the fopencookie() function, you can even pass any PHP stream to any library that uses ANSI stdio!

后退 | 起点 | 前进
API Macros |  | Streams Basics


Streams Basics

Using streams is very much like using ANSI stdio functions. The main difference is in how you obtain the stream handle to begin with. In most cases, you will use php_stream_open_wrapper() to obtain the stream handle. This function works very much like fopen, as can be seen from the example below:

例子 45-1. simple stream example that displays the PHP home page

php_stream * stream = php_stream_open_wrapper("http://www.php.net", "rb", REPORT_ERRORS, NULL);
if (stream) {
    while(!php_stream_eof(stream)) {
        char buf[1024];

        if (php_stream_gets(stream, buf, sizeof(buf))) {
            printf(buf);
        } else {
            break;
        }
    }
    php_stream_close(stream);
}

The table below shows the Streams equivalents of the more common ANSI stdio functions. Unless noted otherwise, the semantics of the functions are identical.

表格 45-1. ANSI stdio equivalent functions in the Streams API

ANSI Stdio Function | PHP Streams Function | Notes
fopen | php_stream_open_wrapper | Streams includes additional parameters
fclose | php_stream_close |
fgets | php_stream_gets |
fread | php_stream_read | The nmemb parameter is assumed to have a value of 1, so the prototype looks more like read(2)
fwrite | php_stream_write | The nmemb parameter is assumed to have a value of 1, so the prototype looks more like write(2)
fseek | php_stream_seek |
ftell | php_stream_tell |
rewind | php_stream_rewind |
feof | php_stream_eof |
fgetc | php_stream_getc |
fputc | php_stream_putc |
fflush | php_stream_flush |
puts | php_stream_puts | Same semantics as puts, NOT fputs
fstat | php_stream_stat | Streams has a richer stat structure

后退 | 起点 | 前进
Streams API for PHP Extension Authors | 上一级 | Streams Common API Reference


Streams Common API Reference

后退 | 起点 | 前进
Streams Basics | 上一级 | php_stream_stat_path


Streams Dir API Reference

The functions listed in this section work on local files, as well as remote files (provided that the wrapper supports this functionality!).

后退 | 起点 | 前进
php_stream_open_wrapper_as_file | 上一级 | php_stream_opendir


Streams File API Reference

后退 | 起点 | 前进
php_stream_closedir | 上一级 | php_stream_fopen_from_file


Streams Socket API Reference

后退 | 起点 | 前进
php_stream_fopen_temporary_file | 上一级 | php_stream_sock_open_from_socket


Streams Structures

后退 | 起点 | 前进
php_stream_sock_open_unix | 上一级 | struct php_stream_statbuf


Streams Constants

后退 | 起点 | 前进
struct php_stream_dirent | 上一级 | Stream open options


FAQ: 常见问题

PHP 手册
后退 前进

VI. FAQ: 常见问题

目录
46. 一般信息
47. 邮件列表
48. 获取 PHP
49. 数据库问题
50. 安装
51. 编译问题
52. 使用 PHP
53. PHP 和 HTML
54. PHP 和 COM
55. PHP 和其它语言
56. 从 PHP/FI 2 移植到 PHP 3
57. 从 PHP 3 移植到 PHP 4
58. 杂类问题

后退 | 起点 | 前进
Stream open options |  | 一般信息


一般信息

PHP 手册
后退 前进

章 46. 一般信息

本章包括了有关 PHP 的大多数一般问题：它是什么和它做什么。

1. PHP 是什么？
2. PHP 这个缩写指的是什么？
3. PHP 版本之间有什么联系？
4. 可以同时运行几个不同版本的 PHP 吗？
5. PHP 3 和 PHP 4 的区别有哪些？
6. 我发现了一个 bug！应该告诉谁？

1. PHP 是什么？

根据本手册的序文：

PHP 是一种 HTML 嵌入式的脚本语言。它的很多语法来自 C，Java 和 Perl，并具有几个 PHP 独有的特点。该语言的主要目标是让 Web 开发人员快速的书写动态生成的网页。

这里有一个位于 Zend 网站中由 Stig Sæther Bakken 所写很好的介绍。同样，大量的PHP 研讨会素材也可以免费得到。

2. PHP 这个缩写指的是什么？

PHP 是 PHP: Hypertext Preprocessor 的缩写。很多人有些糊涂了，因为缩写中第一个字母也是个缩写。这种方法叫做递归缩写，对此好奇的人可以访问 Free On-Line Dictionary of Computing 来得到更多递归缩写的信息。

3. PHP 版本之间有什么联系？

PHP/FI 2.0 是最早的 PHP 版本，已经不再支持。PHP 3 是 PHP/FI 2.0 的后继者，要好很多。PHP 4 是最新一代的 PHP，内部使用了 Zend 引擎。

4. 可以同时运行几个不同版本的 PHP 吗？

可以，见 PHP 4 源程序发行包中的 INSTALL 文件。同样也可以阅读相关附录。

5. PHP 3 和 PHP 4 的区别有哪些？

对此问题有 PHP 4 的作者写的一些说明。这里列出一些比较重要的新特点：

  • 扩展了 API 模块

  • UNIX 下的通用编译步骤

  • 支持多线程 web 服务器的通用 web 服务器接口

  • 增强了语法高亮显示

  • 支持本地 HTTP session

  • 支持输出缓冲

  • 更强大的配置系统

  • 引用计数

请访问PHP 4 新特点概览查看以上及更多特点的详细解释。如果你从 PHP 3 移植到 PHP 4，也请阅读相关的附录。

6. 我发现了一个 bug！应该告诉谁？

你应该访问 PHP Bug 数据库并确认你发现的不是一个已知的 bug。如果你在数据库中没有看到同样的，用报告表单来报告此 bug。使用 bug 数据库而不是给某个邮件列表发邮件非常重要，因为该 bug 会被分配一个跟踪号码，这样你就有可能在以后回来查看该 bug 的状态。Bug 数据库在 http://bugs.php.net/。

后退 | 起点 | 前进
FAQ: 常见问题 | 上一级 | 邮件列表


邮件列表

PHP 手册
后退 前进

章 47. 邮件列表

本节包括有关如何与 PHP 团体接触的问题。最好的方法是邮件列表。

1. 有没有 PHP 的邮件列表？
2. 还有其它的团体吗？
3. 救命！我看来不能订阅／取消任何一个邮件列表！
4. 在哪里有个邮件列表的归档吗？
5. 我可以在邮件列表中问什么？
6. 向邮件列表发帖子时我需要包括些什么信息？

1. 有没有 PHP 的邮件列表？

当然有！有很多关于几个主题的邮件列表。所有邮件列表的完整列表在技术支持页面。

最通用的邮件列表是 php-general。要订阅，发送一封邮件到 php-general-subscribe@lists.php.net。不需要在邮件主题或内容中包括任何特殊单词。要取消订阅，发送一封邮件到 php-general-unsubscribe@lists.php.net。

也可以在我们的技术支持页面通过 web 界面来订阅和取消。

2. 还有其它的团体吗？

世界上有无数 PHP 团体。我们的技术支持页面上有例如一些 IRC 服务器和其它语种的邮件列表。

3. 救命！我看来不能订阅／取消任何一个邮件列表！

如果你在订阅或取消 php-general 邮件列表上有问题，可能是因为邮件列表软件没法决定正确的邮件地址去使用。如果你的 email 地址是 joeblow@example.com，可以将订阅请求发送到 php-general-subscribe-joeblow=example.com@lists.php.net，或者将取消请求发送到 php-general-unsubscribe-joeblow=example.com@lists.php.net。对其它邮件列表用类似的地址。

4. 在哪里有个邮件列表的归档吗？

是的，你可以在技术支持页面找到归档站点的列表。邮件列表的文章也被作为新闻组消息归档。你可以用新闻组客户端来访问位于 news://news.php.net/ 的新闻组服务器。也有一个试验性质的新闻组服务器的 web 界面位于 http://news.php.net/。

5. 我可以在邮件列表中问什么？

由于 PHP 一天比一天更流行，php-general 邮件列表的流量增加到现在的每天 150 到 200 个帖子。由于此原因，为了每个人的利益使用此列表是你在寻找过所有其它地方后的最后手段。

在你向列表发帖之前请先看看本 FAQ 以及手册是不是能找到帮助。如果找不到的话试试邮件列表归档（见上面）。如果你有安装或者配置 PHP 的问题请从头到尾读一遍所有包含的文档和 README's。如果还是不能找到任何可以帮助你的信息，那么很欢迎你使用此邮件列表。

6. 向邮件列表发帖子时我需要包括些什么信息？

像“我不能启动运行 PHP！帮帮我！哪里出错了？”之类的贴子对任何人都完全没有用。如果你在启动和运行 PHP 上有问题你必须包括你运行的操作系统，你试图配置的 PHP 版本，你怎样得到的（预编译的，CVS，RPM 等等），目前为止你都做了些什么，卡在了何处以及确切的错误信息。

这也同样适用于其它问题。你必须包括你做了什么，卡在了哪里，你试图做什么以及，如果有的话，确切的错误信息。如果你有源代码的问题那你需要包括不起作用部分的代码。可是不要包括超出所必需的代码！这将使贴子很难读并使很多人为此而跳过它。如果你不确定应该在邮件中包括多少信息，那包括多一些比一点点更好。

另一件重要的事是记住在主题一行中概述你的问题。类似“救命！”或者“这是什么问题？”的主题会被一大半读者忽略。

后退 | 起点 | 前进
一般信息 | 上一级 | 获取 PHP


获取 PHP

PHP 手册
后退 前进

章 48. 获取 PHP

本节包括 PHP 下载地址以及操作系统相关问题的详细资料。

1. PHP 可以从哪里得到？
2. 有预先编译好的可执行版本吗？
3. 编译一些可选的 PHP 扩展库所需的库文件可以从哪里得到？
4. 怎样使这些库起作用？
5. 我在 Windows 机器中从 CVS 里得到了最新版的 PHP 源代码，需要什么去编译它？
6. 哪里可以找到 browscap.ini 文件？

1. PHP 可以从哪里得到？

可以从任何一个 PHP 网络成员的站点下载 PHP。这些信息在 http://www.php.net/。还可以通过匿名 CVS 得到绝对是最新版的源程序。更多信息请访问 http://cvs.php.net/。

2. 有预先编译好的可执行版本吗？

我们只为 Windows 系统提供了预编译的可执行文件，因为我们没法为每个主流的 Linux/Unix 平台编译每一种扩展库组和的 PHP。同样注意，如今很多 Linux 的发行版本已经内置了 PHP。Windows 可执行文件可以从我们的下载页面下载，至于 Linux 可执行文件，请访问你的 Linux 发布商的站点。

3. 编译一些可选的 PHP 扩展库所需的库文件可以从哪里得到？

注: 有 * 号标记的不是多线程的库，不应该用作多线程 Windows web 服务器（IIS，Netscape）的服务器模块。不过这在 Unix 环境下没有关系。

  • LDAP (Unix).

  • LDAP* (Unix).

  • LDAP (Unix/Win) : Netscape Directory (LDAP) SDK 1.1.

  • free LDAP server.

  • Berkeley DB2 (Unix/Win) : http://www.sleepycat.com/.

  • SNMP* (Unix): .

  • GD* (Unix/Win).

  • mSQL* (Win).

  • mSQL* (Unix).

  • PostgreSQL (Unix).

  • IMAP* (Win/Unix).

  • Sybase-CT* (Linux, libc5) : Available locally.

  • FreeType (libttf):.

  • ZLib (Unix/Win32).

  • expat XML parser (Unix/Win32).

  • PDFLib.

  • mcrypt.

  • mhash.

  • t1lib.

  • dmalloc.

  • aspell.

  • readline.

4. 怎样使这些库起作用？

你需要按照这些库提供的说明进行。一些库可以在你运行 PHP 的“configure”时自动检测到（例如 GD 库），其它的你必需用“--with-EXTENSION”选项来激活。运行“configure --help”来得到完整的列表。

5. 我在 Windows 机器中从 CVS 里得到了最新版的 PHP 源代码，需要什么去编译它？

首先，你需要 Microsoft Visual C++ v6（v5 也许也行，不过我们是用 v6 编译的），此外你还需要一些支持文件。参见手册中的在 Windows 下编译 PHP 源代码一节。

6. 哪里可以找到 browscap.ini 文件？

你可以从 http://www.cyscape.com/asp/browscap/ 得到一个 browscap.ini 文件。

后退 | 起点 | 前进
邮件列表 | 上一级 | 数据库问题


数据库问题

PHP 手册
后退 前进

章 49. 数据库问题

本节包括 PHP 和数据库之间关系的常见问题。是的，PHP 事实上可以访问如今现有的任何数据库。

1. 听说 PHP 有可能访问 Microsoft SQL Server，怎样访问？
2. 能访问 Microsoft Access 数据库吗？
3. 我升级到了 PHP 4，结果 MySQL 不断报告“Warning: MySQL: Unable to save result set in ..”，这是怎么回事？
4. 在安装共享 MySQL 支持之后，只要一加载 libphp4.so，Apache就会 core dump。这个问题能解决吗？
5. 为什么我得到类似如下的错误：“Warning: 0 is not a MySQL result index in <file> on line <x>”或者“Warning: Supplied argument is not a valid MySQL result resource in <file> on line <x>”？

1. 听说 PHP 有可能访问 Microsoft SQL Server，怎样访问？

在 Windows 机器中，你可以简单地使用内置的 ODBC 支持和正确的 ODBC 驱动程序。

在 Unix 机器中，你可以用 Sybase-CT 驱动程序来访问 Microsoft SQL Server，因为它们的协议是（至少大部分）兼容的。Sybase 做了一个 Linux 系统下所需库的免费版本。对于其它 Unix 操作系统，你需要和 Sybase 联系来得到正确的库。同样也看看下一个问题的回答。

2. 能访问 Microsoft Access 数据库吗？

可以。如果你完全在 Windows 9x/Me/NT/2000 下运行，那你已经有了所有所需的工具，你可以用 ODBC 和 Microsoft's ODBC drivers for Microsoft Access database。

如果你在 Unix 下运行 PHP 而想访问 Windows 中的 MS Access，那你需要 Unix ODBC 驱动程序。OpenLink Software 有一个基于 Unix 的 ODBC 驱动程序可以做这件事。你可以下载和试用一个不会过期的免费程序，商业支持版本的价格从 $675 起。

另外一个替代方案是用带 Windows ODBC 驱动的 SQL Server 并用它来储存数据，你可以通过 Microsoft Access（用 ODBC）和 PHP（用内置驱动）来访问，或者用一个 Access 和 PHP 都识别的中间文件格式，例如 flat 文件或者 dBase 数据库。关于这一点 OpenLink Software 的 Tim Hayes 写道：
当你可以通过 ODBC 直接从 PHP 访问数据库时－ 例如用 OpenLink 的驱动程序，
使用其它数据库做中间媒介不是一个好主意。如果你确实需要一个中间文件格式，
OpenLink 已经发布了 Virtuoso（一个虚拟数据库引擎） for NT，Linux 和其它
Unix 平台。请访问我们的网站来免费下载。

还有一个已被证实有效的选择是在 Windows 下用 MySQL 和它的 MyODBC 驱动来同步数据库。Steve Lawrence 写道：

  • 根据 MySQL 的说明在你的平台上安装 MySQL。可以从 www.mysql.com 得到最新版（从你最近的镜像站点下载！）。除了设定数据库和配置用户帐号以外不需要特殊的配置，你应该在 host 字段中放一个 % 或者你要用来访问 MySQL 的 Windows 机器名。记下你的服务器名，用户名和密码。

  • 从 MySQL 网站下载 MyODBC for Windows 驱动程序。最新版是 myodbc-2_50_19-win95.zip（也可以用于 NT，以及源代码）。在你的 Windows 机器中安装它。你可以用此程序中包括的工具来测试其操作。

  • 用控制面板中的 ODBC 管理器新建一个用户或系统 dsn，设定 dsn 名称，输入你在第一步中配置的 MySQL 数据库的主机名，用户名，密码，端口等。

  • 完整安装 Access，这样可以确保得到适当的插件 ... 至少你需要 ODBC 支持和连接表管理器。

  • 新建一个 Access 数据库。在 Table 窗口点击右键并选择 Link Tables，或者在 File 菜单下选择 Get External Data -> Link Tables。当文件浏览窗口打开后，选择文件类型为：ODBC。接着选择 System dsn 以及你在第三步建立的 dsn 的名字。再选择要连接的表，点击 OK。现在你可以在你的 MySQL 服务器中打开表并新建／删除／编辑数据了！你也可以构造查询，导入／导出表到 MySQL，构造表单和报告等。

提示与技巧：

  • 你可以在 Access 中构造表并导出到 MySQL 中，再把它们连接回来。这样可以使表的建立更快。

  • 在 Access 中建立表时，你必需定义一个基本键名来取得表的写权限。确认你在把表连接到 Access 之前在 MySQL 中建立了基本键名。

  • 如果你在 MySQL 中修改了表，必需重新连接到 Access。打开 Tools>Add-ins>Linked table manager，找到你的 ODBC DSN，然后在这里选择要重新连接的表。你也可以在这里移动 dsn 源，在点击 OK 之前选中 always prompt for new location。

3. 我升级到了 PHP 4，结果 MySQL 不断报告“Warning: MySQL: Unable to save result set in ..”，这是怎么回事？

看上去最有可能的是，PHP 4 在编译时使用了“--with-mysql”选项但没有指定 MySQL 的路径。这意味着 PHP 使用了它自己内置的 MySQL 客户端库。如果你的系统运行了使用其它版本的 MySQL 客户端库的应用程序，例如作为 Apache 模块的 PHP 3，那么在两个不同版本的客户端之间有冲突。

重新编译 PHP 4，并在标记中加上 MySQL 的路径，“--with-mysql=/your/path/to/mysql”通常会解决此问题。

4. 在安装共享 MySQL 支持之后，只要一加载 libphp4.so，Apache就会 core dump。这个问题能解决吗？

如果你的 MySQL 库依靠 pthreads 连接就会这样。检查使用 ldd。如果有的话，下载 MySQL 源程序编译，或者从源 rpm 的 spec 文件中去掉打开 threaded client 的选项然后重新编译。以上任一建议会解决此问题。然后再加上新的 MySQL 库重新编译 PHP。

5. 为什么我得到类似如下的错误：“Warning: 0 is not a MySQL result index in <file> on line <x>”或者“Warning: Supplied argument is not a valid MySQL result resource in <file> on line <x>”？

你试图用一个值为 0 的结果资源号。0 表示你的查询由于某原因失败了。你需要在提交查询之后和在使用返回结果资源号之前检查错误。正确的方法是用类似如下的代码：
$result = mysql_query("SELECT * FROM tables_priv");
if (!$result) {
    echo mysql_error();
    exit;
}
or
$result = mysql_query("SELECT * FROM tables_priv")
    or die("Bad query: ".mysql_error());

后退 | 起点 | 前进
获取 PHP | 上一级 | 安装


安装

PHP 手册
后退 前进

章 50. 安装

本章包括了安装 PHP 的常见问题。PHP 可以用于几乎任何操作系统（可能除了 OSX 之前的 MacOS 之外），以及几乎任何 web 服务器。

要安装 PHP，请按照发行包中 INSTALL 文件的说明进行。Windows 用户同样还要阅读 install.txt 文件。对于 Windows 用户还有一些有用的提示在 Windows 系统下安装一节。

1. Unix/Windows：应该上哪儿去找我的 php.ini 文件？
2. Unix：我安装了 PHP，但每次我打开一个页面时，只得到一条“Document Contains No Data”消息！这是怎么回事？
3. Unix：我从 RPMS 安装了 PHP，但是 Apache 不处理 PHP 页面！这是怎么回事？
4. Unix：我从 RPMS 安装了 PHP 3，但它没有把我需要的数据库支持编译进去！这是怎么回事？
5. Unix：我给 Apache 加上了 FrontPage extensions 补丁，结果 PHP 突然不工作了。PHP 和 Apache FrontPage extensions 兼容吗？
6. Unix/Windows：我已经安装了 PHP，但当我试着通过浏览器访问 PHP 脚本时，得到了一个空白页面。
7. Unix/Windows：我已经安装了 PHP，但当我试着通过浏览器访问 PHP 脚本时，得到了一个服务器的 500 错误。
8. 某些操作系统：我已经在不出错的情况下安装了 PHP，但当我试着启动 Apache 时得到了一个未定义符号错误：
[mybox:user /src/php4] root# apachectl configtest
 apachectl: /usr/local/apache/bin/httpd Undefined symbols:
  _compress
  _uncompress
9. Windows：我已经安装了 PHP，但当我试着通过浏览器访问 PHP 脚本时，得到如下错误：
cgi error:
 The specified CGI application misbehaved by not
 returning a complete set of HTTP headers.
 The headers it did return are:
10. Windows：我已经照着所有的说明做了，但还是不能让 PHP 和 IIS 一起工作！

1. Unix/Windows：应该上哪儿去找我的 php.ini 文件？

UNIX 中默认在 /usr/local/lib 目录中，也就是 <install-path>/lib。很多人会在编译时通过 --with-config-file-path 标记来改变路径。例如你可以将路径设为：
--with-config-file-path=/etc
然后从发行包中将 php.ini-dist 拷贝为 /etc/php.ini 并编辑它来作出你想要的修改。

Windows 中 php.ini 文件的默认路径在 Windows 目录下。如果你使用的是 Apache 服务器，则会首先在 Apache 的安装目录中寻找 php.ini，例如 C:\Program Files\Apache Group\Apache。这样同一台机器上不同版本的 Apache 就可以有不同的 php.ini 文件。

参见配置文件。

2. Unix：我安装了 PHP，但每次我打开一个页面时，只得到一条“Document Contains No Data”消息！这是怎么回事？

这可能意味着 PHP 发生了某类错误而导致了 core dump。查看服务器的错误日志看看是不是这样，再用一个小的测试例子试着重现此问题。如果你会用“gdb”的话，那么在 bug 报告中提供回溯跟踪很有助于帮开发人员查明问题。如果你用 Apache 的模块方式使用 PHP，试着这么做：

  • 停止 httpd 进程

  • gdb httpd

  • 停止 httpd 进程

  • > run -X -f /path/to/httpd.conf

  • 然后在你的浏览器中访问导致错误的 URL

  • > run -X -f /path/to/httpd.conf

  • 如果你遇到 core dump，gdb 此时就会通知你

  • 输入：bt

  • 你应该在 bug 报告中包括回溯追踪记录。应该提交到 http://bugs.php.net/

如果你的脚本使用了正则表达式函数（ereg() 等），应该确认在编译 PHP 和 Apache 时使用了同一个正则表达式包。在 PHP 和 Apache 1.3.x 中应该自动就是这样。

3. Unix：我从 RPMS 安装了 PHP，但是 Apache 不处理 PHP 页面！这是怎么回事？

假定你的 Apache 和 PHP 都是从 RPM 包中安装的，你需要在 http.conf 文件中取消以下部分或所有行的注释，或者把它们添加到该文件中：
# Extra Modules
AddModule mod_php.c
AddModule mod_php3.c
AddModule mod_perl.c

# Extra Modules
LoadModule php_module         modules/mod_php.so
LoadModule php3_module        modules/libphp3.so     /* for PHP 3 */
LoadModule php4_module        modules/libphp4.so     /* for PHP 4 */
LoadModule perl_module        modules/libperl.so
并且把：
AddType application/x-httpd-php3 .php3    /* for PHP 3 */
AddType application/x-httpd-php .php      /* for PHP 4 */
添加到全局属性中，或者添加到你希望加入 PHP 支持的虚拟域中。

4. Unix：我从 RPMS 安装了 PHP 3，但它没有把我需要的数据库支持编译进去！这是怎么回事？

由于 PHP 3 构造的原因，不容易编译出一个完全灵活的 PHP RPM 包来。这个问题在 PHP 4 中解决了。对于 PHP 3 来说，我们目前建议你用 PHP 发行包中 INSTALL.REDHAT 文件中所描述的机制。如果你坚持要用 PHP 3 的 RPM 版本，请接着往下看。

为了简化安装以及由于 RPMS 使用了 /usr/ 而不是标准的 /usr/local/ 目录来存放文件，制作 RPM 包的人设定 RPMS 不安装任何数据库支持。你需要告诉 RPM 说明文件，你想要支持哪个数据库以及你的数据库服务器最高层路径。

下面的例子解说了如何在用模块安装下的 Apache 中加入流行的 MySQL 数据库服务器支持的过程。

当然这些信息可以调整用于任何 PHP 支持的数据库服务器。本例中我们也假定你从 RPMS 中完整安装了 MySQL 和 Apache。

  • 先去掉 mod_php3：
    rpm -e mod_php3

  • 然后取得源文件的 rpm 包并安装它，而不是编译它。
    rpm -Uvh mod_php3-3.0.5-2.src.rpm

  • 接着编辑 /usr/src/redhat/SPECS/mod_php3.spec 文件

    在 %build 一节加入你想要的数据库支持，以及路径。

    对应于 MySQL 你应该加入
    --with-mysql=/usr \
    %build 一节看上去将类似这样：
    ./configure --prefix=/usr \
    --with-apxs=/usr/sbin/apxs \
    --with-config-file-path=/usr/lib \
    --enable-debug=no \
    --enable-safe-mode \
    --with-exec-dir=/usr/bin \
    --with-mysql=/usr \
    --with-system-regex

  • 一旦完成了这个修改，就这样建立二进制程序的 rpm 包：
    rpm -bb /usr/src/redhat/SPECS/mod_php3.spec

  • 然后安装 rpm
    rpm -ivh /usr/src/redhat/RPMS/i386/mod_php3-3.0.5-2.i386.rpm

确认重新启动了 Apache，这下你就有了用 RPM 安装的并且带 MySQL 支持的 PHP 3 了。注意按照 PHP 3 发行包中 INSTALL.REDHAT 文件的说明来编译其实也许更容易一些。

5. Unix：我给 Apache 加上了 FrontPage extensions 补丁，结果 PHP 突然不工作了。PHP 和 Apache FrontPage extensions 兼容吗？

兼容的。PHP 可以和 FrontPage extensions 一起工作，问题是 FrontPage 补丁修改了几个 PHP 依赖的 Apache 构造。在 FrontPage 补丁安装之后之后重新编译 PHP（用“make clean ; make”）可以解决此问题。

6. Unix/Windows：我已经安装了 PHP，但当我试着通过浏览器访问 PHP 脚本时，得到了一个空白页面。

用浏览器中的“查看源文件”，你可能会发现你能看到 PHP 脚本的源程序。这意味着 web 服务器没有把脚本发送给 PHP 解释。服务器配置在某处有问题，请对照 PHP 安装说明仔细检查服务器配置。

7. Unix/Windows：我已经安装了 PHP，但当我试着通过浏览器访问 PHP 脚本时，得到了一个服务器的 500 错误。

当服务器尝试运行 PHP 时出了错。要想看到有意义的错误信息，在命令行中转到 PHP 可执行程序（Windows 中是 php.exe）所在目录下并运行 php -i。如果 PHP 运行有任何问题，那么会显示相应的错误信息，这将给你下一步要做什么的线索。如果你得到满屏幕 html 代码（phpinfo() 函数的输出）的话说明 PHP 本身工作正常，你的问题可能和你的服务器配置有关，要仔细检查。

8. 某些操作系统：我已经在不出错的情况下安装了 PHP，但当我试着启动 Apache 时得到了一个未定义符号错误：
[mybox:user /src/php4] root# apachectl configtest
 apachectl: /usr/local/apache/bin/httpd Undefined symbols:
  _compress
  _uncompress

这实际上和 PHP 没有关系，而和 MySQL 的客户端库有关。有的需要 --with-zlib，有的不需要。这个问题也包括在 MySQL 的 FAQ 中。

9. Windows：我已经安装了 PHP，但当我试着通过浏览器访问 PHP 脚本时，得到如下错误：
cgi error:
 The specified CGI application misbehaved by not
 returning a complete set of HTTP headers.
 The headers it did return are:

这个错误信息意味着 PHP 根本就不能产生任何输出。要想看到有意义的错误信息，在命令行中转到 PHP 可执行程序（Windows 中是 php.exe）所在目录下并运行 php -i。如果 PHP 运行有任何问题，那么会显示相应的错误信息，这将给你下一步要做什么的线索。如果你得到满屏幕 html 代码（phpinfo() 函数的输出）的话说明 PHP 本身工作正常。

一旦 PHP 在命令行中工作正常，试着通过浏览器再次访问脚本。如果还失败的话那可能是如下原因之一：

  • 文件权限问题，你的 PHP 脚本，php.exe，php4ts.dll，php.ini 或任何你要加载的 PHP 扩展库是匿名 internet 用户 ISUR_<machinename> 无权访问的。

  • 脚本文件不存在（或者有可能不在你以为的地方，注意 web 文档的目录）。注意在 IIS 中通过 Internet 服务管理器设定脚本映射时选中“检查文件是否存在”可以捕捉到此错误。这样一来如果脚本文件不存在的话服务器就会返回一个 404 错误信息。还有一个额外的好处就是 IIS 会基于 NTLanMan 权限来替你对脚本文件做任何所需要的认证。

10. Windows：我已经照着所有的说明做了，但还是不能让 PHP 和 IIS 一起工作！

确认需要运行 PHP 脚本的任何用户有权限运行 php.exe！IIS 使用了一个在安装 IIS 时添加的匿名用户，这个用户需要有访问 php.exe 的权限。同样任何认证用户也需要执行 php.exe 的权限。在 IIS4 中你还需要告诉它 PHP 是一个脚本引擎。

后退 | 起点 | 前进
数据库问题 | 上一级 | 编译问题


编译问题

PHP 手册
后退 前进

章 51. 编译问题

本节汇集了大多数编译时出现的常见错误。

1. 我用匿名 CVS 得到了最新版的 PHP，但是里面没有 configure 脚本！
2. 我在配置 PHP 和 Apache 一起工作时遇到了问题。说没找到 httpd.h，但这个文件明明就在那里！
3. 当我运行 configure 时，报告说找不到头文件或 GD 库或 gdbm，或其它的什么包！
4. 当编译 language-parser.tab.c 文件时，报错说 yytname undeclared。
5. 当我运行 make 时，看上去一切正常，可当连接最后的程序时报告说找不到某些文件而失败了。
6. 当连接 PHP 时，报告说有一些未定义的引用。
7. 我不知道怎样把 PHP 和 Apache 1.3 一起编译。
8. 我按照所有的步骤在 UNIX 下安装了PHP 的 Apache 模块版本，但我的 PHP 脚本被显示在浏览器中或者提示保存此文件。
9. 说要用：--activate-module=src/modules/php4/libphp4.a，但是此文件根本不存在，于是我改成了 --activate-module=src/modules/php4/libmodphp4.a，结果不行。怎么回事？
10. 当我用 --activate-module=src/modules/php4/libphp4.a 试着把 PHP 编译成 Apache 的静态模块时，报告说我的编译器不服从 ANSI 标准。
11. 当我用 --with-apxs 编译 PHP 时得到奇怪的错误信息。
12. 在 make 的过程中，在 microtime 中出错，还有很多 RUSAGE_ 之类的东西。
13. 我想升级我的 PHP。上哪里找到我用来配置目前的 PHP 的 ./configure 的参数呢？
14. 和 GD 库一起编译 PHP 时，要么给出一个奇怪的编译错误，要么在运行时出现 segfaults。

1. 我用匿名 CVS 得到了最新版的 PHP，但是里面没有 configure 脚本！

你必须安装有 GNU 的 autoconf 包，这样才可以从 configure.in 生成 configure 脚本。从 CVS 得到源程序后只要在最高层的目录中运行 ./buildconf 即可。（同样，除非你用了 --enable-maintainer-mode 选项来运行 configure，否则即使 configure.in 文件更新了，configure 脚本也不会自动重新生成。所以当你发现 configure.in 文件更新了时要确保手工重新生成 configure 脚本。有一个症状是在 configure 之后或者运行 config.status 时在 Makefile 中寻找类似 @VARIABLE@ 的东西。）

2. 我在配置 PHP 和 Apache 一起工作时遇到了问题。说没找到 httpd.h，但这个文件明明就在那里！

你需要告诉 configure/setup 脚本你的 Apache 源程序最上层的目录位置。这意味着你需要这样指定 --with-apache=/path/to/apache 而不是这样 --with-apache=/path/to/apache/src。

3. 当我运行 configure 时，报告说找不到头文件或 GD 库或 gdbm，或其它的什么包！

你可以通过指定附加的选项让 configure 脚本在非标准的路径中寻找头文件和库并传递给 C 预处理器和连接器，例如：
CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure
如果你用 csh 的变种作为你的登陆 shell（为什么？），那就是：
env CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure

4. 当编译 language-parser.tab.c 文件时，报错说 yytname undeclared。

你需要更新 Bison 的版本。最新版本在 ftp://ftp.gnu.org/pub/gnu/bison/。

5. 当我运行 make 时，看上去一切正常，可当连接最后的程序时报告说找不到某些文件而失败了。

一些旧版本的 make 没有正确将 functions 目录下编译后的文件放到同一个目录下。试试运行 cp *.o functions 然后再运行 make 看看有没有什么帮助。如果成功了，那你确实需要更新到最新版的 GNU make。

6. 当连接 PHP 时，报告说有一些未定义的引用。

看看连接的这一行命令，确认所有适当的库都包括在最后了。你通常可能漏掉了“ldl”和你包括的任何数据库支持所需要的库。

如果你和 Apache 1.2.x 一起连接，记得把适当的信息添加到配置文件的 EXTRA_LIBS 这一行并重新运行 Apache 的配置脚本了吗？更多信息参见发行包中的 INSTALL 文件。

一些人也报告说在和 Apache 连接时他们不得不在 libphp4.a 之后立即加上“ldl”。

7. 我不知道怎样把 PHP 和 Apache 1.3 一起编译。

这其实很简单。小心地照着以下步骤来：

  • 从 http://www.apache.org/dist/ 下载最新版的 Apache 1.3。

  • 解压缩到某处，例如 /usr/local/src/apache-1.3。

  • 编译 PHP，先运行 ./configure --with-apache=/<path>/apache-1.3（用你 apache-1.3 所在的真实路径替换掉 <path>。）

  • 输入 make 接着是 make install 来编译 PHP 并把必要的文件拷贝到 Apache 的源程序目录树中。

  • 改变当前目录到 /<path>/apache-1.3/src 目录并编辑 Configuration 文件。添加这一行：AddModule modules/php4/libphp4.a。

  • 输入 ./Configure 接着是 make。

  • 你现在应该有一个包括 PHP 支持的 httpd 可执行程序了！

注意：你也可以用新的 Apache ./configure 脚本。参见 Apache 发行包中 README.configure 文件中的说明。也看看 PHP 发行包中的 INSTALL 文件。

8. 我按照所有的步骤在 UNIX 下安装了PHP 的 Apache 模块版本，但我的 PHP 脚本被显示在浏览器中或者提示保存此文件。

这说明 PHP 模块出于某些原因没有被调用。在寻求更多帮助前先检查三件事：

  • 确认你运行的 httpd 程序就是你刚刚编译的新 httpd 程序。运行： /path/to/binary/httpd -l

    如果你没看到 mod_php4.c 被列出来那你就没有运行对程序。找到并正确安装程序。

  • 确认你在 Apache .conf 文件中加入了正确的 Mime 类型。应该是： AddType application/x-httpd-php3 .php3（PHP 3）

    或者 AddType application/x-httpd-php .php（PHP 4）

    也确认 AddType 这一行没有隐藏在 <Virtualhost> 或者 <Directory> 块中，这可能会造成你的测试脚本所在位置没有被应用到此设置。

  • 最后，Apache 1.2 和 Apache 1.3 之间默认配置文件的位置改变了。你要确认你添加 AddType 行的文件就是实际上用的。你可以在你的 httpd.conf 中添加一个明显的语法错误或者其它明显修改，这可以告诉你是否读取了正确的文件。

9. 说要用：--activate-module=src/modules/php4/libphp4.a，但是此文件根本不存在，于是我改成了 --activate-module=src/modules/php4/libmodphp4.a，结果不行。怎么回事？

注意 libphp4.a 文件本来就不该存在，apache 进程将创建它！

10. 当我用 --activate-module=src/modules/php4/libphp4.a 试着把 PHP 编译成 Apache 的静态模块时，报告说我的编译器不服从 ANSI 标准。

这是一个 Apache 误报的错误信息，在更新的版本中已经修正了。

11. 当我用 --with-apxs 编译 PHP 时得到奇怪的错误信息。

这里要检查三件事。首先，出于某些原因当 Apache 生成 apxs Perl 脚本时，有时没有正确的编译和标记变量就结束了。找到你的 apxs 脚本（用命令 which apxs），有时会在 /usr/local/apache/bin/apxs 或者 /usr/sbin/apxs。打开并检查类似如下的行：
my $CFG_CFLAGS_SHLIB  = ' ';          # substituted via Makefile.tmpl
my $CFG_LD_SHLIB      = ' ';          # substituted via Makefile.tmpl
my $CFG_LDFLAGS_SHLIB = ' ';          # substituted via Makefile.tmpl
如果你看到这几行，那问题就在这里。它们可能包含了仅仅空格或者其它不正确的值，例如“q()”。改成这样：
my $CFG_CFLAGS_SHLIB  = '-fpic -DSHARED_MODULE'; # substituted via Makefile.tmpl
my $CFG_LD_SHLIB      = 'gcc';                   # substituted via Makefile.tmpl
my $CFG_LDFLAGS_SHLIB = q(-shared);              # substituted via Makefile.tmpl
第二个可能的问题仅可能在在 Red Hat 6.1 和 6.2 中发生。Red Hat 发行的 apxs 脚本坏了。查找这一行：
my $CFG_LIBEXECDIR    = 'modules';         # substituted via APACI install
如果你看到上面这一行，改成这样：
my $CFG_LIBEXECDIR    = '/usr/lib/apache'; # substituted via APACI install
最后，如果你重新配置或者重装了 Apache，在 ./configure 之后和 make 之前增加一个 make clean 命令。

12. 在 make 的过程中，在 microtime 中出错，还有很多 RUSAGE_ 之类的东西。

如果 make 时遇到类似这样的问题：
microtime.c: In function `php_if_getrusage':
microtime.c:94: storage size of `usg' isn't known
microtime.c:97: `RUSAGE_SELF' undeclared (first use in this function)
microtime.c:97: (Each undeclared identifier is reported only once
microtime.c:97: for each function it appears in.)
microtime.c:103: `RUSAGE_CHILDREN' undeclared (first use in this function)
make[3]: *** [microtime.lo] Error 1
make[3]: Leaving directory `/home/master/php-4.0.1/ext/standard'
make[2]: *** [all-recursive] Error 1
make[2]: Leaving directory `/home/master/php-4.0.1/ext/standard'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/home/master/php-4.0.1/ext'
make: *** [all-recursive] Error 1

你的系统坏了。你需要安装一个符合你的 glibc 的 glibc-devel 包来修复 /usr/include 中的文件。这和 PHP 绝对没有任何关系。要证实这一点，试试这个简单的测试：
$ cat >test.c <<X
#include <sys/resource.h>
X
$ gcc -E test.c >/dev/null
如果出现错误，那你就知道头文件坏了。

13. 我想升级我的 PHP。上哪里找到我用来配置目前的 PHP 的 ./configure 的参数呢？

要么在你当前的 PHP 的安装目录查看 config.nice 文件，如果没有，只要运行此脚本：
<?php phpinfo(); ?>
在输出的顶端显示了用来配置此 PHP 的 ./configure 参数。

14. 和 GD 库一起编译 PHP 时，要么给出一个奇怪的编译错误，要么在运行时出现 segfaults。

确保你的 GD 库和 PHP 在连接时使用了用同样的支持库（例如 libpng）。

后退 | 起点 | 前进
安装 | 上一级 | 使用 PHP


使用 PHP

PHP 手册
后退 前进

章 52. 使用 PHP

本节汇集了你在写 PHP 脚本时碰到的大多数普通错误。

1. 我想写一个可以处理任何表单来的数据的通用 PHP 脚本。我怎么知道哪个 POST 方法变量可用呢？
2. 我需要把所有的单引号（'）转换为反斜线后面跟着单引号。怎样用正则表达式做到呢？
3. 当我这样做时，输出显示的次序是错的：
function myfunc($argument)
{
    echo $argument + 10;
}
$variable = 10;
echo "myfunc($variable) = " . myfunc($variable);
这是怎么回事？
4. 下面代码怎么没有分成两行显示？
<pre>
<?php echo "This should be the first line."; ?>
<?php echo "This should show up after the new line above."; ?>
</pre>
5. 我得到消息“Warning: Cannot send session cookie - headers already sent...”或者“Cannot add header information - headers already sent...”。
6. 我需要直接访问请求报头中的信息，怎么能办到?
7. 当我用 IIS 进行 HTTP 认证时得到“No Input file specified”消息。
8. 我的 PHP 脚本在 IE 和 Lynx 下能工作，但是在 Netscape 中有的输出丢失了。当我用“查看源文件”时可以在 IE 中看到内容，但是 Netscape 中不能。
9. 我怎样混合使用 XML 和 PHP？它不认我的 <?xml> 标记！
10. 怎样用 FrontPage 或者其它非要把我的代码移来移去的 HTML 编辑器来编辑 PHP？
11. 哪里可以找到所有可用的预定义变量的完整列表？为什么在 PHP 文档中没有？
12. 我试着在用户自定义函数中访问一个标准的 CGI 变量（例如 $DOCUMENT_ROOT 或 $HTTP_REFERER），但是找不到，哪里出了错？

1. 我想写一个可以处理任何表单来的数据的通用 PHP 脚本。我怎么知道哪个 POST 方法变量可用呢？

确保在 php.ini 文件中激活了 track_vars 特性。自从 PHP 4.0.3 开始，此特性总是打开的。当 track_vars 打开时，会建立一些相关的数组，这里最重要的是：$_POST（在 PHP 4.1.0 之前叫做 $HTTP_POST_VARS）。因此要写出处理 POST 方法变量的通用脚本你需要一些类似如下的方法：
foreach ($_POST as $var => $value) {
    echo "$var = $value<br>\n";
}

2. 我需要把所有的单引号（'）转换为反斜线后面跟着单引号。怎样用正则表达式做到呢？

首先看看 addslashes() 函数。它正是做这件事的。同样也看看你的 php.ini 文件中的 magic_quotes_gpc 选项。

3. 当我这样做时，输出显示的次序是错的：
function myfunc($argument)
{
    echo $argument + 10;
}
$variable = 10;
echo "myfunc($variable) = " . myfunc($variable);
这是怎么回事？

要在一个表达式中（例如在上面的例子中和其它字符串连接）使用函数的结果，你需要用 return 返回这个值，而不是 echo() 它。

4. 下面代码怎么没有分成两行显示？
<pre>
<?php echo "This should be the first line."; ?>
<?php echo "This should show up after the new line above."; ?>
</pre>

在 PHP 中，一段代码的结束标记要么是“?>”要么是“?>\n”（\n 表示换行）。因此在上面的例子中，输出的句子将显示在同一行中，因为 PHP 忽略了代码结束标记后面的换行。这意味着如果要输出一个换行符，你需要在每段 PHP 代码的结束标记后面多加一个换行。

PHP 为什么这么做呢？因为在格式化正常的 HTML 时，这样通常会更容易。假如输出了换行而你不需要这个换行时，你就不得不用一个非常长的行来达到这样的效果，或者让产生的 HTML 页面的源文件的格式很难读。

5. 我得到消息“Warning: Cannot send session cookie - headers already sent...”或者“Cannot add header information - headers already sent...”。

函数 header()，setcookie() 和 session 函数需要在输出流中增加报头。但是报头只能在其它任何输出内容之前发送，检查你的代码是否在任何已经发送的内容后面发送报头。

6. 我需要直接访问请求报头中的信息，怎么能办到?

如果你以 Apache 的模块方式运行 PHP，那么函数 getallheaders() 可以做这件事。因此下面的代码可以显示所有的请求报头：
$headers = getallheaders();
foreach ($headers as $name => $content) {
    echo "headers[$name] = $content<br>\n";
}

7. 当我用 IIS 进行 HTTP 认证时得到“No Input file specified”消息。

IIS 的安全模型这里有毛病。这是所有 IIS 下运行的 CGI 程序所共有的问题。一个解决办法是建立一个纯 HTML 文件（不经过 PHP 解析）作为要进入认证目录的登录页面，然后用 META 标记来重定向到 PHP 页面，或者用一个连接到 PHP 页面。然后 PHP 就可以正确识别认证信息了。如果是用 ISAPI 模块，那没有这个问题。其它 NT 下的 web 服务器不受此影响。更多信息见：http://support.microsoft.com/support/kb/articles/q160/4/22.asp。

8. 我的 PHP 脚本在 IE 和 Lynx 下能工作，但是在 Netscape 中有的输出丢失了。当我用“查看源文件”时可以在 IE 中看到内容，但是 Netscape 中不能。

Netscape 在关于 html 标记（例如 table）上比 IE 更严格。用一个 html 验证器，例如 validator.w3.org 来验证你的 html 输出可能会有帮助。例如漏了 </table> 可能会导致这样的结果。

同样，IE 和 Lynx 都忽略了 HTML 流中的任何 NULs（\0），Netscape 就不。最好的检查方法是编译 PHP 的命令行模式版本（也称为 CGI 版本）并从命令行运行你的脚本。在 *nix 中，用管道传递到 od -c 并查看任何 \0 字符。如果在 Windows 下你需要能够查看二进制文件格式的编辑器或程序。当 Netscape 碰到 NUL 时就不会输出之后该行的任何内容而 IE 和 Lynx 都会。

9. 我怎样混合使用 XML 和 PHP？它不认我的 <?xml> 标记！

你需要在 php.ini 文件中通过设定 short_tags 为 0 来关闭 PHP 的简短标记格式，或者通过相应的 Apache 选项。你甚至应该用 <File> 段落来选择性地这样做。

10. 怎样用 FrontPage 或者其它非要把我的代码移来移去的 HTML 编辑器来编辑 PHP？

最简单的方法是让 PHP 代码也能使用 ASP 标记。这可以让你用 ASP 风格的 <% 和 %> 代码定界符。一些流行的 HTML 编辑器在处理此格式上更加智能化一些（目前如此）。要使用 ASP 风格的标记，你需要在 php.ini 中打开 asp_tags，或者用相应的 Apache 配置选项。

11. 哪里可以找到所有可用的预定义变量的完整列表？为什么在 PHP 文档中没有？

最好的方法是把 <?php phpinfo(); ?> 粘贴到某一页并打开来看看。它将显示你的 PHP 的所有分类的设置，包括环境变量和 web 服务器设定的特殊变量的列表。这个列表不能放在 PHP 文档中，因为它在不同的服务器中会改变的。

12. 我试着在用户自定义函数中访问一个标准的 CGI 变量（例如 $DOCUMENT_ROOT 或 $HTTP_REFERER），但是找不到，哪里出了错？

环境变量通常都是全局变量，因此你必须在你的函数中声明它们为全局变量（例如用 global $DOCUMENT_ROOT;），或者用全局变量数组（例如 $GLOBALS["DOCUMENT_ROOT"]）。

后退 | 起点 | 前进
编译问题 | 上一级 | PHP 和 HTML


PHP 和 HTML

PHP 手册
后退 前进

章 53. PHP 和 HTML

PHP 和 HTML 有很多相互作用：PHP 能生成 HTML，HTML 可以向 PHP 传递信息。

1. 当我通过表单／URL 传值时需要用什么编码／解码方法？
2. 我在试用 <input type="image"> 标记，但是没有 $foo.x 和 $foo.y 变量，它们哪去了？
3. 怎样在 HTML 的 <form> 中建立数组？
4. 怎样从可多选的 HTML 的 select multiple 标记中得到所有结果？

1. 当我通过表单／URL 传值时需要用什么编码／解码方法？

在几个环节上编码方式很重要。假定你有 string $data，其中包含了你想通过非编码方式传递的字符串，那这是相关步骤：

  • HTML 解析。要指定一个任意的字符串，你必须将其放在双引号中，并用 htmlspecialchars 处理整个值。

  • URL：URL 由几部分组成。如果你希望自己的数据被当作其中一项来解释，你必须用 urlencode() 对其编码。

例子 53-1. 隐藏的 HTML 表单单元

<?php
    echo "<input type=hidden value=\"" . htmlspecialchars($data) . "\">\n";
?>

注: 用 urlencode() 来处理 $data 是错误的，因为是浏览器的责任来 urlencode() 数据。所有流行的浏览器都能正确处理。注意不论何种方法（例如 GET 或 POST）都会这样。不过你只会在用 GET 请求时注意到这一点，因为 POST 请求通常是隐藏的。

例子 53-2. 等待用户编辑的数据

<?php
    echo "<textarea name=mydata>\n";
    echo htmlspecialchars($data)."\n";
    echo "</textarea>";
?>

注: 数据会按照预期的显示在浏览器中，因为浏览器会解释 HTML 转义符号。

当提交时，不论是 GET 或者 POST 方法，数据都会被浏览器进行 urlencode 来传输，并直接被 PHP urldecode。所以最终你不需要自己处理任何 urlencoding/urldecoding，全都是自动处理的。

例子 53-3. URL 中的例子

<?php
    echo "<a href=\"" . htmlspecialchars("/nextpage.php?stage=23&data=" .
        urlencode($data)) . "\">\n";
?>

注: 事实上你在捏造一个 HTML 的 GET 请求，因此需要手工对数据进行 urlencode()。

注: 你需要对整个 URL 进行 htmlspecialchars()，因为 URL 是作为 HTML 属性的一个值出现的。在本例中，浏览器会首先对值进行 un-htmlspecialchars()，然后再传递此 URL。PHP 将能正确理解 URL，因为你对数据进行了 urlencoded()。

你会注意到 URL 中的 & 被替换成了 &amp;。如果你忘了这一步，尽管大多数浏览器都能恢复，但也不总是这样。因此即使 URL 不是动态的，你也需要对 URL 进行 htmlspecialchars()。

2. 我在试用 <input type="image"> 标记，但是没有 $foo.x 和 $foo.y 变量，它们哪去了？

当提交表单时，可以用图片代替标准的提交按钮，用类似这样的标记：
<input type="image" src="image.gif" name="foo">
当用户点击了图片的任何部分，该表单会被发送到服务器并加上两个额外的变量：foo.x 和 foo.y。

因为 $foo.x 和 $foo.y 在 PHP 中是非法的变量名，它们被自动转换成了 $foo_x 和 $foo_y。也就是用下划线代替了点。

3. 怎样在 HTML 的 <form> 中建立数组？

要使你的 <form> 结果被当成 array 发送到 PHP 脚本，你要对 <input>，<select> 或者 <textarea> 单元这样命名：
<input name="MyArray[]">
<input name="MyArray[]">
<input name="MyArray[]">
<input name="MyArray[]">
注意变量名后的方括号，这使其成为一个数组。你可以通过给不同的单元分配相同的名字来把单元分组到不同的数组里：
<input name="MyArray[]">
<input name="MyArray[]">
<input name="MyOtherArray[]">
<input name="MyOtherArray[]">
这将产生两个数组，MyArray 和 MyOtherArray，并发送给 PHP 脚本。还可以给数组分配指定的键名：
<input name="AnotherArray[]">
<input name="AnotherArray[]">
<input name="AnotherArray[email]">
<input name="AnotherArray[phone]">
AnotherArray 数组将包含键名 0，1，email 和 phone。

注: 指定数组的键名是 HTML 的可选项。如果你不指定键名，则数组被按照单元在表单中出现的顺序填充。第一个例子将包含键名 0，1，2 和 3。

参见数组函数库和PHP 的外部变量。

4. 怎样从可多选的 HTML 的 select multiple 标记中得到所有结果？

可多选的 select multiple 标记是 HTML 的一个构造，允许用户从一个列表中选择多个项目。这些项目接着被传递给该表单 action 中指定的处理程序。问题是它们都会被用同样的名字传递。例如：
<select name="var" multiple>
每个被选项将这样被传递到表单处理程序：
var=option1
var=option2
var=option3
每个选项将覆盖前面一个 $var 变量的内容。解决方案是用 PHP 的“表单单元数组”特性。使用方法如下：
<select name="var[]" multiple>
这将告诉 PHP 将 $var 当成数组对待，每个对 var[] 的赋值都会给数组增加一项。第一项将成为 $var[0]，下一个是 $var[1]，等等。可以用 count() 函数来测定选择了多少个项目，必要时可以用 sort() 函数来对选项的数组进行排序。

注意如果你在 JavaScript 中通过名字来引用单元，单元名字中的 [] 可能会造成问题。用表单单元中的数字序号来替代，或者将变量名用单引号括起来并用其作为单元数组的索引，例如：
variable = documents.forms[0].elements['var[]'];

后退 | 起点 | 前进
使用 PHP | 上一级 | PHP 和 COM


PHP 和 COM

PHP 手册
后退 前进

章 54. PHP 和 COM

PHP 可以在 Win32 平台中访问 COM 和 DCOM 对象。

1. 我建立了一个 DLL 来做某种计算。有办法在 PHP 中运行这个 DLL 吗？
2. “Unsupported variant type: xxxx (0xxxxx)”是什么意思？
3. 在 PHP 中有可能操纵可视对象吗？
4. 可以将一个 COM 对象保存在 session 中吗？
5. 怎样可以捕获 COM 的错误？
6. 我能像在 Perl 中一样从 PHP 脚本生成 DLL 文件吗？
7. “Unable to obtain IDispatch interface for CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}”是什么意思？
8. 怎样从远端服务器运行 COM 对象？
9. 我得到一个“DCOM is disabled in C:\path...\scriptname.php on line 6”信息，应该怎么办？
10. 有可能在 PHP 页面中加载／操纵 ActiveX 对象吗？
11. 有可能得到一个组件在运行中的实例吗？
12. 有办法处理 COM 对象中发送的事件吗？
13. 我在尝试调用一个打开了多于一个接口的 COM 对象中的方法时碰到问题，应该怎么办？
14. 这么说 PHP 可以和 COM 一起工作，那么 COM+ 呢？
15. 如果 PHP 可以操纵 COM 对象，那么可以设想结合 PHP 用 MTS 来管理组件资源吗？

1. 我建立了一个 DLL 来做某种计算。有办法在 PHP 中运行这个 DLL 吗？

如果这是个简单的 DLL 那么还没有办法在 PHP 中运行它。如果这个 DLL 中包含有一个 COM 服务器并且它实现了 IDispatch 接口，那有可能访问它。

2. “Unsupported variant type: xxxx (0xxxxx)”是什么意思？

有几十种 VARIANT 类型以及它们的组合。大多数已经被支持了但还有几种尚未实现。数组没有完全被支持。只有一维的仅用作索引的数组可以在 PHP 和 COM 之间传递。如果你发现其它未支持的类型，请当作一个 bug 报告（如果尚未被报告的话）并提供尽可能多的信息。

3. 在 PHP 中有可能操纵可视对象吗？

一般来说是可以的，但是 PHP 大都用来作为 web 脚本语言并运行在 web 服务器的上下文环境中，因此可视对象决不会在服务器的桌面上显示。如果你把 PHP 用作应用程序脚本例如结合 PHP-GTK 来使用，那么访问和通过 COM 来操纵可视对象方面没有限制。

4. 可以将一个 COM 对象保存在 session 中吗？

不行。COM 的实例被看作是资源，因此只在一个脚本的上下文中有效。

5. 怎样可以捕获 COM 的错误？

当前除了 PHP 自己提供的办法之外（@，track_errors，..）不可能捕获 COM 的错误，但我们正在考虑实现它的方法。

6. 我能像在 Perl 中一样从 PHP 脚本生成 DLL 文件吗？

不行，PHP 没有这样的工具。

7. “Unable to obtain IDispatch interface for CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}”是什么意思？

此错误可以有多种原因：

  • 错误的 CLSID

  • 找不到所请求的 DLL

  • 所请求的组件没有实现 IDispatch 接口

8. 怎样从远端服务器运行 COM 对象？

完全和运行本地对象一样。只须将远端服务器的 IP 作为第二个变量传递给 COM 的构造函数即可。

确认在 php.ini 中设定了 com.allow_dcom=true。

9. 我得到一个“DCOM is disabled in C:\path...\scriptname.php on line 6”信息，应该怎么办？

编辑 php.ini 并设定 com.allow_dcom=true。

10. 有可能在 PHP 页面中加载／操纵 ActiveX 对象吗？

这不关 PHP 的事。如果在 HTML 文档中请求的话，ActiveX 对象被加载在客户端。这和 PHP 脚本没有关系，因此也不可能和服务器端发生直接的交互作用。

11. 有可能得到一个组件在运行中的实例吗？

在绰号的帮助下这有可能。如果你想得到同一个 word 实例的多个引用你可以这样建立此实例：

$word = new COM("C:\docs\word.doc");

如果没有运行中的实例这将建立一个新的实例，否则将会返回正在运行中的实例的句柄，如果可用的话。

12. 有办法处理 COM 对象中发送的事件吗？

还不能。

13. 我在尝试调用一个打开了多于一个接口的 COM 对象中的方法时碰到问题，应该怎么办？

我也不知道怎么办，我想这没办法。如果什么人有对此问题的明确信息请告诉我。:)

14. 这么说 PHP 可以和 COM 一起工作，那么 COM+ 呢？

COM+ 通过使用 MTS 和 MSMQ 来管理组件的框架扩展了 COM，但并没有什么特殊之处使 PHP 非要支持这样的组件。

15. 如果 PHP 可以操纵 COM 对象，那么可以设想结合 PHP 用 MTS 来管理组件资源吗？

PHP 本身还并不处理事务。因而如果出错也不会发动撤回机制。如果你使用了支持事务处理的组件那你不得不自己实现事务管理。

后退 | 起点 | 前进
PHP 和 HTML | 上一级 | PHP 和其它语言


PHP 和其它语言

PHP 手册
后退 前进

章 55. PHP 和其它语言

PHP 是 web 编程最好的语言，但其它语言怎样呢？

1. PHP 对 ASP？
2. 有 ASP 到 PHP 的转换器吗？
3. PHP 对 Cold Fusion？
4. PHP 对 Perl？

1. PHP 对 ASP？

ASP 本身并不真的是一种语言，它是 Active Server Pages 的缩写，实际上用来进行 ASP 编程的语言是 Visual Basic Script 或者 JScript。ASP 最大的缺点是它是一个专有系统而只能在 Microsoft Internet Information Server（IIS）上使用。这限制了它只能在基于 Win32 的服务器上使用。有几项进行中的计划使 ASP 可以在其它环境和 web 服务器中使用：Halcyon（商业的）的 InstantASP，Chili!Soft 的 Chili!Soft ASP 和 ActiveScripting.org 的 OpenASP（免费）。ASP 被认为比 PHP 慢和麻烦，也不稳定。一些 ASP 的正面观点是既然它基本上用 VBScript，那如果你已经懂得用 Visual Basic 编程就会相对容易拾起这种语言。在 IIS 服务器中默认激活了 ASP 支持，这使它容易启动和运行。ASP 中内置的组件实在是很有限，因此如果你需要一些“高级的”特点例如与 FTP 服务器交互，你需要购买额外的组件。

2. 有 ASP 到 PHP 的转换器吗？

有，asp2php 是最经常被提及的。

3. PHP 对 Cold Fusion？

PHP 普遍被认为对复杂的编程任务更快和更有效以及勇于尝试新主意。PHP 也通常被提及更稳定以及占用更少资源。Cold Fusion 具有更好的错误处理，数据库抽象和数据解析，尽管数据库抽象已经在 PHP 4 中解决了。另外一个被作为 Cold Fusion 的强项列出来的是它卓越的搜索引擎，但也被指出搜索引擎不是 web 脚本语言中应该包括的东西。PHP 可以在几乎每一个现有的平台下运行；Cold Fusion 只能在 Win32，Solaris，Linux 和 HP/UX 下运行。Cold Fusion 有很好的集成开发环境以及通常更容易上手，反之 PHP 则一开头就需要更多的编程知识。Cold Fusion 是为非程序员的头脑所设计，而 PHP 则聚焦于程序员。

有关此话题 Michael J Sheldon 在 PHP 邮件列表中发表了一个很棒的摘要。有一个拷贝在这里。

4. PHP 对 Perl？

PHP 对 Perl 最大的优势就是 PHP 是为 web 脚本设计的而 Perl 则被设计用来做更多的事也因此而非常复杂。Perl 的灵活性／复杂性使得用它能很容易写出代码但却让另一个作者／编程者非常难读懂。PHP 则不容易把人搞糊涂以及具有更严谨的格式同时也不失灵活性。PHP 比 Perl 更容易集成进现有的 HTML 中去。PHP 具有差不多所有 Perl 的“好”功能：结构，语法等等，但却没有使它达到 Perl 的费解程度。Perl 是一种久经考验真正的语言，从上个世纪八十年代末起就到处都有，但是 PHP 成熟得非常快。

后退 | 起点 | 前进
PHP 和 COM | 上一级 | 从 PHP/FI 2 移植到 PHP 3


从 PHP/FI 2 移植到 PHP 3

PHP 手册
后退 前进

章 56. 从 PHP/FI 2 移植到 PHP 3

PHP 已经有一段传奇似的历史: PHP/FI 1.0, PHP/FI 2.0, PHP 3.0 和 PHP 4.0。

1. 从 PHP/FI 2 移植到 PHP 3?

1. 从 PHP/FI 2 移植到 PHP 3?

PHP/FI 2.0 不再被支持. 从 PHP/FI 2.0 移植的信息请看手册相应章节

如果你仍然使用 PHP 2, 我们强烈建议你直接升级到 PHP 4.

后退 | 起点 | 前进
PHP 和其它语言 | 上一级 | 从 PHP 3 移植到 PHP 4


从 PHP 3 移植到 PHP 4

PHP 手册
后退 前进

章 57. 从 PHP 3 移植到 PHP 4

PHP 已经有一段传奇似的历史:PHP 1.0, PHP/FI, PHP 3.0 和 PHP 4.0.

1. 从 PHP 3 移植到 PHP 4
2. 不兼容的函数问题?

1. 从 PHP 3 移植到 PHP 4

PHP 4 被尽可能的设计为与早期的 PHP 版本兼容.在 PHP 4 的设计开发过程中,只有非常少的早期 PHP 版本具有的功能被 PHP 4 删除. 如果你不敢确定你的 PHP 文件 的兼容性,你可以安装一个 PHP 4 测试环境来测试你的 PHP 文件.

相关信息请查看该手册附录

2. 不兼容的函数问题?

PHP 4 主要重写了整个 PHP 引擎,所以只有非常少的早期的 PHP 版本中的函数被改变到 PHP 4 中,PHP 4 中的函数大部分是新增加的.

后退 | 起点 | 前进
从 PHP/FI 2 移植到 PHP 3 | 上一级 | 杂类问题


杂类问题

PHP 手册
后退 前进

章 58. 杂类问题

有些问题没法归到其它类中，你可以在这里发现它们。

1. 网站上的浮动窗口哪里去了？我能获得它的代码吗？
2. 在 Windows 中怎样处理 bz2 压缩的文档？

1. 网站上的浮动窗口哪里去了？我能获得它的代码吗？

旧网站上黄颜色的浮动窗口很酷，但是很难维护（因为有些公司很喜欢改变每个新版本浏览器工作的方式）。

网站旧版本的所有代码仍然能够从 CVS 中得到。尤其是最新版的 shared.inc（包括浮动窗口所有的 Javascript 和 DHTML）在这里。

2. 在 Windows 中怎样处理 bz2 压缩的文档？

如果你没有能处理 bz2 文件的压缩工具，从 Redhat 下载一个命令行工具（进一步信息见下面）。

如果你不喜欢用命令行工具，你可以试试免费工具例如 Stuffit Expander，UltimateZip，7-Zip 或者 Quick Zip。如果你有像 WinRAR 或者 Power Archiver 之类的工具，可以很容易用它解压缩 bz2 文件。如果你用 Windows Commander，可以从 Windows Commander 网站免费得到一个 bz2 插件。

Redhat 的 bzip2 命令行工具：

Win2K Sp2 用户下载最新版本 1.0.2，所有其它 Windows 用户应该用版本 1.00。下载后重命名可执行文件为 bzip2.exe。为方便起见将其放到一个在你路径中的目录，例如 C:\Windows，C 表示你安装 Windows 的盘符。

注意：lang 指的是你的语种， x 是想要的格式，例如：pdf。要解压缩 php_manual_lang.x.bz2，按照下面的简单说明进行：

  • 打开一个命令行窗口

  • 进入存放已下载的 php_manual_lang.x.bz2 的目录

  • 调用 bzip2 -d php_manual_lang.x.bz2，将 php_manual_lang.x 释放到同一个目录

在你下载了包含很多 html 文件的 php_manual_lang.tar.bz2 的情况下，过程是一样的。唯一区别是得到了一个 php_manual_lang.tar 文件。tar 格式可以被大多数 Windows 下流行的压缩工具所处理，例如 WinZip。

后退 | 起点 | 前进
从 PHP 3 移植到 PHP 4 | 上一级 | 附录


附录

PHP 手册
后退 前进

VII. 附录

目录
A. PHP 及其相关工程的历史
B. 从 PHP 3 移植到 PHP 4
C. 从 PHP/FI 2 移植到 PHP 3
D. 排除 PHP 程序的错误
E. 扩展 PHP
F. 函数别名列表
G. 保留字列表
H. 资源类型列表
I. List of Supported Protocols/Wrappers
J. 解析器代号列表
K. 关于本手册
L. 函数索引
M. 补充说明

后退 | 起点 | 前进
杂类问题 |  | PHP 及其相关工程的历史


PHP 及其相关工程的历史

PHP 手册
后退 前进

附录 A. PHP 及其相关工程的历史

目录
PHP 的历史
PHP 相关工程的历史
PHP 相关书籍
PHP 相关文章

PHP 在过去的几年里走过了漫长的道路。成长为处理 Web 的最卓越的语言并非易事。如果您对 PHP 如何发展到今天很感兴趣，那么，请继续读下去吧。

PHP 的历史

PHP/FI

PHP 继承自一个老的工程，名叫 PHP/FI。PHP/FI 在1995年由 Rasmus Lerdorf 创建，最初只是一套简单的 Perl 脚本，用来跟踪访问他主页的人们的信息。它给这一套脚本取名为“Personal Home Page Tools”。随着更多功能需求的增加，Rasmus 写了一个更大的 C 语言的实现，它可以访问数据库，可以让用户开发简单的动态 Web 程序。Rasmus 公开了 PHP/FI 的源代码，以便每个人都可以使用它，同时大家也可以修正它的Bug并且改进它的源代码。

PHP/FI，一个专为个人主页/表单提供解释程序的程序，已经包含了今天 PHP 的一些基本功能。它有着 Perl 样式的变量，自动解释表单变量，并可以嵌入 HTML。语法本身与 Perl 很相似，但是它很有限，很简单，还稍微有些不协调。

到1997年，PHP/FI 2.0，也就是它的 C 语言实现的第二版在全世界已经有几千个用户（估计）和大约 50,000 个域名安装，大约是 Internet 所有域名的 1%。但是那时只有几个人在为该工程撰写少量当代码，它仍然只是一个人的工程。

PHP/FI 2.0 在经历了数个beta版本的发布后于1997年11月发布了官方正式版本。不久，PHP 3.0 的第一个 alpha 版本的发布，PHP 从此走向了成功。

PHP 3

PHP 3.0 是类似于当今 PHP 语法结构的第一个版本。Andi Gutmans 和 Zeev Suraski 在开发他们的商业程序时，发现 PHP/FI 2.0 功能明显不足，于是他们重写了代码。这就是 PHP 3.0。经过Andi, Rasmus 和 Zeev 一系列的努力，考虑到 PHP/FI 已存在的用户群，他们决定联合发布 PHP 3.0 作为 PHP/FI 2.0 的官方后继版本。而 PHP/FI 2.0 的进一步开发几乎终止了。

PHP 3.0 的一个最强大的功能是它的可扩展性。除了给最终用户提供数据库、协议和 API 的基础结构，它的可扩展性还吸引了大量的开发人员加入并提交新的模块。后来证实，这是 PHP 3.0 取得巨大成功的关键。PHP 3.0 中的其它关键功能包括面向对象的支持和更强大和协调的语法结构。

这个全新的语言伴随着一个新的名称发布。它从 PHP/FI 2.0 的名称中移去了暗含“本语言只限于个人使用”的部分。它被命名为简单的缩写“PHP”。这是一种递归的缩写，它的全称是——PHP: Hypertext Preprocessor。

1998 年末，PHP 的安装人数几近10,000，有大约100,000个网站报告他们使用了PHP。在 PHP 3.0 的顶峰，Internet 上 10% 的 Web 服务器上都安装了它。

约九个月的公开测试后，官方于1998年6月正式发布 PHP 3.0。

PHP 4

1998 年的冬天，PHP 3.0 官方发布不久，Andi Gutmans 和 Zeev Suraski 开始重新编写 PHP 代码。设计目标是增强复杂程序运行时的性能和 PHP 自身代码的模块性。PHP 3.0 的新功能和广泛的第三方数据库、API的支持使得这样程序的编写成为可能，但是 PHP 3.0 没有高效处理如此复杂程序的能力。

新的被称为“Zend Engine”（这是 Zeev 和 Andi 的缩写）的引擎，成功的实现了设计目标，并在1999年中期首次引入 PHP。基于该引擎并结合了更多新功能的 PHP 4.0，在 PHP 3.0 发布两年后，于2000年5月发布了官方正式版本。除了更高的性能以外，PHP 4.0 还包含了其它一些关键功能，比如：支持更多的 Web 服务器；HTTP Sessions 支持；输出缓存(output buffering)；更安全的处理用户输入的方法；一些新的语言结构。

PHP 4 是当前 PHP 的最新版本。修改和增强 Zend Engine 以使 PHP 5.0 整合新功能的工作已经开始。

今天，已经有10,000名开发人员（估计）和几百万网站报告已安装了 PHP，占整个 Internet 域名的 20%。

PHP 的开发小组有很多优秀的开发人员，同时还有大量的优秀人才在进行 PHP 相关工程的开发工作，如 PEAR 和 PHP 文档的工程。

后退 | 起点 | 前进
附录 | 上一级 | PHP 相关工程的历史


PHP 相关工程的历史

PEAR

PEAR，PHP 扩展与应用资源库（the PHP Extension and Application Repository，原为 PHP Extension and Add-on Repository）是 PHP 程序的基础类，并可能在将来增强为在开发人员间分发 PHP 和 C 语言编写的 PHP 扩展的关键方法。

PEAR 在2000年1月于 Tel Aviv 举行的 PHP 开发者会议(PDM)中诞生。这个工程由 Stig S. Bakken 创建。现在，他正专注于他的第一个小女儿，Malin Bakken。

2000 年早些时候，PEAR 已经成长为一个巨大的，有意义的工程。大量的开发人员在为实现普通的、可重用德、功能强大的代码而努力工作着。这给整个 PHP 团体都带来极大的益处。今天 PEAR 包含了大量的基础类，包括数据库访问、内容缓存、数学计算、电子商务等等。

PHP 质量保证体系(QA)

PHP 质量保证体系于2000年夏设立，因为用户批评 PHP 在发布前没有进行足够的针对产品环境的测试。质量保证小组由精通 PHP 基础代码的核心人员组成。这些开发人员将精力花费在本地化和修复 PHP 的 Bug 上。除此之外，其他小组成员也在各种不同的平台上对这些修复进行测试并提供反馈信息。

PHP-GTK

PHP-GTK 是编写客户端图形用户界面(GUI)程序的 PHP 解决方案。Andrei Zmievski 回忆了 PHP-GTK 计划和创建的过程：

“我总是对 GUI 编程有着浓厚的兴趣。我发现 Gtk+ 是一个非常好的工具包，除了一点——它使用的 C 语言很令人乏味。目睹了 PyGtk 和 GTK-Perl 的实现，我决定尝试 PHP 是否也能够被做成 Gtk+ 的接口。2000年8月，我有了更多的业余时间，于是我开始试验。我参考了 PyGtk 的实现方法，因为它有着相当完全的实现和漂亮的面向对象的接口。James Henstridge，PyG的作者，在最初的筹备阶段提供了极大的帮助。

“手工写 Gtk+ 函数全部的接口几乎是不可能的事情，所以我把重点放在了代码生成上，就像 PyGtk 做的一样。代码生成器是一个PHP 程序，它可以读取包含 Gtk+ 类、常量和方法信息的一系列的 .defs 文件并生成与 PHP 相接口的 C 代码。无法自动生成的部分可以提交到 .overrides 文件。

“代码生成器和基础结构的工作花了我一定的时间，因为我在2000年秋天这段时间里只能花很少的时间在 PHP-GTK 上。在我把 PHP-GTK 给 Frank Kromann 演示过后，他产生了浓厚的兴趣，并开始帮助我完成代码生成器和 Win32 的实现。当我们写了第一个 Hello World 程序并设法使之工作之时，我们的喜悦之情溢于言表。两个多月后，这个工程初见成效，并于2001年3月1日发布了内部版本。这个故事迅速的打击了 SlashDot。(The story promptly hit SlashDot.)(TODO)

“感到 PHP-GTK 前景广阔，我便为它专门设置了邮件列表和 CVS 知识库。同时，gtk.php.net 网站也在 Colin Viebrock 的帮助下建立起来。文档的工作也由 James Moore 承担起来。

“PHP-GTK 发布之后，它愈加流行。我们有自己的文档小组，手册持续更新。人们开始为 PHP-GTK 编写扩展。越来越多的程序已经开始使用它了。

后退 | 起点 | 前进
PHP 及其相关工程的历史 | 上一级 | PHP 相关书籍


PHP 相关书籍

随着 PHP 的成长，人们越来越认识到它是一个世界流行的开发平台。看到这种趋势的最有趣方法之一就是：这些年 PHP 相关书籍越来越多。

据我们所知，最早的 PHP 专业书籍是“php- dynamische webauftritte professionell realisieren”——一本1999年出版的德国书籍，作者是 Egon Schmid、Christian Cartus 和 Richard Blume。第一本关于 PHP 的英文书随后出版，书名是“Core PHP Programming”，作者为： Leon Atkinson。这两本书都是写 PHP 3.0 的。

这两本书是这类图书的第一本——随后，大量的 PHP 相关图书上市。英文版本超过40种，德文50种，法文20种！除此之外，你可以发现西班牙文、韩文、日文、中文和希伯来文等等语言版本的 PHP 相关图书。

这么大量的图书，这么多作者的写作，这么多出版商的出版，并出现了这么多语言的版本——这强烈的证明 PHP 在世界范围内的成功！

后退 | 起点 | 前进
PHP 相关工程的历史 | 上一级 | PHP 相关文章


PHP 相关文章

据我们所知，关于 PHP 的在杂志上的第一篇文章于 1998 年末在法国的“Informatiques Magazine”杂志上发表，是描述 PHP 3.0 的。据记载，这是大量出版在杂志上 PHP 相关文章的第一篇。

关于 PHP 的文章出现在 Dr. Dobbs、Linux Enterprise、Linux Magazine等等出版物上。关于在 Windows 下如何转换 ASP 程序到 PHP 的文章甚至出现在了微软自己的 MSDN 上！

后退 | 起点 | 前进
PHP 相关书籍 | 上一级 | 从 PHP 3 移植到 PHP 4


从 PHP 3 移植到 PHP 4

PHP 手册
后退 前进

附录 B. 从 PHP 3 移植到 PHP 4

目录
PHP 4 所作的改变
同时运行 PHP 3 和 PHP 4
移植配置文件
解析器行为
错误报告
初始化
empty("0")
缺少的函数
PHP 3 扩展
字符串中的变量替换
Cookies
处理全局变量

PHP 4 所作的改变

PHP 4 和其整合的 Zend engine 极大的增强了 PHP 的性能和兼容性，对细节代码也十分注意。所以从 PHP 3 到 PHP 4 的移植要比从 PHP/FI 2 到 PHP 3 的移植容易得多。很多 PHP 3 的代码无需修改就可以在 PHP 4 中运行，但是您还是需要在转换程序运行环境时注意一些细节。下面就是一些提示。

后退 | 起点 | 前进
PHP 相关文章 | 上一级 | 同时运行 PHP 3 和 PHP 4


同时运行 PHP 3 和 PHP 4

最新的操作系统提供了执行多版本和范围程序的能力。这个功能使得在一个 Apache 服务器上同时运行 PHP 3 和 PHP 4 成为可能。

已知该功能可以运行在如下平台：

  • 包含新版本 binutils 的 Linux（binutils 2.9.1.0.25 测试通过）

  • Solaris 2.5 或更高版本

  • FreeBSD（3.2，4.0 测试通过）

要启用该功能，需要配置(configure) PHP3 和 PHP4 的 APXS（使用 --with-apxs 参数）以及所需的链接扩展（使用 --enable-versioning 参数）。其余的和标准安装方法一样。例如：

$ ./configure \
  --with-apxs=/apache/bin/apxs \
  --enable-versioning \
  --with-mysql \
  --enable-track-vars

后退 | 起点 | 前进
从 PHP 3 移植到 PHP 4 | 上一级 | 移植配置文件


移植配置文件

全局配置文件 php3.ini 已经改名为 php.ini。

Apache 配置文件也有一些细微的改动。PHP 模块所属的 MIME 类型已经改变。

application/x-httpd-php3        -->    application/x-httpd-php
application/x-httpd-php3-source -->    application/x-httpd-php-source

您可以使得您的配置文件工作在两个 PHP 版本上（取决于哪个版本编译到服务器上），使用下面的语法：

AddType  application/x-httpd-php3        .php3
AddType  application/x-httpd-php3-source .php3s

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

除此之外，关于 PHP 的 Apache 指令已经改变。

从 PHP 4.0 开始，只有四个 Apache 指令与 PHP 相关：

php_value [PHP directive name] [value]
php_flag [PHP directive name] [On|Off]
php_admin_value [PHP directive name] [value]
php_admin_flag [PHP directive name] [On|Off]

Admin values 和非 Admin values 有两处不同：

  • Admin values（或 flags）指仅可以出现在服务器范围内的 apache 配置文件（例如：httpd.conf）。

  • Standard values（或 flags）无法控制某种 PHP 指令，例如——安全模式（如果您在 .htaccess 文件中覆盖了安全模式的设定，安全模式就失去了它的意义）。相比较，Admin values 可以更改任何 PHP 指令的值。

为了使翻译进程更加容易，PHP 4 捆绑了自动转换您的 Apache 配置文件和 .htaccess 文件使 PHP 3 和 PHP 4 都可以工作。但这些脚本并不转换 MIME 类型！您需要自己转换它。

要转换您的 Apache 配置文件，运行 apconf-conv.sh 脚本（在 scripts/apache/ 目录）例如：

~/php4/scripts/apache:#  ./apconf-conv.sh /usr/local/apache/conf/httpd.conf

您原来的配置文件会更名为 httpd.conf.orig。

要转换您的 .htaccess 文件，运行 aphtaccess-conv.sh 脚本（也在 scripts/apache/ directory 目录下）：

~/php4/scripts/apache:#  find / -name .htaccess -exec ./aphtaccess-conv.sh {} \;

同样的，您原有的 .htaccess 文件会以 .orig 后缀保存。

运行转换脚本需要安装 awk。

后退 | 起点 | 前进
同时运行 PHP 3 和 PHP 4 | 上一级 | 解析器行为


解析器行为

解析和执行现在变为两个完全独立的步骤。只有当完全成功的解析后，程序才会执行。

这种改变所带来的一个新的要求是一个脚本文件所包含的另一个文件必须有着完整的语法结构。您不能将一个完整的控制结构分散在不同的文件中。这意味着您不能在一个文件中开始一个 for 或 while 循环、一个 if 或 switch 块，而在另一个文件中结束它们，或在另一个文件中使用 else、endif、case 或 break。

但是在循环或其它控制结构中包含额外的脚本文件是允许的。只要控制的关键词和相应的 {...} 在同一个单元（文件或使用函数 eval() 结合的字符串）中就可以了。

不过，在循环或其它控制结构中包含额外的脚本文件并不是一个好的遍程习惯。

另外，一种在 PHP 3 中不常见的代码——从一个 require 的文件中返回值——在 PHP 4 中也不能使用。而从一个 include 文件中返回值还是允许的。

后退 | 起点 | 前进
移植配置文件 | 上一级 | 错误报告


错误报告

配置的改变

PHP 3 错误报告的级别是简单的将不同的错误报告级别的数字相加而成。通常 15 代表报告所有错误，而 7 代表报告除了 notice 信息以外的所有错误。

PHP 4 有一整套错误和警告的级别，并且配置解析器允许使用符号常量来定义显示的错误级别。

错误报告级别应该被明确的配置。如果您不想显示某种错误信息，您需要将他们从 E_ALL 符号常量中排除。听起来很复杂吗？让我们看看吧。如果您想显示除了以 E_NOTICE 表示的 notice 信息以外的所有错误信息，您就应该在 php.ini 中设置：error_reporting = E_ALL & ~ ( E_NOTICE ) 。如果您还不想显示 warning 信息，只需要使用“|”运算符：error_reporting= E_ALL & ~ ( E_NOTICE | E_WARNING )。

警告

使用旧有的从 7 到 15 的数字来设置错误报告的级别不是个好主意，因为这屏蔽了 PHP 4 中新的错误类产生的错误信息。这可能导致非常奇怪的现象：脚本不能执行却没有任何错误提示。

这在过去已经导致了许多重复的 bug 报告。人们报告新的脚本引擎不能跟踪脚本文件中经常发生的缺少“}”的错误。事实上，这是由不正确的配置引起的。

所以，检查您错误报告的设置是在脚本无法运行而没有出现错误提示时您应做的第一件事。Zend engine 到现在已经很成熟了，一般不会出现如此奇怪的现象。

额外的警告信息

许多已存在的 PHP 3 代码使用的语言样式在现在应当被看做是非常糟糕的。因此，如果用 PHP 4 编译该脚本，会产生很多额外的警告信息。如果您不想看到这些信息，只要简单的把 E_NOTICE 选项关闭。但更好的做法是修正代码。

最常见的出现 notice 提示信息的情况是在数组索引中使用没有加引号的字符串。PHP 3 和 PHP 4 在没有同名的常量定义时都会把它解释为字符串，但是无论何时只要有常量是以该字符串命名，您的脚本就可能会出现错误。如果有黑客利用这一点，设法重定义该常量，这个脚本就存在安全漏洞。所以只要出现未加引号的索引，PHP 4 就会警告您对它加以修正。举例来说，有漏洞的代码 $_SERVER[REQUEST_METHOD]，只要将它改为 $_SERVER['REQUEST_METHOD']，错误提示就会消失。

PHP 4 还会对未初始化的变量或数组元素加以提示。

后退 | 起点 | 前进
解析器行为 | 上一级 | 初始化


初始化

PHP 4 中静态变量和类成员仅接受标量值，而 PHP 3 中接受任何有效的表达式。这是由于解析和执行的分离，导致只有在解析器看到初始化代码后才能执行。

您应该使用构造器来初始化类。对静态变量，只有静态的值才有意义。

后退 | 起点 | 前进
错误报告 | 上一级 | empty("0")


empty("0")

可能最具争议的改变是对 empty() 函数行为的改变。一个仅包含字符“0”（是零，不是英文字母“O”）的字符串现在被认为是空字符串，而 PHP 3 中则相反。

这个改变对 web 程序很有意义，所有的 input 表单返回的都是 string，甚至填写的是数字。PHP 能够自动进行类型转换。但另一方面，这可能不是您代码的原意，可能导致您代码莫名其妙的错误。

后退 | 起点 | 前进
初始化 | 上一级 | 缺少的函数


缺少的函数

虽然 PHP 4 带来了许多新功能、函数和扩展，您还是会发现一些本在 PHP 3 中存在的函数不见了。少量的内核函数被取消，因为它们不符合 Zend engine 新的解析——执行的模式。另外一些函数甚至是扩展完全的被荒废，是因为新的函数可以更好的完成旧函数的功能。一些函数只是空函数，而另一些因为版权冲突而取消了。

由于概念的改变而取消的函数

PHP 4 现在将解析从执行中分离，因此不可能在运行时间改变解析器（现在已经嵌入 Zend engine）的行为，此时已经解析完毕了。所以函数 short_tags() 不再存在。您仍然可以对 php.ini 文件设置适当的值以改变编译器的行为。

另一个 PHP 3 的功能在 PHP 4 中不复存在：内部捆绑的 debug 接口。现在有第三方 Zend engine 的 add-ons 有着类似的功能。

不推荐使用的函数和扩展

Adabas and Solid 数据库扩展不再推荐使用。最好使用统一的 ODBC 扩展代替。

unset() 的改变

unset()，虽然仍然可以使用，但是它成为了语言结构的一部分，而不是一个函数。

这对 unset() 的行为不会产生什么影响，但是使用 function_exists() 函数测试“unset”时会返回 FALSE。它已经是 PHP 语言的一部分，虽然它很像函数。这和 echo() 是一样的。

另一个实际的改变是，不能间接调用 unset()。因此 $func="unset"; $func($somevar) 不再工作。

后退 | 起点 | 前进
empty("0") | 上一级 | PHP 3 扩展


PHP 3 扩展

为 PHP 3 写的扩展在 PHP 4 中不再工作，二进制或源代码都不行。但如果您有扩展的原始代码，将它转换为 PHP 4 的扩展很容易。这已经不在本文所讨论的范围中了。

后退 | 起点 | 前进
缺少的函数 | 上一级 | 字符串中的变量替换


字符串中的变量替换

PHP 4 添加了一个新的机制以替换字符串中的变量。您现在可以访问字符串中的对象成员变量和多维数组元素。

如果您想这么做，您需要使用大括号将一个美元符号和变量名括起来，就像这样：{$...}。

要在字符串中嵌入对象成员变量，只要简单的写 "text {$obj->member} text"。而在 PHP 3 中，您得使用 "text ".$obj->member." text"。

这个改进可以使代码更易读，但这可能会破坏用 PHP 3 写的代码。但是您很容易修正它：在代码中查找字符串中的 {$，使用搜索替换工具将它替换为 \{$。

后退 | 起点 | 前进
PHP 3 扩展 | 上一级 | Cookies


Cookies

PHP 3 在设置 cookies 时有一个不好的习惯，它总是将 setcookie() 所设置的 cookies 以相反的顺序保存。PHP 4 改变了这个习惯，创建 cookies 时以您的代码中设置 cookies 的顺序保存。

这可能使得原有代码不能正常工作。但是 PHP 3 的行为的确很古怪，应该加以改变以防止将来产生更多的问题。

后退 | 起点 | 前进
字符串中的变量替换 | 上一级 | 处理全局变量


处理全局变量

在 PHP 3 和 PHP 4 早些版本中处理全局变量的重心放在了易用上，而现在，焦点放到了如何更安全的处理它们上。在 PHP 3 中下面的代码工作正常，但是 PHP 4 中就要使用 unset($GLOBALS["id"]);。这仅仅是全局变量处理的一个问题。您应当总是使用 $GLOBALS，在更新版本的 PHP 4 中您应该强迫自己在大部分情况中使用它。更多信息请参考 global 参考章节.

例子 B-1. 全局变量的移植

<?php
$id = 1;
function test()
{
    global $id;
    unset($id);
}
test();
echo($id); // 在 PHP 4 中这里会打印出 1
?>

后退 | 起点 | 前进
Cookies | 上一级 | 从 PHP/FI 2 移植到 PHP 3


从 PHP/FI 2 移植到 PHP 3

PHP 手册
后退 前进

附录 C. 从 PHP/FI 2 移植到 PHP 3

目录
关于 PHP 3.0 的不兼容性
开始/结束标记
if..endif 语法
while 语法
表达式类型
错误消息已经改变
布尔值的快速计算
函数 TRUE/FALSE 返回值
其它不兼容

关于 PHP 3.0 的不兼容性

PHP 3.0 从底层重写了代码。它有着比 2.0 更健壮和统一的解析器。3.0 也更快、占用更少的内存。但是，这些改进难以避免兼容性的削弱，包括语法和功能上兼容性的削弱。

另外，PHP 的开发者尝试在版本 3.0 中使得 PHP 的语法和语义更加简洁，这也导致了一些不兼容。最后，我们相信这些改变是值得的。

本章将会指导你认识从 PHP/FI 2.0 到 PHP 3.0 升级所带来的的障碍并帮助你解决它。这里没有提到 3.0 的新功能，除非必要。

一个转换程序可以帮助您自动转换旧有的 PHP/FI 2.0 脚本。这个程序可以在 PHP 3.0 发布包中的 convertor 子目录中找到。可是，该程序只能转换语法的改变，因此，您仍然需要仔细阅读下面的部分。

后退 | 起点 | 前进
处理全局变量 | 上一级 | 开始/结束标记


开始/结束标记

首先您应该注意 PHP 的开始/结束标记已经改变。老的 <? > 已经被三种新的形式所替换：

例子 C-1. 移植：旧有的开始/结束标记

<? echo "这是 PHP/FI 2.0 的代码。\n"; ?>
PHP/FI 2.0 支持这种变化：

例子 C-2. 移植：第一种开始/结束标记

<? echo "这是 PHP 3.0 的代码！\n"; ?>
请注意，结束标记现在由一个问号和一个大于号组成而不仅是一个大于号。但是，您如果计划在您的服务器上使用 XML，您会发现错误。这是因为 PHP 可能会把 XML 文档中的标记当作 PHP 代码执行。因此，建议使用以下方法：

例子 C-3. 移植：第二种开始/结束标记

<?php echo "这是 PHP 3.0 的代码！\n"; ?>
一些编辑器并不能识别并处理指示标记，Microsoft FrontPage 就是其中之一。为了使之正常工作，您可以使用下面的方法：

例子 C-4. 移植：第三种开始/结束标记

<script language="php">

  echo "这是 PHP 3.0 的代码！\n";

</script>

后退 | 起点 | 前进
从 PHP/FI 2 移植到 PHP 3 | 上一级 | if..endif 语法


if..endif 语法

使用 if(); elseif(); else; endif; 这一系列复杂的语句无助于 PHP 3.0 解析器的效率。因此，语法改变为：

例子 C-5. 移植：旧有 if..endif 语法

if ($foo);
    echo "yep\n";
elseif ($bar);
    echo "almost\n";
else;
    echo "nope\n";
endif;

例子 C-6. 移植：新的 if..endif 语法

if ($foo):
    echo "yep\n";
elseif ($bar):
    echo "almost\n";
else:
    echo "nope\n";
endif;
注意，在所有的声明中分号均改为冒号，除了末尾的 endif 以外。

后退 | 起点 | 前进
开始/结束标记 | 上一级 | while 语法


while 语法

如 if..endif 一样，while..endwhile 的语法也进行了改变：

例子 C-7. 移植：旧有 while..endwhile 语法

while ($more_to_come);
    ...
endwhile;

例子 C-8. 移植：新的 new while..endwhile 语法

while ($more_to_come):
    ...
endwhile;

警告

如果您在 PHP 3.0 中使用旧的 while..endwhile 语法，您的程序会进入死循环.

后退 | 起点 | 前进
if..endif 语法 | 上一级 | 表达式类型


表达式类型

PHP/FI 2.0 根据表达式左边判断表达式的类型，而 PHP 3.0 则根据表达式两边进行判断。这便可能导致 2.0 下运行正常的脚本在 3.0 下导致异常。

考虑以下例子：

$a[0]=5;
$a[1]=7;

$key = key($a);
while ("" != $key) {
    echo "$keyn";
    next($a);
}

在 PHP/FI 2.0 中，这段程序将显示所有 $a 的索引，而在 PHP 3.0 中，这个程序什么都不会现实。原因是，在 PHP 2.0 中，因为左边参数的类型是 string，于是，一个 string 的关系便建立起来。当然 "" 并不等于 "0"，循环从头到尾。而在 PHP 3.0 中，当一个 string 和一个 integer 比较时，将 string 转换为 integer 并比较。结果是比较值为 0 的 atoi("")，和同样是值为 0 的 variablelist，也就是 0==0。所以循环根本没有执行。

很容易修正它。把 while 声明替换为：

while ((string)$key != "") {

后退 | 起点 | 前进
while 语法 | 上一级 | 错误消息已经改变


错误消息已经改变

PHP 3.0 的错误消息通常比 2.0 的更加精确，但是您不会像 2.0 那样得到错误代码的片断。您会获得一个文件名和错误所在的行号。

后退 | 起点 | 前进
表达式类型 | 上一级 | 布尔值的快速计算


布尔值的快速计算

PHP 3.0 中的布尔值采取了快速计算的方法。这就意味着如同 (1 || test_me()) 的表达式将不会执行函数 test_me()。因为这个表达式的值始终为 1。

这只是一个很小的兼容性问题，但是会造成一些意想不到的结果。

后退 | 起点 | 前进
错误消息已经改变 | 上一级 | 函数 TRUE/FALSE 返回值


函数 TRUE/FALSE 返回值

大量的内部函数被重写，使之在成功执行时返回 TRUE，而在失败时返回 FALSE。这就如同 PHP/FI 2.0 分别返回 0 和 -1 一样。这种改变使得更多的逻辑代码得以执行，比如 $fp = fopen("/your/file") or fail("darn!");。因为 PHP/FI 2.0 对函数执行失败的返回值没有明确的规定，所以在使用 2.0 到 3.0 转换器时必须手工检查函数返回值带来的影响。

例子 C-9. 从 2.0 移植：返回值，旧有代码

$fp = fopen($file, "r");
if ($fp == -1);
    echo("无法读取文件：$file。<br>\n");
endif;

例子 C-10. 从 2.0 移植：返回值，新的代码

$fp = @fopen($file, "r") or print("无法读取文件：$file。<br>\n");

后退 | 起点 | 前进
布尔值的快速计算 | 上一级 | 其它不兼容


其它不兼容

  • PHP 3.0 的 Apache 模块不再支持 Apache 1.2 以前的版本。PHP 3.0 需要 Apache 1.2 或更高版本。

  • echo() 不再支持格式化字符串。如果想格式化字符串，使用 printf() 函数。

  • 在 PHP/FI 2.0 中，$foo[0] 和 $foo有着同样的效果。而 3.0 则不是这样的。

  • 不再支持使用 $array[] 读取数组。

    也就是说，您不可以通过作 $data = $array[] 的循环来遍历一个数组。使用 current() 和 next() 函数来代替。

    同样的，$array1[] = $array2 并没有把 $array2 的值赋给 $array1，而是把 $array2 这个数组赋给 $array1 的最后一项。这种情况也发生在多维数组上。

  • "+" 不再重载为字符串串连的运算符，它的作用是把字符串转换为数字并将它们相加。如果想串连字符串，使用 "." 代替。

例子 C-11. 从 2.0 移植：串连字符串

echo "1" + "1";

在 PHP 2.0 中该程序会显示 11，而在 PHP 3.0 中会显示 2。如果要在 PHP 3.0 中达到同样的效果，应该使用：
echo "1"."1";
$a = 1;
$b = 1;
echo $a + $b;

上面的程序在 PHP 2.0 和 3.0 中都会显示 2。
$a = 1;
$b = 1;
echo $a.$b;
面的程序在 PHP 3.0 中会显示 11。

后退 | 起点 | 前进
函数 TRUE/FALSE 返回值 | 上一级 | 排除 PHP 程序的错误


排除 PHP 程序的错误

PHP 手册
后退 前进

附录 D. 排除 PHP 程序的错误

目录
关于除错器(debugger)
使用除错器
除错器协议

关于除错器(debugger)

PHP 3 内建网络除错器支持

PHP 4 并没有内部除错工具。但是您可以使用外部除错工具。Zend IDE 就是其中之一，它包含一个除错器。也有一些免费的除错器，比如在 http://dd.cron.ru/dbg/ 上的 DBG，还有 Advanced PHP Debugger (APD)。

后退 | 起点 | 前进
其它不兼容 | 上一级 | 使用除错器


使用除错器

PHP 3 中的内建除错器对跟踪一些逻辑 Bug (evasive bugs) 是非常有用的。除错器在 PHP 3 每次启动时连接到一个 TCP 端口。从 Web 请求中产生的所有错误信息都将发送到该 TCP 连接。这些信息可以被可运行在 IDE 或者可编程编辑器（例如 Emacs）中的除错服务器处理。

如何设置除错器：

  1. 在配置文件中为除错器设置一个 TCP 端口（设定 debugger.port 参数）并且启用它（设定 debugger.enabled 参数）。

  2. 在某处设置该 TCP 端口的监听器(listener)（例如：在 UNIX 上使用 socket -l -s 1400 命令）。

  3. 在你的代码中，运行“debugger_on(host)”，host 指运行 TCP 监听器的主机名或 IP 地址。

现在，所有的错误、警告、注意等的 debug 信息都会显示在那个监听器中。即使你使用 error_reporting() 关闭它们，它们也会在监听器中显示。

后退 | 起点 | 前进
排除 PHP 程序的错误 | 上一级 | 除错器协议


除错器协议

PHP 3 除错器协议以行为单位。每一行有一个类型(type)，某几行组成一个消息(message)。每一个消息起始于包含类型 start 的一行，并终止于包含类型 end 的一行。PHP 3 可以同时发送不同的消息行。

行的格式如下：

date time
host(pid)
type:
message-data

date

date 使用 ISO 8601 格式： (yyyy-mm-dd)

time

Time 精确到毫秒： hh:mm:uuuuuu

host

产生错误的 PHP 脚本所在主机的 DNS 名或 IP 地址。

pid

产生错误的 PHP 脚本在 host 中的PID （进程 id）。

type

行的类型。它告诉接收信息的程序如何处理下面的数据：

表格 D-1. 除错器行类型

名称 | 含义
start | 告诉接收的程序，除错信息由此开始。data 的内容将会是错误消息的类型，在本页面下方列出。
message | PHP 3 错误消息。
location | 发生错误的文件名和行号。location 的第一行总是包含顶级(top-level)地址。data 包含 file:line。在 message 和每一个 function 之后总有一行 location 行。
frames | Number of frames in the following stack dump. If there are four frames, expect information about four levels of called functions. If no "frames" line is given, the depth should be assumed to be 0 (the error occurred at top-level).(TODO)
function | 发生错误的函数。在调用函数堆栈的每级只重复一次。
end | 告诉接收的程序，除错信息到此结束。

data

每行的数据。

表格 D-2. 除错器错误类型

除错器 | PHP 3 内部
warning | E_WARNING
error | E_ERROR
parse | E_PARSE
notice | E_NOTICE
core-error | E_CORE_ERROR
core-warning | E_CORE_WARNING
unknown | （其它任何错误）

例子 D-1. 除错器错误消息示例

1998-04-05 23:27:400966 lucifer.guardian.no(20481) start: notice
1998-04-05 23:27:400966 lucifer.guardian.no(20481) message: Uninitialized variable
1998-04-05 23:27:400966 lucifer.guardian.no(20481) location: (NULL):7
1998-04-05 23:27:400966 lucifer.guardian.no(20481) frames: 1
1998-04-05 23:27:400966 lucifer.guardian.no(20481) function: display
1998-04-05 23:27:400966 lucifer.guardian.no(20481) location: /home/ssb/public_html/test.php3:10
1998-04-05 23:27:400966 lucifer.guardian.no(20481) end: notice

后退 | 起点 | 前进
使用除错器 | 上一级 | 扩展 PHP


扩展 PHP

PHP 手册
后退 前进

附录 E. 扩展 PHP

目录
为 PHP 新增函数
Calling User Functions
Reporting Errors

为 PHP 新增函数

函数原型

所有的函数有着如下形式：
void php3_foo(INTERNAL_FUNCTION_PARAMETERS) {

}
即使您的函数没有任何参数，这也是它被调用的方式。

函数参数

参数总是属于 pval 类型。该类型包含了各个参数的实际类型。因此，如果您的函数有两个参数，您应该在您的函数顶部做如下工作：

例子 E-1. 取得函数参数

pval *arg1, *arg2;
if (ARG_COUNT(ht) != 2 || getParameters(ht,2,&arg1,&arg2)==FAILURE) {
   WRONG_PARAM_COUNT;
}
注意：参数既可以被值(value)传递又可以被引用(reference)传递。两种情况您都需要将 &(pval *) 传递给 getParameters 函数。如果您想检查第 n 个参数是否通过引用传递给您，您可以使用 ParameterPassedByReference(ht,n) 函数。它的返回值为 0 或者 1。

当您改变了任何已传递的参数，无论它们是以值或者引用的方式传递，您都可以对它使用 pval_destructor 函数来销毁它。或者如果它是一个您想添加的数组，您可以使用类似于 internal_functions.h 中定义函数的方法来将返回值 return_value 作为数组来操作。

Also if you change a parameter to IS_STRING make sure you first assign the new estrdup()'ed string and the string length, and only later change the type to IS_STRING. If you change the string of a parameter which already IS_STRING or IS_ARRAY you should run pval_destructor on it first.

Variable Function Arguments

A function can take a variable number of arguments. If your function can take either 2 or 3 arguments, use the following:

例子 E-2. Variable function arguments

pval *arg1, *arg2, *arg3;
int arg_count = ARG_COUNT(ht);

if (arg_count < 2 || arg_count > 3 ||
    getParameters(ht,arg_count,&arg1,&arg2,&arg3)==FAILURE) {
    WRONG_PARAM_COUNT;
}

Using the Function Arguments

The type of each argument is stored in the pval type field. This type can be any of the following:

表格 E-1. PHP Internal Types

IS_STRING | String
IS_DOUBLE | Double-precision floating point
IS_LONG | Long integer
IS_ARRAY | Array
IS_EMPTY | None
IS_USER_FUNCTION | ??
IS_INTERNAL_FUNCTION | ?? (if some of these cannot be passed to a function - delete)
IS_CLASS | ??
IS_OBJECT | ??

If you get an argument of one type and would like to use it as another, or if you just want to force the argument to be of a certain type, you can use one of the following conversion functions:
convert_to_long(arg1);
convert_to_double(arg1);
convert_to_string(arg1);
convert_to_boolean_long(arg1); /* If the string is "" or "0" it becomes 0, 1 otherwise */
convert_string_to_number(arg1);  /* Converts string to either LONG or DOUBLE depending on string */

These function all do in-place conversion. They do not return anything.

The actual argument is stored in a union; the members are:

  • IS_STRING: arg1->value.str.val

  • IS_LONG: arg1->value.lval

  • IS_DOUBLE: arg1->value.dval

Memory Management in Functions

Any memory needed by a function should be allocated with either emalloc() or estrdup(). These are memory handling abstraction functions that look and smell like the normal malloc() and strdup() functions. Memory should be freed with efree().

There are two kinds of memory in this program: memory which is returned to the parser in a variable, and memory which you need for temporary storage in your internal function. When you assign a string to a variable which is returned to the parser you need to make sure you first allocate the memory with either emalloc() or estrdup(). This memory should NEVER be freed by you, unless you later in the same function overwrite your original assignment (this kind of programming practice is not good though).

For any temporary/permanent memory you need in your functions/library you should use the three emalloc(), estrdup(), and efree() functions. They behave EXACTLY like their counterpart functions. Anything you emalloc() or estrdup() you have to efree() at some point or another, unless it's supposed to stick around until the end of the program; otherwise, there will be a memory leak. The meaning of "the functions behave exactly like their counterparts" is: if you efree() something which was not emalloc()'ed nor estrdup()'ed you might get a segmentation fault. So please take care and free all of your wasted memory.

If you compile with "-DDEBUG", PHP will print out a list of all memory that was allocated using emalloc() and estrdup() but never freed with efree() when it is done running the specified script.

Setting Variables in the Symbol Table

A number of macros are available which make it easier to set a variable in the symbol table:

  • SET_VAR_STRING(name,value)

  • SET_VAR_DOUBLE(name,value)

  • SET_VAR_LONG(name,value)

警告

Be careful with SET_VAR_STRING. The value part must be malloc'ed manually because the memory management code will try to free this pointer later. Do not pass statically allocated memory into a SET_VAR_STRING.

Symbol tables in PHP are implemented as hash tables. At any given time, &symbol_table is a pointer to the 'main' symbol table, and active_symbol_table points to the currently active symbol table (these may be identical like in startup, or different, if you're inside a function).

The following examples use 'active_symbol_table'. You should replace it with &symbol_table if you specifically want to work with the 'main' symbol table. Also, the same functions may be applied to arrays, as explained below.

例子 E-3. Checking whether $foo exists in a symbol table

if (hash_exists(active_symbol_table,"foo",sizeof("foo"))) { exists... }
else { doesn't exist }

例子 E-4. Finding a variable's size in a symbol table

hash_find(active_symbol_table,"foo",sizeof("foo"),&pvalue);
check(pvalue.type);
Arrays in PHP are implemented using the same hashtables as symbol tables. This means the two above functions can also be used to check variables inside arrays.

If you want to define a new array in a symbol table, you should do the following.

First, you may want to check whether it exists and abort appropriately, using hash_exists() or hash_find().

Next, initialize the array:

例子 E-5. Initializing a new array

pval arr;

if (array_init(&arr) == FAILURE) { failed... };
hash_update(active_symbol_table,"foo",sizeof("foo"),&arr,sizeof(pval),NULL);
This code declares a new array, named $foo, in the active symbol table. This array is empty.

Here's how to add new entries to it:

例子 E-6. Adding entries to a new array

pval entry;

entry.type = IS_LONG;
entry.value.lval = 5;

/* defines $foo["bar"] = 5 */
hash_update(arr.value.ht,"bar",sizeof("bar"),&entry,sizeof(pval),NULL);

/* defines $foo[7] = 5 */
hash_index_update(arr.value.ht,7,&entry,sizeof(pval),NULL);

/* defines the next free place in $foo[],
 * $foo[8], to be 5 (works like php2)
 */
hash_next_index_insert(arr.value.ht,&entry,sizeof(pval),NULL);
If you'd like to modify a value that you inserted to a hash, you must first retrieve it from the hash. To prevent that overhead, you can supply a pval ** to the hash add function, and it'll be updated with the pval * address of the inserted element inside the hash. If that value is NULL (like in all of the above examples) - that parameter is ignored.

hash_next_index_insert() uses more or less the same logic as "$foo[] = bar;" in PHP 2.0.

If you are building an array to return from a function, you can initialize the array just like above by doing:

if (array_init(return_value) == FAILURE) { failed...; }

...and then adding values with the helper functions:

add_next_index_long(return_value,long_value);
add_next_index_double(return_value,double_value);
add_next_index_string(return_value,estrdup(string_value));

Of course, if the adding isn't done right after the array initialization, you'd probably have to look for the array first:
pval *arr;

if (hash_find(active_symbol_table,"foo",sizeof("foo"),(void **)&arr)==FAILURE) { can't find... }
else { use arr->value.ht... }

Note that hash_find receives a pointer to a pval pointer, and not a pval pointer.

Just about any hash function returns SUCCESS or FAILURE (except for hash_exists(), which returns a boolean truth value).

Returning simple values

A number of macros are available to make returning values from a function easier.

The RETURN_* macros all set the return value and return from the function:

  • RETURN

  • RETURN_FALSE

  • RETURN_TRUE

  • RETURN_LONG(l)

  • RETURN_STRING(s,dup) If dup is TRUE, duplicates the string

  • RETURN_STRINGL(s,l,dup) Return string (s) specifying length (l).

  • RETURN_DOUBLE(d)

The RETVAL_* macros set the return value, but do not return.

  • RETVAL_FALSE

  • RETVAL_TRUE

  • RETVAL_LONG(l)

  • RETVAL_STRING(s,dup) If dup is TRUE, duplicates the string

  • RETVAL_STRINGL(s,l,dup) Return string (s) specifying length (l).

  • RETVAL_DOUBLE(d)

The string macros above will all estrdup() the passed 's' argument, so you can safely free the argument after calling the macro, or alternatively use statically allocated memory.

If your function returns boolean success/error responses, always use RETURN_TRUE and RETURN_FALSE respectively.

Returning complex values

Your function can also return a complex data type such as an object or an array.

Returning an object:

  1. Call object_init(return_value).

  2. Fill it up with values. The functions available for this purpose are listed below.

  3. Possibly, register functions for this object. In order to obtain values from the object, the function would have to fetch "this" from the active_symbol_table. Its type should be IS_OBJECT, and it's basically a regular hash table (i.e., you can use regular hash functions on .value.ht). The actual registration of the function can be done using:
    add_method( return_value, function_name, function_ptr );

The functions used to populate an object are:

  • add_property_long( return_value, property_name, l ) - Add a property named 'property_name', of type long, equal to 'l'

  • add_property_double( return_value, property_name, d ) - Same, only adds a double

  • add_property_string( return_value, property_name, str ) - Same, only adds a string

  • add_property_stringl( return_value, property_name, str, l ) - Same, only adds a string of length 'l'

Returning an array:

  1. Call array_init(return_value).

  2. Fill it up with values. The functions available for this purpose are listed below.

The functions used to populate an array are:

  • add_assoc_long(return_value,key,l) - add associative entry with key 'key' and long value 'l'

  • add_assoc_double(return_value,key,d)

  • add_assoc_string(return_value,key,str,duplicate)

  • add_assoc_stringl(return_value,key,str,length,duplicate) specify the string length

  • add_index_long(return_value,index,l) - add entry in index 'index' with long value 'l'

  • add_index_double(return_value,index,d)

  • add_index_string(return_value,index,str)

  • add_index_stringl(return_value,index,str,length) - specify the string length

  • add_next_index_long(return_value,l) - add an array entry in the next free offset with long value 'l'

  • add_next_index_double(return_value,d)

  • add_next_index_string(return_value,str)

  • add_next_index_stringl(return_value,str,length) - specify the string length

Using the resource list

PHP has a standard way of dealing with various types of resources. This replaces all of the local linked lists in PHP 2.0.

Available functions:

  • php3_list_insert(ptr, type) - returns the 'id' of the newly inserted resource

  • php3_list_delete(id) - delete the resource with the specified id

  • php3_list_find(id,*type) - returns the pointer of the resource with the specified id, updates 'type' to the resource's type

Typically, these functions are used for SQL drivers but they can be used for anything else; for instance, maintaining file descriptors.

Typical list code would look like this:

例子 E-7. Adding a new resource

RESOURCE *resource;

/* ...allocate memory for resource and acquire resource... */
/* add a new resource to the list */
return_value->value.lval = php3_list_insert((void *) resource, LE_RESOURCE_TYPE);
return_value->type = IS_LONG;

例子 E-8. Using an existing resource

pval *resource_id;
RESOURCE *resource;
int type;

convert_to_long(resource_id);
resource = php3_list_find(resource_id->value.lval, &type);
if (type != LE_RESOURCE_TYPE) {
    php3_error(E_WARNING,"resource index %d has the wrong type",resource_id->value.lval);
    RETURN_FALSE;
}
/* ...use resource... */

例子 E-9. Deleting an existing resource

pval *resource_id;
RESOURCE *resource;
int type;

convert_to_long(resource_id);
php3_list_delete(resource_id->value.lval);
The resource types should be registered in php3_list.h, in enum list_entry_type. In addition, one should add shutdown code for any new resource type defined, in list.c's list_entry_destructor() (even if you don't have anything to do on shutdown, you must add an empty case).

Using the persistent resource table

PHP has a standard way of storing persistent resources (i.e., resources that are kept in between hits). The first module to use this feature was the MySQL module, and mSQL followed it, so one can get the general impression of how a persistent resource should be used by reading mysql.c. The functions you should look at are:

php3_mysql_do_connect
php3_mysql_connect()
php3_mysql_pconnect()

The general idea of persistence modules is this:

  1. Code all of your module to work with the regular resource list mentioned in section (9).

  2. Code extra connect functions that check if the resource already exists in the persistent resource list. If it does, register it as in the regular resource list as a pointer to the persistent resource list (because of 1., the rest of the code should work immediately). If it doesn't, then create it, add it to the persistent resource list AND add a pointer to it from the regular resource list, so all of the code would work since it's in the regular resource list, but on the next connect, the resource would be found in the persistent resource list and be used without having to recreate it. You should register these resources with a different type (e.g. LE_MYSQL_LINK for non-persistent link and LE_MYSQL_PLINK for a persistent link).

If you read mysql.c, you'll notice that except for the more complex connect function, nothing in the rest of the module has to be changed.

The very same interface exists for the regular resource list and the persistent resource list, only 'list' is replaced with 'plist':

  • php3_plist_insert(ptr, type) - returns the 'id' of the newly inserted resource

  • php3_plist_delete(id) - delete the resource with the specified id

  • php3_plist_find(id,*type) - returns the pointer of the resource with the specified id, updates 'type' to the resource's type

However, it's more than likely that these functions would prove to be useless for you when trying to implement a persistent module. Typically, one would want to use the fact that the persistent resource list is really a hash table. For instance, in the MySQL/mSQL modules, when there's a pconnect() call (persistent connect), the function builds a string out of the host/user/passwd that were passed to the function, and hashes the SQL link with this string as a key. The next time someone calls a pconnect() with the same host/user/passwd, the same key would be generated, and the function would find the SQL link in the persistent list.

Until further documented, you should look at mysql.c or msql.c to see how one should use the plist's hash table abilities.

One important thing to note: resources going into the persistent resource list must *NOT* be allocated with PHP's memory manager, i.e., they should NOT be created with emalloc(), estrdup(), etc. Rather, one should use the regular malloc(), strdup(), etc. The reason for this is simple - at the end of the request (end of the hit), every memory chunk that was allocated using PHP's memory manager is deleted. Since the persistent list isn't supposed to be erased at the end of a request, one mustn't use PHP's memory manager for allocating resources that go to it.

When you register a resource that's going to be in the persistent list, you should add destructors to it both in the non-persistent list and in the persistent list. The destructor in the non-persistent list destructor shouldn't do anything. The one in the persistent list destructor should properly free any resources obtained by that type (e.g. memory, SQL links, etc). Just like with the non-persistent resources, you *MUST* add destructors for every resource, even it requires no destruction and the destructor would be empty. Remember, since emalloc() and friends aren't to be used in conjunction with the persistent list, you mustn't use efree() here either.

Adding runtime configuration directives

Many of the features of PHP can be configured at runtime. These configuration directives can appear in either the designated php3.ini file, or in the case of the Apache module version in the Apache .conf files. The advantage of having them in the Apache .conf files is that they can be configured on a per-directory basis. This means that one directory may have a certain safemodeexecdir for example, while another directory may have another. This configuration granularity is especially handy when a server supports multiple virtual hosts.

The steps required to add a new directive:

  1. Add directive to php3_ini_structure struct in mod_php3.h.

  2. In main.c, edit the php3_module_startup function and add the appropriate cfg_get_string() or cfg_get_long() call.

  3. Add the directive, restrictions and a comment to the php3_commands structure in mod_php3.c. Note the restrictions part. RSRC_CONF are directives that can only be present in the actual Apache .conf files. Any OR_OPTIONS directives can be present anywhere, include normal .htaccess files.

  4. In either php3take1handler() or php3flaghandler() add the appropriate entry for your directive.

  5. In the configuration section of the _php3_info() function in functions/info.c you need to add your new directive.

  6. And last, you of course have to use your new directive somewhere. It will be addressable as php3_ini.directive.

后退 | 起点 | 前进
除错器协议 | 上一级 | Calling User Functions


Calling User Functions

To call user functions from an internal function, you should use the call_user_function() function.

call_user_function() returns SUCCESS on success, and FAILURE in case the function cannot be found. You should check that return value! If it returns SUCCESS, you are responsible for destroying the retval pval yourself (or return it as the return value of your function). If it returns FAILURE, the value of retval is undefined, and you mustn't touch it.

All internal functions that call user functions must be reentrant. Among other things, this means they must not use globals or static variables.

call_user_function() takes six arguments:

HashTable *function_table

This is the hash table in which the function is to be looked up.

pval *object

This is a pointer to an object on which the function is invoked. This should be NULL if a global function is called. If it's not NULL (i.e. it points to an object), the function_table argument is ignored, and instead taken from the object's hash. The object *may* be modified by the function that is invoked on it (that function will have access to it via $this). If for some reason you don't want that to happen, send a copy of the object instead.

pval *function_name

The name of the function to call. Must be a pval of type IS_STRING with function_name.str.val and function_name.str.len set to the appropriate values. The function_name is modified by call_user_function() - it's converted to lowercase. If you need to preserve the case, send a copy of the function name instead.

pval *retval

A pointer to a pval structure, into which the return value of the invoked function is saved. The structure must be previously allocated - call_user_function() does NOT allocate it by itself.

int param_count

The number of parameters being passed to the function.

pval *params[]

An array of pointers to values that will be passed as arguments to the function, the first argument being in offset 0, the second in offset 1, etc. The array is an array of pointers to pval's; The pointers are sent as-is to the function, which means if the function modifies its arguments, the original values are changed (passing by reference). If you don't want that behavior, pass a copy instead.

后退 | 起点 | 前进
扩展 PHP | 上一级 | Reporting Errors


Reporting Errors

To report errors from an internal function, you should call the php3_error() function. This takes at least two parameters -- the first is the level of the error, the second is the format string for the error message (as in a standard printf() call), and any following arguments are the parameters for the format string. The error levels are:

E_NOTICE

Notices are not printed by default, and indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script. For example, trying to access the value of a variable which has not been set, or calling stat() on a file that doesn't exist.

E_WARNING

Warnings are printed by default, but do not interrupt script execution. These indicate a problem that should have been trapped by the script before the call was made. For example, calling ereg() with an invalid regular expression.

E_ERROR

Errors are also printed by default, and execution of the script is halted after the function returns. These indicate errors that can not be recovered from, such as a memory allocation problem.

E_PARSE

Parse errors should only be generated by the parser. The code is listed here only for the sake of completeness.

E_CORE_ERROR

This is like an E_ERROR, except it is generated by the core of PHP. Functions should not generate this type of error.

E_CORE_WARNING

This is like an E_WARNING, except it is generated by the core of PHP. Functions should not generate this type of error.

E_COMPILE_ERROR

This is like an E_ERROR, except it is generated by the Zend Scripting Engine. Functions should not generate this type of error.

E_COMPILE_WARNING

This is like an E_WARNING, except it is generated by the Zend Scripting Engine. Functions should not generate this type of error.

E_USER_ERROR

This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error(). Functions should not generate this type of error.

E_USER_WARNING

This is like an E_WARNING, except it is generated by using the PHP function trigger_error(). Functions should not generate this type of error.

E_USER_NOTICE

This is like an E_NOTICE, except it is generated by using the PHP function trigger_error(). Functions should not generate this type of error.

E_ALL

All of the above. Using this error_reporting level will show all error types.

后退 | 起点 | 前进
Calling User Functions | 上一级 | 函数别名列表


函数别名列表

PHP 手册
后退 前进

附录 F. 函数别名列表

这里是函数别名列表。所有的别名列表如下。通常使用别名并不是一个好主意，这是因为它可能会废弃不用或者重新定义。这会导致不可移植脚本的出现。本列表是为了帮助想要升级他们旧有脚本到新版本语法的开发人员。

但是，一些函数只是简单的有两个名称，并没有真正意义上的区别。（例如，is_int() 和 is_integer() 是完全等价的。）

该列表基于 PHP 4.0.6。

表格 F-1. 别名列表

别名 | 主函数 | 使用的扩展模块
_ | gettext() | Gettext
add | swfmovie_add() | Ming (flash)
add | swfsprite_add() | Ming (flash)
add_root | domxml_add_root() | DOM XML
addaction | swfbutton_addAction() | Ming (flash)
addcolor | swfdisplayitem_addColor() | Ming (flash)
addentry | swfgradient_addEntry() | Ming (flash)
addfill | swfshape_addfill() | Ming (flash)
addshape | swfbutton_addShape() | Ming (flash)
addstring | swftext_addString() | Ming (flash)
addstring | swftextfield_addString() | Ming (flash)
align | swftextfield_align() | Ming (flash)
attributes | domxml_attributes() | DOM XML
children | domxml_children() | DOM XML
chop | rtrim() | Base syntax
close | closedir() | Base syntax
com_get | com_propget() | COM
com_propset | com_propput() | COM
com_set | com_propput() | COM
cv_add | ccvs_add() | CCVS
cv_auth | ccvs_auth() | CCVS
cv_command | ccvs_command() | CCVS
cv_count | ccvs_count() | CCVS
cv_delete | ccvs_delete() | CCVS
cv_done | ccvs_done() | CCVS
cv_init | ccvs_init() | CCVS
cv_lookup | ccvs_lookup() | CCVS
cv_new | ccvs_new() | CCVS
cv_report | ccvs_report() | CCVS
cv_return | ccvs_return() | CCVS
cv_reverse | ccvs_reverse() | CCVS
cv_sale | ccvs_sale() | CCVS
cv_status | ccvs_status() | CCVS
cv_textvalue | ccvs_textvalue() | CCVS
cv_void | ccvs_void() | CCVS
die | exit() | Miscellaneous functions
dir | getdir() | Base syntax
diskfreespace | disk_free_space() | Filesystem
domxml_getattr | domxml_get_attribute() | DOM XML
domxml_setattr | domxml_set_attribute() | DOM XML
doubleval | floatval() | Base syntax
drawarc | swfshape_drawarc() | Ming (flash)
drawcircle | swfshape_drawcircle() | Ming (flash)
drawcubic | swfshape_drawcubic() | Ming (flash)
drawcubicto | swfshape_drawcubicto() | Ming (flash)
drawcurve | swfshape_drawcurve() | Ming (flash)
drawcurveto | swfshape_drawcurveto() | Ming (flash)
drawglyph | swfshape_drawglyph() | Ming (flash)
drawline | swfshape_drawline() | Ming (flash)
drawlineto | swfshape_drawlineto() | Ming (flash)
dtd | domxml_intdtd() | DOM XML
dumpmem | domxml_dumpmem() | DOM XML
fbsql | fbsql_db_query() | FrontBase
fputs | fwrite() | Base syntax
get_attribute | domxml_get_attribute() | DOM XML
getascent | swffont_getAscent() | Ming (flash)
getascent | swftext_getAscent() | Ming (flash)
getattr | domxml_get_attribute() | DOM XML
getdescent | swffont_getDescent() | Ming (flash)
getdescent | swftext_getDescent() | Ming (flash)
getheight | swfbitmap_getHeight() | Ming (flash)
getleading | swffont_getLeading() | Ming (flash)
getleading | swftext_getLeading() | Ming (flash)
getshape1 | swfmorph_getShape1() | Ming (flash)
getshape2 | swfmorph_getShape2() | Ming (flash)
getwidth | swfbitmap_getWidth() | Ming (flash)
getwidth | swffont_getWidth() | Ming (flash)
getwidth | swftext_getWidth() | Ming (flash)
gzputs | gzwrite() | Zlib
i18n_convert | mb_convert_encoding() | Multi-bytes Strings
i18n_discover_encoding | mb_detect_encoding() | Multi-bytes Strings
i18n_http_input | mb_http_input() | Multi-bytes Strings
i18n_http_output | mb_http_output() | Multi-bytes Strings
i18n_internal_encoding | mb_internal_encoding() | Multi-bytes Strings
i18n_ja_jp_hantozen | mb_convert_kana() | Multi-bytes Strings
i18n_mime_header_decode | mb_decode_mimeheader() | Multi-bytes Strings
i18n_mime_header_encode | mb_encode_mimeheader() | Multi-bytes Strings
imap_create | imap_createmailbox() | IMAP
imap_fetchtext | imap_body() | IMAP
imap_getmailboxes | imap_list_full() | IMAP
imap_getsubscribed | imap_lsub_full() | IMAP
imap_header | imap_headerinfo() | IMAP
imap_listmailbox | imap_list() | IMAP
imap_listsubscribed | imap_lsub() | IMAP
imap_rename | imap_renamemailbox() | IMAP
imap_scan | imap_listscan() | IMAP
imap_scanmailbox | imap_listscan() | IMAP
ini_alter | ini_set() | Base syntax
is_double | is_float() | Base syntax
is_integer | is_int() | Base syntax
is_long | is_int() | Base syntax
is_real | is_float() | Base syntax
is_writeable | is_writable() | Base syntax
join | implode() | Base syntax
labelframe | swfmovie_labelFrame() | Ming (flash)
labelframe | swfsprite_labelFrame() | Ming (flash)
last_child | domxml_last_child() | DOM XML
lastchild | domxml_last_child() | DOM XML
ldap_close | ldap_unbind() | LDAP
magic_quotes_runtime | set_magic_quotes_runtime() | Base syntax
mbstrcut | mb_strcut() | Multi-bytes Strings
mbstrlen | mb_strlen() | Multi-bytes Strings
mbstrpos | mb_strpos() | Multi-bytes Strings
mbstrrpos | mb_strrpos() | Multi-bytes Strings
mbsubstr | mb_substr() | Multi-bytes Strings
ming_setcubicthreshold | ming_setCubicThreshold() | Ming (flash)
ming_setscale | ming_setScale() | Ming (flash)
move | swfdisplayitem_move() | Ming (flash)
movepen | swfshape_movepen() | Ming (flash)
movepento | swfshape_movepento() | Ming (flash)
moveto | swfdisplayitem_moveTo() | Ming (flash)
moveto | swffill_moveTo() | Ming (flash)
moveto | swftext_moveTo() | Ming (flash)
msql | msql_db_query() | mSQL
msql_createdb | msql_create_db() | mSQL
msql_dbname | msql_result() | mSQL
msql_dropdb | msql_drop_db() | mSQL
msql_fieldflags | msql_field_flags() | mSQL
msql_fieldlen | msql_field_len() | mSQL
msql_fieldname | msql_field_name() | mSQL
msql_fieldtable | msql_field_table() | mSQL
msql_fieldtype | msql_field_type() | mSQL
msql_freeresult | msql_free_result() | mSQL
msql_listdbs | msql_list_dbs() | mSQL
msql_listfields | msql_list_fields() | mSQL
msql_listtables | msql_list_tables() | mSQL
msql_numfields | msql_num_fields() | mSQL
msql_numrows | msql_num_rows() | mSQL
msql_regcase | sql_regcase() | mSQL
msql_selectdb | msql_select_db() | mSQL
msql_tablename | msql_result() | mSQL
mssql_affected_rows | sybase_affected_rows() | Sybase
mssql_affected_rows | sybase_affected_rows() | Sybase
mssql_close | sybase_close() | Sybase
mssql_close | sybase_close() | Sybase
mssql_connect | sybase_connect() | Sybase
mssql_connect | sybase_connect() | Sybase
mssql_data_seek | sybase_data_seek() | Sybase
mssql_data_seek | sybase_data_seek() | Sybase
mssql_fetch_array | sybase_fetch_array() | Sybase
mssql_fetch_array | sybase_fetch_array() | Sybase
mssql_fetch_field | sybase_fetch_field() | Sybase
mssql_fetch_field | sybase_fetch_field() | Sybase
mssql_fetch_object | sybase_fetch_object() | Sybase
mssql_fetch_object | sybase_fetch_object() | Sybase
mssql_fetch_row | sybase_fetch_row() | Sybase
mssql_fetch_row | sybase_fetch_row() | Sybase
mssql_field_seek | sybase_field_seek() | Sybase
mssql_field_seek | sybase_field_seek() | Sybase
mssql_free_result | sybase_free_result() | Sybase
mssql_free_result | sybase_free_result() | Sybase
mssql_get_last_message | sybase_get_last_message() | Sybase
mssql_get_last_message | sybase_get_last_message() | Sybase
mssql_min_client_severity | sybase_min_client_severity() | Sybase
mssql_min_error_severity | sybase_min_error_severity() | Sybase
mssql_min_message_severity | sybase_min_message_severity() | Sybase
mssql_min_server_severity | sybase_min_server_severity() | Sybase
mssql_num_fields | sybase_num_fields() | Sybase
mssql_num_fields | sybase_num_fields() | Sybase
mssql_num_rows | sybase_num_rows() | Sybase
mssql_num_rows | sybase_num_rows() | Sybase
mssql_pconnect | sybase_pconnect() | Sybase
mssql_pconnect | sybase_pconnect() | Sybase
mssql_query | sybase_query() | Sybase
mssql_query | sybase_query() | Sybase
mssql_result | sybase_result() | Sybase
mssql_result | sybase_result() | Sybase
mssql_select_db | sybase_select_db() | Sybase
mssql_select_db | sybase_select_db() | Sybase
multcolor | swfdisplayitem_multColor() | Ming (flash)
mysql | mysql_db_query() | MySQL
mysql_createdb | mysql_create_db() | MySQL
mysql_db_name | mysql_result() | MySQL
mysql_dbname | mysql_result() | MySQL
mysql_dropdb | mysql_drop_db() | MySQL
mysql_fieldflags | mysql_field_flags() | MySQL
mysql_fieldlen | mysql_field_len() | MySQL
mysql_fieldname | mysql_field_name() | MySQL
mysql_fieldtable | mysql_field_table() | MySQL
mysql_fieldtype | mysql_field_type() | MySQL
mysql_freeresult | mysql_free_result() | MySQL
mysql_listdbs | mysql_list_dbs() | MySQL
mysql_listfields | mysql_list_fields() | MySQL
mysql_listtables | mysql_list_tables() | MySQL
mysql_numfields | mysql_num_fields() | MySQL
mysql_numrows | mysql_num_rows() | MySQL
mysql_selectdb | mysql_select_db() | MySQL
mysql_tablename | mysql_result() | MySQL
name | domxml_attrname() | DOM XML
new_child | domxml_new_child() | DOM XML
new_xmldoc | domxml_new_xmldoc() | DOM XML
nextframe | swfmovie_nextFrame() | Ming (flash)
nextframe | swfsprite_nextFrame() | Ming (flash)
node | domxml_node() | DOM XML
oci8append | ocicollappend() | OCI8
oci8assign | ocicollassign() | OCI8
oci8assignelem | ocicollassignelem() | OCI8
oci8close | ocicloselob() | OCI8
oci8free | ocifreecoll() | OCI8
oci8free | ocifreedesc() | OCI8
oci8getelem | ocicollgetelem() | OCI8
oci8load | ociloadlob() | OCI8
oci8max | ocicollmax() | OCI8
oci8ocifreecursor | ocifreestatement() | OCI8
oci8save | ocisavelob() | OCI8
oci8savefile | ocisavelobfile() | OCI8
oci8size | ocicollsize() | OCI8
oci8trim | ocicolltrim() | OCI8
oci8writetemporary | ociwritetemporarylob() | OCI8
oci8writetofile | ociwritelobtofile() | OCI8
odbc_do | odbc_exec() | OCI8
odbc_field_precision | odbc_field_len() | OCI8
output | swfmovie_output() | Ming (flash)
parent | domxml_parent() | DOM XML
pdf_add_outline | pdf_add_bookmark() | PDF
pg_clientencoding | pg_client_encoding() | PostgreSQL
pg_setclientencoding | pg_set_client_encoding() | PostgreSQL
pos | current() | Base syntax
recode | recode_string() | Recode
remove | swfmovie_remove() | Ming (flash)
remove | swfsprite_remove() | Ming (flash)
rewind | rewinddir() | Base syntax
root | domxml_root() | DOM XML
rotate | swfdisplayitem_rotate() | Ming (flash)
rotateto | swfdisplayitem_rotateTo() | Ming (flash)
rotateto | swffill_rotateTo() | Ming (flash)
save | swfmovie_save() | Ming (flash)
savetofile | swfmovie_saveToFile() | Ming (flash)
scale | swfdisplayitem_scale() | Ming (flash)
scaleto | swfdisplayitem_scaleTo() | Ming (flash)
scaleto | swffill_scaleTo() | Ming (flash)
set_attribute | domxml_set_attribute() | DOM XML
set_content | domxml_set_content() | DOM XML
setaction | swfbutton_setAction() | Ming (flash)
setattr | domxml_set_attribute() | DOM XML
setbackground | swfmovie_setBackground() | Ming (flash)
setbounds | swftextfield_setBounds() | Ming (flash)
setcolor | swftext_setColor() | Ming (flash)
setcolor | swftextfield_setColor() | Ming (flash)
setdepth | swfdisplayitem_setDepth() | Ming (flash)
setdimension | swfmovie_setDimension() | Ming (flash)
setdown | swfbutton_setDown() | Ming (flash)
setfont | swftext_setFont() | Ming (flash)
setfont | swftextfield_setFont() | Ming (flash)
setframes | swfmovie_setFrames() | Ming (flash)
setframes | swfsprite_setFrames() | Ming (flash)
setheight | swftext_setHeight() | Ming (flash)
setheight | swftextfield_setHeight() | Ming (flash)
sethit | swfbutton_setHit() | Ming (flash)
setindentation | swftextfield_setIndentation() | Ming (flash)
setleftfill | swfshape_setleftfill() | Ming (flash)
setleftmargin | swftextfield_setLeftMargin() | Ming (flash)
setline | swfshape_setline() | Ming (flash)
setlinespacing | swftextfield_setLineSpacing() | Ming (flash)
setmargins | swftextfield_setMargins() | Ming (flash)
setmatrix | swfdisplayitem_setMatrix() | Ming (flash)
setname | swfdisplayitem_setName() | Ming (flash)
setname | swftextfield_setName() | Ming (flash)
setover | swfbutton_setOver() | Ming (flash)
setrate | swfmovie_setRate() | Ming (flash)
setratio | swfdisplayitem_setRatio() | Ming (flash)
setrightfill | swfshape_setrightfill() | Ming (flash)
setrightmargin | swftextfield_setRightMargin() | Ming (flash)
setspacing | swftext_setSpacing() | Ming (flash)
setup | swfbutton_setUp() | Ming (flash)
show_source | highlight_file () | Base syntax
sizeof | count() | Base syntax
skewx | swfdisplayitem_skewX() | Ming (flash)
skewxto | swfdisplayitem_skewXTo() | Ming (flash)
skewxto | swffill_skewXTo() | Ming (flash)
skewy | swfdisplayitem_skewY() | Ming (flash)
skewyto | swfdisplayitem_skewYTo() | Ming (flash)
skewyto | swffill_skewYTo() | Ming (flash)
snmpwalkoid | snmprealwalk() | SNMP
strchr | strstr() | Base syntax
streammp3 | swfmovie_streamMp3() | Ming (flash)
swfaction | swfaction_init() | Ming (flash)
swfbitmap | swfbitmap_init() | Ming (flash)
swfbutton | swfbutton_init() | Ming (flash)
swffill | swffill_init() | Ming (flash)
swffont | swffont_init() | Ming (flash)
swfgradient | swfgradient_init() | Ming (flash)
swfmorph | swfmorph_init() | Ming (flash)
swfmovie | swfmovie_init() | Ming (flash)
swfshape | swfshape_init() | Ming (flash)
swfsprite | swfsprite_init() | Ming (flash)
swftext | swftext_init() | Ming (flash)
swftextfield | swftextfield_init() | Ming (flash)
unlink | domxml_unlink_node() | DOM XML
xptr_new_context | xpath_new_context() | DOM XML

后退 | 起点 | 前进
Reporting Errors | 上一级 | 保留字列表


保留字列表

PHP 手册
后退 前进

附录 G. 保留字列表

目录
关键词列表
预定义变量
预定义类
预定义常量

下面是 PHP 中预定义标识符的列表。没有列在后面的标识符可以在您的脚本中作为自定义标识符使用。这些列表包括关键字和预定义变量、常量和类名。这些列表可能有遗漏，它是不完整的。

关键词列表

这些词语在 PHP 中有着特殊的意义。它们中有些像是函数，有些像是常量……但是它们不是的，它们只是语言结构的一部分。您不能使用它们的任何一个作为常量、函数名或是类名。但是可以将它们作为变量名使用，不过这样会导致混淆。

表格 G-1. PHP 关键词

and | or | xor | __FILE__
__LINE__ | array() | as | break | case
cfunction | class | const | continue | declare
default | die() | do | echo() | else
elseif | empty() | enddeclare | endfor | endforeach
endif | endswitch | endwhile | eval | exit()
extends | for | foreach | function | global
if | include() | include_once() | isset() | list()
new | old_function | print() | require() | require_once()
return() | static | switch | unset() | use
var | while | __FUNCTION__ | __CLASS__

后退 | 起点 | 前进
函数别名列表 | 上一级 | 预定义变量


预定义变量

服务器变量：$_SERVER

注: 在 PHP 4.1.0 及以后版本使用。之前的版本，使用 $HTTP_SERVER_VARS。

$_SERVER 是一个包含诸如头部(headers)、路径(paths)和脚本位置(script locations)的数组。数组的实体由 web 服务器创建。不能保证所有的服务器都能产生所有的信息；服务器可能忽略了一些信息，或者产生了一些未在下面列出的新的信息。这意味着，大量的这些变量在 CGI 1.1 specification 中说明，所以您应该仔细研究它。

这是一个“superglobal”，或者可以描述为自动全局变量。这只不过意味这它在所有的脚本中都有效。在函数或方法中您不需要使用 global $_SERVER; 访问它，就如同使用 $HTTP_SERVER_VARS 一样。

$HTTP_SERVER_VARS 包含着同样的信息，但是不是一个自动全局变量。（注意： $HTTP_SERVER_VARS 和 $_SERVER 是不同的变量，PHP 处理它们的方式不同。）

如果设置了 register_globals 指令，这些变量也在所有脚本中可用；也就是，分离了 $_SERVER 和 $HTTP_SERVER_VARS 数组。相关信息，请参阅安全的相关章节 使用 Register Globals。这些单独的全局变量不是自动全局变量。

您或许会发现下面列出的某些 $_SERVER 元素并不可用。注意，如果以命令行方式运行 PHP，下面列出的元素几乎没有有效的（或是没有任何实际意义的）。

“PHP_SELF”

当前正在执行脚本的文件名，与 document root相关。举例来说，在URL地址为 http://example.com/test.php/foo.bar 的脚本中使用 $_SERVER['PHP_SELF'] 将会得到 /test.php/foo.bar 这个结果。

如果 PHP 以命令行方式运行，该变量无效。

“argv”

传递给该脚本的参数。当脚本运行在命令行方式时，argv 变量传递给程序 C 语言样式的命令行参数。当调用 GET 方法时，该变量包含请求的数据。

“argc”

包含传递给程序的命令行参数的个数（如果运行在命令行模式）。

“GATEWAY_INTERFACE”

服务器使用的 CGI 规范的版本。例如，“CGI/1.1”。

'SERVER_NAME'

当前运行脚本所在服务器主机的名称。如果该脚本运行在一个虚拟主机上，该名称是由那个虚拟主机所设置的值决定。

'SERVER_SOFTWARE'

服务器标识的字串，在响应请求时的头部中给出。

“SERVER_PROTOCOL”

请求页面时通信协议的名称和版本。例如，“HTTP/1.0”。

“REQUEST_METHOD”

访问页面时的请求方法。例如：“GET”、“HEAD”，“POST”，“PUT”。

“QUERY_STRING”

查询(query)的字符串。

“DOCUMENT_ROOT”

当前运行脚本所在的文档根目录。在服务器配置文件中定义。

“HTTP_ACCEPT”

当前请求的 Accept: 头部的内容。

“HTTP_ACCEPT_CHARSET”

当前请求的 Accept-Charset: 头部的内容。例如：“iso-8859-1,*,utf-8”。

“HTTP_ACCEPT_ENCODING”

当前请求的 Accept-Encoding: 头部的内容。例如：“gzip”。

“HTTP_ACCEPT_LANGUAGE”

当前请求的 Accept-Language: 头部的内容。例如：“en”。

“HTTP_CONNECTION”

当前请求的 Connection: 头部的内容。例如：“Keep-Alive”。

“HTTP_HOST”

当前请求的 Host: 头部的内容。

“HTTP_REFERER”

链接到当前页面的前一页面的 URL 地址。不是所有的用户代理（浏览器）都会设置这个变量，而且有的还可以手工修改 HTTP_REFERER。因此，这个变量不总是正确真实的。

“HTTP_USER_AGENT”

当前请求的 User_Agent: 头部的内容。该字符串表明了访问该页面的用户代理的信息。一个典型的例子是：Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586)。您也可以使用 get_browser() 得到这个信息。

“REMOTE_ADDR”

正在浏览当前页面用户的 IP 地址。

“REMOTE_PORT”

用户连接到服务器时所使用的端口。

“SCRIPT_FILENAME”

当前执行脚本的绝对路径名。

“SERVER_ADMIN”

该值指明了 Apache 服务器配置文件中的 SERVER_ADMIN 参数。如果脚本运行在一个虚拟主机上，则该值是那个虚拟主机的值。

“SERVER_PORT”

服务器所使用的端口。默认为“80”。如果你使用 SSL 安全连接，则这个值为您所设置的 HTTP 端口。

“SERVER_SIGNATURE”

包含服务器版本和虚拟主机名的字符串。

“PATH_TRANSLATED”

当前脚本所在文件系统（不是文档根目录）的基本路径。这是在服务器进行虚拟到真实路径的映像后的结果。

“SCRIPT_NAME”

包含当前脚本的路径。这在页面需要指向自己时非常有用。

“REQUEST_URI”

访问此页面所需的 URI。例如，“/index.html”。

“PHP_AUTH_USER”

当 PHP 运行在 Apache 模块方式下，并且正在使用 HTTP 认证功能，这个变量便是用户输入的用户名。

“PHP_AUTH_PW”

当 PHP 运行在 Apache 模块方式下，并且正在使用 HTTP 认证功能，这个变量便是用户输入的密码。

“PHP_AUTH_TYPE”

当 PHP 运行在 Apache 模块方式下，并且正在使用 HTTP 认证功能，这个变量便是认证的类型。

环境变量：$_ENV

注: 在 PHP 4.1.0 及以后版本使用。之前的版本，使用 $HTTP_ENV_VARS。

在解析器运行时，这些变量从环境变量转变为 PHP 全局变量名称空间(namespace)。它们中的许多都是由 PHP 所运行的系统决定。完整的列表是不可能的。请查看您系统的文档以确定其特定的环境变量。

其它环境变量（包括 CGI 变量），无论 PHP 是以服务器模块或是以 CGI 处理方式运行，都在这里列出了。

这是一个“superglobal”，或者可以描述为自动全局变量。这只不过意味这它在所有的脚本中都有效。在函数或方法中您不需要使用 global $_ENV; 来访问它，就如同使用 $HTTP_ENV_VARS 一样。

$HTTP_ENV_VARS 包含着同样的信息，但是不是一个自动全局变量。（注意： HTTP_ENV_VARS 和 $_ENV 是不同的变量，PHP 处理它们的方式不同。）

如果设置了 register_globals 指令，这些变量也在所有脚本中可用；也就是，分离了 $_ENV 和 $HTTP_ENV_VARS 数组。相关信息，请参阅安全的相关章节 使用 Register Globals。这些单独的全局变量不是自动全局变量。

HTTP Cookies：$_COOKIE

注: 在 PHP 4.1.0 及以后版本使用。之前的版本，使用 $HTTP_COOKIE_VARS。

通过 HTTP cookies 传递的变量组成的数组。是自动全局变量。

这是一个“superglobal”，或者可以描述为自动全局变量。这只不过意味这它在所有的脚本中都有效。在函数或方法中您不需要使用 global $_COOKIE; 来访问它，就如同使用 $HTTP_COOKIE_VARS 一样。

$HTTP_COOKIE_VARS 包含着同样的信息，但是不是一个自动全局变量。（注意： HTTP_COOKIE_VARS 和 $_COOKIE 是不同的变量，PHP 处理它们的方式不同。）

如果设置了 register_globals 指令，这些变量也在所有脚本中可用；也就是，分离了 $_COOKIE 和 $HTTP_COOKIE_VARS 数组。相关信息，请参阅安全的相关章节 使用 Register Globals。这些单独的全局变量不是自动全局变量。

HTTP GET 变量：$_GET

注: 在 PHP 4.1.0 及以后版本使用。之前的版本，使用 $HTTP_GET_VARS。

通过 HTTP GET 方法传递的变量组成的数组。是自动全局变量。

这是一个“superglobal”，或者可以描述为自动全局变量。这只不过意味这它在所有的脚本中都有效。在函数或方法中您不需要使用 global $_GET; 来访问它，就如同使用 $HTTP_GET_VARS 一样。

$HTTP_GET_VARS 包含着同样的信息，但是不是一个自动全局变量。（注意： HTTP_GET_VARS 和 $_GET 是不同的变量，PHP 处理它们的方式不同。）

如果设置了 register_globals 指令，这些变量也在所有脚本中可用；也就是，分离了 $_GET 和 $HTTP_GET_VARS 数组。相关信息，请参阅安全的相关章节 使用 Register Globals。这些单独的全局变量不是自动全局变量。

HTTP POST 变量：$_POST

注: 在 PHP 4.1.0 及以后版本使用。之前的版本，使用 $HTTP_POST_VARS。

通过 HTTP POST 方法传递的变量组成的数组。是自动全局变量。

这是一个“superglobal”，或者可以描述为自动全局变量。这只不过意味这它在所有的脚本中都有效。在函数或方法中您不需要使用 global $_POST; 来访问它，就如同使用 $HTTP_POST_VARS 一样。

$HTTP_POST_VARS 包含着同样的信息，但是不是一个自动全局变量。（注意： HTTP_POST_VARS 和 $_POST 是不同的变量，PHP 处理它们的方式不同。）

如果设置了 register_globals 指令，这些变量也在所有脚本中可用；也就是，分离了 $_POST 和 $HTTP_POST_VARS 数组。相关信息，请参阅安全的相关章节 使用 Register Globals。这些单独的全局变量不是自动全局变量。

HTTP 文件上传变量：$_FILES

注: 在 PHP 4.1.0 及以后版本使用。之前的版本，使用 $HTTP_POST_FILES。

通过 HTTP POST 方法传递的已上传文件项目组成的数组。是自动全局变量。

这是一个“superglobal”，或者可以描述为自动全局变量。这只不过意味这它在所有的脚本中都有效。在函数或方法中您不需要使用 global $_FILES; 来访问它，就如同使用 $HTTP_POST_FILES 一样。

$HTTP_POST_FILES 包含着同样的信息，但是不是一个自动全局变量。

如果设置了 register_globals 指令，这些变量也在所有脚本中可用；也就是，分离了 $_FILES 和 $HTTP_POST_FILES 数组。相关信息，请参阅安全的相关章节 使用 Register Globals。这些单独的全局变量不是自动全局变量。

Request 变量：$_REQUEST

注: 在 PHP 4.1.0 及以后版本使用。之前的版本，没有等价的数组。

由 $_GET，$_POST，$_COOKIE, 和 $_FILES 内容的全部组成的数组。

这是一个“superglobal”，或者可以描述为自动全局变量。这只不过意味这它在所有的脚本中都有效。在函数或方法中您不需要使用 global $_REQUEST; 来访问它。

如果设置了 register_globals 指令，这些变量也在所有脚本中可用；也就是，分离了 $_REQUEST 数组。相关信息，请参阅安全的相关章节 使用 Register Globals。这些单独的全局变量不是自动全局变量。

Session 变量：$_SESSION

注: 在 PHP 4.1.0 及以后版本使用。之前的版本，使用 $HTTP_SESSION_VARS。

包含当前脚本中 session 变量的数组。参阅 Session 函数 文档以获得更多信息。

这是一个“superglobal”，或者可以描述为自动全局变量。这只不过意味这它在所有的脚本中都有效。在函数或方法中您不需要使用 global $_SESSION; 来访问它，就如同使用 $HTTP_SESSION_VARS 一样。

$HTTP_SESSION_VARS 包含着同样的信息，但是不是一个自动全局变量。

如果设置了 register_globals 指令，这些变量也在所有脚本中可用；也就是，分离了 $_SESSION 和 $HTTP_SESSION_VARS 数组。相关信息，请参阅安全的相关章节 使用 Register Globals。这些单独的全局变量不是自动全局变量。

Global 变量：$GLOBALS

注: $GLOBALS 在 PHP 3.0.0 及以后版本中适用。

由所有已定义全局变量组成的数组。变量名就是该数组的索引。

这是一个“superglobal”，或者可以描述为自动全局变量。这只不过意味这它在所有的脚本中都有效。在函数或方法中您不需要使用 global $GLOBALS; 来访问它。

前一个错误消息：$php_errormsg

$php_errormsg 是包含 PHP 产生的上一错误消息内容的变量。该变量在发生错误并且track_errors 选项打开（默认为关闭）后才有效。

后退 | 起点 | 前进
保留字列表 | 上一级 | 预定义类


预定义类

标准类

这些类由一些内建在 PHP 中的标准函数定义。

Directory

使用 dir() 函数后返回的类。

stdClass

Ming 类

这些类在 Ming 扩展中定义，只有在该扩展被编译到 PHP 中或者动态装载后才可以使用。

swfshape

swffill

swfgradient

swfbitmap

swftext

swftextfield

swffont

swfdisplayitem

swfmovie

swfbutton

swfaction

swfmorph

swfsprite

Oracle 8 类

这些类在 Oracle 8 扩展中定义，只有在该扩展被编译到 PHP 中或者动态装载后才可以使用。

OCI-Lob

OCI-Collection

qtdom 类

这些类在 qtdom 扩展中定义，只有在该扩展被编译到 PHP 中或者动态装载后才可以使用。

QDomDocument

QDomNode

后退 | 起点 | 前进
预定义变量 | 上一级 | 预定义常量


预定义常量

后退 | 起点 | 前进
预定义类 | 上一级 | 内核预定义常量


资源类型列表

PHP 手册
后退 前进

附录 H. 资源类型列表

以下是一个建立，使用和销毁资源的函数列表。可以用 is_resource() 函数测定一个变量是否是资源，函数 get_resource_type() 则返回该资源的类型。

表格 H-1. 资源类型

资源类型名称 | 建立者 | 使用者 | 销毁者 | 定义
aspell | aspell_new() | aspell_check(), aspell_check_raw(), aspell_suggest() | None | Aspell dictionary
bzip2 | bzopen() | bzerrno(), bzerror(), bzerrstr(), bzflush(), bzread(), bzwrite() | bzclose() | Bzip2 file
COM | com_load() | com_invoke(), com_propget(), com_get(), com_propput(), com_set(), com_propput() | None | COM object reference
VARIANT
cpdf | cpdf_open() | cpdf_page_init(), cpdf_finalize_page(), cpdf_finalize(), cpdf_output_buffer(), cpdf_save_to_file(), cpdf_set_current_page(), cpdf_begin_text(), cpdf_end_text(), cpdf_show(), cpdf_show_xy(), cpdf_text(), cpdf_set_font(), cpdf_set_leading(), cpdf_set_text_rendering(), cpdf_set_horiz_scaling(), cpdf_set_text_rise(), cpdf_set_text_matrix(), cpdf_set_text_pos(), cpdf_set_text_pos(), cpdf_set_word_spacing(), cpdf_continue_text(), cpdf_stringwidth(), cpdf_save(), cpdf_translate(), cpdf_restore(), cpdf_scale(), cpdf_rotate(), cpdf_setflat(), cpdf_setlinejoin(), cpdf_setlinecap(), cpdf_setmiterlimit(), cpdf_setlinewidth(), cpdf_setdash(), cpdf_moveto(), cpdf_rmoveto(), cpdf_curveto(), cpdf_lineto(), cpdf_rlineto(), cpdf_circle(), cpdf_arc(), cpdf_rect(), cpdf_closepath(), cpdf_stroke(), cpdf_closepath_fill_stroke(), cpdf_fill_stroke(), cpdf_clip(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray_stroke(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor(), cpdf_add_outline(), cpdf_set_page_animation(), cpdf_import_jpeg(), cpdf_place_inline_image(), cpdf_add_annotation() | cpdf_close() | PDF document with CPDF lib
cpdf outline
curl | curl_init() | curl_init(), curl_exec() | curl_close() | Curl session
dbm | dbmopen() | dbmexists(), dbmfetch(), dbminsert(), dbmreplace(), dbmdelete(), dbmfirstkey(), dbmnextkey() | dbmclose() | Link to DBM database
dba | dba_open() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | dba_close() | Link to DBA base
dba persistent | dba_popen() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | None | Persistent link to DBA base
dbase | dbase_open() | dbase_pack(), dbase_add_record(), dbase_replace_record(), dbase_delete_record(), dbase_get_record(), dbase_get_record_with_names(), dbase_numfields(), dbase_numrecords() | dbase_close() | Link to Dbase base
dbx_link_object | dbx_connect() | dbx_query() | dbx_close() | dbx connection
dbx_result_object dbx_query() () None dbx result
domxml attribute
domxml document
domxml node
xpath context
xpath object
fbsql database fbsql_select_db() () None fbsql database
fbsql link | fbsql_change_user(), fbsql_connect() | fbsql_autocommit(), fbsql_change_user(), fbsql_create_db(), fbsql_data_seek(), fbsql_db_query(), fbsql_drop_db(), (), fbsql_select_db(), fbsql_errno(), fbsql_error(), fbsql_insert_id(), fbsql_list_dbs() | fbsql_close() | Link to fbsql database
fbsql plink | fbsql_change_user(), fbsql_pconnect() | fbsql_autocommit(), fbsql_change_user(), fbsql_create_db(), fbsql_data_seek(), fbsql_db_query(), fbsql_drop_db(), (), fbsql_select_db(), fbsql_errno(), fbsql_error(), fbsql_insert_id(), fbsql_list_dbs() | None | Persistent link to fbsql database
fbsql result | fbsql_db_query(), fbsql_list_dbs(), fbsql_query(), fbsql_list_fields(), fbsql_list_tables(), fbsql_tablename() | fbsql_affected_rows(), fbsql_fetch_array(), fbsql_fetch_assoc(), fbsql_fetch_field(), fbsql_fetch_lengths(), fbsql_fetch_object(), fbsql_fetch_row(), fbsql_field_flags(), fbsql_field_name(), fbsql_field_len(), fbsql_field_seek(), fbsql_field_table(), fbsql_field_type(), fbsql_next_result(), fbsql_num_fields(), fbsql_num_rows(), fbsql_result(), fbsql_num_rows() | fbsql_free_result() | fbsql result
fdf | fdf_open() | fdf_create(), fdf_save(), fdf_get_value(), fdf_set_value(), fdf_next_field_name(), fdf_set_ap(), fdf_set_status(), fdf_get_status(), fdf_set_file(), fdf_get_file(), fdf_set_flags(), fdf_set_opt(), fdf_set_submit_form_action(), fdf_set_javascript_action() | fdf_close() | FDF File
ftp | ftp_connect() | ftp_login(), ftp_pwd(), ftp_cdup(), ftp_chdir(), ftp_mkdir(), ftp_rmdir(), ftp_nlist(), ftp_rawlist(), ftp_systype(), ftp_pasv(), ftp_get(), ftp_fget(), ftp_put(), ftp_fput(), ftp_size(), ftp_mdtm(), ftp_rename(), ftp_delete(), ftp_site() | ftp_quit() | FTP stream
gd | imagecreate(), imagecreatefromgif(), imagecreatefromjpeg(), imagecreatefrompng(), imagecreatefromwbmp(), imagecreatefromstring(), imagecreatetruecolor() | imagearc(), imagechar(), imagecharup(), imagecolorallocate(), imagecolorat(), imagecolorclosest(), imagecolorexact(), imagecolorresolve(), imagegammacorrect(), imagegammacorrect(), imagecolorset(), imagecolorsforindex(), imagecolorstotal(), imagecolortransparent(), imagecopy(), imagecopyresized(), imagedashedline(), imagefill(), imagefilledpolygon(), imagefilledrectangle(), imagefilltoborder(), imagegif(), imagepng(), imagejpeg(), imagewbmp(), imageinterlace(), imageline(), imagepolygon(), imagepstext(), imagerectangle(), imagesetpixel(), imagestring(), imagestringup(), imagesx(), imagesy(), imagettftext(), imagefilledarc(), imageellipse(), imagefilledellipse(), imagecolorclosestalpha(), imagecolorexactalpha(), imagecolorresolvealpha(), imagecopymerge(), imagecopymergegray(), imagecopyresampled(), imagetruecolortopalette(), imagesetbrush(), imagesettile(), imagesetthickness() | imagedestroy() | GD Image
gd font | imageloadfont() | imagechar(), imagecharup(), imagefontheight() | None | Font for GD
gd PS encoding
gd PS font | imagepsloadfont() | imagepstext(), imagepsslantfont(), imagepsextendfont(), imagepsencodefont(), imagepsbbox() | imagepsfreefont() | PS font for GD
GMP integer | gmp_init() | gmp_intval(), gmp_strval(), gmp_add(), gmp_sub(), gmp_mul(), gmp_div_q(), gmp_div_r(), gmp_div_qr(), gmp_div(), gmp_mod(), gmp_divexact(), gmp_cmp(), gmp_neg(), gmp_abs(), gmp_sign(), gmp_fact(), gmp_sqrt(), gmp_sqrtrm(), gmp_perfect_square(), gmp_pow(), gmp_powm(), gmp_prob_prime(), gmp_gcd(), gmp_gcdext(), gmp_invert(), gmp_legendre(), gmp_jacobi(), gmp_random(), gmp_and(), gmp_or(), gmp_xor(), gmp_setbit(), gmp_clrbit(), gmp_scan0(), gmp_scan1(), gmp_popcount(), gmp_hamdist() | None | GMP Number
hyperwave document | hw_cp(), hw_docbyanchor(), hw_getremote(), hw_getremotechildren() | hw_children(), hw_childrenobj(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getsrcbydestobj(), hw_getandlock(), hw_gettext(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_inscoll(), hw_pipedocument(), hw_unlock() | hw_deleteobject() | Hyperwave object
hyperwave link | hw_connect() | hw_children(), hw_childrenobj(), hw_cp(), hw_deleteobject(), hw_docbyanchor(), hw_docbyanchorobj(), hw_errormsg(), hw_edittext(), hw_error(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getremotechildren(), hw_getsrcbydestobj(), hw_getobject(), hw_getandlock(), hw_gettext(), hw_getobjectbyquery(), hw_getobjectbyqueryobj(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_mv(), hw_incollections(), hw_info(), hw_inscoll(), hw_insdoc(), hw_insertdocument(), hw_insertobject(), hw_mapid(), hw_modifyobject(), hw_pipedocument(), hw_unlock(), hw_who(), hw_getusername() | hw_close(), hw_free_document() | Link to Hyperwave server
hyperwave link persistent | hw_pconnect() | hw_children(), hw_childrenobj(), hw_cp(), hw_deleteobject(), hw_docbyanchor(), hw_docbyanchorobj(), hw_errormsg(), hw_edittext(), hw_error(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getremotechildren(), hw_getsrcbydestobj(), hw_getobject(), hw_getandlock(), hw_gettext(), hw_getobjectbyquery(), hw_getobjectbyqueryobj(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_mv(), hw_incollections(), hw_info(), hw_inscoll(), hw_insdoc(), hw_insertdocument(), hw_insertobject(), hw_mapid(), hw_modifyobject(), hw_pipedocument(), hw_unlock(), hw_who(), hw_getusername() | None | Persistent link to Hyperwave server
icap | icap_open() | icap_fetch_event(), icap_list_events(), icap_store_event(), icap_snooze(), icap_list_alarms(), icap_delete_event() | icap_close() | Link to icap server
imap | imap_open() | imap_append(), imap_body(), imap_check(), imap_createmailbox(), imap_delete(), imap_deletemailbox(), imap_expunge(), imap_fetchbody(), imap_fetchstructure(), imap_headerinfo(), imap_header(), imap_headers(), imap_listmailbox(), imap_getmailboxes(), imap_get_quota(), imap_status(), imap_listsubscribed(), imap_set_quota(), imap_set_quota(), imap_getsubscribed(), imap_mail_copy(), imap_mail_move(), imap_num_msg(), imap_num_recent(), imap_ping(), imap_renamemailbox(), imap_reopen(), imap_subscribe(), imap_undelete(), imap_unsubscribe(), imap_scanmailbox(), imap_mailboxmsginfo(), imap_fetchheader(), imap_uid(), imap_msgno(), imap_search(), imap_fetch_overview() | imap_close() | Link to IMAP, POP3 server
imap chain persistent
imap persistent
ingres | ingres_connect() | ingres_query(), ingres_num_rows(), ingres_num_fields(), ingres_field_name(), ingres_field_type(), ingres_field_nullable(), ingres_field_length(), ingres_field_precision(), ingres_field_scale(), ingres_fetch_array(), ingres_fetch_row(), ingres_fetch_object(), ingres_rollback(), ingres_commit(), ingres_autocommit() | ingres_close() | Link to ingresII base
ingres persistent | ingres_pconnect() | ingres_query(), ingres_num_rows(), ingres_num_fields(), ingres_field_name(), ingres_field_type(), ingres_field_nullable(), ingres_field_length(), ingres_field_precision(), ingres_field_scale(), ingres_fetch_array(), ingres_fetch_row(), ingres_fetch_object(), ingres_rollback(), ingres_commit(), ingres_autocommit() | None | Persistent link to ingresII base
interbase blob
interbase link | ibase_connect() | ibase_query(), ibase_prepare(), ibase_trans() | ibase_close() | Link to Interbase database
interbase link persistent | ibase_pconnect() | ibase_query(), ibase_prepare(), ibase_trans() | None | Persistent link to Interbase database
interbase query | ibase_prepare() | ibase_execute() | ibase_free_query() | Interbase query
interbase result | ibase_query() | ibase_fetch_row(), ibase_fetch_object(), ibase_field_info(), ibase_num_fields() | ibase_free_result() | Interbase Result
interbase transaction | ibase_trans() | ibase_commit() | ibase_rollback() | Interbase transaction
java
ldap link | ldap_connect(), ldap_search() | ldap_count_entries(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_next_attribute(), ldap_next_entry() | ldap_close() | ldap connection
ldap result | ldap_read() | ldap_add(), ldap_compare(), ldap_bind(), ldap_count_entries(), ldap_delete(), ldap_errno(), ldap_error(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_get_option(), ldap_list(), ldap_modify(), ldap_mod_add(), ldap_mod_replace(), ldap_next_attribute(), ldap_next_entry(), ldap_mod_del(), ldap_set_option(), ldap_unbind() | ldap_free_result() | ldap search result
ldap result entry
mcal | mcal_open(), mcal_popen() | mcal_create_calendar(), mcal_rename_calendar(), mcal_rename_calendar(), mcal_delete_calendar(), mcal_fetch_event(), mcal_list_events(), mcal_append_event(), mcal_store_event(), mcal_delete_event(), mcal_list_alarms(), mcal_event_init(), mcal_event_set_category(), mcal_event_set_title(), mcal_event_set_description(), mcal_event_set_start(), mcal_event_set_end(), mcal_event_set_alarm(), mcal_event_set_class(), mcal_next_recurrence(), mcal_event_set_recur_none(), mcal_event_set_recur_daily(), mcal_event_set_recur_weekly(), mcal_event_set_recur_monthly_mday(), mcal_event_set_recur_monthly_wday(), mcal_event_set_recur_yearly(), mcal_fetch_current_stream_event(), mcal_event_add_attribute(), mcal_expunge() | mcal_close() | Link to calendar server
SWFAction
SWFBitmap
SWFButton
SWFDisplayItem
SWFFill
SWFFont
SWFGradient
SWFMorph
SWFMovie
SWFShape
SWFSprite
SWFText
SWFTextField
mnogosearch agent
mnogosearch result
msql link | msql_connect() | msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() | msql_close() | Link to mSQL database
msql link persistent | msql_pconnect() | msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() | None | Persistent link to mSQL
msql query | msql_query() | msql(), msql_affected_rows(), msql_data_seek(), msql_dbname(), msql_fetch_array(), msql_fetch_field(), msql_fetch_object(), msql_fetch_row(), msql_fieldname(), msql_field_seek(), msql_fieldtable(), msql_fieldtype(), msql_fieldflags(), msql_fieldlen(), msql_num_fields(), msql_num_rows(), msql_numfields(), msql_numrows(), msql_result() | msql_free_result(), msql_free_result() | mSQL result
mssql link | mssql_connect() | mssql_query(), mssql_select_db() | mssql_close() | Link to Microsft SQL Server database
mssql link persistent | mssql_pconnect() | mssql_query(), mssql_select_db() | None | Persistent link to Microsft SQL Server
mssql result | mssql_query() | mssql_data_seek(), mssql_fetch_array(), mssql_fetch_field(), mssql_fetch_object(), mssql_fetch_row(), mssql_field_length(), mssql_field_name(), mssql_field_seek(), mssql_field_type(), mssql_num_fields(), mssql_num_rows(), mssql_result() | mssql_free_result() | Microsft SQL Server result
mysql link | mysql_connect() | mysql_affected_rows(), mysql_change_user(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | mysql_close() | Link to MySQL database
mysql link persistent | mysql_pconnect() | mysql_affected_rows(), mysql_change_user(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | None | Persistent link to MySQL database
mysql result | mysql_db_query(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query() | mysql_data_seek(), mysql_db_name(), mysql_fetch_array(), mysql_fetch_assoc(), mysql_fetch_field(), mysql_fetch_lengths(), mysql_fetch_object(), mysql_fetch_row(), mysql_fetch_row(), mysql_field_flags(), mysql_field_name(), mysql_field_len(), mysql_field_seek(), mysql_field_table(), mysql_field_type(), mysql_num_fields(), mysql_num_rows(), mysql_result(), mysql_tablename() | mysql_free_result() | MySQL result
oci8 collection
oci8 connection | ocilogon(), ociplogon(), ocinlogon() | ocicommit(), ociserverversion(), ocinewcursor(), ociparse(), ocierror() | ocilogoff() | Link to Oracle database
oci8 descriptor
oci8 server
oci8 session
oci8 statement | ocinewdescriptor() | ocirollback(), ocinewdescriptor(), ocirowcount(), ocidefinebyname(), ocibindbyname(), ociexecute(), ocinumcols(), ociresult(), ocifetch(), ocifetchinto(), ocifetchstatement(), ocicolumnisnull(), ocicolumnname(), ocicolumnsize(), ocicolumntype(), ocistatementtype(), ocierror() | ocifreestatement() | Oracle Cursor
odbc link | odbc_connect() | odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() | odbc_close() | Link to ODBC database
odbc link persistent | odbc_connect() | odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() | None | Persistent link to ODBC database
odbc result | odbc_prepare() | odbc_binmode(), odbc_cursor(), odbc_execute(), odbc_fetch_into(), odbc_fetch_row(), odbc_field_name(), odbc_field_num(), odbc_field_type(), odbc_field_len(), odbc_field_precision(), odbc_field_scale(), odbc_longreadlen(), odbc_num_fields(), odbc_num_rows(), odbc_result(), odbc_result_all(), odbc_setoption() | odbc_free_result() | ODBC result
birdstep link
birdstep result
OpenSSL key | openssl_get_privatekey(), openssl_get_publickey() | openssl_sign(), openssl_seal(), openssl_open(), openssl_verify() | openssl_free_key() | OpenSSL key
OpenSSL X.509 | openssl_x509_read() | openssl_x509_parse(), openssl_x509_checkpurpose() | openssl_x509_free() | Public Key
oracle Cursor | ora_open() | ora_bind(), ora_columnname(), ora_columnsize(), ora_columntype(), ora_error(), ora_errorcode(), ora_exec(), ora_fetch(), ora_fetch_into(), ora_getcolumn(), ora_numcols(), ora_numrows(), ora_parse() | ora_close() | Oracle cursor
oracle link | ora_logon() | ora_do(), ora_error(), ora_errorcode(), ora_rollback(), ora_commitoff(), ora_commiton(), ora_open(), ora_commit() | ora_logoff() | Link to oracle database
oracle link persistent | ora_plogon() | ora_do(), ora_error(), ora_errorcode(), ora_rollback(), ora_commitoff(), ora_commiton(), ora_open(), ora_commit() | None | Persistent link to oracle database
pdf document | pdf_new() | pdf_add_bookmark(), pdf_add_launchlink(), pdf_add_locallink(), pdf_add_note(), pdf_add_pdflink(), pdf_add_weblink(), pdf_arc(), pdf_attach_file(), pdf_begin_page(), pdf_circle(), pdf_clip(), pdf_closepath(), pdf_closepath_fill_stroke(), pdf_closepath_stroke(), pdf_concat(), pdf_continue_text(), pdf_curveto(), pdf_end_page(), pdf_endpath(), pdf_fill(), pdf_fill_stroke(), pdf_findfont(), pdf_get_buffer(), pdf_get_image_height(), pdf_get_image_width(), pdf_get_parameter(), pdf_get_value(), pdf_lineto(), pdf_moveto(), pdf_open_ccitt(), pdf_open_file(), pdf_open_image_file(), pdf_place_image(), pdf_rect(), pdf_restore(), pdf_rotate(), pdf_save(), pdf_scale(), pdf_setdash(), pdf_setflat(), pdf_setfont(), pdf_setgray(), pdf_setgray_fill(), pdf_setgray_stroke(), pdf_setlinecap(), pdf_setlinejoin(), pdf_setlinewidth(), pdf_setmiterlimit(), pdf_setpolydash(), pdf_setrgbcolor(), pdf_setrgbcolor_fill(), pdf_setrgbcolor_stroke(), pdf_set_border_color(), pdf_set_border_dash(), pdf_set_border_style(), pdf_set_char_spacing(), pdf_set_duration(), pdf_set_font(), pdf_set_horiz_scaling(), pdf_set_parameter(), pdf_set_text_pos(), pdf_set_text_rendering(), pdf_set_value(), pdf_set_word_spacing(), pdf_show(), pdf_show_boxed(), pdf_show_xy(), pdf_skew(), pdf_stringwidth(), pdf_stroke(), pdf_translate(), pdf_open_memory_image() | pdf_close(), pdf_delete() | PDF document
pdf image | pdf_open_image(), pdf_open_image_file(), pdf_open_memory_image() | pdf_get_image_height(), pdf_get_image_width(), pdf_open_CCITT(), pdf_place_image() | pdf_close_image() | Image in PDF file
pdf object
pdf outline
pgsql large object | pg_lo_open() | pg_lo_open(), pg_lo_create(), pg_lo_read(), pg_lo_read_all(), pg_lo_seek(), pg_lo_tell(), pg_lo_unlink(), pg_lo_write() | pg_lo_close() | PostgreSQL Large Object
pgsql link | pg_connect() | pg_affected_rows(), pg_query(), pg_send_query(), pg_get_result(), pg_connection_busy(), pg_connection_reset(), pg_connection_status(), pg_last_error(), pg_last_notice(), pg_lo_create(), pg_lo_export(), pg_lo_import(), pg_lo_open(), pg_lo_unlink(), pg_host(), pg_port(), pg_dbname(), pg_options(), pg_copy_from(), pg_copy_to(), pg_end_copy(), pg_put_line(), pg_tty(), pg_trace(), pg_untrace(), pg_set_client_encoding(), pg_client_encoding(), pg_metadata(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() | pg_close() | Link to PostgreSQL database
pgsql link persistent | pg_pconnect() | pg_affected_rows(), pg_query(), pg_send_query(), pg_get_result(), pg_connection_busy(), pg_connection_reset(), pg_connection_status(), pg_last_error(), pg_last_notice(), pg_lo_create(), pg_lo_export(), pg_lo_import(), pg_lo_open(), pg_lo_unlink(), pg_host(), pg_port(), pg_dbname(), pg_options(), pg_copy_from(), pg_copy_to(), pg_end_copy(), pg_put_line(), pg_tty(), pg_trace(), pg_untrace(), pg_set_client_encoding(), pg_client_encoding(), pg_metadata(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() | None | Persistent link to PostgreSQL database
pgsql result | pg_query(), pg_get_result() | pg_fetch_array(), pg_fetch_object(), pg_fetch_result(), pg_fetch_row(), pg_field_is_null(), pg_field_name(), pg_field_num(), pg_field_prtlen(), pg_field_size(), pg_field_type(), pg_last_oid(), pg_num_fields(), pg_num_rows(), pg_result_error(), pg_result_status() | pg_free_result() | PostgreSQL result
pgsql string
printer
printer brush
printer font
printer pen
pspell | pspell_new(), pspell_new_config(), pspell_new_personal() | pspell_add_to_personal(), pspell_add_to_session(), pspell_check(), pspell_clear_session(), pspell_config_ignore(), pspell_config_mode(), pspell_config_personal(), pspell_config_repl(), pspell_config_runtogether(), pspell_config_save_repl(), pspell_save_wordlist(), pspell_store_replacement(), pspell_suggest() | None | pspell dictionary
pspell config | pspell_config_create() | pspell_new_config() | None | pspell configuration
Sablotron XSLT | xslt_create() | xslt_closelog(), xslt_openlog(), xslt_run(), xslt_set_sax_handler(), xslt_errno(), xslt_error(), xslt_fetch_result(), xslt_free() | xslt_free() | XSLT parser
shmop | shmop_open() | shmop_read(), shmop_write(), shmop_size(), shmop_delete() | shmop_close()
sockets file descriptor set | socket() | accept_connect(), bind(), connect(), listen(), read(), write() | close() | Socket
sockets i/o vector
dir | dir() | readdir(), rewinddir() | closedir() | Dir handle
file | fopen() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), flock(), fpassthru(), fputs(), fwrite(), fread(), fseek(), ftell(), fstat(), ftruncate(), set_file_buffer(), rewind() | fclose() | File handle
pipe | popen() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | pclose() | Process handle
socket | fsockopen() | fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | fclose() | Socket handle
stream
sybase-db link | sybase_connect() | sybase_query(), sybase_select_db() | sybase_close() | Link to Sybase database using DB library
sybase-db link persistent | sybase_pconnect() | sybase_query(), sybase_select_db() | None | Persistent link to Sybase database using DB library
sybase-db result | sybase_query() | sybase_data_seek(), sybase_fetch_array(), sybase_fetch_field(), sybase_fetch_object(), sybase_fetch_row(), sybase_field_seek(), sybase_num_fields(), sybase_num_rows(), sybase_result() | sybase_free_result() | Sybase result using DB library
sybase-ct link | sybase_connect() | sybase_affected_rows(), sybase_query(), sybase_select_db() | sybase_close() | Link to Sybase database using CT library
sybase-ct link persistent | sybase_pconnect() | sybase_affected_rows(), sybase_query(), sybase_select_db() | None | Persistent link to Sybase database using CT library
sybase-ct result | sybase_query() | sybase_data_seek(), sybase_fetch_array(), sybase_fetch_field(), sybase_fetch_object(), sybase_fetch_row(), sybase_field_seek(), sybase_num_fields(), sybase_num_rows(), sybase_result() | sybase_free_result() | Sybase result using CT library
sysvsem | sem_get() | sem_acquire() | sem_release() | System V Semaphore
sysvshm | shm_attach() | shm_remove(), shm_put_var(), shm_get_var(), shm_remove_var() | shm_detach() | System V Shared Memory
wddx | wddx_packet_start() | wddx_add_vars() | wddx_packet_end() | WDDX packet
xml | xml_parser_create() | xml_set_object(), xml_set_element_handler(), xml_set_character_data_handler(), xml_set_processing_instruction_handler(), xml_set_default_handler(), xml_set_unparsed_entity_decl_handler(), xml_set_notation_decl_handler(), xml_set_external_entity_ref_handler(), xml_parse(), xml_get_error_code(), xml_error_string(), xml_get_current_line_number(), xml_get_current_column_number(), xml_get_current_byte_index(), xml_parse_into_struct(), xml_parser_set_option(), xml_parser_get_option() | xml_parser_free() | XML parser
zlib | gzopen() | gzeof(), gzgetc(), gzgets(), gzgetss(), gzpassthru(), gzputs(), gzread(), gzrewind(), gzseek(), gztell(), gzwrite() | gzclose() | gz-compressed file

后退 | 起点 | 前进
标准预定义常量 | 上一级 | List of Supported Protocols/Wrappers


List of Supported Protocols/Wrappers

PHP 手册
后退 前进

附录 I. List of Supported Protocols/Wrappers

The following is a list of the various URL style protocols that PHP has built-in for use with the filesystem functions such as fopen() and copy(). In addition to these wrappers, as of PHP 4.3, you can write your own wrappers using PHP script and file_register_wrapper().

表格 I-1. URL Wrappers

Protocol | Versions | Description
http:// | All | Allows read-only access to files/resources via HTTP.
https:// | PHP 4.3 and up, with SSL support | Allows read-only access to files/resources via SSL secured HTTP.
ftp:// | All | Allows read access to existing files and creation of new files via FTP.
ftps:// | PHP 4.3 and up, with SSL support | The same as ftp://, but uses SSL when supported by the FTP server.
php://stdin | PHP 3.0.13 and up | Allows read acess to the standard input stream of the PHP process.
php://stdout | PHP 3.0.13 and up | Allows write acess to the standard output stream of the PHP process.
php://stderr | PHP 3.0.13 and up | Allows write acess to the standard error stream of the PHP process.
php://output | PHP 4.3 and up | Allows write acess to the output buffer mechanism, just like echo() and print().
zlib: | PHP 4.0.4 - PHP 4.2.3, systems with fopencookie only | Works like gzopen(), except that the stream can be used with fread() and the other filesystem functions. This is deprecated as of PHP 4.3 due to ambiguities with filenames containing ':' characters; use compress.zlib:// instead.
compress.zlib:// | PHP 4.3 and up | Works just like gzopen(), even on systems without fopencookie.
compress.bzip2:// | PHP 4.3 and up | Works just like bzopen().

后退 | 起点 | 前进
资源类型列表 | 上一级 | 解析器代号列表


解析器代号列表

PHP 手册
后退 前进

附录 J. 解析器代号列表

PHP 语言的不同部分在内部被表示为类似 T_SR 的类型。PHP 在解析错误时输出这样的标识符，例如 "Parse error: unexpected T_SR, expecting ',' or ';' in script.php on line 10."。

你应该知道 T_SR 的含义。对于所有不知道的人，这里有一张表列出了这些标识符，PHP 语法和在手册中适当位置的参考。

表格 J-1. 代号

代号 | 语法 | 参考
T_AND_EQUAL | &= | assignment operators
T_ARRAY | array() | array(), array syntax
T_ARRAY_CAST | (array) | type-casting
T_AS | as | foreach
T_BAD_CHARACTER |  | anything below ASCII 32 except \t (0x09), \n (0x0a) and \r (0x0d)
T_BOOLEAN_AND | && | logical operators
T_BOOLEAN_OR | || | logical operators
T_BOOL_CAST | (bool) or (boolean) | type-casting
T_BREAK | break; | break
T_CASE | case | switch
T_CHARACTER |  |
T_CLASS | class | classes and objects
T_CLOSE_TAG | ?> or %> |
T_COMMENT | // or # | comments
T_CONCAT_EQUAL | .= | assignment operators
T_CONST | const |
T_CONSTANT_ENCAPSED_STRING | "foo" or 'bar' | string syntax
T_CONTINUE | continue |
T_CURLY_OPEN |  |
T_DEC | -- | incrementing/decrementing operators
T_DECLARE | declare | declare
T_DEFAULT | default | switch
T_DIV_EQUAL | /= | assignment operators
T_DNUMBER | 0.12, etc | floating point numbers
T_DO | do | do..while
T_DOLLAR_OPEN_CURLY_BRACES | ${ | complex variable parsed syntax
T_DOUBLE_ARROW | => | array syntax
T_DOUBLE_CAST | (real), (double) or (float) | type-casting
T_ECHO | echo | echo()
T_ELSE | else | else
T_ELSEIF | elseif | elseif
T_EMPTY | empty | empty()
T_ENCAPSED_AND_WHITESPACE |  |
T_ENDDECLARE | enddeclare | declare, alternative syntax
T_ENDFOR | endfor | for, alternative syntax
T_ENDFOREACH | endforeach | foreach, alternative syntax
T_ENDIF | endif | if, alternative syntax
T_ENDSWITCH | endswitch | switch, alternative syntax
T_ENDWHILE | endwhile | while, alternative syntax
T_END_HEREDOC |  | heredoc syntax
T_EVAL | eval() | eval()
T_EXIT | exit or die | exit(), die()
T_EXTENDS | extends | extends, classes and objects
T_FILE | __FILE__ | constants
T_FOR | for | for
T_FOREACH | foreach | foreach
T_FUNCTION | function or cfunction | functions
T_GLOBAL | global | variable scope
T_IF | if | if
T_INC | ++ | incrementing/decrementing operators
T_INCLUDE | include() | include()
T_INCLUDE_ONCE | include_once() | include_once()
T_INLINE_HTML |  |
T_INT_CAST | (int) or (integer) | type-casting
T_ISSET | isset() | isset()
T_IS_EQUAL | == | comparison operators
T_IS_GREATER_OR_EQUAL | >= | comparison operators
T_IS_IDENTICAL | === | comparison operators
T_IS_NOT_EQUAL | != or <> | comparison operators
T_IS_NOT_IDENTICAL | !== | comparison operators
T_SMALLER_OR_EQUAL | <= | comparison operators
T_LINE | __LINE__ | constants
T_LIST | list() | list()
T_LNUMBER | 123, 012, 0x1ac, etc | integers
T_LOGICAL_AND | and | logical operators
T_LOGICAL_OR | or | logical operators
T_LOGICAL_XOR | xor | logical operators
T_MINUS_EQUAL | -= | assignment operators
T_ML_COMMENT | /* and */ | comments
T_MOD_EQUAL | %= | assignment operators
T_MUL_EQUAL | *= | assignment operators
T_NEW | new | classes and objects
T_NUM_STRING |  |
T_OBJECT_CAST | (object) | type-casting
T_OBJECT_OPERATOR | -> | classes and objects
T_OLD_FUNCTION | old_function | old_function
T_OPEN_TAG | <?php, <? or <% | escaping from HTML
T_OPEN_TAG_WITH_ECHO | <?= or <%= | escaping from HTML
T_OR_EQUAL | |= | assignment operators
T_PAAMAYIM_NEKUDOTAYIM | :: | ::
T_PLUS_EQUAL | += | assignment operators
T_PRINT | print() | print()
T_REQUIRE | require() | require()
T_REQUIRE_ONCE | require_once() | require_once()
T_RETURN | return | returning values
T_SL | << | bitwise operators
T_SL_EQUAL | <<= | assignment operators
T_SR | >> | bitwise operators
T_SR_EQUAL | >>= | assignment operators
T_START_HEREDOC | <<< | heredoc syntax
T_STATIC | static | variable scope
T_STRING |  |
T_STRING_CAST | (string) | type-casting
T_STRING_VARNAME |  |
T_SWITCH | switch | switch
T_UNSET | unset() | unset()
T_UNSET_CAST | (unset) | (not documented; casts to NULL)
T_USE | use | (not implemented)
T_VAR | var | classes and objects
T_VARIABLE | $foo | variables
T_WHILE | while | while, do..while
T_WHITESPACE |  |
T_XOR_EQUAL | ^= | assignment operators
T_FUNC_C | __FUNCTION__ | constants, since PHP 4.3.0
T_CLASS_C | __CLASS__ | constants, since PHP 4.3.0

后退 | 起点 | 前进
List of Supported Protocols/Wrappers | 上一级 | 关于本手册


关于本手册

PHP 手册
后退 前进

附录 K. 关于本手册

目录
手册的格式
关于用户注释
如何得到关于 PHP 更多的信息
如何帮助改进本文档
如何生成手册的各种格式
手册译文

手册的格式

《PHP 参考手册》提供了多种不同格式的版本，它们可以分为两组：在线阅读版本和可下载包。

注: 有些出版商可能已经出版了本手册的一些印刷版本，但我们不推荐您使用它们，因为 PHP 参考手册更新的非常快，这些印刷版本将很快失去时效性。

您可以访问 http://www.php.net/ 及其众多的镜像站点来在线阅读《PHP 参考手册》。为了保证最佳的访问速度，您应该选择离您的地理位置最接近的镜像站点。您可以选择阅读可直接打印的 HTML 版本，也可以阅读集成在 PHP 官方站点中的 HTML 版本，该版本让您感觉《PHP 参考手册》就是该网站的一部分。

和绝大多数离线格式的手册相比，在线阅读版本有一个很大的优点，即它集成了用户注释；同时，它的明显的缺点是您必须保持一直在线来阅读。

目前，《PHP 参考手册》提供多种离线阅读格式，最适合于您的格式取决于您使用的操作系统和您个人的阅读习惯。关于《PHP 参考手册》如何被制作成如此多的版本，请查阅本附录中“如何生成手册的各种格式”一节。

跨平台性最好的格式是 HTML 格式和纯文本格式。HTML 格式提供了两种方式：一种只有一个很大的 HTML 文件；另一种方式是每一节分成一个独立文件，它们形成一个包含有几千个文件的文件包。HTML 和纯文本格式的《PHP 参考手册》都是以 bzip2 方式压缩的 tar 文件提供。文件的后缀名为 tar.bz2。

另一种流行的跨平台格式，也是最适合打印的格式，是 PDF（也就是 Adobe Acrobat）格式。不过，当您急匆匆地下载该版本，并点击“打印”按钮的时候，我们需要提醒您本手册有 2000 多页，并且还在不断地被修订。

注: 如果您还没有可以直接阅读 PDF 格式文档的软件，您可能需要下载 Adobe Acrobat Reader。

对于手掌机及其兼容设备的用户来说，该平台最理想的格式是 Palm 文档或者 iSilo 格式。您可以在日常工作中带着您的手掌机，利用 DOC 或 iSilo 阅读器来温习 PHP 知识，当然，也可以作为快速的参考。

对于 Windows 平台，我们利用了 Windows 的超文本帮助应用程序结合本手册的 HTML 格式，形成了本手册的 Windows 超文本帮助版本。该版本提供手册的全文搜索、完整的索引以及书签功能。很多 Windows 平台下流行的 PHP 集成开发环境也集成了该版本的手册，以给开发者提供最方便快捷的参考。

后退 | 起点 | 前进
解析器代号列表 | 上一级 | 关于用户注释


关于用户注释

用户注释在本手册的开发过程中搬演了相当重要的角色。通过允许手册的读者利用它们的浏览器提供范例、解释和进一步的阐述，我们便能够把这些反馈信息包含到手册的正文中。而且，当这些注释被包含后，读者就可以在线通过它们被提交的格式来阅读它们，也可以通过某些离线格式来阅读。

注: 用户注释在网上出现之前并不成熟，因此这些文字和代码的质量，甚至它们的真实性无从得到保证。（这并不是说本手册本身的质量和准确性没有任何的保证。）

后退 | 起点 | 前进
关于本手册 | 上一级 | 如何得到关于 PHP 更多的信息


如何得到关于 PHP 更多的信息

本手册并不打算提供基本的编程开发指导。如果您是一个初级的程序员，甚至是第一次编程，您可能会发现利用本手册来学习如何用 PHP 编程是一件很困难的事情。为了寻找一本更适合初学者的书，请访问 http://www.php.net/books.php 查看 PHP 相关书籍的列表。

目前，PHP 官方提供了许多邮件列表来讨论 PHP 编程相关的各个方面的问题。当您在 PHP 的开发过程中碰到了难题，而且自己无法找到合适的解决方法时，您可以到该邮件列表寻求帮助。请访问 http://www.php.net/support.php 查看邮件列表清单，我们同时提供了邮件列表的存档和其它在线支持的资料。此外，在 http://www.php.net/links.php 有一个关于 PHP 相关网站的列表，在这些网站中您可以找到和 PHP 相关的文章、论坛和代码。

后退 | 起点 | 前进
关于用户注释 | 上一级 | 如何帮助改进本文档


如何帮助改进本文档

您可以通过以下三种途径来帮助改善本文档。

如果您发现本手册任何一个格式的版本中有错误， 请通过设在 http://bugs.php.net/ 的纠错系统向我们报告，并将您提交的错误分类为“文档问题 (Documentation Problem)”。您在这里也可以提交和某一格式的手册相关的问题。

注: 请勿滥用纠错系统来寻求帮助。如需帮助请使用前面提到的邮件列表和虚拟社区网站。

通过提交注释，您可以向其它读者提供更多的范例、解释和阐述。提交注释请使用注释系统，而非纠错系统。请阅读本附录中“关于用户注释”一节以获得更多关于注释的信息。

如果您懂英语和其它语种的语言，您也可以参与我们的翻译工作。如果您希望开始一个新语言版本的翻译，或者希望参与某一个语言版本的翻译工作，请下载并阅读 PHP Documentation HOWTO。

该文档的简体中文版可在 http://cvs.php.net/co.php/phpdoc-zh/howto/howto_zh_cn.html.tar.gz 下载。

后退 | 起点 | 前进
如何得到关于 PHP 更多的信息 | 上一级 | 如何生成手册的各种格式


如何生成手册的各种格式

本手册使用 XML 语言编写，同时运用了 DocBook XML DTD。我们使用了 DSSSL （Document Style and Semantics Specification Language，文档样式和语义规格语言）来控制格式。同时，在实验上我们运用 XSLT （Extensible Stylesheet Language Transformations，可扩展样式表语言转换）来维护格式。

将 XML 语言作为源文件格式，使得我们只需维护该源文件文档，就可以可以利用它生成许多其它的输出格式。输出 HTML 和 TeX 版本的工具是由 James Clark 开发的 Jade，以及由 Norman Walsh 开发的 The Modular DocBook Stylesheets。我们使用 Microsoft HTML Help Workshop 来生成本手册的 Windows 超文本帮助格式。当然，PHP 本身也完成了其它一些转换和格式化工作。

您可以从 http://www.php.net/docs.php 下载本手册各种不同语言和格式的版本，包括纯文本、普通 HTML、PDF、PalmPilot DOC、PalmPilot iSilo 和 Windows 超文本帮助格式。当手册内容更新时，其它格式的版本将自动更新。

在 http://cvs.php.net/ 您可以找到更多关于下载本文档 XML 源代码的信息。它们被存放在 phpdoc 模块下。

后退 | 起点 | 前进
如何帮助改进本文档 | 上一级 | 手册译文


手册译文

《PHP 参考手册》不但有各种不同的格式，而且还有各种语言的版本。手册的正文最初是用英语撰写的，后来有来自全世界各地的工作组致力于本手册各种语言版本的翻译工作。如果某个函数或者章节的内容尚未被翻译，则该语言版本手册的发布将落后于英语版本。

翻译工作者首先从本手册的 XML 源代码（可于 http://cvs.php.net/ 下载）入手，将这些源代码翻译成他们的母语，而并非翻译 HTML 版本，纯文本，或者PDF 版本。我们的编译系统负责将 XML 源代码转换成人类可以阅读的版本。

注: 如果您愿意帮助将本手册翻译成您的母语，请发一封空的电子邮件到 phpdoc-subscribe@lists.php.net 加入 phpdoc 邮件列表以便与文档翻译小组取得联系。邮件列表的地址为 phpdoc@lists.php.net。请在电子邮件中声明您对文档翻译成您的母语的翻译工作感兴趣，有人会给您回应，并帮助您加入到已经存在的翻译小组，或者开始新语种的翻译工作。

目前，本手册已经（或部分）有下列语种的译文：巴西葡萄牙语、捷克语、荷兰语、法语、德语、匈牙利语、意大利语、日语、韩语、波兰语和西班牙语。

您可以访问 http://www.php.net/docs.php 来下载各种版本。

后退 | 起点 | 前进
如何生成手册的各种格式 | 上一级 | 函数索引


函数索引

PHP 手册
后退 前进

附录 L. 函数索引

目录
函数索引

后退 | 起点 | 前进
手册译文 | 上一级 | 函数索引


函数索引

A

abs()
acos()
acosh()
addcslashes()
addslashes()
apache_child_terminate()
apache_lookup_uri()
apache_note()
apache_request_headers()
apache_response_headers()
apache_setenv()
array()
array_change_key_case()
array_chunk()
array_count_values()
array_diff()
array_fill()
array_filter()
array_flip()
array_intersect()
array_key_exists()
array_keys()
array_map()
array_merge()
array_merge_recursive()
array_multisort()
array_pad()
array_pop()
array_push()
array_rand()
array_reduce()
array_reverse()
array_search()
array_shift()
array_slice()
array_splice()
array_sum()
array_unique()
array_unshift()
array_values()
array_walk()
arsort()
ascii2ebcdic()
asin()
asinh()
asort()
aspell_check()
aspell_check_raw()
aspell_new()
aspell_suggest()
assert()
assert_options()
atan()
atan2()
atanh()

B

base64_decode()
base64_encode()
base_convert()
basename()
bcadd()
bccomp()
bcdiv()
bcmod()
bcmul()
bcpow()
bcscale()
bcsqrt()
bcsub()
bin2hex()
bind_textdomain_codeset()
bindec()
bindtextdomain()
bzclose()
bzcompress()
bzdecompress()
bzerrno()
bzerror()
bzerrstr()
bzflush()
bzopen()
bzread()
bzwrite()

C

cal_days_in_month()
cal_from_jd()
cal_info()
cal_to_jd()
call_user_func()
call_user_func_array()
call_user_method()
call_user_method_array()
ccvs_add()
ccvs_auth()
ccvs_command()
ccvs_count()
ccvs_delete()
ccvs_done()
ccvs_init()
ccvs_lookup()
ccvs_new()
ccvs_report()
ccvs_return()
ccvs_reverse()
ccvs_sale()
ccvs_status()
ccvs_textvalue()
ccvs_void()
ceil()
chdir()
checkdate()
checkdnsrr()
chgrp()
chmod()
chop()
chown()
chr()
chroot()
chunk_split()
class_exists()
clearstatcache()
closedir()
closelog()
com()
com_addref()
com_get()
com_invoke()
com_isenum()
com_load()
com_load_typelib()
com_propget()
com_propput()
com_propset()
com_release()
com_set()
compact()
connection_aborted()
connection_status()
connection_timeout()
constant()
convert_cyr_string()
copy()
cos()
cosh()
count()
count_chars()
cpdf_add_annotation()
cpdf_add_outline()
cpdf_arc()
cpdf_begin_text()
cpdf_circle()
cpdf_clip()
cpdf_close()
cpdf_closepath()
cpdf_closepath_fill_stroke()
cpdf_closepath_stroke()
cpdf_continue_text()
cpdf_curveto()
cpdf_end_text()
cpdf_fill()
cpdf_fill_stroke()
cpdf_finalize()
cpdf_finalize_page()
cpdf_global_set_document_limits()
cpdf_import_jpeg()
cpdf_lineto()
cpdf_moveto()
cpdf_newpath()
cpdf_open()
cpdf_output_buffer()
cpdf_page_init()
cpdf_place_inline_image()
cpdf_rect()
cpdf_restore()
cpdf_rlineto()
cpdf_rmoveto()
cpdf_rotate()
cpdf_rotate_text()
cpdf_save()
cpdf_save_to_file()
cpdf_scale()
cpdf_set_action_url()
cpdf_set_char_spacing()
cpdf_set_creator()
cpdf_set_current_page()
cpdf_set_font()
cpdf_set_font_directories()
cpdf_set_font_map_file()
cpdf_set_horiz_scaling()
cpdf_set_keywords()
cpdf_set_leading()
cpdf_set_page_animation()
cpdf_set_subject()
cpdf_set_text_matrix()
cpdf_set_text_pos()
cpdf_set_text_rendering()
cpdf_set_text_rise()
cpdf_set_title()
cpdf_set_viewer_preferences()
cpdf_set_word_spacing()
cpdf_setdash()
cpdf_setflat()
cpdf_setgray()
cpdf_setgray_fill()
cpdf_setgray_stroke()
cpdf_setlinecap()
cpdf_setlinejoin()
cpdf_setlinewidth()
cpdf_setmiterlimit()
cpdf_setrgbcolor()
cpdf_setrgbcolor_fill()
cpdf_setrgbcolor_stroke()
cpdf_show()
cpdf_show_xy()
cpdf_stringwidth()
cpdf_stroke()
cpdf_text()
cpdf_translate()
crack_check()
crack_closedict()
crack_getlastmessage()
crack_opendict()
crc32()
create_function()
crypt()
ctype_alnum()
ctype_alpha()
ctype_cntrl()
ctype_digit()
ctype_graph()
ctype_lower()
ctype_print()
ctype_punct()
ctype_space()
ctype_upper()
ctype_xdigit()
curl_close()
curl_errno()
curl_error()
curl_exec()
curl_getinfo()
curl_init()
curl_setopt()
curl_version()
current()
cybercash_base64_decode()
cybercash_base64_encode()
cybercash_decr()
cybercash_encr()
cybermut_creerformulairecm()
cybermut_creerreponsecm()
cybermut_testmac()
cyrus_authenticate()
cyrus_bind()
cyrus_close()
cyrus_connect()
cyrus_query()
cyrus_unbind()

D

date()
dba_close()
dba_delete()
dba_exists()
dba_fetch()
dba_firstkey()
dba_insert()
dba_nextkey()
dba_open()
dba_optimize()
dba_popen()
dba_replace()
dba_sync()
dbase_add_record()
dbase_close()
dbase_create()
dbase_delete_record()
dbase_get_record()
dbase_get_record_with_names()
dbase_numfields()
dbase_numrecords()
dbase_open()
dbase_pack()
dbase_replace_record()
dblist()
dbmclose()
dbmdelete()
dbmexists()
dbmfetch()
dbmfirstkey()
dbminsert()
dbmnextkey()
dbmopen()
dbmreplace()
dbplus_add()
dbplus_aql()
dbplus_chdir()
dbplus_close()
dbplus_curr()
dbplus_errcode()
dbplus_errno()
dbplus_find()
dbplus_first()
dbplus_flush()
dbplus_freealllocks()
dbplus_freelock()
dbplus_freerlocks()
dbplus_getlock()
dbplus_getunique()
dbplus_info()
dbplus_last()
dbplus_lockrel()
dbplus_next()
dbplus_open()
dbplus_prev()
dbplus_rchperm()
dbplus_rcreate()
dbplus_rcrtexact()
dbplus_rcrtlike()
dbplus_resolve()
dbplus_restorepos()
dbplus_rkeys()
dbplus_ropen()
dbplus_rquery()
dbplus_rrename()
dbplus_rsecindex()
dbplus_runlink()
dbplus_rzap()
dbplus_savepos()
dbplus_setindex()
dbplus_setindexbynumber()
dbplus_sql()
dbplus_tcl()
dbplus_tremove()
dbplus_undo()
dbplus_undoprepare()
dbplus_unlockrel()
dbplus_unselect()
dbplus_update()
dbplus_xlockrel()
dbplus_xunlockrel()
dbx_close()
dbx_compare()
dbx_connect()
dbx_error()
dbx_query()
dbx_sort()
dcgettext()
dcngettext()
debugger_off()
debugger_on()
decbin()
dechex()
decoct()
define()
define_syslog_variables()
defined()
deg2rad()
delete()
dgettext()
die()
dio_close()
dio_fcntl()
dio_open()
dio_read()
dio_seek()
dio_stat()
dio_truncate()
dio_write()
dir()
dirname()
disk_free_space()
disk_total_space()
diskfreespace()
dl()
dngettext()
domattribute->name()
domattribute->specified()
domattribute->value()
domdocument->add_root [deprecated]()
domdocument->create_attribute()
domdocument->create_cdata_section()
domdocument->create_comment()
domdocument->create_element()
domdocument->create_entity_reference()
domdocument->create_processing_instruction()
domdocument->create_text_node()
domdocument->doctype()
domdocument->document_element()
domdocument->dump_file()
domdocument->dump_mem()
domdocument->get_element_by_id()
domdocument->get_elements_by_tagname()
domdocument->html_dump_mem()
domdocumenttype->entities()
domdocumenttype->internal_subset()
domdocumenttype->name()
domdocumenttype->notations()
domdocumenttype->public_id()
domdocumenttype->system_id()
domelement->get_attribute()
domelement->get_attribute_node()
domelement->get_elements_by_tagname()
domelement->has_attribute()
domelement->remove_attribute()
domelement->set_attribute()
domelement->tagname()
domnode->append_child()
domnode->append_sibling()
domnode->attributes()
domnode->child_nodes()
domnode->clone_node()
domnode->dump_node()
domnode->first_child()
domnode->get_content()
domnode->has_attributess()
domnode->has_child_nodes()
domnode->insert_before()
domnode->is_blank_node()
domnode->last_child()
domnode->next_sibling()
domnode->node_name()
domnode->node_type()
domnode->node_value()
domnode->owner_document()
domnode->parent_node()
domnode->prefix()
domnode->previous_sibling()
domnode->remove_child()
domnode->replace_child()
domnode->replace_node()
domnode->set_content()
domnode->set_name()
domnode->unlink_node()
domprocessinginstruction->data()
domprocessinginstruction->target()
domxml_new_doc()
domxml_open_file()
domxml_open_mem()
domxml_version()
domxml_xmltree()
dotnet_load()
doubleval()

E

each()
easter_date()
easter_days()
ebcdic2ascii()
echo()
empty()
end()
ereg()
ereg_replace()
eregi()
eregi_replace()
error_log()
error_reporting()
escapeshellarg()
escapeshellcmd()
eval()
exec()
exif_imagetype()
exif_read_data()
exif_thumbnail()
exit()
exp()
explode()
expm1()
extension_loaded()
extract()
ezmlm_hash()

F

fbsql_affected_rows()
fbsql_autocommit()
fbsql_change_user()
fbsql_close()
fbsql_commit()
fbsql_connect()
fbsql_create_blob()
fbsql_create_clob()
fbsql_create_db()
fbsql_data_seek()
fbsql_database()
fbsql_database_password()
fbsql_db_query()
fbsql_db_status()
fbsql_drop_db()
fbsql_errno()
fbsql_error()
fbsql_fetch_array()
fbsql_fetch_assoc()
fbsql_fetch_field()
fbsql_fetch_lengths()
fbsql_fetch_object()
fbsql_fetch_row()
fbsql_field_flags()
fbsql_field_len()
fbsql_field_name()
fbsql_field_seek()
fbsql_field_table()
fbsql_field_type()
fbsql_free_result()
fbsql_get_autostart_info()
fbsql_hostname()
fbsql_insert_id()
fbsql_list_dbs()
fbsql_list_fields()
fbsql_list_tables()
fbsql_next_result()
fbsql_num_fields()
fbsql_num_rows()
fbsql_password()
fbsql_pconnect()
fbsql_query()
fbsql_read_blob()
fbsql_read_clob()
fbsql_result()
fbsql_rollback()
fbsql_select_db()
fbsql_set_lob_mode()
fbsql_set_transaction()
fbsql_start_db()
fbsql_stop_db()
fbsql_tablename()
fbsql_username()
fbsql_warnings()
fclose()
fdf_add_template()
fdf_close()
fdf_create()
fdf_get_file()
fdf_get_status()
fdf_get_value()
fdf_next_field_name()
fdf_open()
fdf_save()
fdf_set_ap()
fdf_set_encoding()
fdf_set_file()
fdf_set_flags()
fdf_set_javascript_action()
fdf_set_opt()
fdf_set_status()
fdf_set_submit_form_action()
fdf_set_value()
feof()
fflush()
fgetc()
fgetcsv()
fgets()
fgetss()
file()
file_exists()
file_get_contents()
file_get_wrapper_data()
file_register_wrapper()
fileatime()
filectime()
filegroup()
fileinode()
filemtime()
fileowner()
fileperms()
filepro()
filepro_fieldcount()
filepro_fieldname()
filepro_fieldtype()
filepro_fieldwidth()
filepro_retrieve()
filepro_rowcount()
filesize()
filetype()
floatval()
flock()
floor()
flush()
fopen()
fpassthru()
fputs()
fread()
frenchtojd()
fribidi_log2vis()
fscanf()
fseek()
fsockopen()
fstat()
ftell()
ftok()
ftp_async_continue()
ftp_async_fget()
ftp_async_fput()
ftp_async_get()
ftp_async_put()
ftp_cdup()
ftp_chdir()
ftp_close()
ftp_connect()
ftp_delete()
ftp_exec()
ftp_fget()
ftp_fput()
ftp_get()
ftp_get_option()
ftp_login()
ftp_mdtm()
ftp_mkdir()
ftp_nlist()
ftp_pasv()
ftp_put()
ftp_pwd()
ftp_quit()
ftp_rawlist()
ftp_rename()
ftp_rmdir()
ftp_set_option()
ftp_site()
ftp_size()
ftp_systype()
ftruncate()
func_get_arg()
func_get_args()
func_num_args()
function_exists()
fwrite()

G

get_browser()
get_cfg_var()
get_class()
get_class_methods()
get_class_vars()
get_current_user()
get_declared_classes()
get_defined_constants()
get_defined_functions()
get_defined_vars()
get_extension_funcs()
get_html_translation_table()
get_included_files()
get_loaded_extensions()
get_magic_quotes_gpc()
get_magic_quotes_runtime()
get_meta_tags()
get_object_vars()
get_parent_class()
get_required_files()
get_resource_type()
getallheaders()
getcwd()
getdate()
getenv()
gethostbyaddr()
gethostbyname()
gethostbynamel()
getimagesize()
getlastmod()
getmxrr()
getmygid()
getmyinode()
getmypid()
getmyuid()
getprotobyname()
getprotobynumber()
getrandmax()
getrusage()
getservbyname()
getservbyport()
gettext()
gettimeofday()
gettype()
glob()
gmdate()
gmmktime()
gmp_abs()
gmp_add()
gmp_and()
gmp_clrbit()
gmp_cmp()
gmp_com()
gmp_div()
gmp_div_q()
gmp_div_qr()
gmp_div_r()
gmp_divexact()
gmp_fact()
gmp_gcd()
gmp_gcdext()
gmp_hamdist()
gmp_init()
gmp_intval()
gmp_invert()
gmp_jacobi()
gmp_legendre()
gmp_mod()
gmp_mul()
gmp_neg()
gmp_or()
gmp_perfect_square()
gmp_popcount()
gmp_pow()
gmp_powm()
gmp_prob_prime()
gmp_random()
gmp_scan0()
gmp_scan1()
gmp_setbit()
gmp_sign()
gmp_sqrt()
gmp_sqrtrm()
gmp_strval()
gmp_sub()
gmp_xor()
gmstrftime()
gregoriantojd()
gzclose()
gzcompress()
gzdeflate()
gzencode()
gzeof()
gzfile()
gzgetc()
gzgets()
gzgetss()
gzinflate()
gzopen()
gzpassthru()
gzputs()
gzread()
gzrewind()
gzseek()
gztell()
gzuncompress()
gzwrite()

H

header()
headers_sent()
hebrev()
hebrevc()
hexdec()
highlight_file()
highlight_string()
htmlentities()
htmlspecialchars()
hw_api->checkin()
hw_api->checkout()
hw_api->children()
hw_api->content()
hw_api->copy()
hw_api->dbstat()
hw_api->dcstat()
hw_api->dstanchors()
hw_api->dstofsrcanchors()
hw_api->find()
hw_api->ftstat()
hw_api->hwstat()
hw_api->identify()
hw_api->info()
hw_api->insert()
hw_api->insertanchor()
hw_api->insertcollection()
hw_api->insertdocument()
hw_api->link()
hw_api->lock()
hw_api->move()
hw_api->object()
hw_api->objectbyanchor()
hw_api->parents()
hw_api->remove()
hw_api->replace()
hw_api->setcommitedversion()
hw_api->srcanchors()
hw_api->srcsofdst()
hw_api->unlock()
hw_api->user()
hw_api->userlist()
hw_api_attribute()
hw_api_attribute->key()
hw_api_attribute->langdepvalue()
hw_api_attribute->value()
hw_api_attribute->values()
hw_api_content()
hw_api_content->mimetype()
hw_api_content->read()
hw_api_error->count()
hw_api_error->reason()
hw_api_object()
hw_api_object->assign()
hw_api_object->attreditable()
hw_api_object->count()
hw_api_object->insert()
hw_api_object->remove()
hw_api_object->title()
hw_api_object->value()
hw_api_reason->description()
hw_api_reason->type()
hw_array2objrec()
hw_changeobject()
hw_children()
hw_childrenobj()
hw_close()
hw_connect()
hw_connection_info()
hw_cp()
hw_deleteobject()
hw_docbyanchor()
hw_docbyanchorobj()
hw_document_attributes()
hw_document_bodytag()
hw_document_content()
hw_document_setcontent()
hw_document_size()
hw_dummy()
hw_edittext()
hw_error()
hw_errormsg()
hw_free_document()
hw_getanchors()
hw_getanchorsobj()
hw_getandlock()
hw_getchildcoll()
hw_getchildcollobj()
hw_getchilddoccoll()
hw_getchilddoccollobj()
hw_getobject()
hw_getobjectbyquery()
hw_getobjectbyquerycoll()
hw_getobjectbyquerycollobj()
hw_getobjectbyqueryobj()
hw_getparents()
hw_getparentsobj()
hw_getrellink()
hw_getremote()
hw_getremotechildren()
hw_getsrcbydestobj()
hw_gettext()
hw_getusername()
hw_identify()
hw_incollections()
hw_info()
hw_inscoll()
hw_insdoc()
hw_insertanchors()
hw_insertdocument()
hw_insertobject()
hw_mapid()
hw_modifyobject()
hw_mv()
hw_new_document()
hw_objrec2array()
hw_output_document()
hw_pconnect()
hw_pipedocument()
hw_root()
hw_setlinkroot()
hw_stat()
hw_unlock()
hw_who()
hwapi_hgcsp()
hypot()

I

ibase_blob_add()
ibase_blob_cancel()
ibase_blob_close()
ibase_blob_create()
ibase_blob_echo()
ibase_blob_get()
ibase_blob_import()
ibase_blob_info()
ibase_blob_open()
ibase_close()
ibase_commit()
ibase_connect()
ibase_errmsg()
ibase_execute()
ibase_fetch_object()
ibase_fetch_row()
ibase_field_info()
ibase_free_query()
ibase_free_result()
ibase_num_fields()
ibase_pconnect()
ibase_prepare()
ibase_query()
ibase_rollback()
ibase_timefmt()
ibase_trans()
icap_close()
icap_create_calendar()
icap_delete_calendar()
icap_delete_event()
icap_fetch_event()
icap_list_alarms()
icap_list_events()
icap_open()
icap_rename_calendar()
icap_reopen()
icap_snooze()
icap_store_event()
iconv()
iconv_get_encoding()
iconv_set_encoding()
ifx_affected_rows()
ifx_blobinfile_mode()
ifx_byteasvarchar()
ifx_close()
ifx_connect()
ifx_copy_blob()
ifx_create_blob()
ifx_create_char()
ifx_do()
ifx_error()
ifx_errormsg()
ifx_fetch_row()
ifx_fieldproperties()
ifx_fieldtypes()
ifx_free_blob()
ifx_free_char()
ifx_free_result()
ifx_get_blob()
ifx_get_char()
ifx_getsqlca()
ifx_htmltbl_result()
ifx_nullformat()
ifx_num_fields()
ifx_num_rows()
ifx_pconnect()
ifx_prepare()
ifx_query()
ifx_textasvarchar()
ifx_update_blob()
ifx_update_char()
ifxus_close_slob()
ifxus_create_slob()
ifxus_free_slob()
ifxus_open_slob()
ifxus_read_slob()
ifxus_seek_slob()
ifxus_tell_slob()
ifxus_write_slob()
ignore_user_abort()
image2wbmp()
image_type_to_mime_type()
imagealphablending()
imagearc()
imagechar()
imagecharup()
imagecolorallocate()
imagecolorat()
imagecolorclosest()
imagecolorclosestalpha()
imagecolorclosesthwb()
imagecolordeallocate()
imagecolorexact()
imagecolorexactalpha()
imagecolorresolve()
imagecolorresolvealpha()
imagecolorset()
imagecolorsforindex()
imagecolorstotal()
imagecolortransparent()
imagecopy()
imagecopymerge()
imagecopymergegray()
imagecopyresampled()
imagecopyresized()
imagecreate()
imagecreatefromgd()
imagecreatefromgd2()
imagecreatefromgd2part()
imagecreatefromgif()
imagecreatefromjpeg()
imagecreatefrompng()
imagecreatefromstring()
imagecreatefromwbmp()
imagecreatefromxbm()
imagecreatefromxpm()
imagecreatetruecolor()
imagedashedline()
imagedestroy()
imageellipse()
imagefill()
imagefilledarc()
imagefilledellipse()
imagefilledpolygon()
imagefilledrectangle()
imagefilltoborder()
imagefontheight()
imagefontwidth()
imageftbbox()
imagefttext()
imagegammacorrect()
imagegd()
imagegd2()
imagegif()
imageinterlace()
imagejpeg()
imageline()
imageloadfont()
imagepalettecopy()
imagepng()
imagepolygon()
imagepsbbox()
imagepscopyfont()
imagepsencodefont()
imagepsextendfont()
imagepsfreefont()
imagepsloadfont()
imagepsslantfont()
imagepstext()
imagerectangle()
imagesetbrush()
imagesetpixel()
imagesetstyle()
imagesetthickness()
imagesettile()
imagestring()
imagestringup()
imagesx()
imagesy()
imagetruecolortopalette()
imagettfbbox()
imagettftext()
imagetypes()
imagewbmp()
imap_8bit()
imap_alerts()
imap_append()
imap_base64()
imap_binary()
imap_body()
imap_bodystruct()
imap_check()
imap_clearflag_full()
imap_close()
imap_createmailbox()
imap_delete()
imap_deletemailbox()
imap_errors()
imap_expunge()
imap_fetch_overview()
imap_fetchbody()
imap_fetchheader()
imap_fetchstructure()
imap_get_quota()
imap_getmailboxes()
imap_getsubscribed()
imap_header()
imap_headerinfo()
imap_headers()
imap_last_error()
imap_listmailbox()
imap_listsubscribed()
imap_mail()
imap_mail_compose()
imap_mail_copy()
imap_mail_move()
imap_mailboxmsginfo()
imap_mime_header_decode()
imap_msgno()
imap_num_msg()
imap_num_recent()
imap_open()
imap_ping()
imap_popen()
imap_qprint()
imap_renamemailbox()
imap_reopen()
imap_rfc822_parse_adrlist()
imap_rfc822_parse_headers()
imap_rfc822_write_address()
imap_scanmailbox()
imap_search()
imap_set_quota()
imap_setacl()
imap_setflag_full()
imap_sort()
imap_status()
imap_subscribe()
imap_thread()
imap_uid()
imap_undelete()
imap_unsubscribe()
imap_utf7_decode()
imap_utf7_encode()
imap_utf8()
implode()
import_request_variables()
in_array()
ingres_autocommit()
ingres_close()
ingres_commit()
ingres_connect()
ingres_fetch_array()
ingres_fetch_object()
ingres_fetch_row()
ingres_field_length()
ingres_field_name()
ingres_field_nullable()
ingres_field_precision()
ingres_field_scale()
ingres_field_type()
ingres_num_fields()
ingres_num_rows()
ingres_pconnect()
ingres_query()
ingres_rollback()
ini_alter()
ini_get()
ini_get_all()
ini_restore()
ini_set()
intval()
ip2long()
iptcembed()
iptcparse()
ircg_channel_mode()
ircg_disconnect()
ircg_fetch_error_msg()
ircg_get_username()
ircg_html_encode()
ircg_ignore_add()
ircg_ignore_del()
ircg_is_conn_alive()
ircg_join()
ircg_kick()
ircg_lookup_format_messages()
ircg_msg()
ircg_nick()
ircg_nickname_escape()
ircg_nickname_unescape()
ircg_notice()
ircg_part()
ircg_pconnect()
ircg_register_format_messages()
ircg_set_current()
ircg_set_file()
ircg_set_on_die()
ircg_topic()
ircg_whois()
is_a()
is_array()
is_bool()
is_callable()
is_dir()
is_double()
is_executable()
is_file()
is_finite()
is_float()
is_infinite()
is_int()
is_integer()
is_link()
is_long()
is_nan()
is_null()
is_numeric()
is_object()
is_readable()
is_real()
is_resource()
is_scalar()
is_string()
is_subclass_of()
is_uploaded_file()
is_writable()
is_writeable()
isset()

J

java_last_exception_clear()
java_last_exception_get()
jddayofweek()
jdmonthname()
jdtofrench()
jdtogregorian()
jdtojewish()
jdtojulian()
jdtounix()
jewishtojd()
join()
jpeg2wbmp()
juliantojd()

K

key()
krsort()
ksort()

L

lcg_value()
ldap_8859_to_t61()
ldap_add()
ldap_bind()
ldap_close()
ldap_compare()
ldap_connect()
ldap_count_entries()
ldap_delete()
ldap_dn2ufn()
ldap_err2str()
ldap_errno()
ldap_error()
ldap_explode_dn()
ldap_first_attribute()
ldap_first_entry()
ldap_first_reference()
ldap_free_result()
ldap_get_attributes()
ldap_get_dn()
ldap_get_entries()
ldap_get_option()
ldap_get_values()
ldap_get_values_len()
ldap_list()
ldap_mod_add()
ldap_mod_del()
ldap_mod_replace()
ldap_modify()
ldap_next_attribute()
ldap_next_entry()
ldap_next_reference()
ldap_parse_reference()
ldap_parse_result()
ldap_read()
ldap_rename()
ldap_search()
ldap_set_option()
ldap_set_rebind_proc()
ldap_sort()
ldap_start_tls()
ldap_t61_to_8859()
ldap_unbind()
leak()
levenshtein()
link()
linkinfo()
list()
localeconv()
localtime()
log()
log10()
log1p()
long2ip()
lstat()
ltrim()

M

mail()
mailparse_determine_best_xfer_encoding()
mailparse_msg_create()
mailparse_msg_extract_part()
mailparse_msg_extract_part_file()
mailparse_msg_free()
mailparse_msg_get_part()
mailparse_msg_get_part_data()
mailparse_msg_get_structure()
mailparse_msg_parse()
mailparse_msg_parse_file()
mailparse_rfc822_parse_addresses()
mailparse_stream_encode()
mailparse_uudecode_all()
max()
mb_convert_encoding()
mb_convert_kana()
mb_convert_variables()
mb_decode_mimeheader()
mb_decode_numericentity()
mb_detect_encoding()
mb_detect_order()
mb_encode_mimeheader()
mb_encode_numericentity()
mb_ereg()
mb_ereg_match()
mb_ereg_replace()
mb_ereg_search()
mb_ereg_search_getpos()
mb_ereg_search_getregs()
mb_ereg_search_init()
mb_ereg_search_pos()
mb_ereg_search_regs()
mb_ereg_search_setpos()
mb_eregi()
mb_eregi_replace()
mb_get_info()
mb_http_input()
mb_http_output()
mb_internal_encoding()
mb_language()
mb_output_handler()
mb_parse_str()
mb_preferred_mime_name()
mb_regex_encoding()
mb_send_mail()
mb_split()
mb_strcut()
mb_strimwidth()
mb_strlen()
mb_strpos()
mb_strrpos()
mb_strwidth()
mb_substitute_character()
mb_substr()
mcal_append_event()
mcal_close()
mcal_create_calendar()
mcal_date_compare()
mcal_date_valid()
mcal_day_of_week()
mcal_day_of_year()
mcal_days_in_month()
mcal_delete_calendar()
mcal_delete_event()
mcal_event_add_attribute()
mcal_event_init()
mcal_event_set_alarm()
mcal_event_set_category()
mcal_event_set_class()
mcal_event_set_description()
mcal_event_set_end()
mcal_event_set_recur_daily()
mcal_event_set_recur_monthly_mday()
mcal_event_set_recur_monthly_wday()
mcal_event_set_recur_none()
mcal_event_set_recur_weekly()
mcal_event_set_recur_yearly()
mcal_event_set_start()
mcal_event_set_title()
mcal_expunge()
mcal_fetch_current_stream_event()
mcal_fetch_event()
mcal_is_leap_year()
mcal_list_alarms()
mcal_list_events()
mcal_next_recurrence()
mcal_open()
mcal_popen()
mcal_rename_calendar()
mcal_reopen()
mcal_snooze()
mcal_store_event()
mcal_time_valid()
mcal_week_of_year()
mcrypt_cbc()
mcrypt_cfb()
mcrypt_create_iv()
mcrypt_decrypt()
mcrypt_ecb()
mcrypt_enc_get_algorithms_name()
mcrypt_enc_get_block_size()
mcrypt_enc_get_iv_size()
mcrypt_enc_get_key_size()
mcrypt_enc_get_modes_name()
mcrypt_enc_get_supported_key_sizes()
mcrypt_enc_is_block_algorithm()
mcrypt_enc_is_block_algorithm_mode()
mcrypt_enc_is_block_mode()
mcrypt_enc_self_test()
mcrypt_encrypt()
mcrypt_generic()
mcrypt_generic_deinit()
mcrypt_generic_end()
mcrypt_generic_init()
mcrypt_get_block_size()
mcrypt_get_cipher_name()
mcrypt_get_iv_size()
mcrypt_get_key_size()
mcrypt_list_algorithms()
mcrypt_list_modes()
mcrypt_module_close()
mcrypt_module_get_algo_block_size()
mcrypt_module_get_algo_key_size()
mcrypt_module_get_supported_key_sizes()
mcrypt_module_is_block_algorithm()
mcrypt_module_is_block_algorithm_mode()
mcrypt_module_is_block_mode()
mcrypt_module_open()
mcrypt_module_self_test()
mcrypt_ofb()
md5()
md5_file()
mdecrypt_generic()
metaphone()
method_exists()
mhash()
mhash_count()
mhash_get_block_size()
mhash_get_hash_name()
mhash_keygen_s2k()
microtime()
mime_content_type()
min()
ming_setcubicthreshold()
ming_setscale()
ming_useswfversion()
mkdir()
mktime()
move_uploaded_file()
msession_connect()
msession_count()
msession_create()
msession_destroy()
msession_disconnect()
msession_find()
msession_get()
msession_get_array()
msession_getdata()
msession_inc()
msession_list()
msession_listvar()
msession_lock()
msession_plugin()
msession_randstr()
msession_set()
msession_set_array()
msession_setdata()
msession_timeout()
msession_uniq()
msession_unlock()
msg_get_queue()
msg_receive()
msg_remove_queue()
msg_send()
msg_set_queue()
msg_stat_queue()
msql()
msql_affected_rows()
msql_close()
msql_connect()
msql_create_db()
msql_createdb()
msql_data_seek()
msql_dbname()
msql_drop_db()
msql_dropdb()
msql_error()
msql_fetch_array()
msql_fetch_field()
msql_fetch_object()
msql_fetch_row()
msql_field_seek()
msql_fieldflags()
msql_fieldlen()
msql_fieldname()
msql_fieldtable()
msql_fieldtype()
msql_free_result()
msql_freeresult()
msql_list_dbs()
msql_list_fields()
msql_list_tables()
msql_listdbs()
msql_listfields()
msql_listtables()
msql_num_fields()
msql_num_rows()
msql_numfields()
msql_numrows()
msql_pconnect()
msql_query()
msql_regcase()
msql_result()
msql_select_db()
msql_selectdb()
msql_tablename()
mssql_bind()
mssql_close()
mssql_connect()
mssql_data_seek()
mssql_execute()
mssql_fetch_array()
mssql_fetch_assoc()
mssql_fetch_batch()
mssql_fetch_field()
mssql_fetch_object()
mssql_fetch_row()
mssql_field_length()
mssql_field_name()
mssql_field_seek()
mssql_field_type()
mssql_free_result()
mssql_get_last_message()
mssql_guid_string()
mssql_init()
mssql_min_error_severity()
mssql_min_message_severity()
mssql_next_result()
mssql_num_fields()
mssql_num_rows()
mssql_pconnect()
mssql_query()
mssql_result()
mssql_rows_affected()
mssql_select_db()
mt_getrandmax()
mt_rand()
mt_srand()
muscat_close()
muscat_get()
muscat_give()
muscat_setup()
muscat_setup_net()
mysql_affected_rows()
mysql_change_user()
mysql_character_set_name()
mysql_close()
mysql_connect()
mysql_create_db()
mysql_data_seek()
mysql_db_name()
mysql_db_query()
mysql_drop_db()
mysql_errno()
mysql_error()
mysql_escape_string()
mysql_fetch_array()
mysql_fetch_assoc()
mysql_fetch_field()
mysql_fetch_lengths()
mysql_fetch_object()
mysql_fetch_row()
mysql_field_flags()
mysql_field_len()
mysql_field_name()
mysql_field_seek()
mysql_field_table()
mysql_field_type()
mysql_free_result()
mysql_get_client_info()
mysql_get_host_info()
mysql_get_proto_info()
mysql_get_server_info()
mysql_info()
mysql_insert_id()
mysql_list_dbs()
mysql_list_fields()
mysql_list_processes()
mysql_list_tables()
mysql_num_fields()
mysql_num_rows()
mysql_pconnect()
mysql_ping()
mysql_query()
mysql_real_escape_string()
mysql_result()
mysql_select_db()
mysql_stat()
mysql_tablename()
mysql_thread_id()
mysql_unbuffered_query()

N

natcasesort()
natsort()
ncurses_addch()
ncurses_addchnstr()
ncurses_addchstr()
ncurses_addnstr()
ncurses_addstr()
ncurses_assume_default_colors()
ncurses_attroff()
ncurses_attron()
ncurses_attrset()
ncurses_baudrate()
ncurses_beep()
ncurses_bkgd()
ncurses_bkgdset()
ncurses_border()
ncurses_can_change_color()
ncurses_cbreak()
ncurses_clear()
ncurses_clrtobot()
ncurses_clrtoeol()
ncurses_color_set()
ncurses_curs_set()
ncurses_def_prog_mode()
ncurses_def_shell_mode()
ncurses_define_key()
ncurses_delay_output()
ncurses_delch()
ncurses_deleteln()
ncurses_delwin()
ncurses_doupdate()
ncurses_echo()
ncurses_echochar()
ncurses_end()
ncurses_erase()
ncurses_erasechar()
ncurses_filter()
ncurses_flash()
ncurses_flushinp()
ncurses_getch()
ncurses_getmouse()
ncurses_halfdelay()
ncurses_has_colors()
ncurses_has_ic()
ncurses_has_il()
ncurses_has_key()
ncurses_hline()
ncurses_inch()
ncurses_init()
ncurses_init_color()
ncurses_init_pair()
ncurses_insch()
ncurses_insdelln()
ncurses_insertln()
ncurses_insstr()
ncurses_instr()
ncurses_isendwin()
ncurses_keyok()
ncurses_killchar()
ncurses_longname()
ncurses_mouseinterval()
ncurses_mousemask()
ncurses_move()
ncurses_mvaddch()
ncurses_mvaddchnstr()
ncurses_mvaddchstr()
ncurses_mvaddnstr()
ncurses_mvaddstr()
ncurses_mvcur()
ncurses_mvdelch()
ncurses_mvgetch()
ncurses_mvhline()
ncurses_mvinch()
ncurses_mvvline()
ncurses_mvwaddstr()
ncurses_napms()
ncurses_newwin()
ncurses_nl()
ncurses_nocbreak()
ncurses_noecho()
ncurses_nonl()
ncurses_noqiflush()
ncurses_noraw()
ncurses_putp()
ncurses_qiflush()
ncurses_raw()
ncurses_refresh()
ncurses_resetty()
ncurses_savetty()
ncurses_scr_dump()
ncurses_scr_init()
ncurses_scr_restore()
ncurses_scr_set()
ncurses_scrl()
ncurses_slk_attr()
ncurses_slk_attroff()
ncurses_slk_attron()
ncurses_slk_attrset()
ncurses_slk_clear()
ncurses_slk_color()
ncurses_slk_init()
ncurses_slk_noutrefresh()
ncurses_slk_refresh()
ncurses_slk_restore()
ncurses_slk_touch()
ncurses_standend()
ncurses_standout()
ncurses_start_color()
ncurses_termattrs()
ncurses_termname()
ncurses_timeout()
ncurses_typeahead()
ncurses_ungetch()
ncurses_ungetmouse()
ncurses_use_default_colors()
ncurses_use_env()
ncurses_use_extended_names()
ncurses_vidattr()
ncurses_vline()
ncurses_wrefresh()
next()
ngettext()
nl2br()
nl_langinfo()
notes_body()
notes_copy_db()
notes_create_db()
notes_create_note()
notes_drop_db()
notes_find_note()
notes_header_info()
notes_list_msgs()
notes_mark_read()
notes_mark_unread()
notes_nav_create()
notes_search()
notes_unread()
notes_version()
number_format()

O

ob_clean()
ob_end_clean()
ob_end_flush()
ob_flush()
ob_get_contents()
ob_get_length()
ob_get_level()
ob_get_status()
ob_gzhandler()
ob_iconv_handler()
ob_implicit_flush()
ob_start()
ocibindbyname()
ocicancel()
ocicollappend()
ocicollassign()
ocicollassignelem()
ocicollgetelem()
ocicollmax()
ocicollsize()
ocicolltrim()
ocicolumnisnull()
ocicolumnname()
ocicolumnprecision()
ocicolumnscale()
ocicolumnsize()
ocicolumntype()
ocicolumntyperaw()
ocicommit()
ocidefinebyname()
ocierror()
ociexecute()
ocifetch()
ocifetchinto()
ocifetchstatement()
ocifreecollection()
ocifreecursor()
ocifreedesc()
ocifreestatement()
ociinternaldebug()
ociloadlob()
ocilogoff()
ocilogon()
ocinewcollection()
ocinewcursor()
ocinewdescriptor()
ocinlogon()
ocinumcols()
ociparse()
ociplogon()
ociresult()
ocirollback()
ocirowcount()
ocisavelob()
ocisavelobfile()
ociserverversion()
ocisetprefetch()
ocistatementtype()
ociwritelobtofile()
octdec()
odbc_autocommit()
odbc_binmode()
odbc_close()
odbc_close_all()
odbc_columnprivileges()
odbc_columns()
odbc_commit()
odbc_connect()
odbc_cursor()
odbc_do()
odbc_error()
odbc_errormsg()
odbc_exec()
odbc_execute()
odbc_fetch_array()
odbc_fetch_into()
odbc_fetch_object()
odbc_fetch_row()
odbc_field_len()
odbc_field_name()
odbc_field_num()
odbc_field_precision()
odbc_field_scale()
odbc_field_type()
odbc_foreignkeys()
odbc_free_result()
odbc_gettypeinfo()
odbc_longreadlen()
odbc_next_result()
odbc_num_fields()
odbc_num_rows()
odbc_pconnect()
odbc_prepare()
odbc_primarykeys()
odbc_procedurecolumns()
odbc_procedures()
odbc_result()
odbc_result_all()
odbc_rollback()
odbc_setoption()
odbc_specialcolumns()
odbc_statistics()
odbc_tableprivileges()
odbc_tables()
opendir()
openlog()
openssl_csr_export()
openssl_csr_export_to_file()
openssl_csr_new()
openssl_csr_sign()
openssl_error_string()
openssl_free_key()
openssl_get_privatekey()
openssl_get_publickey()
openssl_open()
openssl_pkcs7_decrypt()
openssl_pkcs7_encrypt()
openssl_pkcs7_sign()
openssl_pkcs7_verify()
openssl_pkey_export()
openssl_pkey_export_to_file()
openssl_pkey_new()
openssl_private_decrypt()
openssl_private_encrypt()
openssl_public_decrypt()
openssl_public_encrypt()
openssl_seal()
openssl_sign()
openssl_verify()
openssl_x509_check_private_key()
openssl_x509_checkpurpose()
openssl_x509_export()
openssl_x509_export_to_file()
openssl_x509_free()
openssl_x509_parse()
openssl_x509_read()
ora_bind()
ora_close()
ora_columnname()
ora_columnsize()
ora_columntype()
ora_commit()
ora_commitoff()
ora_commiton()
ora_do()
ora_error()
ora_errorcode()
ora_exec()
ora_fetch()
ora_fetch_into()
ora_getcolumn()
ora_logoff()
ora_logon()
ora_numcols()
ora_numrows()
ora_open()
ora_parse()
ora_plogon()
ora_rollback()
ord()
overload()
ovrimos_close()
ovrimos_commit()
ovrimos_connect()
ovrimos_cursor()
ovrimos_exec()
ovrimos_execute()
ovrimos_fetch_into()
ovrimos_fetch_row()
ovrimos_field_len()
ovrimos_field_name()
ovrimos_field_num()
ovrimos_field_type()
ovrimos_free_result()
ovrimos_longreadlen()
ovrimos_num_fields()
ovrimos_num_rows()
ovrimos_prepare()
ovrimos_result()
ovrimos_result_all()
ovrimos_rollback()

P

pack()
parse_ini_file()
parse_str()
parse_url()
passthru()
pathinfo()
pattern modifiers()
pattern syntax()
pclose()
pcntl_exec()
pcntl_fork()
pcntl_signal()
pcntl_waitpid()
pcntl_wexitstatus()
pcntl_wifexited()
pcntl_wifsignaled()
pcntl_wifstopped()
pcntl_wstopsig()
pcntl_wtermsig()
pdf_add_annotation()
pdf_add_bookmark()
pdf_add_launchlink()
pdf_add_locallink()
pdf_add_note()
pdf_add_outline()
pdf_add_pdflink()
pdf_add_thumbnail()
pdf_add_weblink()
pdf_arc()
pdf_arcn()
pdf_attach_file()
pdf_begin_page()
pdf_begin_pattern()
pdf_begin_template()
pdf_circle()
pdf_clip()
pdf_close()
pdf_close_image()
pdf_close_pdi()
pdf_close_pdi_page()
pdf_closepath()
pdf_closepath_fill_stroke()
pdf_closepath_stroke()
pdf_concat()
pdf_continue_text()
pdf_curveto()
pdf_delete()
pdf_end_page()
pdf_end_pattern()
pdf_end_template()
pdf_endpath()
pdf_fill()
pdf_fill_stroke()
pdf_findfont()
pdf_get_buffer()
pdf_get_font()
pdf_get_fontname()
pdf_get_fontsize()
pdf_get_image_height()
pdf_get_image_width()
pdf_get_majorversion()
pdf_get_minorversion()
pdf_get_parameter()
pdf_get_pdi_parameter()
pdf_get_pdi_value()
pdf_get_value()
pdf_initgraphics()
pdf_lineto()
pdf_makespotcolor()
pdf_moveto()
pdf_new()
pdf_open()
pdf_open_ccitt()
pdf_open_file()
pdf_open_gif()
pdf_open_image()
pdf_open_image_file()
pdf_open_jpeg()
pdf_open_memory_image()
pdf_open_pdi()
pdf_open_pdi_page()
pdf_open_png()
pdf_open_tiff()
pdf_place_image()
pdf_place_pdi_page()
pdf_rect()
pdf_restore()
pdf_rotate()
pdf_save()
pdf_scale()
pdf_set_border_color()
pdf_set_border_dash()
pdf_set_border_style()
pdf_set_char_spacing()
pdf_set_duration()
pdf_set_font()
pdf_set_horiz_scaling()
pdf_set_info()
pdf_set_info_author()
pdf_set_info_creator()
pdf_set_info_keywords()
pdf_set_info_subject()
pdf_set_info_title()
pdf_set_leading()
pdf_set_parameter()
pdf_set_text_matrix()
pdf_set_text_pos()
pdf_set_text_rendering()
pdf_set_text_rise()
pdf_set_value()
pdf_set_word_spacing()
pdf_setcolor()
pdf_setdash()
pdf_setflat()
pdf_setfont()
pdf_setgray()
pdf_setgray_fill()
pdf_setgray_stroke()
pdf_setlinecap()
pdf_setlinejoin()
pdf_setlinewidth()
pdf_setmatrix()
pdf_setmiterlimit()
pdf_setpolydash()
pdf_setrgbcolor()
pdf_setrgbcolor_fill()
pdf_setrgbcolor_stroke()
pdf_show()
pdf_show_boxed()
pdf_show_xy()
pdf_skew()
pdf_stringwidth()
pdf_stroke()
pdf_translate()
pfpro_cleanup()
pfpro_init()
pfpro_process()
pfpro_process_raw()
pfpro_version()
pfsockopen()
pg_affected_rows()
pg_cancel_query()
pg_client_encoding()
pg_close()
pg_connect()
pg_connection_busy()
pg_connection_reset()
pg_connection_status()
pg_convert()
pg_copy_from()
pg_copy_to()
pg_dbname()
pg_delete()
pg_end_copy()
pg_escape_bytea()
pg_escape_string()
pg_fetch_array()
pg_fetch_object()
pg_fetch_result()
pg_fetch_row()
pg_field_is_null()
pg_field_name()
pg_field_num()
pg_field_prtlen()
pg_field_size()
pg_field_type()
pg_free_result()
pg_get_result()
pg_host()
pg_insert()
pg_last_error()
pg_last_notice()
pg_last_oid()
pg_lo_close()
pg_lo_create()
pg_lo_export()
pg_lo_import()
pg_lo_open()
pg_lo_read()
pg_lo_read_all()
pg_lo_seek()
pg_lo_tell()
pg_lo_unlink()
pg_lo_write()
pg_metadata()
pg_num_fields()
pg_num_rows()
pg_options()
pg_pconnect()
pg_port()
pg_put_line()
pg_query()
pg_result_error()
pg_result_status()
pg_select()
pg_send_query()
pg_set_client_encoding()
pg_trace()
pg_tty()
pg_untrace()
pg_update()
php_logo_guid()
php_sapi_name()
php_uname()
phpcredits()
phpinfo()
phpversion()
pi()
png2wbmp()
popen()
pos()
posix_ctermid()
posix_getcwd()
posix_getegid()
posix_geteuid()
posix_getgid()
posix_getgrgid()
posix_getgrnam()
posix_getgroups()
posix_getlogin()
posix_getpgid()
posix_getpgrp()
posix_getpid()
posix_getppid()
posix_getpwnam()
posix_getpwuid()
posix_getrlimit()
posix_getsid()
posix_getuid()
posix_isatty()
posix_kill()
posix_mkfifo()
posix_setegid()
posix_seteuid()
posix_setgid()
posix_setpgid()
posix_setsid()
posix_setuid()
posix_times()
posix_ttyname()
posix_uname()
pow()
preg_grep()
preg_match()
preg_match_all()
preg_quote()
preg_replace()
preg_replace_callback()
preg_split()
prev()
print()
print_r()
printer_abort()
printer_close()
printer_create_brush()
printer_create_dc()
printer_create_font()
printer_create_pen()
printer_delete_brush()
printer_delete_dc()
printer_delete_font()
printer_delete_pen()
printer_draw_bmp()
printer_draw_chord()
printer_draw_elipse()
printer_draw_line()
printer_draw_pie()
printer_draw_rectangle()
printer_draw_roundrect()
printer_draw_text()
printer_end_doc()
printer_end_page()
printer_get_option()
printer_list()
printer_logical_fontheight()
printer_open()
printer_select_brush()
printer_select_font()
printer_select_pen()
printer_set_option()
printer_start_doc()
printer_start_page()
printer_write()
printf()
proc_close()
proc_open()
pspell_add_to_personal()
pspell_add_to_session()
pspell_check()
pspell_clear_session()
pspell_config_create()
pspell_config_ignore()
pspell_config_mode()
pspell_config_personal()
pspell_config_repl()
pspell_config_runtogether()
pspell_config_save_repl()
pspell_new()
pspell_new_config()
pspell_new_personal()
pspell_save_wordlist()
pspell_store_replacement()
pspell_suggest()
putenv()

Q

qdom_error()
qdom_tree()
quoted_printable_decode()
quotemeta()

R

rad2deg()
rand()
range()
rawurldecode()
rawurlencode()
read_exif_data()
readdir()
readfile()
readgzfile()
readline()
readline_add_history()
readline_clear_history()
readline_completion_function()
readline_info()
readline_list_history()
readline_read_history()
readline_write_history()
readlink()
realpath()
recode()
recode_file()
recode_string()
register_shutdown_function()
register_tick_function()
rename()
reset()
restore_error_handler()
rewind()
rewinddir()
rmdir()
round()
rsort()
rtrim()

S

sem_acquire()
sem_get()
sem_release()
sem_remove()
serialize()
sesam_affected_rows()
sesam_commit()
sesam_connect()
sesam_diagnostic()
sesam_disconnect()
sesam_errormsg()
sesam_execimm()
sesam_fetch_array()
sesam_fetch_result()
sesam_fetch_row()
sesam_field_array()
sesam_field_name()
sesam_free_result()
sesam_num_fields()
sesam_query()
sesam_rollback()
sesam_seek_row()
sesam_settransaction()
session_cache_expire()
session_cache_limiter()
session_decode()
session_destroy()
session_encode()
session_get_cookie_params()
session_id()
session_is_registered()
session_module_name()
session_name()
session_readonly()
session_register()
session_save_path()
session_set_cookie_params()
session_set_save_handler()
session_start()
session_unregister()
session_unset()
session_write_close()
set_error_handler()
set_file_buffer()
set_magic_quotes_runtime()
set_time_limit()
setcookie()
setlocale()
settype()
shell_exec()
shm_attach()
shm_detach()
shm_get_var()
shm_put_var()
shm_remove()
shm_remove_var()
shmop_close()
shmop_delete()
shmop_open()
shmop_read()
shmop_size()
shmop_write()
show_source()
shuffle()
similar_text()
sin()
sinh()
sizeof()
sleep()
snmp_get_quick_print()
snmp_set_quick_print()
snmpget()
snmprealwalk()
snmpset()
snmpwalk()
snmpwalkoid()
socket_accept()
socket_bind()
socket_clear_error()
socket_close()
socket_connect()
socket_create()
socket_create_listen()
socket_create_pair()
socket_get_option()
socket_get_status()
socket_getpeername()
socket_getsockname()
socket_iovec_add()
socket_iovec_alloc()
socket_iovec_delete()
socket_iovec_fetch()
socket_iovec_free()
socket_iovec_set()
socket_last_error()
socket_listen()
socket_read()
socket_readv()
socket_recv()
socket_recvfrom()
socket_recvmsg()
socket_select()
socket_send()
socket_sendmsg()
socket_sendto()
socket_set_blocking()
socket_set_nonblock()
socket_set_option()
socket_set_timeout()
socket_shutdown()
socket_strerror()
socket_write()
socket_writev()
sort()
soundex()
split()
spliti()
sprintf()
sql_regcase()
sqrt()
srand()
sscanf()
stat()
str_pad()
str_repeat()
str_replace()
str_rot13()
strcasecmp()
strchr()
strcmp()
strcoll()
strcspn()
strftime()
strip_tags()
stripcslashes()
stripslashes()
stristr()
strlen()
strnatcasecmp()
strnatcmp()
strncasecmp()
strncmp()
strpos()
strrchr()
strrev()
strrpos()
strspn()
strstr()
strtok()
strtolower()
strtotime()
strtoupper()
strtr()
strval()
substr()
substr_count()
substr_replace()
swf_actiongeturl()
swf_actiongotoframe()
swf_actiongotolabel()
swf_actionnextframe()
swf_actionplay()
swf_actionprevframe()
swf_actionsettarget()
swf_actionstop()
swf_actiontogglequality()
swf_actionwaitforframe()
swf_addbuttonrecord()
swf_addcolor()
swf_closefile()
swf_definebitmap()
swf_definefont()
swf_defineline()
swf_definepoly()
swf_definerect()
swf_definetext()
swf_endbutton()
swf_enddoaction()
swf_endshape()
swf_endsymbol()
swf_fontsize()
swf_fontslant()
swf_fonttracking()
swf_getbitmapinfo()
swf_getfontinfo()
swf_getframe()
swf_labelframe()
swf_lookat()
swf_modifyobject()
swf_mulcolor()
swf_nextid()
swf_oncondition()
swf_openfile()
swf_ortho()
swf_ortho2()
swf_perspective()
swf_placeobject()
swf_polarview()
swf_popmatrix()
swf_posround()
swf_pushmatrix()
swf_removeobject()
swf_rotate()
swf_scale()
swf_setfont()
swf_setframe()
swf_shapearc()
swf_shapecurveto()
swf_shapecurveto3()
swf_shapefillbitmapclip()
swf_shapefillbitmaptile()
swf_shapefilloff()
swf_shapefillsolid()
swf_shapelinesolid()
swf_shapelineto()
swf_shapemoveto()
swf_showframe()
swf_startbutton()
swf_startdoaction()
swf_startshape()
swf_startsymbol()
swf_textwidth()
swf_translate()
swf_viewport()
swfaction()
swfbitmap()
swfbitmap->getheight()
swfbitmap->getwidth()
swfbutton()
swfbutton->addaction()
swfbutton->addshape()
swfbutton->setaction()
swfbutton->setdown()
swfbutton->sethit()
swfbutton->setover()
swfbutton->setup()
swfbutton_keypress()
swfdisplayitem()
swfdisplayitem->addcolor()
swfdisplayitem->move()
swfdisplayitem->moveto()
swfdisplayitem->multcolor()
swfdisplayitem->remove()
swfdisplayitem->rotate()
swfdisplayitem->rotateto()
swfdisplayitem->scale()
swfdisplayitem->scaleto()
swfdisplayitem->setdepth()
swfdisplayitem->setname()
swfdisplayitem->setratio()
swfdisplayitem->skewx()
swfdisplayitem->skewxto()
swfdisplayitem->skewy()
swfdisplayitem->skewyto()
swffill()
swffill->moveto()
swffill->rotateto()
swffill->scaleto()
swffill->skewxto()
swffill->skewyto()
swffont()
swffont->getwidth()
swfgradient()
swfgradient->addentry()
swfmorph()
swfmorph->getshape1()
swfmorph->getshape2()
swfmovie()
swfmovie->add()
swfmovie->nextframe()
swfmovie->output()
swfmovie->remove()
swfmovie->save()
swfmovie->setbackground()
swfmovie->setdimension()
swfmovie->setframes()
swfmovie->setrate()
swfmovie->streammp3()
swfshape()
swfshape->addfill()
swfshape->drawcurve()
swfshape->drawcurveto()
swfshape->drawline()
swfshape->drawlineto()
swfshape->movepen()
swfshape->movepento()
swfshape->setleftfill()
swfshape->setline()
swfshape->setrightfill()
swfsprite()
swfsprite->add()
swfsprite->nextframe()
swfsprite->remove()
swfsprite->setframes()
swftext()
swftext->addstring()
swftext->getwidth()
swftext->moveto()
swftext->setcolor()
swftext->setfont()
swftext->setheight()
swftext->setspacing()
swftextfield()
swftextfield->addstring()
swftextfield->align()
swftextfield->setbounds()
swftextfield->setcolor()
swftextfield->setfont()
swftextfield->setheight()
swftextfield->setindentation()
swftextfield->setleftmargin()
swftextfield->setlinespacing()
swftextfield->setmargins()
swftextfield->setname()
swftextfield->setrightmargin()
sybase_affected_rows()
sybase_close()
sybase_connect()
sybase_data_seek()
sybase_fetch_array()
sybase_fetch_field()
sybase_fetch_object()
sybase_fetch_row()
sybase_field_seek()
sybase_free_result()
sybase_get_last_message()
sybase_min_client_severity()
sybase_min_error_severity()
sybase_min_message_severity()
sybase_min_server_severity()
sybase_num_fields()
sybase_num_rows()
sybase_pconnect()
sybase_query()
sybase_result()
sybase_select_db()
symlink()
syslog()
system()

T

tan()
tanh()
tempnam()
textdomain()
time()
tmpfile()
token_get_all()
token_name()
touch()
trigger_error()
trim()

U

uasort()
ucfirst()
ucwords()
udm_add_search_limit()
udm_alloc_agent()
udm_api_version()
udm_cat_list()
udm_cat_path()
udm_check_charset()
udm_check_stored()
udm_clear_search_limits()
udm_close_stored()
udm_crc32()
udm_errno()
udm_error()
udm_find()
udm_free_agent()
udm_free_ispell_data()
udm_free_res()
udm_get_doc_count()
udm_get_res_field()
udm_get_res_param()
udm_load_ispell_data()
udm_open_stored()
udm_set_agent_param()
uksort()
umask()
uniqid()
unixtojd()
unlink()
unpack()
unregister_tick_function()
unserialize()
unset()
urldecode()
urlencode()
user_error()
usleep()
usort()
utf8_decode()
utf8_encode()

V

var_dump()
var_export()
variant()
version_compare()
virtual()
vpopmail_add_alias_domain()
vpopmail_add_alias_domain_ex()
vpopmail_add_domain()
vpopmail_add_domain_ex()
vpopmail_add_user()
vpopmail_alias_add()
vpopmail_alias_del()
vpopmail_alias_del_domain()
vpopmail_alias_get()
vpopmail_alias_get_all()
vpopmail_auth_user()
vpopmail_del_domain()
vpopmail_del_domain_ex()
vpopmail_del_user()
vpopmail_error()
vpopmail_passwd()
vpopmail_set_user_quota()
vprintf()
vsprintf()

W

w32api_deftype()
w32api_init_dtype()
w32api_invoke_function()
w32api_register_function()
w32api_set_call_method()
wddx_add_vars()
wddx_deserialize()
wddx_packet_end()
wddx_packet_start()
wddx_serialize_value()
wddx_serialize_vars()
wordwrap()

X

xml_error_string()
xml_get_current_byte_index()
xml_get_current_column_number()
xml_get_current_line_number()
xml_get_error_code()
xml_parse()
xml_parse_into_struct()
xml_parser_create()
xml_parser_create_ns()
xml_parser_free()
xml_parser_get_option()
xml_parser_set_option()
xml_set_character_data_handler()
xml_set_default_handler()
xml_set_element_handler()
xml_set_end_namespace_decl_handler()
xml_set_external_entity_ref_handler()
xml_set_notation_decl_handler()
xml_set_object()
xml_set_processing_instruction_handler()
xml_set_start_namespace_decl_handler()
xml_set_unparsed_entity_decl_handler()
xmlrpc_decode()
xmlrpc_decode_request()
xmlrpc_encode()
xmlrpc_encode_request()
xmlrpc_get_type()
xmlrpc_parse_method_descriptions()
xmlrpc_server_add_introspection_data()
xmlrpc_server_call_method()
xmlrpc_server_create()
xmlrpc_server_destroy()
xmlrpc_server_register_introspection_callback()
xmlrpc_server_register_method()
xmlrpc_set_type()
xpath_eval()
xpath_eval_expression()
xpath_new_context()
xptr_eval()
xptr_new_context()
xslt_create()
xslt_errno()
xslt_error()
xslt_free()
xslt_process()
xslt_set_base()
xslt_set_encoding()
xslt_set_error_handler()
xslt_set_log()
xslt_set_sax_handler()
xslt_set_sax_handlers()
xslt_set_scheme_handler()
xslt_set_scheme_handlers()

Y

yaz_addinfo()
yaz_ccl_conf()
yaz_ccl_parse()
yaz_close()
yaz_connect()
yaz_database()
yaz_element()
yaz_errno()
yaz_error()
yaz_hits()
yaz_itemorder()
yaz_present()
yaz_range()
yaz_record()
yaz_scan()
yaz_scan_result()
yaz_search()
yaz_sort()
yaz_syntax()
yaz_wait()
yp_all()
yp_cat()
yp_err_string()
yp_errno()
yp_first()
yp_get_default_domain()
yp_master()
yp_match()
yp_next()
yp_order()

Z

zend_logo_guid()
zend_version()
zip_close()
zip_entry_close()
zip_entry_compressedsize()
zip_entry_compressionmethod()
zip_entry_filesize()
zip_entry_name()
zip_entry_open()
zip_entry_read()
zip_open()
zip_read()

后退 | 起点 | 前进
函数索引 | 上一级 | 补充说明


补充说明

PHP 手册
后退 前进

附录 M. 补充说明

后退 | 起点 | 前进
函数索引 | 上一级 | 微软 HTML 帮助版本


微软 HTML 帮助版本

PHP 手册
后退 前进

VIII. 微软 HTML 帮助版本

目录
59. 关于此版本
60. Using PHP Manual CHM Edition
61. The Full Text Search
62. Specialities of this Edition
63. Integrating the PHP Manual
64. Skin development
65. CHM Edition Credits

后退 | 起点 | 前进
补充说明 |  | 关于此版本


关于此版本

PHP 手册
后退 前进

章 59. 关于此版本

PHP 手册的 Windows HTML Help 版本是针对开发人员的，他们希望每时每刻都有手册在手头，并且不需要等待远程页面下载就可以阅读手册以及用户注解。此版本给你完整的手册内容加上用户注解，以及一些很棒的特色。这是由我们用来生成此格式的脚本产生的阅读程序以及其他人在皮肤样式上的贡献所提供的。

PHP 手册的此发行包中由很多文件组成，包括主要的手册文件 php_manual_zh.chm。你可以通过双击此文件查看本手册（你可能已经猜到了）。用户注解在 php_manual_notes.chm 中。你只需要在你的机器上保留此文件的一个拷贝，不用管用了多少种语言来阅读 PHP 手册。唯一需要的就是将所有的 php_manual_LANG.chm 文件放在 php_manual_notes.chm 同一个目录中。你可能也会在目录中看到 php_manual_zh.chw 文件，该文件是在你第一次使用索引标签时生成的，包含了手册页面的索引。

对那些对 Microsoft HTML Help 的技术细节有兴趣的人来说，http://www.helpware.net/ 是一个很棒的资源。有关 Microsoft 帮助格式和服务历史中的 Windows HTML Help 的更多信息与配置，见 WinWriters article。

后退 | 起点 | 前进
微软 HTML 帮助版本 | 上一级 | Using PHP Manual CHM Edition


Using PHP Manual CHM Edition

PHP 手册
后退 前进

章 60. Using PHP Manual CHM Edition

目录
The HTML Help Toolbar
The Navigation Pane
Keyboard Shortcuts

When you double click on a CHM, a HTML Help Viewer window opens with three panes. On the left side of the window is the Navigation pane. It contains four navigational tabs: the Contents, Index, Search and Favorites tabs. On the right side of the window is the Topic pane. It displays the selected help topic, or the default help topic on startup. The help pages are all separate HTML files, your Internet Explorer displays the pages in the Topic pane. The third pane is the toolbar, which is located below the help window title bar. You can adjust the horizontal layout with dragging the vertical border between the Navigation pane and the Topic pane.

Note, that when you open the CHM the first time, it may appear in a strange position and size. From then, Windows remembers the window position, size and the last opened tab. All these including your favorites are stored in a file named hh.dat. If you move your file to another directory, all these remembered settings will be lost (including your favorites listing!). If you replace your CHM file with a new one, with the same name, this is not a problem though. The file names and path values are stored in hh.dat.

The HTML Help Toolbar

The HTML Help Toolbar contains the following icons, when you view the PHP Manual:

  • Hide/Show - Hides/shows the navigation pane.

  • Locate - Locates a topic in the contents tab (in case you reached a topic with search, index or favorites, and would like to see where it is in the table of contents tree view).

  • Back - Goes back in the history.

  • Forward - Goes forward in the history.

  • Refresh - Reloads the current page.

  • Home - Opens the startup page of the CHM.

  • Print - Opens the print dialog box.

  • Options - Provides a dropdown with more options.

Using this toolbar is really easy, many of the toolbar icons are strongly related to their Internet Explorer equivalents.

后退 | 起点 | 前进
关于此版本 | 上一级 | The Navigation Pane


The Navigation Pane

The Navigation Pane contains four navigational tabs: the Contents, Index, Search and Favorites tabs. These all provide different methods to access a topic in the help file.

  • The contents tab reveals a tree like table of contents, where you can navigate to the desired topic by opening and closing parts of the tree. You can even access the deepest sections using this TOC. If you right click on an item here and choose "Print...", you'll have the option to print the selected topic or the selected topic and all subtopics. However printing is not the initial goal of this representation of the manual (the PDF version is suitable for printing).

  • The index tab lists a huge number of "keywords" (actually manual page titles). You can pick one, or start to type a keyword, see the list adjusting to your input, and then click on a topic, or press enter if the selected topic is the one you would like to see.

  • The search tab shows one of the most powerful features of the HTML Help Viewer, the full text search (also known as FTS). Here you can type in your search expression, optionally connecting words with AND/OR/NEAR/NOT. Before you click 'List topics', you can also set some options at the bottom. After the search results are displayed, you'll realize that manual text and user note results are separated. To sort out the two types, click on the 'Location' column header. Now from the search results list, you can pick a topic, and see it's page. The keywords you searched for are highlighted on the page.

  • The favorites tab enables you to store your most used topics in a list, easily accessible. Here you can see the list, add the current topic to it, remove one, or display a selected item. You can also specify your own title for the favorite, by typing it into the 'Current topic:' box. The user note page titles are prepended with a 'N:' string so you can distinguish them from normal manual pages in the favorites listing.

后退 | 起点 | 前进
Using PHP Manual CHM Edition | 上一级 | Keyboard Shortcuts


Keyboard Shortcuts

There are many keyboard shortcuts you can use to increase your productivity. Many users find it more appropriate to use these keyboard shortcuts to access topics, instead of clicking.

表格 60-1. General Help Viewer Shortcuts

To | Press
Close the Help Viewer | ALT+F4
Display the Options menu | ALT+O
Hide or show the Navigation pane | ALT+O, and then T
Print a topic | ALT+O, and then P
Move back to the previous topic | ALT+LEFT ARROW
Move forward to the next topic (provided you have viewed it just previously) | ALT+RIGHT ARROW
Turn on or off search highlighting. | ALT+O, and then O
Return to the help file home page | ALT+O, and then H
Switch between the Navigation pane and the Topic pane | F6
Scroll through all the links in a topic or through all the options on a Navigation pane tab | TAB
Display context (right click) menu [see the User Preferences section] | SHIFT+F10

表格 60-2. Contents Tab Shortcuts

To | Press
Display the Contents tab | ALT+C
Open and close a book or folder | PLUS SIGN and MINUS SIGN, or LEFT ARROW and RIGHT ARROW
Select a topic | DOWN ARROW and UP ARROW
Display the selected topic | ENTER

表格 60-3. Index Tab Shortcuts

To | Press
Display the Index tab | ALT+N
Type a keyword to search for | ALT+W, and then type the word
Select a keyword in the list | UP ARROW and DOWN ARROW
Display the associated topic | ENTER or ALT+D

表格 60-4. Search Tab shortcuts

To | Press
Display the Search tab | ALT+S
Type a keyword to search for | ALT+W, and then type the word
Start a search | ALT+L
Select a topic in the results list | ALT+T, and then UP ARROW and DOWN ARROW
Display the selected topic | ENTER or ALT+D
Search for a keyword in the result list of a prior search | ALT+U
Search for words similar to the keyword. For example, to find words like "running" and "runs" for the keyword "run" | ALT+M
Only search through topic titles | ALT+R

表格 60-5. Favorites Tab Shortcuts

To | Press
Display the Favorites tab | ALT+I
Add the currently displayed topic to the Favorites list | ALT+A
Select a topic in the Favorites list | ALT+P, and then UP ARROW and DOWN ARROW
Display the selected topic | ENTER or ALT+D
Remove the selected topic from the list | ALT+R

表格 60-6. Topic Pane Shortcuts

To | Press
Index Lookup | Select the words you would like to look up and press F1
Find on page | CTRL+F, and then adjust options
Refresh page | F5

后退 | 起点 | 前进
The Navigation Pane | 上一级 | The Full Text Search


The Full Text Search

PHP 手册
后退 前进

章 61. The Full Text Search

目录
General searching rules
Searching for words or phrases
Defining search terms
Using nested expressions when searching
Manual Content and User Note Separation

This edition of the PHP Manual includes an advanced full text search possibilty provided by the viewer application. This enables users to to search through every word in the help file to find a match. For example, if a user does a full-text search on the word "Apache", every topic that contains the word "Apache" will be listed. Advanced full-text search allows a user to search using boolean, wildcard, and nested expressions. A user can also limit the search to previous results, match similar words, or search topic titles only.

The usage of the search feature is fairly straightforward. Click on the search tab, type in the desired words and press ENTER (or click on "List Topics"). Then you'll receive a list of matches from the PHP Manual (and the notes). You can use the button with a right arrow on it to add boolean operators to your search (or you can type them in). As you see the results, you can use the column headings (Title, Location and Rank) to sort the topic list. The default order is by Rank. You can also adjust some parameters at the bottom of this tab.

The words found are highlighted on the current page in the Topic pane by default. You can turn off this feature by choosing the "Search Highlight Off" menu item in the Options menu. To can get this feature back similarly. If you are viewing a long topic, only the first 500 instances of a search word or phrase will be highlighted, due to a limitation of the viewer.

General searching rules

A basic search consists of the word or phrase you want to find. You can use wildcard expressions, nested expressions, boolean operators, similar word matches, a previous results list, or topic titles to further define your search.

The basic rules for formulating queries are as follows:

  • Searches are not case-sensitive, so you can type your search in uppercase or lowercase characters.

  • You may search for any combination of letters (a-z) and numbers (0-9). You cannot search for single letters (a, b, c, etc.) and common words, like: an, and, as, at, be, but, by, do, for, from, have, he, in, it, not, of, on, or, she, that, the, there, they, this, to, we, which, with, you.

  • Punctuation marks such as the period (.), colon (:), semicolon (;), comma (,), and hyphen (-) are ignored during a search.

  • Group the elements of your search using double quotes or parentheses to set apart each element. You cannot search for quotation marks.

注: If you are searching for a file name with an extension, you should group the entire string in double quotes, ("filename.ext"). Otherwise, the period will break the file name into two separate terms. The default operation between terms is AND, so you will create the logical equivalent to "filename AND ext."

后退 | 起点 | 前进
Keyboard Shortcuts | 上一级 | Searching for words or phrases


Searching for words or phrases

You can search for words or phrases and use wildcard expressions. Wildcard expressions allow you to search for one or more characters using a question mark or asterisk. The table below describes the results of these different kinds of searches.

表格 61-1. Word and phrase searches

Search for | Example | Results
A single word | select | Topics that contain the word "select". (You will also find its grammatical variations, such as "selector" and "selection".)
A phrase "new operator" or new operator

Topics that contain the literal phrase "new operator" and all its grammatical variations.

Without the quotation marks, the query is equivalent to specifying "new AND operator," which will find topics containing both of the individual words, instead of the phrase.

Wildcard expressions esc* or HT??

Results for the first example include topics that contain the terms "ESC", "escape", "escalation", and so on. The asterisk cannot be the only character in the term.

Results for the second example include topics that contain the terms "HTTP", "HTML" and so on. The question mark cannot be the only character in the term.

注: Select the Match similar words check box to include minor grammatical variations for the phrase you search. This feature only locates variations of the word with common suffixes. For example, a search on the word "add" will find "added," but it will not find "additive". This option is independent of other options or syntax. If you do a titles-only search, variations in titles will be matched. If you use quotes (or any other query operator) any variation of the word can appear; for example, "stemmed search" will also match "stemming search".

后退 | 起点 | 前进
The Full Text Search | 上一级 | Defining search terms


Defining search terms

The AND, OR, NOT, and NEAR operators enable you to precisely define your search by creating a relationship between search terms. The following table shows how you can use each of these operators. If no operator is specified, AND is used. For example, the query "server cgi security" is equivalent to "server AND cgi AND security".

表格 61-2. Search operators

Search for | Example | Results
Both terms in the same topic | http AND apache | Topics containing both the words "http" and "apache".
Either term in a topic | ming OR swflib | Topics containing either the word "ming" or the word "swflib" or both.
The first term without the second term | xml NOT expat | Topics containing the word "xml" but not the word "expat".
Both terms in the same topic, close together | database NEAR security | Topics containing the word "database" within eight words of the word "security".

注: The |, &, and ! characters can also be used in place of OR AND and NOT respectively. This may not work if you use a very old version of the viewer.

后退 | 起点 | 前进
Searching for words or phrases | 上一级 | Using nested expressions when searching


Using nested expressions when searching

Nested expressions allow you to create complex searches for information. For example, "html AND ((smtp OR pop3) NEAR mail)" finds topics containing the word "html" along with the words "smtp" and "mail" close together, or containing "html" along with the words "pop3" and "mail" close together.

The basic rules for searching help topics using nested expressions are as follows:

  • You can use parentheses to nest expressions within a query. The expressions in parentheses are evaluated before the rest of the query.

  • If a query does not contain a nested expression, it is evaluated from left to right. For example: "mail NOT pop3 OR smtp" finds topics containing the word "mail" without the word "pop3" or topics containing the word "smtp". On the other hand, "mail NOT (pop3 OR smtp)" finds topics containing the word "mail" without either of the words "pop3" or "smtp".

  • You cannot nest expressions more than five levels deep.

后退 | 起点 | 前进
Defining search terms | 上一级 | Manual Content and User Note Separation


Manual Content and User Note Separation

The manual content and the user notes are separated to php_manual_LANG.chm and php_manual_notes.chm. There were several resons to do this, including:

  • This way you can update the user notes and the manual independently as you need.

  • You can have more than one language of the manual, while only need to have one notes file. All the CHM files need to be in the same directory, and all translations need to share the same preferences if you would not like to have more then one notes file.

  • You can bookmark manual pages with notes, or just a notes part of a page separately.

  • You can "turn off" user note display and user note search results by simply deleting php_manual_notes.chm, moving it out of the directory or renaming it.

All these benefits lead us to provide the manual the way you can see it right now. This distribution had the effect on the full text search that you get search results from the manual content and from the user notes as separate ones. The "Location" column shows the source of the result, also enabling you to "add precedence" to manual content results with ordering the results by "Location". User note page titles are also prefixed with "N:" to make them easily distinguisable in the favorites list (there's no location info in the favorites list).

后退 | 起点 | 前进
Using nested expressions when searching | 上一级 | Specialities of this Edition


Specialities of this Edition

PHP 手册
后退 前进

章 62. Specialities of this Edition

目录
User Preferences
Presentational Specialities

The Windows HTML Help Edition of the PHP Manual overperforms the presentational and interactive capabilities offered by other editions (including the online manual). This was possible because currently CHMs can only be viewed on Windows using Internet explorer, so we can develop for one browser family and one operating system. Viewers for other OSes may be developed in the future by third parties.

User Preferences

Most of the interactive features of this manual are provided by the viewer application (including full text search, index, favorites list), but we extended this list with PHP Manual specific tools. All these can be adjusted to your needs using a simple desktop application named php_manual_prefs.exe. If you run this program you can see three groups of settings: Online Functions, Context Menu, and Skin. All your settings are stored in php_manual_prefs.js.

Online functions enable you to have elements connected to websites. The two ones you can see on all manual pages are "This page online" and "Report a bug". As you can figure out the first one shows you the same page in the online manual, the second one opens a page from http://bugs.php.net/ and prefills some bug data for you. You need to select a mirror site to use for "php.net sensitive" online functions. We recommend choosing a close mirror site to get the best speed. Other components that may be limited by this online functions setting include context menu items opening new websites ("Google search selection" for example). Custom designs may also include elements restricted by this setting.

The context menu settings enables you to choose which context menu you prefer. This application provides you with an option to define your own context menu adding elements to it from a predefined set. You can have this custom context menu for the right click of your mouse, and have the original menu for CTRL+right click, or the opposite way. Three special types of custom context menu items exist:

表格 62-1. Context menu items

Type | Examples | Comments
Page Jump | Function Reference, Function Index | These items jump to a specific page in the CHM. Page Jump options are not restricted to point inside the CHM though. They can point to websites or other resources. Page jump options with a protocol part in the URL open in new window.
Function Call | Print page, Select all, Copy selection to clipboard, Google Search Selection | These are "function calls" for internally defined context menu functions. The last two examples have the speciality that they only show up in the menu if you rightclicked on a selection. Currently there is no way to extend the context menu with skin defined functions.
Special display | Google SearchBox, AlltheWeb SearchBox | These are displayed as HTML forms, where you can enter search keywords, press ENTER, and receive a new window with the search issued in the appropriate search engine. Currently there is no way to extend the set of specialy displayed context menu items.
Possible context menu elements and their "abstract implementations" are stored in context.ini. You have the ability to add possible page jump options there, but there is no way currently to extend the context menu system with user (skin) defined functions. The possible mirror sites are listed in mirrors.ini. Feel free to suggest more bundled context menu items to us at php-doc-chm@lists.php.net.

The skins setting enables you to choose from the two bundled default skins, or from any user defined skins. The Low skin is optimized to display correctly at any small size, the High skin is optimized for your viewing pleasure. Other skins may be developed according to our skins development guide. The recommended place for skins on the file system is the skins/SKINNAME subfolder of the PHP Manual directory. Though this is not required, some skins may define other rules (not recommended). We included sample skins for you to see examples of how to develop skins for the PHP Manual.

You have three buttons to choose from at the bottom. The Apply button applies your changes without exiting, the OK button applies and closes the application, the Cancel button does not modify your settings and closes the program.

后退 | 起点 | 前进
Manual Content and User Note Separation | 上一级 | Presentational Specialities


Presentational Specialities

This edition of the PHP Manual is highly optimized for screen presentation. Skins may be developed to better support printing, as this was not the goal of the included skins. This approach allowed us to make many modifications to the presentation of different parts of the manual.

The first thing you'll notice is that all examples are color coded, using the PHP function show_source(). The actual colors used are defined by CSS classes. Examples also have links to PHP functions used in them to provide quick access to reference material. All code examples have a "copy to clipboard" link by the side of them with which you can copy the text contents of the example to the clipboard.

External links are marked with a special » sign, and open in a new browser window. We also included the "path to this page" information on all pages for you to easily identify where you are and navigate as needed.

Other parts of the manual are quite similar to the online ones by default, though custom skins can modify many elements on the pages.

后退 | 起点 | 前进
Specialities of this Edition | 上一级 | Integrating the PHP Manual


Integrating the PHP Manual

PHP 手册
后退 前进

章 63. Integrating the PHP Manual

注: The information provided here is mainly aimed at IDE authors, or advanced users who would like to integrate this CHM file to their favorite IDEs or other production environment components.

There are several editors out there with support for CHM integration, but you may need to know a few things about what the CHM contains to successfully integrate the manual into your environment.

The CHM is built using XSL style sheets from XML sources. This is unique currently in the PHP Manual family, as all other versions are generated using DSSSL style sheets. This also means, that non-intentional rendering differences may come up. A special conversion script is run on the XSLT output, adding several cute features, and packing up the manual with the preferences files and skin examples.

If you never worked with CHMs, you can think of them as compressed files with OS supported access for files inside and some added search and index support. However CHMs can only be viewed using the HTML Help Viewer, you can directly access files inside them using a special URL prefix, the CHM file name and the file you request from inside. As all the help content is stored in HTML files, you can show pages of the CHM in Internet Explorer.

Assume that you placed your php_manual_en.chm to c:\phpmanual the index file in the manual (which you see the first time) can be accessed with the following URL: mk:@MSITStore:C:\phpmanual\php_manual_en.chm::/_index.html. Here mk:@MSITStore: is the special "protocol", C:\phpmanual\php_manual_en.chm is the CHM with it's full path. The /_index.html part is the path to the index file inside the CHM and :: is just what you need to put between the CHM path and this file path.

注: All files are in the root directory of the CHM, unlike the previous CHM versions which included a language directory. Images, style sheets and other supplemental files have names starting with an underscore (like the main index shown above), to avoid name colissions.

The names of generated files follow the same rules as the online manual, except that the extension is .html and not .php. The most important is that function documentation files are named function.FUNCNAME.html where FUNCNAME is the function name, with all underscores converted to hyphens. Some examples are function.echo.html, function.mysql-close.html, function.imagecopy.html.

Using all this information, you can show a manual page for a function requested by a user. A simple example is included in the distribution, named php_quickref.hta. This is a HTML Application to demonstrate the simple process of showing a manual page for a function. The quickRef() function defined therein does the job.

The index of the manual (accessible via the index tab on the navigation pane) can also be used for integrational purposes. All the HTML pages are included in the index with their titles as index terms (including function description pages).

If you are a desktop application developer and would like to tightly integrate the CHM into your program (such as displaying the TOC tree in your IDE's help box), you can find more information at http://www.helpware.net/, as well as links to other useful resources. The official site for HTML Help is at http://msdn.microsoft.com/library/en-us/htmlhelp/html/vsconhh1start.asp.

后退 | 起点 | 前进
Presentational Specialities | 上一级 | Skin development


Skin development

PHP 手册
后退 前进

章 64. Skin development

目录
Page Display Process
Page Elements
CSS classes

This edition of the PHP Manual allows users to choose from skins to display the contents, as well as develop custom skins to meet some special needs. We decided to support skins because we realized that one skin cannot satisfy everybodies needs in a such heavily used edition.

We included two skins by default inside the CHM. These cannot be modified or removed, so if you have the CHM, you have these two skins inside. The Low skin is optimized for small window display, the High skin is a variation of the Low one with some graphics added to spice it up.

A skin must have at least two files, a skin loader JavaScript file and a CSS file. The two inline skins have these files inside the CHM. The skin loader JS should at least load in the CSS file and display the page contents to the viewer. Theoretically there are two kinds of skins: CSS skins and Full skins. CSS skins only modify the CSS and does not amend the page layout. Full skins also modify the page layout. We have included sample skins for both the CSS skin type and the Full skin type ("greenlinks" and "headernostalgia" respectively).

警告

Note that though the current skin development methods are quite final, there may be heavy changes in used CSS classes or page elements while we refine the skin development ideas. As this edition is currently in development stage, the information described herein is not to be considered completely stable.

Page Display Process

If you are going to develop your own skin, you should know how one page is loaded and displayed to the user, and how a skin fits in this process. For these paragraphs, we assume that you have put your CHM into c:\phpmanual, so it's accessible as c:\phpmanual\php_manual_LANG.chm (where LANG is the language code), and you would like to see the function page of "echo", which is function.echo.html inside the CHM. See the sections about integration for more information on CHM contents.

  • First of all the HTML content is loaded in from function.echo.html from inside the CHM.

  • At the top of this file, there is a HTML <script> tag, which loads in the _script.js file from the CHM. This file contains all the JS code needed to move on with the process. Most importantly this JS defines many variables (like where the CHM is, or what is the actual page viewed) and many functions to print out the context menu or handle online functions.

  • At last _script.js loads in the preferences file from outside the CHM (c:\phpmanual\php_manual_prefs.js in our example). This JS file defines the preference variables, and calls back prefHandler() which is also defined in _script.js.

  • That function loads in the skin JS file as the preferences dictate. The sknin JS file should load in the needed CSS file, and define a displayPage() function, which displays the page if called.

  • The HTML file (function.echo.html in this example) also contains a function call to load in the user notes, which simply puts the notes into this HTML file using DHTML to be displayed as if they were here before...

  • The HTML file also contains a body onload attribute which calls the skin-defined displayPage() function to show the page to the user. This is the last function called, it should present the page in it's complete form to the user.

Every action is syncronized with calling back a function in the previously loaded file when the JS is in memory. The notes loading and skin JS loading is only syncronized with the page's onload event (which as the Microsoft documentation says only fires if the page is completely loaded).

This load and callback chain may seem to be too complicated, but so far this seemed to be the best way to do as many things as possible paralelly, while also syncronize some calls.

As you can see your skin JavaScript file is loaded in by _script.js and it's displayPage() function is called by the body onload event.

后退 | 起点 | 前进
Integrating the PHP Manual | 上一级 | Page Elements


Page Elements

The PHP Manual pages are all HTML files with several HTML tags in them for both presentational and divisional purposes. The HTML pages contain divisions to be used for skinning purposes and misc divisions added by the DocBook XSL sheets.

A HTML page can be either a function reference page or another kind of page (like a feature description). Skins should get ready to skin these two kinds of pages separately most of the time (depending on the actual design).

The pages are structured using <div> tags with appropriate IDs to ease the skin writers work. A page consists of these parts:

  • <div id="pageContent"></div> contains all the page contents. This begins right after <body> and ends just before </body>. This division is hidden by default, you need to show it after you are ready with the page rewriting process.

  • <div id="pageHeaders"></div> contains the page header parts. This includes the text only main title (in a <span id="pageTitle"></span>) and function properties, in case this is a function page (contained in <span id="funcPurpose"></span>, <span id="funcAvail"></span> and <span id="funcUsage"></span>). In case one of these three is not available, the current page is not a function page.

  • <div id="pageText"></div> contains the majority of the page contents, including examples, manual notes, warnings, etc. This also includes see also parts for now, as we still cannot differentiate between see also and normal text parts (may be a thing to change in the future).

  • <div id="pageNotes"></div> contains the user notes (itself loaded in from another HTML file by JS). It contains a heading, and then a <div> without ID for every user note and spans in that divs for every element of a user note (with "email", "date" and "text" IDs respectively).

  • <div id="pageNav"></div> contains the
navigation table, which is further divided into spans (<span
id="navPrev"></span>, <span
id="navPath"></span>, <span
id="navNext"></span>, <span
id="navOnline"></span>, <span
id="navThisOnline"></span> and <span
id="navReportBug"></span>), where navThisOnline
and navReportBug is inside navOnline.

If you would like to rewrite the page, you should first read in the parts you need from the page to JS variables, then clear the contents of pageContent (or just the part you would like to rewrite), write in the new content and show the pageContent div for the user. If you would not like to make any structural changes, you can simply display the pageContent div and only specify a special style sheet in your skin JS file (see the "greenlinks" skin for an example).

You can find a "Full skin" developed to show you how to make skins built on top of this structure. The skin name is "headernostalgia". It rewrites the header part and removes the footer navigational table.

后退 | 起点 | 前进
Skin development | 上一级 | CSS classes


CSS classes

We cannot provide accurate documentation currently on useable CSS classes, as some of the DocBook XSL sheets classes are not used and some classes are added. Please see the sample CSS files included for first time reference.

后退 | 起点 | 前进
Page Elements | 上一级 | CHM Edition Credits


CHM Edition Credits

PHP 手册
后退

章 65. CHM Edition Credits

This enhanced version of the PHP Manual would never come to existance, if the following people would not help with their contribution to the project (in no particular order):

  • Holger Eggert, who created the two default designs, and provided many useability tips

  • Gonzalo De la Pena Andreu, who added many comments on how it would be ideal to provide the skinnable interface

  • Olexandr Vynnychenko added countless comments and testing all the time

  • Brendan Ferguson, who provided many optimizations, improvements to the HTML and JS codes behind the manual pages

  • Sandor Hojtsy, who coded the manual preferences desktop application

  • And at last but not least, everybody, who provided feedback through our mailing list, and in the user survey

后退 | 起点
CSS classes | 上一级


PHP 手册

版权信息

© Copyright 1997, 1998, 1999, 2000, 2001, 2002 本手册版权归 PHP Documentation Group 所有。本手册首页上列出了 PHP 文档小组的成员列表。

该手册如同由自由软件基金会发布一样，在 GNU 的常规公共许可协议之下同样可以重新发布。包括许可协议的第二版，以及任何的后续版本。

本手册“Extending PHP 4.0”有关章节的版权归 © 2000 Zend Technologies, Ltd 所有。发布本资料须遵守开放出版物许可协议 1.0 或者更新的版本中所宣布的条款（在 http://www.opencontent.org/openpub/ 可获得最新的版本）。

起点


内核预定义常量

内核预定义常量 -- 在 PHP 内核、Zend 和 SAPI 模块中定义的常量

描述

这些常量在 PHP 的内核中定义。它包含 PHP、Zend 引擎和 SAPI 模块。

PHP_VERSION (string)

PHP_OS (string)

DEFAULT_INCLUDE_PATH (string)

PEAR_INSTALL_DIR (string)

PEAR_EXTENSION_DIR (string)

PHP_EXTENSION_DIR (string)

PHP_BINDIR (string)

PHP_LIBDIR (string)

PHP_DATADIR (string)

PHP_SYSCONFDIR (string)

PHP_LOCALSTATEDIR (string)

PHP_CONFIG_FILE_PATH (string)

PHP_OUTPUT_HANDLER_START (integer)

PHP_OUTPUT_HANDLER_CONT (integer)

PHP_OUTPUT_HANDLER_END (integer)

E_ERROR (integer)

E_WARNING (integer)

E_PARSE (integer)

E_NOTICE (integer)

E_CORE_ERROR (integer)

E_CORE_WARNING (integer)

E_COMPILE_ERROR (integer)

E_COMPILE_WARNING (integer)

E_USER_ERROR (integer)

E_USER_WARNING (integer)

E_USER_NOTICE (integer)

E_ALL (integer)

后退 | 起点 | 前进
预定义常量 | 上一级 | 标准预定义常量


标准预定义常量

标准预定义常量 -- PHP 中默认定义的常量

描述

这些常量是 PHP 默认定义的。

EXTR_OVERWRITE (integer)

EXTR_SKIP (integer)

EXTR_PREFIX_SAME (integer)

EXTR_PREFIX_ALL (integer)

EXTR_PREFIX_INVALID (integer)

EXTR_PREFIX_IF_EXISTS (integer)

EXTR_IF_EXISTS (integer)

SORT_ASC (integer)

SORT_DESC (integer)

SORT_REGULAR (integer)

SORT_NUMERIC (integer)

SORT_STRING (integer)

CASE_LOWER (integer)

CASE_UPPER (integer)

COUNT_NORMAL (integer)

COUNT_RECURSIVE (integer)

ASSERT_ACTIVE (integer)

ASSERT_CALLBACK (integer)

ASSERT_BAIL (integer)

ASSERT_WARNING (integer)

ASSERT_QUIET_EVAL (integer)

CONNECTION_ABORTED (integer)

CONNECTION_NORMAL (integer)

CONNECTION_TIMEOUT (integer)

INI_USER (integer)

INI_PERDIR (integer)

INI_SYSTEM (integer)

INI_ALL (integer)

M_E (float)

M_LOG2E (float)

M_LOG10E (float)

M_LN2 (float)

M_LN10 (float)

M_PI (float)

M_PI_2 (float)

M_PI_4 (float)

M_1_PI (float)

M_2_PI (float)

M_2_SQRTPI (float)

M_SQRT2 (float)

M_SQRT1_2 (float)

CRYPT_SALT_LENGTH (integer)

CRYPT_STD_DES (integer)

CRYPT_EXT_DES (integer)

CRYPT_MD5 (integer)

CRYPT_BLOWFISH (integer)

DIRECTORY_SEPARATOR (integer)

SEEK_SET (integer)

SEEK_CUR (integer)

SEEK_END (integer)

LOCK_SH (integer)

LOCK_EX (integer)

LOCK_UN (integer)

LOCK_NB (integer)

HTML_SPECIALCHARS (integer)

HTML_ENTITIES (integer)

ENT_COMPAT (integer)

ENT_QUOTES (integer)

ENT_NOQUOTES (integer)

INFO_GENERAL (integer)

INFO_CREDITS (integer)

INFO_CONFIGURATION (integer)

INFO_MODULES (integer)

INFO_ENVIRONMENT (integer)

INFO_VARIABLES (integer)

INFO_LICENSE (integer)

INFO_ALL (integer)

CREDITS_GROUP (integer)

CREDITS_GENERAL (integer)

CREDITS_SAPI (integer)

CREDITS_MODULES (integer)

CREDITS_DOCS (integer)

CREDITS_FULLPAGE (integer)

CREDITS_QA (integer)

CREDITS_ALL (integer)

STR_PAD_LEFT (integer)

STR_PAD_RIGHT (integer)

STR_PAD_BOTH (integer)

PATHINFO_DIRNAME (integer)

PATHINFO_BASENAME (integer)

PATHINFO_EXTENSION (integer)

CHAR_MAX (integer)

LC_CTYPE (integer)

LC_NUMERIC (integer)

LC_TIME (integer)

LC_COLLATE (integer)

LC_MONETARY (integer)

LC_ALL (integer)

LC_MESSAGES (integer)

ABDAY_1 (integer)

ABDAY_2 (integer)

ABDAY_3 (integer)

ABDAY_4 (integer)

ABDAY_5 (integer)

ABDAY_6 (integer)

ABDAY_7 (integer)

DAY_1 (integer)

DAY_2 (integer)

DAY_3 (integer)

DAY_4 (integer)

DAY_5 (integer)

DAY_6 (integer)

DAY_7 (integer)

ABMON_1 (integer)

ABMON_2 (integer)

ABMON_3 (integer)

ABMON_4 (integer)

ABMON_5 (integer)

ABMON_6 (integer)

ABMON_7 (integer)

ABMON_8 (integer)

ABMON_9 (integer)

ABMON_10 (integer)

ABMON_11 (integer)

ABMON_12 (integer)

MON_1 (integer)

MON_2 (integer)

MON_3 (integer)

MON_4 (integer)

MON_5 (integer)

MON_6 (integer)

MON_7 (integer)

MON_8 (integer)

MON_9 (integer)

MON_10 (integer)

MON_11 (integer)

MON_12 (integer)

AM_STR (integer)

PM_STR (integer)

D_T_FMT (integer)

D_FMT (integer)

T_FMT (integer)

T_FMT_AMPM (integer)

ERA (integer)

ERA_YEAR (integer)

ERA_D_T_FMT (integer)

ERA_D_FMT (integer)

ERA_T_FMT (integer)

ALT_DIGITS (integer)

INT_CURR_SYMBOL (integer)

CURRENCY_SYMBOL (integer)

CRNCYSTR (integer)

MON_DECIMAL_POINT (integer)

MON_THOUSANDS_SEP (integer)

MON_GROUPING (integer)

POSITIVE_SIGN (integer)

NEGATIVE_SIGN (integer)

INT_FRAC_DIGITS (integer)

FRAC_DIGITS (integer)

P_CS_PRECEDES (integer)

P_SEP_BY_SPACE (integer)

N_CS_PRECEDES (integer)

N_SEP_BY_SPACE (integer)

P_SIGN_POSN (integer)

N_SIGN_POSN (integer)

DECIMAL_POINT (integer)

RADIXCHAR (integer)

THOUSANDS_SEP (integer)

THOUSEP (integer)

GROUPING (integer)

YESEXPR (integer)

NOEXPR (integer)

YESSTR (integer)

NOSTR (integer)

CODESET (integer)

LOG_EMERG (integer)

LOG_ALERT (integer)

LOG_CRIT (integer)

LOG_ERR (integer)

LOG_WARNING (integer)

LOG_NOTICE (integer)

LOG_INFO (integer)

LOG_DEBUG (integer)

LOG_KERN (integer)

LOG_USER (integer)

LOG_MAIL (integer)

LOG_DAEMON (integer)

LOG_AUTH (integer)

LOG_SYSLOG (integer)

LOG_LPR (integer)

LOG_NEWS (integer)

LOG_UUCP (integer)

LOG_CRON (integer)

LOG_AUTHPRIV (integer)

LOG_LOCAL0 (integer)

LOG_LOCAL1 (integer)

LOG_LOCAL2 (integer)

LOG_LOCAL3 (integer)

LOG_LOCAL4 (integer)

LOG_LOCAL5 (integer)

LOG_LOCAL6 (integer)

LOG_LOCAL7 (integer)

LOG_PID (integer)

LOG_CONS (integer)

LOG_ODELAY (integer)

LOG_NDELAY (integer)

LOG_NOWAIT (integer)

LOG_PERROR (integer)

后退 | 起点 | 前进
内核预定义常量 | 上一级 | 资源类型列表


Stream open options

Stream open options -- Affects the operation of stream factory functions

Description

One or more of these values can be combined using the OR operator.

IGNORE_PATH

This is the default option for streams; it requests that the include_path is not to be searched for the requested file.

USE_PATH

Requests that the include_path is to be searched for the requested file.

IGNORE_URL

Requests that registered URL wrappers are to be ignored when opening the stream. Other non-URL wrappers will be taken into consideration when decoding the path. There is no opposite form for this flag; the streams API will use all registered wrappers by default.

IGNORE_URL_WIN

On Windows systems, this is equivalent to IGNORE_URL. On all other systems, this flag has no effect.

ENFORCE_SAFE_MODE

Requests that the underlying stream implementation perform safe_mode checks on the file before opening the file. Omitting this flag will skip safe_mode checks and allow opening of any file that the PHP process has rights to access.

REPORT_ERRORS

If this flag is set, and there was an error during the opening of the file or URL, the streams API will call the php_error function for you. This is useful because the path may contain username/password information that should not be displayed in the browser output (it would be a security risk to do so). When the streams API raises the error, it first strips username/password information from the path, making the error message safe to display in the browser.

STREAM_MUST_SEEK

This flag is useful when your extension really must be able to randomly seek around in a stream. Some streams may not be seekable in their native form, so this flag asks the streams API to check to see if the stream does support seeking. If it does not, it will copy the stream into temporary storage (which may be a temporary file or a memory stream) which does support seeking. Please note that this flag is not useful when you want to seek the stream and write to it, because the stream you are accessing might not be bound to the actual resource you requested.

注: If the requested resource is network based, this flag will cause the opener to block until the whole contents have been downloaded.

STREAM_WILL_CAST

If your extension is using a third-party library that expects a FILE* or file descriptor, you can use this flag to request the streams API to open the resource but avoid buffering. You can then use php_stream_cast() to retrieve the FILE* or file descriptor that the library requires.

The is particularly useful when accessing HTTP URLs where the start of the actual stream data is found after an indeterminate offset into the stream.

Since this option disables buffering at the streams API level, you may experience lower performance when using streams functions on the stream; this is deemed acceptable because you have told streams that you will be using the functions to match the underlying stream implementation. Only use this option when you are sure you need it.

后退 | 起点 | 前进
Streams Constants | 上一级 | FAQ: 常见问题


php_register_url_stream_wrapper

(no version information, might be only in CVS)

php_register_url_stream_wrapper -- Registers a wrapper with the Streams API

Description

int php_register_url_stream_wrapper ( char * protocol, php_stream_wrapper * wrapper, TSRMLS_DC )

php_register_url_stream_wrapper() registers wrapper as the handler for the protocol specified by protocol.

注: If you call this function from a loadable module, you *MUST* call php_unregister_url_stream_wrapper() in your module shutdown function, otherwise PHP will crash.

后退 | 起点 | 前进
php_stream_passthru | 上一级 | php_unregister_url_stream_wrapper


php_stream_can_cast

(no version information, might be only in CVS)

php_stream_can_cast -- Determines if a stream can be converted into another form, such as a FILE* or socket

Description

int php_stream_can_cast ( php_stream * stream, int castas)

This function is equivalent to calling php_stream_cast() with ret set to NULL and flags set to 0. It returns SUCCESS if the stream can be converted into the form requested, or FAILURE if the conversion cannot be performed.

注: Although this function will not perform the conversion, some internal stream state *might* be changed by this call.

注: You must explicity compare the return value of this function with one of the constants, as described in php_stream_cast().

See also php_stream_cast() and php_stream_is().

后退 | 起点 | 前进
php_stream_cast | 上一级 | php_stream_is_persistent


php_stream_cast

(no version information, might be only in CVS)

php_stream_cast -- Convert a stream into another form, such as a FILE* or socket

Description

int php_stream_cast ( php_stream * stream, int castas, void ** ret, int flags)

php_stream_cast() attempts to convert stream into a resource indicated by castas. If ret is NULL, the stream is queried to find out if such a conversion is possible, without actually performing the conversion (however, some internal stream state *might* be changed in this case). If flags is set to REPORT_ERRORS, an error message will be displayed is there is an error during conversion.

注: This function returns SUCCESS for success or FAILURE for failure. Be warned that you must explicitly compare the return value with SUCCESS or FAILURE because of the underlying values of those constants. A simple boolean expression will not be interpreted as you intended.

表格 45-1. Resource types for castas

Value | Meaning
PHP_STREAM_AS_STDIO | Requests an ANSI FILE* that represents the stream
PHP_STREAM_AS_FD | Requests a POSIX file descriptor that represents the stream
PHP_STREAM_AS_SOCKETD | Requests a network socket descriptor that represents the stream

In addition to the basic resource types above, the conversion process can be altered by using the following flags by using the OR operator to combine the resource type with one or more of the following values:

表格 45-2. Resource types for castas

Value | Meaning
PHP_STREAM_CAST_TRY_HARD | Tries as hard as possible, at the expense of additional resources, to ensure that the conversion succeeds
PHP_STREAM_CAST_RELEASE | Informs the streams API that some other code (possibly a third party library) will be responsible for closing the underlying handle/resource. This causes the stream to be closed in such a way the underlying handle is preserved and returned in ret. If this function succeeds, stream should be considered closed and should no longer be used.

注: If your system supports fopencookie() (systems using glibc 2 or later), the streams API will always be able to synthesize an ANSI FILE* pointer over any stream. While this is tremendously useful for passing any PHP stream to any third-party libraries, such behaviour is not portable. You are requested to consider the portability implications before distributing you extension. If the fopencookie synthesis is not desireable, you should query the stream to see if it naturally supports FILE* by using php_stream_is()

注: If you ask a socket based stream for a FILE*, the streams API will use fdopen() to create it for you. Be warned that doing do may cause data that was buffered in the streams layer to be lost if you intermix streams API calls with ANSI stdio calls.

See also php_stream_is() and php_stream_can_cast().

后退 | 起点 | 前进
php_stream_make_seekable | 上一级 | php_stream_can_cast


php_stream_close

(no version information, might be only in CVS)

php_stream_close -- Close a stream

Description

int php_stream_close ( php_stream * stream)

php_stream_close() safely closes stream and releases the resources associated with it. After stream has been closed, it's value is undefined and should not be used.

php_stream_close() returns 0 if the stream was closed or EOF to indicate an error. Regardless of the success of the call, stream is undefined and should not be used after a call to this function.

后退 | 起点 | 前进
php_stream_gets | 上一级 | php_stream_flush


php_stream_closedir

(no version information, might be only in CVS)

php_stream_closedir -- Close a directory stream and release resources

Description

int php_stream_closedir ( php_stream * dirstream)

php_stream_closedir() closes a directory stream and releases resources associated with it. Returns 0 on success, but -1 on failure.

后退 | 起点 | 前进
php_stream_rewinddir | 上一级 | Streams File API Reference


php_stream_copy_to_mem

(no version information, might be only in CVS)

php_stream_copy_to_mem -- Copy data from stream and into an allocated buffer

Description

size_t php_stream_copy_to_mem ( php_stream * src, char ** buf, size_t maxlen, int persistent)

php_stream_copy_to_mem() allocates a buffer maxlen+1 bytes in length using pemalloc() (passing persistent). It then reads maxlen bytes from src and stores them in the allocated buffer.

The allocated buffer is returned in buf, and the number of bytes successfully read. You, the caller, are responsible for freeing the buffer by passing it and persistent to pefree().

If you want to copy all remaining data from the src stream, pass the constant PHP_STREAM_COPY_ALL as the value of maxlen.

注: This function will attempt to copy the data in the most efficient manner, using memory mapped files when possible.

后退 | 起点 | 前进
php_stream_copy_to_stream | 上一级 | php_stream_make_seekable


php_stream_copy_to_stream

(no version information, might be only in CVS)

php_stream_copy_to_stream -- Copy data from one stream to another

Description

size_t php_stream_copy_to_stream ( php_stream * src, php_stream * dest, size_t maxlen)

php_stream_copy_to_stream() attempts to read up to maxlen bytes of data from src and write them to dest, and returns the number of bytes that were successfully copied.

If you want to copy all remaining data from the src stream, pass the constant PHP_STREAM_COPY_ALL as the value of maxlen.

注: This function will attempt to copy the data in the most efficient manner, using memory mapped files when possible.

后退 | 起点 | 前进
php_stream_tell | 上一级 | php_stream_copy_to_mem


php_stream_eof

(no version information, might be only in CVS)

php_stream_eof -- Check for an end-of-file condition on a stream

Description

int php_stream_eof ( php_stream * stream)

php_stream_eof() checks for an end-of-file condition on stream.

php_stream_read() returns the 1 to indicate EOF, 0 if there is no EOF and -1 to indicate an error.

后退 | 起点 | 前进
php_stream_write | 上一级 | php_stream_getc


php_stream_flush

(no version information, might be only in CVS)

php_stream_flush -- Flush stream buffers to storage

Description

int php_stream_flush ( php_stream * stream)

php_stream_flush() causes any data held in write buffers in stream to be committed to the underlying storage.

php_stream_flush() returns 0 if the buffers were flushed, or if the buffers did not need to be flushed, but returns EOF to indicate an error.

后退 | 起点 | 前进
php_stream_close | 上一级 | php_stream_seek


php_stream_fopen_from_file

(no version information, might be only in CVS)

php_stream_fopen_from_file -- Convert an ANSI FILE* into a stream

Description

php_stream * php_stream_fopen_from_file ( FILE * file, char * mode)

php_stream_fopen_from_file() returns a stream based on the file. mode must be the same as the mode used to open file, otherwise strange errors may occur when trying to write when the mode of the stream is different from the mode on the file.

后退 | 起点 | 前进
Streams File API Reference | 上一级 | php_stream_fopen_tmpfile


php_stream_fopen_temporary_file

(no version information, might be only in CVS)

php_stream_fopen_temporary_file -- Generate a temporary file name and open a stream on it

Description

php_stream * php_stream_fopen_temporary_file ( const char * dir, const char * pfx, char ** opened)

php_stream_fopen_temporary_file() generates a temporary file name in the directory specified by dir and with a prefix of pfx. The generated file name is returns in the opened parameter, which you are responsible for cleaning up using efree(). A stream is opened on that generated filename in "w+b" mode. The file is NOT automatically deleted; you are responsible for unlinking or moving the file when you have finished with it.

后退 | 起点 | 前进
php_stream_fopen_tmpfile | 上一级 | Streams Socket API Reference


php_stream_fopen_tmpfile

(no version information, might be only in CVS)

php_stream_fopen_tmpfile -- Open a FILE* with tmpfile() and convert into a stream

Description

php_stream * php_stream_fopen_tmpfile ( void )

php_stream_fopen_from_file() returns a stream based on a temporary file opened with a mode of "w+b". The temporary file will be deleted automatically when the stream is closed or the process terminates.

后退 | 起点 | 前进
php_stream_fopen_from_file | 上一级 | php_stream_fopen_temporary_file


php_stream_getc

(no version information, might be only in CVS)

php_stream_getc -- Read a single byte from a stream

Description

int php_stream_getc ( php_stream * stream)

php_stream_getc() reads a single character from stream and returns it as an unsigned char cast as an int, or EOF if the end-of-file is reached, or an error occurred.

php_stream_getc() may block in the same way as php_stream_read() blocks.

The internal position of the stream is advanced by 1 if successful.

后退 | 起点 | 前进
php_stream_eof | 上一级 | php_stream_gets


php_stream_gets

(no version information, might be only in CVS)

php_stream_gets -- Read a line of data from a stream into a buffer

Description

char * php_stream_gets ( php_stream * stream, char * buf, size_t maxlen)

php_stream_gets() reads up to count-1 bytes of data from stream and copies them into the buffer buf. Reading stops after an EOF or a newline. If a newline is read, it is stored in buf as part of the returned data. A NUL terminating character is stored as the last character in the buffer.

php_stream_read() returns buf when successful or NULL otherwise.

The internal position of the stream is advanced by the number of bytes that were read, so that subsequent reads will continue reading from that point.

This function may block in the same way as php_stream_read().

后退 | 起点 | 前进
php_stream_getc | 上一级 | php_stream_close


php_stream_is

(no version information, might be only in CVS)

php_stream_is -- Determines if a stream is of a particular type

Description

int php_stream_is ( php_stream * stream, int istype)

php_stream_is() returns 1 if stream is of the type specified by istype, or 0 otherwise.

表格 45-1. Values for istype

Value | Meaning
PHP_STREAM_IS_STDIO | The stream is implemented using the stdio implementation
PHP_STREAM_IS_SOCKET | The stream is implemented using the network stream implementation
PHP_STREAM_IS_USERSPACE | The stream is implemented using the userspace object implementation
PHP_STREAM_IS_MEMORY | The stream is implemented using the grow-on-demand memory stream implementation

注: The PHP_STREAM_IS_XXX "constants" are actually defined as pointers to the underlying stream operations structure. If your extension (or some other extension) defines additional streams, it should also declare a PHP_STREAM_IS_XXX constant in it's header file that you can use as the basis of this comparison.

注: This function is implemented as a simple (and fast) pointer comparision, and does not change the stream state in any way.

See also php_stream_cast() and php_stream_can_cast().

后退 | 起点 | 前进
php_stream_is_persistent | 上一级 | php_stream_passthru


php_stream_is_persistent

(no version information, might be only in CVS)

php_stream_is_persistent -- Determines if a stream is a persistent stream

Description

int php_stream_is_persistent ( php_stream * stream)

php_stream_is_persistent() returns 1 if the stream is a persistent stream, 0 otherwise.

后退 | 起点 | 前进
php_stream_can_cast | 上一级 | php_stream_is


php_stream_make_seekable

(no version information, might be only in CVS)

php_stream_make_seekable -- Convert a stream into a stream is seekable

Description

int php_stream_make_seekable ( php_stream * origstream, php_stream ** newstream, int flags)

php_stream_make_seekable() checks if origstream is seekable. If it is not, it will copy the data into a new temporary stream. If successful, newstream is always set to the stream that is valid to use, even if the original stream was seekable.

flags allows you to specify your preference for the seekeable stream that is returned: use PHP_STREAM_NO_PREFERENCE to use the default seekable stream (which uses a dynamically expanding memory buffer, but switches to temporary file backed storage when the stream size becomes large), or use PHP_STREAM_PREFER_STDIO to use "regular" temporary file backed storage.

表格 45-1. php_stream_make_seekable() return values

Value | Meaning
PHP_STREAM_UNCHANGED | Original stream was seekable anyway. newstream is set to the value of origstream.
PHP_STREAM_RELEASED | Original stream was not seekable and has been released. newstream is set to the new seekable stream. You should not access origstream anymore.
PHP_STREAM_FAILED | An error occurred while attempting conversion. newstream is set to NULL; origstream is still valid.
PHP_STREAM_CRITICAL | An error occurred while attempting conversion that has left origstream in an indeterminate state. newstream is set to NULL and it is highly recommended that you close origstream.

注: If you need to seek and write to the stream, it does not make sense to use this function, because the stream it returns is not guaranteed to be bound to the same resource as the original stream.

注: If you only need to seek forwards, there is no need to call this function, as the streams API will emulate forward seeks when the whence parameter is SEEK_CUR.

注: If origstream is network based, this function will block until the whole contents have been downloaded.

注: NEVER call this function with an origstream that is reference by a file pointer in a PHP script! This function may cause the underlying stream to be closed which could cause a crash when the script next accesses the file pointer!

注: In many cases, this function can only succeed when origstream is a newly opened stream with no data buffered in the stream layer. For that reason, and because this function is complicated to use correctly, it is recommended that you use php_stream_open_wrapper() and pass in PHP_STREAM_MUST_SEEK in your options instead of calling this function directly.

后退 | 起点 | 前进
php_stream_copy_to_mem | 上一级 | php_stream_cast


php_stream_open_wrapper

(no version information, might be only in CVS)

php_stream_open_wrapper -- Opens a stream on a file or URL

Description

php_stream * php_stream_open_wrapper ( char * path, char * mode, int options, char ** opened)

php_stream_open_wrapper() opens a stream on the file, URL or other wrapped resource specified by path. Depending on the value of mode, the stream may be opened for reading, writing, appending or combinations of those. See the table below for the different modes that can be used; in addition to the characters listed below, you may include the character 'b' either as the second or last character in the mode string. The presence of the 'b' character informs the relevant stream implementation to open the stream in a binary safe mode.

The 'b' character is ignored on all POSIX conforming systems which treat binary and text files in the same way. It is a good idea to specify the 'b' character whenever your stream is accessing data where the full 8 bits are important, so that your code will work when compiled on a system where the 'b' flag is important.

Any local files created by the streams API will have their initial permissions set according to the operating system defaults - under UNIX based systems this means that the umask of the process will be used. Under Windows, the file will be owned by the creating process. Any remote files will be created according to the URL wrapper that was used to open the file, and the credentials supplied to the remote server.

r

Open text file for reading. The stream is positioned at the beginning of the file.

r+

Open text file for reading and writing. The stream is positioned at the beginning of the file.

w

Truncate the file to zero length or create text file for writing. The stream is positioned at the beginning of the file.

w+

Open text file for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.

a

Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file.

a+

Open text file for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file.

options affects how the path/URL of the stream is interpreted, safe mode checks and actions taken if there is an error during opening of the stream. See Stream open options for more information about options.

If opened is not NULL, it will be set to a string containing the name of the actual file/resource that was opened. This is important when the options include USE_PATH, which causes the include_path to be searched for the file. You, the caller, are responsible for calling efree() on the filename returned in this parameter.

注: If you specified STREAM_MUST_SEEK in options, the path returned in opened may not be the name of the actual stream that was returned to you. It will, however, be the name of the original resource from which the seekable stream was manufactured.

后退 | 起点 | 前进
php_stream_stat | 上一级 | php_stream_read


php_stream_open_wrapper_as_file

(no version information, might be only in CVS)

php_stream_open_wrapper_as_file -- Opens a stream on a file or URL, and converts to a FILE*

Description

FILE * php_stream_open_wrapper_as_file ( char * path, char * mode, int options, char ** opened)

php_stream_open_wrapper_as_file() is exactly like php_stream_open_wrapper(), but converts the stream into an ANSI stdio FILE* and returns that instead of the stream. This is a convenient shortcut for extensions that pass FILE* to third-party libraries.

后退 | 起点 | 前进
php_stream_open_wrapper_ex | 上一级 | Streams Dir API Reference


php_stream_open_wrapper_ex

(no version information, might be only in CVS)

php_stream_open_wrapper_ex -- Opens a stream on a file or URL, specifying context

Description

php_stream * php_stream_open_wrapper_ex ( char * path, char * mode, int options, char ** opened, php_stream_context * context)

php_stream_open_wrapper_ex() is exactly like php_stream_open_wrapper(), but allows you to specify a php_stream_context object using context. To find out more about stream contexts, see XXX

后退 | 起点 | 前进
php_unregister_url_stream_wrapper | 上一级 | php_stream_open_wrapper_as_file


php_stream_opendir

(no version information, might be only in CVS)

php_stream_opendir -- Open a directory for file enumeration

Description

php_stream * php_stream_opendir ( char * path, php_stream_context * context)

php_stream_opendir() returns a stream that can be used to list the files that are contained in the directory specified by path. This function is functionally equivalent to POSIX opendir(). Although this function returns a php_stream object, it is not recommended to try to use the functions from the common API on these streams.

后退 | 起点 | 前进
Streams Dir API Reference | 上一级 | php_stream_readdir


php_stream_passthru

(no version information, might be only in CVS)

php_stream_passthru -- Outputs all remaining data from a stream

Description

size_t php_stream_passthru ( php_stream * stream)

php_stream_passthru() outputs all remaining data from stream to the active output buffer and returns the number of bytes output. If buffering is disabled, the data is written straight to the output, which is the browser making the request in the case of PHP on a web server, or stdout for CLI based PHP. This function will use memory mapped files if possible to help improve performance.

后退 | 起点 | 前进
php_stream_is | 上一级 | php_register_url_stream_wrapper


php_stream_read

(no version information, might be only in CVS)

php_stream_read -- Read a number of bytes from a stream into a buffer

Description

size_t php_stream_read ( php_stream * stream, char * buf, size_t count)

php_stream_read() reads up to count bytes of data from stream and copies them into the buffer buf.

php_stream_read() returns the number of bytes that were read successfully. There is no distinction between a failed read or an end-of-file condition - use php_stream_eof() to test for an EOF.

The internal position of the stream is advanced by the number of bytes that were read, so that subsequent reads will continue reading from that point.

If less than count bytes are available to be read, this call will block (or wait) until the required number are available, depending on the blocking status of the stream. By default, a stream is opened in blocking mode. When reading from regular files, the blocking mode will not usually make any difference: when the stream reaches the EOF php_stream_read() will return a value less than count, and 0 on subsequent reads.

后退 | 起点 | 前进
php_stream_open_wrapper | 上一级 | php_stream_write


php_stream_readdir

(no version information, might be only in CVS)

php_stream_readdir -- Fetch the next directory entry from an opened dir

Description

php_stream_dirent * php_stream_readdir ( php_stream * dirstream, php_stream_dirent * ent)

php_stream_readdir() reads the next directory entry from dirstream and stores it into ent. If the function succeeds, the return value is ent. If the function fails, the return value is NULL.

后退 | 起点 | 前进
php_stream_opendir | 上一级 | php_stream_rewinddir


php_stream_rewinddir

(no version information, might be only in CVS)

php_stream_rewinddir -- Rewind a directory stream to the first entry

Description

int php_stream_rewinddir ( php_stream * dirstream)

php_stream_rewinddir() rewinds a directory stream to the first entry. Returns 0 on success, but -1 on failure.

后退 | 起点 | 前进
php_stream_readdir | 上一级 | php_stream_closedir


php_stream_seek

(no version information, might be only in CVS)

php_stream_seek -- Reposition a stream

Description

int php_stream_seek ( php_stream * stream, off_t offset, int whence)

php_stream_seek() repositions the internal position of stream. The new position is determined by adding the offset to the position indicated by whence. If whence is set to SEEK_SET, SEEK_CUR or SEEK_END the offset is relative to the start of the stream, the current position or the end of the stream, respectively.

php_stream_seek() returns 0 on success, but -1 if there was an error.

注: Not all streams support seeking, although the streams API will emulate a seek if whence is set to SEEK_CUR and offset is positive, by calling php_stream_read() to read (and discard) offset bytes.

The emulation is only applied when the underlying stream implementation does not support seeking. If the stream is (for example) a file based stream that is wrapping a non-seekable pipe, the streams api will not apply emulation because the file based stream implements a seek operation; the seek will fail and an error result will be returned to the caller.

后退 | 起点 | 前进
php_stream_flush | 上一级 | php_stream_tell


php_stream_sock_open_from_socket

(no version information, might be only in CVS)

php_stream_sock_open_from_socket -- Convert a socket descriptor into a stream

Description

php_stream * php_stream_sock_open_from_socket ( int socket, int persistent)

php_stream_sock_open_from_socket() returns a stream based on the socket. persistent is a flag that controls whether the stream is opened as a persistent stream. Generally speaking, this parameter will usually be 0.

后退 | 起点 | 前进
Streams Socket API Reference | 上一级 | php_stream_sock_open_host


php_stream_sock_open_host

(no version information, might be only in CVS)

php_stream_sock_open_host -- Open a connection to a host and return a stream

Description

php_stream * php_stream_sock_open_host ( const char * host, unsigned short port, int socktype, struct timeval * timeout, int persistent)

php_stream_sock_open_host() establishes a connect to the specified host and port. socktype specifies the connection semantics that should apply to the connection. Values for socktype are system dependent, but will usually include (at a minimum) SOCK_STREAM for sequenced, reliable, two-way connection based streams (TCP), or SOCK_DGRAM for connectionless, unreliable messages of a fixed maximum length (UDP).

persistent is a flag the controls whether the stream is opened as a persistent stream. Generally speaking, this parameter will usually be 0.

If not NULL, timeout specifies a maximum time to allow for the connection to be made. If the connection attempt takes longer than the timeout value, the connection attempt is aborted and NULL is returned to indicate that the stream could not be opened.

注: The timeout value does not include the time taken to perform a DNS lookup. The reason for this is because there is no portable way to implement a non-blocking DNS lookup.

The timeout only applies to the connection phase; if you need to set timeouts for subsequent read or write operations, you should use php_stream_sock_set_timeout() to configure the timeout duration for your stream once it has been opened.

The streams API places no restrictions on the values you use for socktype, but encourages you to consider the portability of values you choose before you release your extension.

后退 | 起点 | 前进
php_stream_sock_open_from_socket | 上一级 | php_stream_sock_open_unix


php_stream_sock_open_unix

(no version information, might be only in CVS)

php_stream_sock_open_unix -- Open a UNIX domain socket and convert into a stream

Description

php_stream * php_stream_sock_open_unix ( const char * path, int pathlen, int persistent, struct timeval * timeout)

php_stream_sock_open_unix() attempts to open the UNIX domain socket specified by path. pathlen specifies the length of path. If timeout is not NULL, it specifies a timeout period for the connection attempt. persistent indicates if the stream should be opened as a persistent stream. Generally speaking, this parameter will usually be 0.

注: This function will not work under Windows, which does not implement unix domain sockets. A possible exception to this rule is if your PHP binary was built using cygwin. You are encouraged to consider this aspect of the portability of your extension before it's release.

注: This function treats path in a binary safe manner, suitable for use on systems with an abstract namespace (such as Linux), where the first character of path is a NUL character.

后退 | 起点 | 前进
php_stream_sock_open_host | 上一级 | Streams Structures


php_stream_stat

(no version information, might be only in CVS)

php_stream_stat -- Gets the status for the underlying storage associated with a stream

Description

int php_stream_stat ( php_stream * stream, php_stream_statbuf * ssb)

php_stream_stat() examines the storage to which stream is bound, and returns information such as file size, access and creation times and so on. The return value is 0 on success, -1 on error. For more information about the information returned, see php_stream_statbuf.

后退 | 起点 | 前进
php_stream_stat_path | 上一级 | php_stream_open_wrapper


php_stream_stat_path

(no version information, might be only in CVS)

php_stream_stat_path -- Gets the status for a file or URL

Description

int php_stream_stat_path ( char * path, php_stream_statbuf * ssb)

php_stream_stat_path() examines the file or URL specified by path and returns information such as file size, access and creation times and so on. The return value is 0 on success, -1 on error. For more information about the information returned, see php_stream_statbuf.

后退 | 起点 | 前进
Streams Common API Reference | 上一级 | php_stream_stat


php_stream_tell

(no version information, might be only in CVS)

php_stream_tell -- Determine the position of a stream

Description

off_t php_stream_tell ( php_stream * stream)

php_stream_tell() returns the internal position of stream, relative to the start of the stream. If there is an error, -1 is returned.

后退 | 起点 | 前进
php_stream_seek | 上一级 | php_stream_copy_to_stream


php_stream_write

(no version information, might be only in CVS)

php_stream_write -- Write a number of bytes from a buffer to a stream

Description

size_t php_stream_write ( php_stream * stream, const char * buf, size_t count)

php_stream_write() writes count bytes of data from buf into stream.

php_stream_write() returns the number of bytes that were read successfully. If there was an error, the number of bytes written will be less than count.

The internal position of the stream is advanced by the number of bytes that were written, so that subsequent writes will continue writing from that point.

后退 | 起点 | 前进
php_stream_read | 上一级 | php_stream_eof


php_unregister_url_stream_wrapper

(no version information, might be only in CVS)

php_unregister_url_stream_wrapper -- Un-registers a wrapper from the Streams API

Description

int php_unregister_url_stream_wrapper ( char * protocol, TSRMLS_DC )

php_unregister_url_stream_wrapper() unregisters the wrapper associated with protocol.

后退 | 起点 | 前进
php_register_url_stream_wrapper | 上一级 | php_stream_open_wrapper_ex


struct php_stream_dirent

struct php_stream_dirent -- Holds information about a single file during dir scanning

Description

php_stream_dirent
     char d_name[MAXPATHLEN]

d_name holds the name of the file, relative to the directory being scanned.

后退 | 起点 | 前进
struct php_stream_statbuf | 上一级 | Streams Constants


struct php_stream_statbuf

struct php_stream_statbuf -- Holds information about a file or URL

Description

php_stream_statbuf
     struct stat sb

sb is a regular, system defined, struct stat.

后退 | 起点 | 前进
Streams Structures | 上一级 | struct php_stream_dirent